Cotrans 漫画/图片翻译器 (常规版)

(WIP) 一键翻译图片内文字,支持 Pixiv, Twitter, Misskey, Calckey

  1. // ==UserScript==
  2. // @name Cotrans Manga/Image Translator (Regular Edition)
  3. // @name:zh-CN Cotrans 漫画/图片翻译器 (常规版)
  4. // @namespace https://cotrans.touhou.ai/userscript/#regular
  5. // @version 0.8.0-bata.17
  6. // @description (WIP) Translate texts in images on Pixiv, Twitter, Misskey, Calckey
  7. // @description:zh-CN (WIP) 一键翻译图片内文字,支持 Pixiv, Twitter, Misskey, Calckey
  8. // @author QiroNT
  9. // @license GPL-3.0
  10. // @contributionURL https://ko-fi.com/voilelabs
  11. // @supportURL https://discord.gg/975FRV8ca6
  12. // @source https://cotrans.touhou.ai/
  13. // @include https://www.pixiv.net/*
  14. // @match https://www.pixiv.net/*
  15. // @include https://twitter.com/*
  16. // @match https://twitter.com/*
  17. // @include https://misskey.io/*
  18. // @match https://misskey.io/*
  19. // @include https://calckey.social/*
  20. // @match https://calckey.social/*
  21. // @include https://*
  22. // @match https://*
  23. // @connect pixiv.net
  24. // @connect pximg.net
  25. // @connect twitter.com
  26. // @connect twimg.com
  27. // @connect misskey.io
  28. // @connect misskeyusercontent.com
  29. // @connect s3.arkjp.net
  30. // @connect nfs.pub
  31. // @connect calckey.social
  32. // @connect backblazeb2.com
  33. // @connect dvd.moe
  34. // @connect api.cotrans.touhou.ai
  35. // @connect r2.cotrans.touhou.ai
  36. // @connect cotrans-r2.moe.ci
  37. // @connect *
  38. // @grant GM.xmlHttpRequest
  39. // @grant GM_xmlhttpRequest
  40. // @grant GM.setValue
  41. // @grant GM_setValue
  42. // @grant GM.getValue
  43. // @grant GM_getValue
  44. // @grant GM.deleteValue
  45. // @grant GM_deleteValue
  46. // @grant GM.addValueChangeListener
  47. // @grant GM_addValueChangeListener
  48. // @grant GM.removeValueChangeListener
  49. // @grant GM_removeValueChangeListener
  50. // @grant window.onurlchange
  51. // @run-at document-idle
  52. // ==/UserScript==
  53.  
  54. /* eslint-disable no-undef, unused-imports/no-unused-vars */
  55. const VERSION = '0.8.0-bata.17'
  56. const EDITION = 'regular'
  57. let GMP
  58. {
  59. // polyfill functions
  60. const GMPFunctionMap = {
  61. xmlHttpRequest: typeof GM_xmlhttpRequest !== 'undefined' ? GM_xmlhttpRequest : undefined,
  62. setValue: typeof GM_setValue !== 'undefined' ? GM_setValue : undefined,
  63. getValue: typeof GM_getValue !== 'undefined' ? GM_getValue : undefined,
  64. deleteValue: typeof GM_deleteValue !== 'undefined' ? GM_deleteValue : undefined,
  65. addValueChangeListener: typeof GM_addValueChangeListener !== 'undefined' ? GM_addValueChangeListener : undefined,
  66. removeValueChangeListener: typeof GM_removeValueChangeListener !== 'undefined' ? GM_removeValueChangeListener : undefined,
  67. }
  68. const xmlHttpRequest = GM.xmlHttpRequest.bind(GM) || GMPFunctionMap.xmlHttpRequest
  69. GMP = new Proxy(GM, {
  70. get(target, prop) {
  71. if (prop === 'xmlHttpRequest') {
  72. return (context) => {
  73. return new Promise((resolve, reject) => {
  74. xmlHttpRequest({
  75. ...context,
  76. onload(event) {
  77. context.onload?.()
  78. resolve(event)
  79. },
  80. onerror(event) {
  81. context.onerror?.()
  82. reject(event)
  83. },
  84. })
  85. })
  86. }
  87. }
  88. if (prop in target) {
  89. const v = target[prop]
  90. return typeof v === 'function' ? v.bind(target) : v
  91. }
  92. if (prop in GMPFunctionMap && typeof GMPFunctionMap[prop] === 'function')
  93. return GMPFunctionMap[prop]
  94.  
  95. 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.`)
  96. },
  97. })
  98. }
  99.  
  100. (function () {
  101. 'use strict';
  102.  
  103. const equalFn = (a, b) => a === b;
  104. const $PROXY = Symbol("solid-proxy");
  105. const $TRACK = Symbol("solid-track");
  106. const $DEVCOMP = Symbol("solid-dev-component");
  107. const signalOptions = {
  108. equals: equalFn
  109. };
  110. let runEffects = runQueue;
  111. const STALE = 1;
  112. const PENDING = 2;
  113. const UNOWNED = {
  114. owned: null,
  115. cleanups: null,
  116. context: null,
  117. owner: null
  118. };
  119. var Owner = null;
  120. let Transition = null;
  121. let Listener = null;
  122. let Updates = null;
  123. let Effects = null;
  124. let ExecCount = 0;
  125. function createRoot(fn, detachedOwner) {
  126. const listener = Listener,
  127. owner = Owner,
  128. unowned = fn.length === 0,
  129. root = unowned ? UNOWNED : {
  130. owned: null,
  131. cleanups: null,
  132. context: null,
  133. owner: detachedOwner === undefined ? owner : detachedOwner
  134. },
  135. updateFn = unowned ? fn : () => fn(() => untrack(() => cleanNode(root)));
  136. Owner = root;
  137. Listener = null;
  138. try {
  139. return runUpdates(updateFn, true);
  140. } finally {
  141. Listener = listener;
  142. Owner = owner;
  143. }
  144. }
  145. function createSignal(value, options) {
  146. options = options ? Object.assign({}, signalOptions, options) : signalOptions;
  147. const s = {
  148. value,
  149. observers: null,
  150. observerSlots: null,
  151. comparator: options.equals || undefined
  152. };
  153. const setter = value => {
  154. if (typeof value === "function") {
  155. value = value(s.value);
  156. }
  157. return writeSignal(s, value);
  158. };
  159. return [readSignal.bind(s), setter];
  160. }
  161. function createRenderEffect(fn, value, options) {
  162. const c = createComputation(fn, value, false, STALE);
  163. updateComputation(c);
  164. }
  165. function createEffect(fn, value, options) {
  166. runEffects = runUserEffects;
  167. const c = createComputation(fn, value, false, STALE);
  168. if (!options || !options.render) c.user = true;
  169. Effects ? Effects.push(c) : updateComputation(c);
  170. }
  171. function createMemo(fn, value, options) {
  172. options = options ? Object.assign({}, signalOptions, options) : signalOptions;
  173. const c = createComputation(fn, value, true, 0);
  174. c.observers = null;
  175. c.observerSlots = null;
  176. c.comparator = options.equals || undefined;
  177. updateComputation(c);
  178. return readSignal.bind(c);
  179. }
  180. function batch(fn) {
  181. return runUpdates(fn, false);
  182. }
  183. function untrack(fn) {
  184. if (Listener === null) return fn();
  185. const listener = Listener;
  186. Listener = null;
  187. try {
  188. return fn();
  189. } finally {
  190. Listener = listener;
  191. }
  192. }
  193. function on(deps, fn, options) {
  194. const isArray = Array.isArray(deps);
  195. let prevInput;
  196. let defer = options && options.defer;
  197. return prevValue => {
  198. let input;
  199. if (isArray) {
  200. input = Array(deps.length);
  201. for (let i = 0; i < deps.length; i++) input[i] = deps[i]();
  202. } else input = deps();
  203. if (defer) {
  204. defer = false;
  205. return undefined;
  206. }
  207. const result = untrack(() => fn(input, prevInput, prevValue));
  208. prevInput = input;
  209. return result;
  210. };
  211. }
  212. function onMount(fn) {
  213. createEffect(() => untrack(fn));
  214. }
  215. function onCleanup(fn) {
  216. if (Owner === null) ;else if (Owner.cleanups === null) Owner.cleanups = [fn];else Owner.cleanups.push(fn);
  217. return fn;
  218. }
  219. function getListener() {
  220. return Listener;
  221. }
  222. function getOwner() {
  223. return Owner;
  224. }
  225. function children(fn) {
  226. const children = createMemo(fn);
  227. const memo = createMemo(() => resolveChildren(children()));
  228. memo.toArray = () => {
  229. const c = memo();
  230. return Array.isArray(c) ? c : c != null ? [c] : [];
  231. };
  232. return memo;
  233. }
  234. function readSignal() {
  235. if (this.sources && (this.state)) {
  236. if ((this.state) === STALE) updateComputation(this);else {
  237. const updates = Updates;
  238. Updates = null;
  239. runUpdates(() => lookUpstream(this), false);
  240. Updates = updates;
  241. }
  242. }
  243. if (Listener) {
  244. const sSlot = this.observers ? this.observers.length : 0;
  245. if (!Listener.sources) {
  246. Listener.sources = [this];
  247. Listener.sourceSlots = [sSlot];
  248. } else {
  249. Listener.sources.push(this);
  250. Listener.sourceSlots.push(sSlot);
  251. }
  252. if (!this.observers) {
  253. this.observers = [Listener];
  254. this.observerSlots = [Listener.sources.length - 1];
  255. } else {
  256. this.observers.push(Listener);
  257. this.observerSlots.push(Listener.sources.length - 1);
  258. }
  259. }
  260. return this.value;
  261. }
  262. function writeSignal(node, value, isComp) {
  263. let current = node.value;
  264. if (!node.comparator || !node.comparator(current, value)) {
  265. node.value = value;
  266. if (node.observers && node.observers.length) {
  267. runUpdates(() => {
  268. for (let i = 0; i < node.observers.length; i += 1) {
  269. const o = node.observers[i];
  270. const TransitionRunning = Transition && Transition.running;
  271. if (TransitionRunning && Transition.disposed.has(o)) ;
  272. if (TransitionRunning ? !o.tState : !o.state) {
  273. if (o.pure) Updates.push(o);else Effects.push(o);
  274. if (o.observers) markDownstream(o);
  275. }
  276. if (!TransitionRunning) o.state = STALE;
  277. }
  278. if (Updates.length > 10e5) {
  279. Updates = [];
  280. if (false) ;
  281. throw new Error();
  282. }
  283. }, false);
  284. }
  285. }
  286. return value;
  287. }
  288. function updateComputation(node) {
  289. if (!node.fn) return;
  290. cleanNode(node);
  291. const owner = Owner,
  292. listener = Listener,
  293. time = ExecCount;
  294. Listener = Owner = node;
  295. runComputation(node, node.value, time);
  296. Listener = listener;
  297. Owner = owner;
  298. }
  299. function runComputation(node, value, time) {
  300. let nextValue;
  301. try {
  302. nextValue = node.fn(value);
  303. } catch (err) {
  304. if (node.pure) {
  305. {
  306. node.state = STALE;
  307. node.owned && node.owned.forEach(cleanNode);
  308. node.owned = null;
  309. }
  310. }
  311. node.updatedAt = time + 1;
  312. return handleError(err);
  313. }
  314. if (!node.updatedAt || node.updatedAt <= time) {
  315. if (node.updatedAt != null && "observers" in node) {
  316. writeSignal(node, nextValue);
  317. } else node.value = nextValue;
  318. node.updatedAt = time;
  319. }
  320. }
  321. function createComputation(fn, init, pure, state = STALE, options) {
  322. const c = {
  323. fn,
  324. state: state,
  325. updatedAt: null,
  326. owned: null,
  327. sources: null,
  328. sourceSlots: null,
  329. cleanups: null,
  330. value: init,
  331. owner: Owner,
  332. context: null,
  333. pure
  334. };
  335. if (Owner === null) ;else if (Owner !== UNOWNED) {
  336. {
  337. if (!Owner.owned) Owner.owned = [c];else Owner.owned.push(c);
  338. }
  339. }
  340. return c;
  341. }
  342. function runTop(node) {
  343. if ((node.state) === 0) return;
  344. if ((node.state) === PENDING) return lookUpstream(node);
  345. if (node.suspense && untrack(node.suspense.inFallback)) return node.suspense.effects.push(node);
  346. const ancestors = [node];
  347. while ((node = node.owner) && (!node.updatedAt || node.updatedAt < ExecCount)) {
  348. if (node.state) ancestors.push(node);
  349. }
  350. for (let i = ancestors.length - 1; i >= 0; i--) {
  351. node = ancestors[i];
  352. if ((node.state) === STALE) {
  353. updateComputation(node);
  354. } else if ((node.state) === PENDING) {
  355. const updates = Updates;
  356. Updates = null;
  357. runUpdates(() => lookUpstream(node, ancestors[0]), false);
  358. Updates = updates;
  359. }
  360. }
  361. }
  362. function runUpdates(fn, init) {
  363. if (Updates) return fn();
  364. let wait = false;
  365. if (!init) Updates = [];
  366. if (Effects) wait = true;else Effects = [];
  367. ExecCount++;
  368. try {
  369. const res = fn();
  370. completeUpdates(wait);
  371. return res;
  372. } catch (err) {
  373. if (!wait) Effects = null;
  374. Updates = null;
  375. handleError(err);
  376. }
  377. }
  378. function completeUpdates(wait) {
  379. if (Updates) {
  380. runQueue(Updates);
  381. Updates = null;
  382. }
  383. if (wait) return;
  384. const e = Effects;
  385. Effects = null;
  386. if (e.length) runUpdates(() => runEffects(e), false);
  387. }
  388. function runQueue(queue) {
  389. for (let i = 0; i < queue.length; i++) runTop(queue[i]);
  390. }
  391. function runUserEffects(queue) {
  392. let i,
  393. userLength = 0;
  394. for (i = 0; i < queue.length; i++) {
  395. const e = queue[i];
  396. if (!e.user) runTop(e);else queue[userLength++] = e;
  397. }
  398. for (i = 0; i < userLength; i++) runTop(queue[i]);
  399. }
  400. function lookUpstream(node, ignore) {
  401. node.state = 0;
  402. for (let i = 0; i < node.sources.length; i += 1) {
  403. const source = node.sources[i];
  404. if (source.sources) {
  405. const state = source.state;
  406. if (state === STALE) {
  407. if (source !== ignore && (!source.updatedAt || source.updatedAt < ExecCount)) runTop(source);
  408. } else if (state === PENDING) lookUpstream(source, ignore);
  409. }
  410. }
  411. }
  412. function markDownstream(node) {
  413. for (let i = 0; i < node.observers.length; i += 1) {
  414. const o = node.observers[i];
  415. if (!o.state) {
  416. o.state = PENDING;
  417. if (o.pure) Updates.push(o);else Effects.push(o);
  418. o.observers && markDownstream(o);
  419. }
  420. }
  421. }
  422. function cleanNode(node) {
  423. let i;
  424. if (node.sources) {
  425. while (node.sources.length) {
  426. const source = node.sources.pop(),
  427. index = node.sourceSlots.pop(),
  428. obs = source.observers;
  429. if (obs && obs.length) {
  430. const n = obs.pop(),
  431. s = source.observerSlots.pop();
  432. if (index < obs.length) {
  433. n.sourceSlots[s] = index;
  434. obs[index] = n;
  435. source.observerSlots[index] = s;
  436. }
  437. }
  438. }
  439. }
  440. if (node.owned) {
  441. for (i = node.owned.length - 1; i >= 0; i--) cleanNode(node.owned[i]);
  442. node.owned = null;
  443. }
  444. if (node.cleanups) {
  445. for (i = node.cleanups.length - 1; i >= 0; i--) node.cleanups[i]();
  446. node.cleanups = null;
  447. }
  448. node.state = 0;
  449. node.context = null;
  450. }
  451. function castError(err) {
  452. if (err instanceof Error) return err;
  453. return new Error(typeof err === "string" ? err : "Unknown error", {
  454. cause: err
  455. });
  456. }
  457. function handleError(err, owner = Owner) {
  458. const error = castError(err);
  459. throw error;
  460. }
  461. function resolveChildren(children) {
  462. if (typeof children === "function" && !children.length) return resolveChildren(children());
  463. if (Array.isArray(children)) {
  464. const results = [];
  465. for (let i = 0; i < children.length; i++) {
  466. const result = resolveChildren(children[i]);
  467. Array.isArray(result) ? results.push.apply(results, result) : results.push(result);
  468. }
  469. return results;
  470. }
  471. return children;
  472. }
  473. const FALLBACK = Symbol("fallback");
  474. function dispose(d) {
  475. for (let i = 0; i < d.length; i++) d[i]();
  476. }
  477. function mapArray(list, mapFn, options = {}) {
  478. let items = [],
  479. mapped = [],
  480. disposers = [],
  481. len = 0,
  482. indexes = mapFn.length > 1 ? [] : null;
  483. onCleanup(() => dispose(disposers));
  484. return () => {
  485. let newItems = list() || [],
  486. i,
  487. j;
  488. newItems[$TRACK];
  489. return untrack(() => {
  490. let newLen = newItems.length,
  491. newIndices,
  492. newIndicesNext,
  493. temp,
  494. tempdisposers,
  495. tempIndexes,
  496. start,
  497. end,
  498. newEnd,
  499. item;
  500. if (newLen === 0) {
  501. if (len !== 0) {
  502. dispose(disposers);
  503. disposers = [];
  504. items = [];
  505. mapped = [];
  506. len = 0;
  507. indexes && (indexes = []);
  508. }
  509. if (options.fallback) {
  510. items = [FALLBACK];
  511. mapped[0] = createRoot(disposer => {
  512. disposers[0] = disposer;
  513. return options.fallback();
  514. });
  515. len = 1;
  516. }
  517. } else if (len === 0) {
  518. mapped = new Array(newLen);
  519. for (j = 0; j < newLen; j++) {
  520. items[j] = newItems[j];
  521. mapped[j] = createRoot(mapper);
  522. }
  523. len = newLen;
  524. } else {
  525. temp = new Array(newLen);
  526. tempdisposers = new Array(newLen);
  527. indexes && (tempIndexes = new Array(newLen));
  528. for (start = 0, end = Math.min(len, newLen); start < end && items[start] === newItems[start]; start++);
  529. for (end = len - 1, newEnd = newLen - 1; end >= start && newEnd >= start && items[end] === newItems[newEnd]; end--, newEnd--) {
  530. temp[newEnd] = mapped[end];
  531. tempdisposers[newEnd] = disposers[end];
  532. indexes && (tempIndexes[newEnd] = indexes[end]);
  533. }
  534. newIndices = new Map();
  535. newIndicesNext = new Array(newEnd + 1);
  536. for (j = newEnd; j >= start; j--) {
  537. item = newItems[j];
  538. i = newIndices.get(item);
  539. newIndicesNext[j] = i === undefined ? -1 : i;
  540. newIndices.set(item, j);
  541. }
  542. for (i = start; i <= end; i++) {
  543. item = items[i];
  544. j = newIndices.get(item);
  545. if (j !== undefined && j !== -1) {
  546. temp[j] = mapped[i];
  547. tempdisposers[j] = disposers[i];
  548. indexes && (tempIndexes[j] = indexes[i]);
  549. j = newIndicesNext[j];
  550. newIndices.set(item, j);
  551. } else disposers[i]();
  552. }
  553. for (j = start; j < newLen; j++) {
  554. if (j in temp) {
  555. mapped[j] = temp[j];
  556. disposers[j] = tempdisposers[j];
  557. if (indexes) {
  558. indexes[j] = tempIndexes[j];
  559. indexes[j](j);
  560. }
  561. } else mapped[j] = createRoot(mapper);
  562. }
  563. mapped = mapped.slice(0, len = newLen);
  564. items = newItems.slice(0);
  565. }
  566. return mapped;
  567. });
  568. function mapper(disposer) {
  569. disposers[j] = disposer;
  570. if (indexes) {
  571. const [s, set] = createSignal(j);
  572. indexes[j] = set;
  573. return mapFn(newItems[j], s);
  574. }
  575. return mapFn(newItems[j]);
  576. }
  577. };
  578. }
  579. function createComponent(Comp, props) {
  580. return untrack(() => Comp(props || {}));
  581. }
  582. function trueFn() {
  583. return true;
  584. }
  585. const propTraps = {
  586. get(_, property, receiver) {
  587. if (property === $PROXY) return receiver;
  588. return _.get(property);
  589. },
  590. has(_, property) {
  591. if (property === $PROXY) return true;
  592. return _.has(property);
  593. },
  594. set: trueFn,
  595. deleteProperty: trueFn,
  596. getOwnPropertyDescriptor(_, property) {
  597. return {
  598. configurable: true,
  599. enumerable: true,
  600. get() {
  601. return _.get(property);
  602. },
  603. set: trueFn,
  604. deleteProperty: trueFn
  605. };
  606. },
  607. ownKeys(_) {
  608. return _.keys();
  609. }
  610. };
  611. function splitProps(props, ...keys) {
  612. if ($PROXY in props) {
  613. const blocked = new Set(keys.length > 1 ? keys.flat() : keys[0]);
  614. const res = keys.map(k => {
  615. return new Proxy({
  616. get(property) {
  617. return k.includes(property) ? props[property] : undefined;
  618. },
  619. has(property) {
  620. return k.includes(property) && property in props;
  621. },
  622. keys() {
  623. return k.filter(property => property in props);
  624. }
  625. }, propTraps);
  626. });
  627. res.push(new Proxy({
  628. get(property) {
  629. return blocked.has(property) ? undefined : props[property];
  630. },
  631. has(property) {
  632. return blocked.has(property) ? false : property in props;
  633. },
  634. keys() {
  635. return Object.keys(props).filter(k => !blocked.has(k));
  636. }
  637. }, propTraps));
  638. return res;
  639. }
  640. const otherObject = {};
  641. const objects = keys.map(() => ({}));
  642. for (const propName of Object.getOwnPropertyNames(props)) {
  643. const desc = Object.getOwnPropertyDescriptor(props, propName);
  644. const isDefaultDesc = !desc.get && !desc.set && desc.enumerable && desc.writable && desc.configurable;
  645. let blocked = false;
  646. let objectIndex = 0;
  647. for (const k of keys) {
  648. if (k.includes(propName)) {
  649. blocked = true;
  650. isDefaultDesc ? objects[objectIndex][propName] = desc.value : Object.defineProperty(objects[objectIndex], propName, desc);
  651. }
  652. ++objectIndex;
  653. }
  654. if (!blocked) {
  655. isDefaultDesc ? otherObject[propName] = desc.value : Object.defineProperty(otherObject, propName, desc);
  656. }
  657. }
  658. return [...objects, otherObject];
  659. }
  660. const narrowedError = name => `Stale read from <${name}>.`;
  661. function For(props) {
  662. const fallback = "fallback" in props && {
  663. fallback: () => props.fallback
  664. };
  665. return createMemo(mapArray(() => props.each, props.children, fallback || undefined));
  666. }
  667. function Show(props) {
  668. const keyed = props.keyed;
  669. const condition = createMemo(() => props.when, undefined, {
  670. equals: (a, b) => keyed ? a === b : !a === !b
  671. });
  672. return createMemo(() => {
  673. const c = condition();
  674. if (c) {
  675. const child = props.children;
  676. const fn = typeof child === "function" && child.length > 0;
  677. return fn ? untrack(() => child(keyed ? c : () => {
  678. if (!untrack(condition)) throw narrowedError("Show");
  679. return props.when;
  680. })) : child;
  681. }
  682. return props.fallback;
  683. }, undefined, undefined);
  684. }
  685. function Switch(props) {
  686. let keyed = false;
  687. const equals = (a, b) => a[0] === b[0] && (keyed ? a[1] === b[1] : !a[1] === !b[1]) && a[2] === b[2];
  688. const conditions = children(() => props.children),
  689. evalConditions = createMemo(() => {
  690. let conds = conditions();
  691. if (!Array.isArray(conds)) conds = [conds];
  692. for (let i = 0; i < conds.length; i++) {
  693. const c = conds[i].when;
  694. if (c) {
  695. keyed = !!conds[i].keyed;
  696. return [i, c, conds[i]];
  697. }
  698. }
  699. return [-1];
  700. }, undefined, {
  701. equals
  702. });
  703. return createMemo(() => {
  704. const [index, when, cond] = evalConditions();
  705. if (index < 0) return props.fallback;
  706. const c = cond.children;
  707. const fn = typeof c === "function" && c.length > 0;
  708. return fn ? untrack(() => c(keyed ? when : () => {
  709. if (untrack(evalConditions)[0] !== index) throw narrowedError("Match");
  710. return cond.when;
  711. })) : c;
  712. }, undefined, undefined);
  713. }
  714. function Match(props) {
  715. return props;
  716. }
  717.  
  718. 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"];
  719. const Properties = /*#__PURE__*/new Set(["className", "value", "readOnly", "formNoValidate", "isMap", "noModule", "playsInline", ...booleans]);
  720. const ChildProperties = /*#__PURE__*/new Set(["innerHTML", "textContent", "innerText", "children"]);
  721. const Aliases = /*#__PURE__*/Object.assign(Object.create(null), {
  722. className: "class",
  723. htmlFor: "for"
  724. });
  725. const PropAliases = /*#__PURE__*/Object.assign(Object.create(null), {
  726. class: "className",
  727. formnovalidate: {
  728. $: "formNoValidate",
  729. BUTTON: 1,
  730. INPUT: 1
  731. },
  732. ismap: {
  733. $: "isMap",
  734. IMG: 1
  735. },
  736. nomodule: {
  737. $: "noModule",
  738. SCRIPT: 1
  739. },
  740. playsinline: {
  741. $: "playsInline",
  742. VIDEO: 1
  743. },
  744. readonly: {
  745. $: "readOnly",
  746. INPUT: 1,
  747. TEXTAREA: 1
  748. }
  749. });
  750. function getPropAlias(prop, tagName) {
  751. const a = PropAliases[prop];
  752. return typeof a === "object" ? a[tagName] ? a["$"] : undefined : a;
  753. }
  754. 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"]);
  755. 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"]);
  756. const SVGNamespace = {
  757. xlink: "http://www.w3.org/1999/xlink",
  758. xml: "http://www.w3.org/XML/1998/namespace"
  759. };
  760. function reconcileArrays(parentNode, a, b) {
  761. let bLength = b.length,
  762. aEnd = a.length,
  763. bEnd = bLength,
  764. aStart = 0,
  765. bStart = 0,
  766. after = a[aEnd - 1].nextSibling,
  767. map = null;
  768. while (aStart < aEnd || bStart < bEnd) {
  769. if (a[aStart] === b[bStart]) {
  770. aStart++;
  771. bStart++;
  772. continue;
  773. }
  774. while (a[aEnd - 1] === b[bEnd - 1]) {
  775. aEnd--;
  776. bEnd--;
  777. }
  778. if (aEnd === aStart) {
  779. const node = bEnd < bLength ? bStart ? b[bStart - 1].nextSibling : b[bEnd - bStart] : after;
  780. while (bStart < bEnd) parentNode.insertBefore(b[bStart++], node);
  781. } else if (bEnd === bStart) {
  782. while (aStart < aEnd) {
  783. if (!map || !map.has(a[aStart])) a[aStart].remove();
  784. aStart++;
  785. }
  786. } else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {
  787. const node = a[--aEnd].nextSibling;
  788. parentNode.insertBefore(b[bStart++], a[aStart++].nextSibling);
  789. parentNode.insertBefore(b[--bEnd], node);
  790. a[aEnd] = b[bEnd];
  791. } else {
  792. if (!map) {
  793. map = new Map();
  794. let i = bStart;
  795. while (i < bEnd) map.set(b[i], i++);
  796. }
  797. const index = map.get(a[aStart]);
  798. if (index != null) {
  799. if (bStart < index && index < bEnd) {
  800. let i = aStart,
  801. sequence = 1,
  802. t;
  803. while (++i < aEnd && i < bEnd) {
  804. if ((t = map.get(a[i])) == null || t !== index + sequence) break;
  805. sequence++;
  806. }
  807. if (sequence > index - bStart) {
  808. const node = a[aStart];
  809. while (bStart < index) parentNode.insertBefore(b[bStart++], node);
  810. } else parentNode.replaceChild(b[bStart++], a[aStart++]);
  811. } else aStart++;
  812. } else a[aStart++].remove();
  813. }
  814. }
  815. }
  816. const $$EVENTS = "_$DX_DELEGATE";
  817. function render(code, element, init, options = {}) {
  818. let disposer;
  819. createRoot(dispose => {
  820. disposer = dispose;
  821. element === document ? code() : insert(element, code(), element.firstChild ? null : undefined, init);
  822. }, options.owner);
  823. return () => {
  824. disposer();
  825. element.textContent = "";
  826. };
  827. }
  828. function template(html, isCE, isSVG) {
  829. let node;
  830. const create = () => {
  831. const t = document.createElement("template");
  832. t.innerHTML = html;
  833. return isSVG ? t.content.firstChild.firstChild : t.content.firstChild;
  834. };
  835. const fn = isCE ? () => untrack(() => document.importNode(node || (node = create()), true)) : () => (node || (node = create())).cloneNode(true);
  836. fn.cloneNode = fn;
  837. return fn;
  838. }
  839. function delegateEvents(eventNames, document = window.document) {
  840. const e = document[$$EVENTS] || (document[$$EVENTS] = new Set());
  841. for (let i = 0, l = eventNames.length; i < l; i++) {
  842. const name = eventNames[i];
  843. if (!e.has(name)) {
  844. e.add(name);
  845. document.addEventListener(name, eventHandler);
  846. }
  847. }
  848. }
  849. function setAttribute(node, name, value) {
  850. if (value == null) node.removeAttribute(name);else node.setAttribute(name, value);
  851. }
  852. function setAttributeNS(node, namespace, name, value) {
  853. if (value == null) node.removeAttributeNS(namespace, name);else node.setAttributeNS(namespace, name, value);
  854. }
  855. function className(node, value) {
  856. if (value == null) node.removeAttribute("class");else node.className = value;
  857. }
  858. function addEventListener(node, name, handler, delegate) {
  859. if (delegate) {
  860. if (Array.isArray(handler)) {
  861. node[`$$${name}`] = handler[0];
  862. node[`$$${name}Data`] = handler[1];
  863. } else node[`$$${name}`] = handler;
  864. } else if (Array.isArray(handler)) {
  865. const handlerFn = handler[0];
  866. node.addEventListener(name, handler[0] = e => handlerFn.call(node, handler[1], e));
  867. } else node.addEventListener(name, handler);
  868. }
  869. function classList(node, value, prev = {}) {
  870. const classKeys = Object.keys(value || {}),
  871. prevKeys = Object.keys(prev);
  872. let i, len;
  873. for (i = 0, len = prevKeys.length; i < len; i++) {
  874. const key = prevKeys[i];
  875. if (!key || key === "undefined" || value[key]) continue;
  876. toggleClassKey(node, key, false);
  877. delete prev[key];
  878. }
  879. for (i = 0, len = classKeys.length; i < len; i++) {
  880. const key = classKeys[i],
  881. classValue = !!value[key];
  882. if (!key || key === "undefined" || prev[key] === classValue || !classValue) continue;
  883. toggleClassKey(node, key, true);
  884. prev[key] = classValue;
  885. }
  886. return prev;
  887. }
  888. function style(node, value, prev) {
  889. if (!value) return prev ? setAttribute(node, "style") : value;
  890. const nodeStyle = node.style;
  891. if (typeof value === "string") return nodeStyle.cssText = value;
  892. typeof prev === "string" && (nodeStyle.cssText = prev = undefined);
  893. prev || (prev = {});
  894. value || (value = {});
  895. let v, s;
  896. for (s in prev) {
  897. value[s] == null && nodeStyle.removeProperty(s);
  898. delete prev[s];
  899. }
  900. for (s in value) {
  901. v = value[s];
  902. if (v !== prev[s]) {
  903. nodeStyle.setProperty(s, v);
  904. prev[s] = v;
  905. }
  906. }
  907. return prev;
  908. }
  909. function spread(node, props = {}, isSVG, skipChildren) {
  910. const prevProps = {};
  911. if (!skipChildren) {
  912. createRenderEffect(() => prevProps.children = insertExpression(node, props.children, prevProps.children));
  913. }
  914. createRenderEffect(() => props.ref && props.ref(node));
  915. createRenderEffect(() => assign(node, props, isSVG, true, prevProps, true));
  916. return prevProps;
  917. }
  918. function insert(parent, accessor, marker, initial) {
  919. if (marker !== undefined && !initial) initial = [];
  920. if (typeof accessor !== "function") return insertExpression(parent, accessor, initial, marker);
  921. createRenderEffect(current => insertExpression(parent, accessor(), current, marker), initial);
  922. }
  923. function assign(node, props, isSVG, skipChildren, prevProps = {}, skipRef = false) {
  924. props || (props = {});
  925. for (const prop in prevProps) {
  926. if (!(prop in props)) {
  927. if (prop === "children") continue;
  928. prevProps[prop] = assignProp(node, prop, null, prevProps[prop], isSVG, skipRef);
  929. }
  930. }
  931. for (const prop in props) {
  932. if (prop === "children") {
  933. if (!skipChildren) insertExpression(node, props.children);
  934. continue;
  935. }
  936. const value = props[prop];
  937. prevProps[prop] = assignProp(node, prop, value, prevProps[prop], isSVG, skipRef);
  938. }
  939. }
  940. function toPropertyName(name) {
  941. return name.toLowerCase().replace(/-([a-z])/g, (_, w) => w.toUpperCase());
  942. }
  943. function toggleClassKey(node, key, value) {
  944. const classNames = key.trim().split(/\s+/);
  945. for (let i = 0, nameLen = classNames.length; i < nameLen; i++) node.classList.toggle(classNames[i], value);
  946. }
  947. function assignProp(node, prop, value, prev, isSVG, skipRef) {
  948. let isCE, isProp, isChildProp, propAlias, forceProp;
  949. if (prop === "style") return style(node, value, prev);
  950. if (prop === "classList") return classList(node, value, prev);
  951. if (value === prev) return prev;
  952. if (prop === "ref") {
  953. if (!skipRef) value(node);
  954. } else if (prop.slice(0, 3) === "on:") {
  955. const e = prop.slice(3);
  956. prev && node.removeEventListener(e, prev);
  957. value && node.addEventListener(e, value);
  958. } else if (prop.slice(0, 10) === "oncapture:") {
  959. const e = prop.slice(10);
  960. prev && node.removeEventListener(e, prev, true);
  961. value && node.addEventListener(e, value, true);
  962. } else if (prop.slice(0, 2) === "on") {
  963. const name = prop.slice(2).toLowerCase();
  964. const delegate = DelegatedEvents.has(name);
  965. if (!delegate && prev) {
  966. const h = Array.isArray(prev) ? prev[0] : prev;
  967. node.removeEventListener(name, h);
  968. }
  969. if (delegate || value) {
  970. addEventListener(node, name, value, delegate);
  971. delegate && delegateEvents([name]);
  972. }
  973. } else if (prop.slice(0, 5) === "attr:") {
  974. setAttribute(node, prop.slice(5), value);
  975. } 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("-"))) {
  976. if (forceProp) {
  977. prop = prop.slice(5);
  978. isProp = true;
  979. }
  980. if (prop === "class" || prop === "className") className(node, value);else if (isCE && !isProp && !isChildProp) node[toPropertyName(prop)] = value;else node[propAlias || prop] = value;
  981. } else {
  982. const ns = isSVG && prop.indexOf(":") > -1 && SVGNamespace[prop.split(":")[0]];
  983. if (ns) setAttributeNS(node, ns, prop, value);else setAttribute(node, Aliases[prop] || prop, value);
  984. }
  985. return value;
  986. }
  987. function eventHandler(e) {
  988. const key = `$$${e.type}`;
  989. let node = e.composedPath && e.composedPath()[0] || e.target;
  990. if (e.target !== node) {
  991. Object.defineProperty(e, "target", {
  992. configurable: true,
  993. value: node
  994. });
  995. }
  996. Object.defineProperty(e, "currentTarget", {
  997. configurable: true,
  998. get() {
  999. return node || document;
  1000. }
  1001. });
  1002. while (node) {
  1003. const handler = node[key];
  1004. if (handler && !node.disabled) {
  1005. const data = node[`${key}Data`];
  1006. data !== undefined ? handler.call(node, data, e) : handler.call(node, e);
  1007. if (e.cancelBubble) return;
  1008. }
  1009. node = node._$host || node.parentNode || node.host;
  1010. }
  1011. }
  1012. function insertExpression(parent, value, current, marker, unwrapArray) {
  1013. while (typeof current === "function") current = current();
  1014. if (value === current) return current;
  1015. const t = typeof value,
  1016. multi = marker !== undefined;
  1017. parent = multi && current[0] && current[0].parentNode || parent;
  1018. if (t === "string" || t === "number") {
  1019. if (t === "number") value = value.toString();
  1020. if (multi) {
  1021. let node = current[0];
  1022. if (node && node.nodeType === 3) {
  1023. node.data = value;
  1024. } else node = document.createTextNode(value);
  1025. current = cleanChildren(parent, current, marker, node);
  1026. } else {
  1027. if (current !== "" && typeof current === "string") {
  1028. current = parent.firstChild.data = value;
  1029. } else current = parent.textContent = value;
  1030. }
  1031. } else if (value == null || t === "boolean") {
  1032. current = cleanChildren(parent, current, marker);
  1033. } else if (t === "function") {
  1034. createRenderEffect(() => {
  1035. let v = value();
  1036. while (typeof v === "function") v = v();
  1037. current = insertExpression(parent, v, current, marker);
  1038. });
  1039. return () => current;
  1040. } else if (Array.isArray(value)) {
  1041. const array = [];
  1042. const currentArray = current && Array.isArray(current);
  1043. if (normalizeIncomingArray(array, value, current, unwrapArray)) {
  1044. createRenderEffect(() => current = insertExpression(parent, array, current, marker, true));
  1045. return () => current;
  1046. }
  1047. if (array.length === 0) {
  1048. current = cleanChildren(parent, current, marker);
  1049. if (multi) return current;
  1050. } else if (currentArray) {
  1051. if (current.length === 0) {
  1052. appendNodes(parent, array, marker);
  1053. } else reconcileArrays(parent, current, array);
  1054. } else {
  1055. current && cleanChildren(parent);
  1056. appendNodes(parent, array);
  1057. }
  1058. current = array;
  1059. } else if (value.nodeType) {
  1060. if (Array.isArray(current)) {
  1061. if (multi) return current = cleanChildren(parent, current, marker, value);
  1062. cleanChildren(parent, current, null, value);
  1063. } else if (current == null || current === "" || !parent.firstChild) {
  1064. parent.appendChild(value);
  1065. } else parent.replaceChild(value, parent.firstChild);
  1066. current = value;
  1067. } else console.warn(`Unrecognized value. Skipped inserting`, value);
  1068. return current;
  1069. }
  1070. function normalizeIncomingArray(normalized, array, current, unwrap) {
  1071. let dynamic = false;
  1072. for (let i = 0, len = array.length; i < len; i++) {
  1073. let item = array[i],
  1074. prev = current && current[i],
  1075. t;
  1076. if (item == null || item === true || item === false) ;else if ((t = typeof item) === "object" && item.nodeType) {
  1077. normalized.push(item);
  1078. } else if (Array.isArray(item)) {
  1079. dynamic = normalizeIncomingArray(normalized, item, prev) || dynamic;
  1080. } else if (t === "function") {
  1081. if (unwrap) {
  1082. while (typeof item === "function") item = item();
  1083. dynamic = normalizeIncomingArray(normalized, Array.isArray(item) ? item : [item], Array.isArray(prev) ? prev : [prev]) || dynamic;
  1084. } else {
  1085. normalized.push(item);
  1086. dynamic = true;
  1087. }
  1088. } else {
  1089. const value = String(item);
  1090. if (prev && prev.nodeType === 3 && prev.data === value) normalized.push(prev);else normalized.push(document.createTextNode(value));
  1091. }
  1092. }
  1093. return dynamic;
  1094. }
  1095. function appendNodes(parent, array, marker = null) {
  1096. for (let i = 0, len = array.length; i < len; i++) parent.insertBefore(array[i], marker);
  1097. }
  1098. function cleanChildren(parent, current, marker, replacement) {
  1099. if (marker === undefined) return parent.textContent = "";
  1100. const node = replacement || document.createTextNode("");
  1101. if (current.length) {
  1102. let inserted = false;
  1103. for (let i = current.length - 1; i >= 0; i--) {
  1104. const el = current[i];
  1105. if (node !== el) {
  1106. const isParent = el.parentNode === parent;
  1107. if (!inserted && !i) isParent ? parent.replaceChild(node, el) : parent.insertBefore(node, marker);else isParent && el.remove();
  1108. } else inserted = true;
  1109. }
  1110. } else parent.insertBefore(node, marker);
  1111. return [node];
  1112. }
  1113. const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
  1114. function createElement(tagName, isSVG = false) {
  1115. return isSVG ? document.createElementNS(SVG_NAMESPACE, tagName) : document.createElement(tagName);
  1116. }
  1117. function Dynamic(props) {
  1118. const [p, others] = splitProps(props, ["component"]);
  1119. const cached = createMemo(() => p.component);
  1120. return createMemo(() => {
  1121. const component = cached();
  1122. switch (typeof component) {
  1123. case "function":
  1124. Object.assign(component, {
  1125. [$DEVCOMP]: true
  1126. });
  1127. return untrack(() => component(others));
  1128. case "string":
  1129. const isSvg = SVGElements.has(component);
  1130. const el = createElement(component, isSvg);
  1131. spread(el, others, isSvg);
  1132. return el;
  1133. }
  1134. });
  1135. }
  1136.  
  1137. var throttle = (callback, wait) => {
  1138. let isThrottled = false,
  1139. timeoutId,
  1140. lastArgs;
  1141. const throttled = (...args) => {
  1142. lastArgs = args;
  1143. if (isThrottled) return;
  1144. isThrottled = true;
  1145. timeoutId = setTimeout(() => {
  1146. callback(...lastArgs);
  1147. isThrottled = false;
  1148. }, wait);
  1149. };
  1150. const clear = () => {
  1151. clearTimeout(timeoutId);
  1152. isThrottled = false;
  1153. };
  1154. if (getOwner()) onCleanup(clear);
  1155. return Object.assign(throttled, {
  1156. clear
  1157. });
  1158. };
  1159.  
  1160. var access = v => typeof v === "function" && !v.length ? v() : v;
  1161. var asArray$1 = value => Array.isArray(value) ? value : value ? [value] : [];
  1162. var tryOnCleanup = onCleanup;
  1163.  
  1164. function createGMSignal(key, initialValue) {
  1165. const [signal, setSignal] = createSignal(initialValue);
  1166. let listener;
  1167. Promise.resolve().then(() => GMP.addValueChangeListener?.(key, (name, oldValue, newValue, remote) => {
  1168. if (name === key && (remote === void 0 || remote === true)) read(newValue);
  1169. })).then(l => listener = l);
  1170. let effectPaused = false;
  1171. createEffect(on(signal, () => {
  1172. if (effectPaused) return;
  1173. if (signal() == null) {
  1174. GMP.deleteValue(key);
  1175. effectPaused = true;
  1176. setSignal(() => initialValue);
  1177. effectPaused = false;
  1178. } else {
  1179. GMP.setValue(key, signal());
  1180. }
  1181. }, {
  1182. defer: true
  1183. }));
  1184. async function read(newValue) {
  1185. effectPaused = true;
  1186. const rawValue = newValue ?? (await GMP.getValue(key));
  1187. if (rawValue == null) setSignal(() => initialValue);else setSignal(() => rawValue);
  1188. effectPaused = false;
  1189. }
  1190. const [isReady, setIsReady] = createSignal(false);
  1191. signal.isReady = isReady;
  1192. signal.ready = read().then(() => {
  1193. setIsReady(true);
  1194. });
  1195. onCleanup(() => {
  1196. if (listener) GMP.removeValueChangeListener?.(listener);
  1197. });
  1198. return [signal, setSignal];
  1199. }
  1200. const [detectionResolution, setDetectionResolution] = createGMSignal("detectionResolution", "M");
  1201. const [textDetector, setTextDetector] = createGMSignal("textDetector", "default");
  1202. const [translatorService, setTranslatorService] = createGMSignal("translator", "gpt3.5");
  1203. const [renderTextOrientation, setRenderTextOrientation] = createGMSignal("renderTextOrientation", "auto");
  1204. const [targetLang, setTargetLang] = createGMSignal("targetLang", "");
  1205. const [scriptLang, setScriptLang] = createGMSignal("scriptLanguage", "");
  1206. const [keepInstances, setKeepInstances] = createGMSignal("keepInstances", "until-reload");
  1207. const storageReady = Promise.all([detectionResolution.ready, textDetector.ready, translatorService.ready, renderTextOrientation.ready, targetLang.ready, scriptLang.ready, keepInstances.ready]);
  1208.  
  1209. var data$1 = { common:{ source:{ "download-image":"正在拉取原图",
  1210. "download-image-progress":"正在拉取原图({progress})",
  1211. "download-image-error":"拉取原图出错" },
  1212. client:{ submit:"正在提交翻译",
  1213. "submit-progress":"正在提交翻译({progress})",
  1214. "submit-final":"等待图片转存",
  1215. "submit-error":"提交翻译出错",
  1216. "download-image":"正在下载图片",
  1217. "download-image-progress":"正在下载图片({progress})",
  1218. "download-image-error":"下载图片出错",
  1219. resize:"正在缩放图片",
  1220. merging:"正在合并图层" },
  1221. status:{ "default":"未知状态",
  1222. pending:"正在等待",
  1223. "pending-pos":"正在等待,列队还有 {pos} 张图片",
  1224. downloading:"正在传输图片",
  1225. preparing:"等待空闲窗口",
  1226. colorizing:"正在上色",
  1227. upscaling:"正在放大图片",
  1228. downscaling:"正在缩小图片",
  1229. detection:"正在检测文本",
  1230. ocr:"正在识别文本",
  1231. textline_merge:"正在整合文本",
  1232. "mask-generation":"正在生成文本掩码",
  1233. inpainting:"正在修补图片",
  1234. translating:"正在翻译文本",
  1235. rendering:"正在渲染文本",
  1236. finished:"正在整理结果",
  1237. saved:"保存结果",
  1238. saving:"正在保存结果",
  1239. uploading:"正在传输结果",
  1240. error:"翻译出错",
  1241. "error-download":"传输图片失败",
  1242. "error-upload":"传输结果失败",
  1243. "error-lang":"你选择的翻译服务不支持你选择的语言",
  1244. "error-translating":"翻译服务没有返回任何文本",
  1245. "skip-no-regions":"图片中没有检测到文本区域",
  1246. "skip-no-text":"图片中没有检测到文本",
  1247. "error-with-id":"翻译出错 (ID: {id})" },
  1248. control:{ translate:"翻译",
  1249. batch:"翻译全部 ({count})",
  1250. reset:"还原" },
  1251. batch:{ progress:"翻译中 ({count}/{total})",
  1252. finish:"翻译完成",
  1253. error:"翻译完成(有失败)" } },
  1254. settings:{ title:"Cotrans 图片翻译器设置",
  1255. "inline-options-title":"设置当前翻译",
  1256. "detection-resolution":"文本扫描清晰度",
  1257. "text-detector":"文本扫描器",
  1258. "text-detector-options":{ "default":"默认" },
  1259. translator:"翻译服务",
  1260. "render-text-orientation":"渲染字体方向",
  1261. "render-text-orientation-options":{ auto:"跟随原文本",
  1262. horizontal:"仅限水平",
  1263. vertical:"仅限垂直" },
  1264. "target-language":"翻译语言",
  1265. "target-language-options":{ auto:"跟随网页语言" },
  1266. "script-language":"用户脚本语言",
  1267. "script-language-options":{ auto:"跟随网页语言" },
  1268. reset:"重置所有设置",
  1269. "detection-resolution-desc":"设置检测图片文本所用的清晰度,小文字适合使用更高的清晰度。",
  1270. "text-detector-desc":"设置使用的文本扫描器。",
  1271. "translator-desc":"设置翻译图片所用的翻译服务。",
  1272. "render-text-orientation-desc":"设置嵌字的文本方向。",
  1273. "target-language-desc":"设置图片翻译后的语言。",
  1274. "script-language-desc":"设置此用户脚本的语言。",
  1275. "translator-options":{ none:"None (删除文字)" },
  1276. "keep-instances-options":{ "until-reload":"直到页面刷新",
  1277. "until-navigate":"直到下次跳转" },
  1278. "keep-instances":"保留翻译进度",
  1279. "keep-instances-desc":"设置翻译进度的保留时间。 翻译进度即图片的翻译状态和翻译结果。 保留更多的翻译进度会占用更多的内存。",
  1280. "force-retry":"强制重试 (忽略缓存)" },
  1281. sponsor:{ text:"制作不易,请考虑赞助我们!" } };
  1282. data$1.common;
  1283. data$1.settings;
  1284. data$1.sponsor;
  1285.  
  1286. var data = { common:{ source:{ "download-image":"Downloading original image",
  1287. "download-image-progress":"Downloading original image ({progress})",
  1288. "download-image-error":"Error during original image download" },
  1289. client:{ submit:"Submitting translation",
  1290. "submit-progress":"Submitting translation ({progress})",
  1291. "submit-final":"Waiting for image transpile",
  1292. "submit-error":"Error during translation submission",
  1293. "download-image":"Downloading translated image",
  1294. "download-image-progress":"Downloading translated image ({progress})",
  1295. "download-image-error":"Error during translated image download",
  1296. resize:"Resizing image",
  1297. merging:"Merging layers" },
  1298. status:{ "default":"Unknown status",
  1299. pending:"Pending",
  1300. "pending-pos":"Pending, {pos} in queue",
  1301. downloading:"Transferring image",
  1302. preparing:"Waiting for idle window",
  1303. colorizing:"Colorizing",
  1304. upscaling:"Upscaling",
  1305. downscaling:"Downscaling",
  1306. detection:"Detecting text",
  1307. ocr:"Scanning text",
  1308. textline_merge:"Merging text lines",
  1309. "mask-generation":"Generating mask",
  1310. inpainting:"Inpainting",
  1311. translating:"Translating",
  1312. rendering:"Rendering",
  1313. finished:"Finishing",
  1314. saved:"Saved",
  1315. saving:"Saving result",
  1316. uploading:"Transferring result",
  1317. error:"Error during translation",
  1318. "error-download":"Image transfer failed",
  1319. "error-upload":"Result transfer failed",
  1320. "error-lang":"The target language is not supported by the chosen translator",
  1321. "error-translating":"Did not get any text back from the text translation service",
  1322. "skip-no-regions":"No text regions detected in the image",
  1323. "skip-no-text":"No text detected in the image",
  1324. "error-with-id":"Error during translation (ID: {id})" },
  1325. control:{ translate:"Translate",
  1326. batch:"Translate all ({count})",
  1327. reset:"Reset" },
  1328. batch:{ progress:"Translating ({count}/{total} finished)",
  1329. finish:"Translation finished",
  1330. error:"Translation finished with errors" } },
  1331. settings:{ "detection-resolution":"Text detection resolution",
  1332. "render-text-orientation":"Render text orientation",
  1333. "render-text-orientation-options":{ auto:"Follow source",
  1334. horizontal:"Horizontal only",
  1335. vertical:"Vertical only" },
  1336. reset:"Reset Settings",
  1337. "target-language":"Translate target language",
  1338. "target-language-options":{ auto:"Follow website" },
  1339. "text-detector":"Text detector",
  1340. "text-detector-options":{ "default":"Default" },
  1341. title:"Cotrans Manga Translator Settings",
  1342. translator:"Translator",
  1343. "script-language":"Userscript language",
  1344. "script-language-options":{ auto:"Follow website language" },
  1345. "inline-options-title":"Current Settings",
  1346. "detection-resolution-desc":"The resolution used to scan texts on an image, higher value are better suited for smaller texts.",
  1347. "script-language-desc":"Language of this userscript.",
  1348. "render-text-orientation-desc":"Overwrite the orientation of texts rendered in the translated image.",
  1349. "target-language-desc":"The language that images are translated to.",
  1350. "text-detector-desc":"The detector used to scan texts in an image.",
  1351. "translator-desc":"The translate service used to translate texts.",
  1352. "translator-options":{ none:"None (remove texts)" },
  1353. "keep-instances-options":{ "until-reload":"Until page reload",
  1354. "until-navigate":"Until next navigation" },
  1355. "keep-instances":"Keep translation instances",
  1356. "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.",
  1357. "force-retry":"Force retry (ignore cache)" },
  1358. sponsor:{ text:"If you find this script helpful, please consider supporting us!" } };
  1359. data.common;
  1360. data.settings;
  1361. data.sponsor;
  1362.  
  1363. const messages = {
  1364. "zh-CN": data$1,
  1365. "en-US": data
  1366. };
  1367. function tryMatchLang(lang2) {
  1368. if (lang2.startsWith("zh")) return "zh-CN";
  1369. if (lang2.startsWith("en")) return "en-US";
  1370. return "en-US";
  1371. }
  1372. const [realLang, setRealLang] = createSignal(navigator.language);
  1373. const lang = createMemo(() => scriptLang() || tryMatchLang(realLang()));
  1374. function t$1(key_, props = {}) {
  1375. return createMemo(() => {
  1376. const key = access(key_);
  1377. const segments = key.split(".");
  1378. const msg = segments.reduce((obj, k) => obj[k], messages[lang()]) ?? segments.reduce((obj, k) => obj[k], messages["zh-CN"]);
  1379. if (!msg) return key;
  1380. return msg.replace(/\{([^}]+)\}/g, (_, k) => String(access(access(props)[k])) ?? "");
  1381. });
  1382. }
  1383. let langEL;
  1384. let langObserver;
  1385. function changeLangEl(el) {
  1386. if (langEL === el) return;
  1387. if (langObserver) langObserver.disconnect();
  1388. langObserver = new MutationObserver(mutations => {
  1389. for (const mutation of mutations) {
  1390. if (mutation.type === "attributes" && mutation.attributeName === "lang") {
  1391. const target = mutation.target;
  1392. if (target.lang) setRealLang(target.lang);
  1393. break;
  1394. }
  1395. }
  1396. });
  1397. langObserver.observe(el, {
  1398. attributes: true
  1399. });
  1400. langEL = el;
  1401. setRealLang(el.lang);
  1402. }
  1403. function BCP47ToISO639(code) {
  1404. try {
  1405. const lo = new Intl.Locale(code);
  1406. switch (lo.language) {
  1407. case "zh":
  1408. {
  1409. switch (lo.script) {
  1410. case "Hans":
  1411. return "CHS";
  1412. case "Hant":
  1413. return "CHT";
  1414. }
  1415. switch (lo.region) {
  1416. case "CN":
  1417. return "CHS";
  1418. case "HK":
  1419. case "TW":
  1420. return "CHT";
  1421. }
  1422. return "CHS";
  1423. }
  1424. case "ja":
  1425. return "JPN";
  1426. case "en":
  1427. return "ENG";
  1428. case "ko":
  1429. return "KOR";
  1430. case "vi":
  1431. return "VIE";
  1432. case "cs":
  1433. return "CSY";
  1434. case "nl":
  1435. return "NLD";
  1436. case "fr":
  1437. return "FRA";
  1438. case "de":
  1439. return "DEU";
  1440. case "hu":
  1441. return "HUN";
  1442. case "it":
  1443. return "ITA";
  1444. case "pl":
  1445. return "PLK";
  1446. case "pt":
  1447. return "PTB";
  1448. case "ro":
  1449. return "ROM";
  1450. case "ru":
  1451. return "RUS";
  1452. case "es":
  1453. return "ESP";
  1454. case "tr":
  1455. return "TRK";
  1456. case "uk":
  1457. return "UKR";
  1458. }
  1459. return "ENG";
  1460. } catch (e) {
  1461. return "ENG";
  1462. }
  1463. }
  1464.  
  1465. DelegatedEvents.clear();
  1466. function createScopedInstance(cb) {
  1467. return createRoot(dispose => {
  1468. const instance = cb();
  1469. return {
  1470. ...instance,
  1471. dispose
  1472. };
  1473. });
  1474. }
  1475. let currentURL;
  1476. let translator$3;
  1477. let settingsInjector$2;
  1478. async function start(translators, settingsInjectors) {
  1479. await storageReady;
  1480. async function onUpdate() {
  1481. await new Promise(resolve => (queueMicrotask ?? setTimeout)(resolve));
  1482. if (currentURL !== location.href) {
  1483. currentURL = location.href;
  1484. changeLangEl(document.documentElement);
  1485. if (translator$3?.canKeep?.(currentURL)) {
  1486. translator$3.onURLChange?.(currentURL);
  1487. } else {
  1488. translator$3?.dispose();
  1489. translator$3 = void 0;
  1490. const url = new URL(location.href);
  1491. const matched = translators.find(t => t.match(url));
  1492. if (matched) translator$3 = createScopedInstance(matched.mount);
  1493. }
  1494. if (settingsInjector$2?.canKeep?.(currentURL)) {
  1495. settingsInjector$2.onURLChange?.(currentURL);
  1496. } else {
  1497. settingsInjector$2?.dispose();
  1498. settingsInjector$2 = void 0;
  1499. const url = new URL(location.href);
  1500. const matched = settingsInjectors.find(t => t.match(url));
  1501. if (matched) settingsInjector$2 = createScopedInstance(matched.mount);
  1502. }
  1503. }
  1504. }
  1505. if (window.onurlchange === null) {
  1506. window.addEventListener("urlchange", onUpdate);
  1507. const pushState = history.pushState;
  1508. window.history.pushState = function () {
  1509. pushState.apply(this, arguments);
  1510. if (typeof arguments[2] === "string" && arguments[2].startsWith("#")) onUpdate();
  1511. };
  1512. } else {
  1513. const installObserver = new MutationObserver(throttle(onUpdate, 200));
  1514. installObserver.observe(document.body, {
  1515. childList: true,
  1516. subtree: true
  1517. });
  1518. }
  1519. onUpdate();
  1520. }
  1521.  
  1522. // src/index.ts
  1523. var triggerOptions = {
  1524. equals: false
  1525. };
  1526. var triggerCacheOptions = triggerOptions;
  1527. var TriggerCache = class {
  1528. #map;
  1529. constructor(mapConstructor = Map) {
  1530. this.#map = new mapConstructor();
  1531. }
  1532. dirty(key) {
  1533. this.#map.get(key)?.$$();
  1534. }
  1535. track(key) {
  1536. if (!getListener()) return;
  1537. let trigger = this.#map.get(key);
  1538. if (!trigger) {
  1539. const [$, $$] = createSignal(void 0, triggerCacheOptions);
  1540. this.#map.set(key, trigger = {
  1541. $,
  1542. $$,
  1543. n: 1
  1544. });
  1545. } else trigger.n++;
  1546. onCleanup(() => {
  1547. if (trigger.n-- === 1) queueMicrotask(() => trigger.n === 0 && this.#map.delete(key));
  1548. });
  1549. trigger.$();
  1550. }
  1551. };
  1552.  
  1553. // src/index.ts
  1554. var $KEYS = Symbol("track-keys");
  1555. var ReactiveMap = class extends Map {
  1556. #keyTriggers = new TriggerCache();
  1557. #valueTriggers = new TriggerCache();
  1558. constructor(initial) {
  1559. super();
  1560. if (initial) for (const v of initial) super.set(v[0], v[1]);
  1561. }
  1562. // reads
  1563. has(key) {
  1564. this.#keyTriggers.track(key);
  1565. return super.has(key);
  1566. }
  1567. get(key) {
  1568. this.#valueTriggers.track(key);
  1569. return super.get(key);
  1570. }
  1571. get size() {
  1572. this.#keyTriggers.track($KEYS);
  1573. return super.size;
  1574. }
  1575. keys() {
  1576. this.#keyTriggers.track($KEYS);
  1577. return super.keys();
  1578. }
  1579. values() {
  1580. this.#keyTriggers.track($KEYS);
  1581. for (const v of super.keys()) this.#valueTriggers.track(v);
  1582. return super.values();
  1583. }
  1584. entries() {
  1585. this.#keyTriggers.track($KEYS);
  1586. for (const v of super.keys()) this.#valueTriggers.track(v);
  1587. return super.entries();
  1588. }
  1589. // writes
  1590. set(key, value) {
  1591. batch(() => {
  1592. if (super.has(key)) {
  1593. if (super.get(key) === value) return;
  1594. } else {
  1595. this.#keyTriggers.dirty(key);
  1596. this.#keyTriggers.dirty($KEYS);
  1597. }
  1598. this.#valueTriggers.dirty(key);
  1599. super.set(key, value);
  1600. });
  1601. return this;
  1602. }
  1603. delete(key) {
  1604. const r = super.delete(key);
  1605. if (r) {
  1606. batch(() => {
  1607. this.#keyTriggers.dirty(key);
  1608. this.#keyTriggers.dirty($KEYS);
  1609. this.#valueTriggers.dirty(key);
  1610. });
  1611. }
  1612. return r;
  1613. }
  1614. clear() {
  1615. if (super.size) {
  1616. batch(() => {
  1617. for (const v of super.keys()) {
  1618. this.#keyTriggers.dirty(v);
  1619. this.#valueTriggers.dirty(v);
  1620. }
  1621. super.clear();
  1622. this.#keyTriggers.dirty($KEYS);
  1623. });
  1624. }
  1625. }
  1626. // callback
  1627. forEach(callbackfn) {
  1628. this.#keyTriggers.track($KEYS);
  1629. super.forEach((value, key) => callbackfn(value, key, this));
  1630. }
  1631. [Symbol.iterator]() {
  1632. return this.entries();
  1633. }
  1634. };
  1635.  
  1636. // src/index.ts
  1637. function createMutationObserver(initial, b, c) {
  1638. let defaultOptions, callback;
  1639. const isSupported = typeof window !== "undefined" && "MutationObserver" in window;
  1640. if (typeof b === "function") {
  1641. defaultOptions = {};
  1642. callback = b;
  1643. } else {
  1644. defaultOptions = b;
  1645. callback = c;
  1646. }
  1647. const instance = isSupported ? new MutationObserver(callback) : void 0;
  1648. const add = (el, options) => instance?.observe(el, access(options) ?? defaultOptions);
  1649. const start = () => {
  1650. asArray$1(access(initial)).forEach(item => {
  1651. item instanceof Node ? add(item, defaultOptions) : add(item[0], item[1]);
  1652. });
  1653. };
  1654. const stop = () => instance?.disconnect();
  1655. onMount(start);
  1656. onCleanup(stop);
  1657. return [add, {
  1658. start,
  1659. stop,
  1660. instance,
  1661. isSupported
  1662. }];
  1663. }
  1664.  
  1665. function toClassName(rule) {
  1666. return [...rule.v, (rule.i ? '!' : '') + rule.n].join(':');
  1667. }
  1668. function format(rules, seperator = ',') {
  1669. return rules.map(toClassName).join(seperator);
  1670. }
  1671. /**
  1672. * @internal
  1673. */
  1674. let escape = 'undefined' != typeof CSS && CSS.escape || (
  1675. // Simplified: escaping only special characters
  1676. // Needed for NodeJS and Edge <79 (https://caniuse.com/mdn-api_css_escape)
  1677. className => className.
  1678. // Simplifed escape testing only for chars that we know happen to be in tailwind directives
  1679. replace(/[!"'`*+.,;:\\/<=>?@#$%&^|~()[\]{}]/g, '\\$&').
  1680. // If the character is the first character and is in the range [0-9] (2xl, ...)
  1681. // https://drafts.csswg.org/cssom/#escape-a-character-as-code-point
  1682. replace(/^\d/, '\\3$& '));
  1683. // Based on https://stackoverflow.com/a/52171480
  1684. /**
  1685. * @group Configuration
  1686. * @param value
  1687. * @returns
  1688. */
  1689. function hash(value) {
  1690. // eslint-disable-next-line no-var
  1691. for (var h = 9, index = value.length; index--;) h = Math.imul(h ^ value.charCodeAt(index), 0x5f356495);
  1692. return '#' + ((h ^ h >>> 9) >>> 0).toString(36);
  1693. }
  1694. /**
  1695. * @internal
  1696. * @param screen
  1697. * @param prefix
  1698. * @returns
  1699. */
  1700. function mql(screen, prefix = '@media ') {
  1701. return prefix + asArray(screen).map(screen => {
  1702. return 'string' == typeof screen && (screen = {
  1703. min: screen
  1704. }), screen.raw || Object.keys(screen).map(feature => `(${feature}-width:${screen[feature]})`).join(' and ');
  1705. }).join(',');
  1706. }
  1707. /**
  1708. * @internal
  1709. * @param value
  1710. * @returns
  1711. */
  1712. function asArray(value = []) {
  1713. return Array.isArray(value) ? value : null == value ? [] : [value];
  1714. }
  1715. /**
  1716. * @internal
  1717. * @param value
  1718. * @returns
  1719. */
  1720. function identity(value) {
  1721. return value;
  1722. }
  1723. /**
  1724. * @internal
  1725. */
  1726. function noop() {}
  1727. // no-op
  1728. // Based on https://github.com/kripod/otion
  1729. // License MIT
  1730. // export const enum Shifts {
  1731. // darkMode = 30,
  1732. // layer = 27,
  1733. // screens = 26,
  1734. // responsive = 22,
  1735. // atRules = 18,
  1736. // variants = 0,
  1737. // }
  1738. let Layer = {
  1739. /**
  1740. * 1. `default` (public)
  1741. */
  1742. d: /* efaults */0,
  1743. /* Shifts.layer */ /**
  1744. * 2. `base` (public) — for things like reset rules or default styles applied to plain HTML elements.
  1745. */b: /* ase */134217728,
  1746. /* Shifts.layer */ /**
  1747. * 3. `components` (public, used by `style()`) — is for class-based styles that you want to be able to override with utilities.
  1748. */c: /* omponents */268435456,
  1749. /* Shifts.layer */ // reserved for style():
  1750. // - props: 0b011
  1751. // - when: 0b100
  1752. /**
  1753. * 6. `aliases` (public, used by `apply()`) — `~(...)`
  1754. */a: /* liases */671088640,
  1755. /* Shifts.layer */ /**
  1756. * 6. `utilities` (public) — for small, single-purpose classes
  1757. */u: /* tilities */805306368,
  1758. /* Shifts.layer */ /**
  1759. * 7. `overrides` (public, used by `css()`)
  1760. */o: /* verrides */939524096
  1761. };
  1762. /*
  1763. To set a bit: n |= mask;
  1764. To clear a bit: n &= ~mask;
  1765. To test if a bit is set: (n & mask)
  1766.  
  1767. Bit shifts for the primary bits:
  1768.  
  1769. | bits | trait | shift |
  1770. | ---- | ------------------------------------------------------- | ----- |
  1771. | 1 | dark mode | 30 |
  1772. | 3 | layer: preflight, global, components, utilities, css | 27 |
  1773. | 1 | screens: is this a responsive variation of a rule | 26 |
  1774. | 4 | responsive based on min-width, max-width or width | 22 |
  1775. | 4 | at-rules | 18 |
  1776. | 18 | pseudo and group variants | 0 |
  1777.  
  1778. Layer: 0 - 7: 3 bits
  1779. - defaults: 0 << 27
  1780. - base: 1 << 27
  1781. - components: 2 << 27
  1782. - variants: 3 << 27
  1783. - joints: 4 << 27
  1784. - aliases: 5 << 27
  1785. - utilities: 6 << 27
  1786. - overrides: 7 << 27
  1787.  
  1788. These are calculated by serialize and added afterwards:
  1789.  
  1790. | bits | trait |
  1791. | ---- | ----------------------------------- |
  1792. | 4 | number of selectors (descending) |
  1793. | 4 | number of declarations (descending) |
  1794. | 4 | greatest precedence of properties |
  1795.  
  1796. These are added by shifting the primary bits using multiplication as js only
  1797. supports bit shift up to 32 bits.
  1798. */ // Colon and dash count of string (ascending)
  1799. function seperatorPrecedence(string) {
  1800. return string.match(/[-=:;]/g)?.length || 0;
  1801. }
  1802. function atRulePrecedence(css) {
  1803. // 0 - 15: 4 bits (max 144rem or 2304px)
  1804. // rem -> bit
  1805. // <20 -> 0 (<320px)
  1806. // 20 -> 1 (320px)
  1807. // 24 -> 2 (384px)
  1808. // 28 -> 3 (448px)
  1809. // 32 -> 4 (512px)
  1810. // 36 -> 5 (576px)
  1811. // 42 -> 6 (672px)
  1812. // 48 -> 7 (768px)
  1813. // 56 -> 8 (896px)
  1814. // 64 -> 9 (1024px)
  1815. // 72 -> 10 (1152px)
  1816. // 80 -> 11 (1280px)
  1817. // 96 -> 12 (1536px)
  1818. // 112 -> 13 (1792px)
  1819. // 128 -> 14 (2048px)
  1820. // 144 -> 15 (2304px)
  1821. // https://www.dcode.fr/function-equation-finder
  1822. return Math.min(/(?:^|width[^\d]+)(\d+(?:.\d+)?)(p)?/.test(css) ? Math.max(0, 29.63 * (+RegExp.$1 / (RegExp.$2 ? 15 : 1)) ** 0.137 - 43) : 0, 15) << 22 | /* Shifts.responsive */Math.min(seperatorPrecedence(css), 15) << 18;
  1823. }
  1824. /* Shifts.atRules */ // Pesudo variant presedence
  1825. // Chars 3 - 8: Uniquely identifies a pseudo selector
  1826. // represented as a bit set for each relevant value
  1827. // 18 bits: one for each variant plus one for unknown variants
  1828. //
  1829. // ':group-*' variants are normalized to their native pseudo class (':group-hover' -> ':hover')
  1830. // as they already have a higher selector presedence due to the add '.group' ('.group:hover .group-hover:...')
  1831. // Sources:
  1832. // - https://bitsofco.de/when-do-the-hover-focus-and-active-pseudo-classes-apply/#orderofstyleshoverthenfocusthenactive
  1833. // - https://developer.mozilla.org/docs/Web/CSS/:active#Active_links
  1834. // - https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/defaultConfig.stub.js#L931
  1835. let PRECEDENCES_BY_PSEUDO_CLASS = [/* fi */'rst-c', /* hild: 0 */ /* la */'st-ch', /* ild: 1 */ // even and odd use: nth-child
  1836. /* nt */'h-chi', /* ld: 2 */ /* an */'y-lin', /* k: 3 */ /* li */'nk', /* : 4 */ /* vi */'sited', /* : 5 */ /* ch */'ecked', /* : 6 */ /* em */'pty', /* : 7 */ /* re */'ad-on', /* ly: 8 */ /* fo */'cus-w', /* ithin : 9 */ /* ho */'ver', /* : 10 */ /* fo */'cus', /* : 11 */ /* fo */'cus-v', /* isible : 12 */ /* ac */'tive', /* : 13 */ /* di */'sable', /* d : 14 */ /* op */'tiona', /* l: 15 */ /* re */'quire'];
  1837. /** The name to use for `&` expansion in selectors. Maybe empty for at-rules like `@import`, `@font-face`, `@media`, ... */ /** The calculated precedence taking all variants into account. */ /** The rulesets (selectors and at-rules). expanded variants `@media ...`, `@supports ...`, `&:focus`, `.dark &` */ /** Is this rule `!important` eg something like `!underline` or `!bg-red-500` or `!red-500` */
  1838. function convert({
  1839. n: name,
  1840. i: important,
  1841. v: variants = []
  1842. }, context, precedence, conditions) {
  1843. name && (name = toClassName({
  1844. n: name,
  1845. i: important,
  1846. v: variants
  1847. }));
  1848. conditions = [...asArray(conditions)];
  1849. for (let variant of variants) {
  1850. let screen = context.theme('screens', variant);
  1851. for (let condition of asArray(screen && mql(screen) || context.v(variant))) {
  1852. var /* d: 16 */selector;
  1853. conditions.push(condition);
  1854. precedence |= screen ? 67108864 | /* Shifts.screens */atRulePrecedence(condition) : 'dark' == variant ? 1073741824 : /* Shifts.darkMode */'@' == condition[0] ? atRulePrecedence(condition) : (selector = condition,
  1855. // use first found pseudo-class
  1856. 1 << ~(/:([a-z-]+)/.test(selector) && ~PRECEDENCES_BY_PSEUDO_CLASS.indexOf(RegExp.$1.slice(2, 7)) || -18));
  1857. }
  1858. }
  1859. return {
  1860. n: name,
  1861. p: precedence,
  1862. r: conditions,
  1863. i: important
  1864. };
  1865. }
  1866. let registry = new Map();
  1867. function stringify$1(rule) {
  1868. if (rule.d) {
  1869. let groups = [],
  1870. selector = replaceEach(
  1871. // merge all conditions into a selector string
  1872. rule.r.reduce((selector, condition) => {
  1873. return '@' == condition[0] ? (groups.push(condition), selector) :
  1874. // Go over the selector and replace the matching multiple selectors if any
  1875. condition ? replaceEach(selector, selectorPart => replaceEach(condition,
  1876. // If the current condition has a nested selector replace it
  1877. conditionPart => {
  1878. let mergeMatch = /(:merge\(.+?\))(:[a-z-]+|\\[.+])/.exec(conditionPart);
  1879. if (mergeMatch) {
  1880. let selectorIndex = selectorPart.indexOf(mergeMatch[1]);
  1881. return ~selectorIndex ?
  1882. // [':merge(.group):hover .rule', ':merge(.group):focus &'] -> ':merge(.group):focus:hover .rule'
  1883. // ':merge(.group)' + ':focus' + ':hover .rule'
  1884. selectorPart.slice(0, selectorIndex) + mergeMatch[0] + selectorPart.slice(selectorIndex + mergeMatch[1].length) :
  1885. // [':merge(.peer):focus~&', ':merge(.group):hover &'] -> ':merge(.peer):focus~:merge(.group):hover &'
  1886. replaceReference(selectorPart, conditionPart);
  1887. }
  1888. // Return the current selector with the key matching multiple selectors if any
  1889. return replaceReference(conditionPart, selectorPart);
  1890. })) : selector;
  1891. }, '&'),
  1892. // replace '&' with rule name or an empty string
  1893. selectorPart => replaceReference(selectorPart, rule.n ? '.' + escape(rule.n) : ''));
  1894. return selector && groups.push(selector.replace(/:merge\((.+?)\)/g, '$1')), groups.reduceRight((body, grouping) => grouping + '{' + body + '}', rule.d);
  1895. }
  1896. }
  1897. function replaceEach(selector, iteratee) {
  1898. return selector.replace(/ *((?:\(.+?\)|\[.+?\]|[^,])+) *(,|$)/g, (_, selectorPart, comma) => iteratee(selectorPart) + comma);
  1899. }
  1900. function replaceReference(selector, reference) {
  1901. return selector.replace(/&/g, reference);
  1902. }
  1903. let collator = new Intl.Collator('en', {
  1904. numeric: true
  1905. });
  1906. /** The calculated precedence taking all variants into account. */ /* The precedence of the properties within {@link d}. */ /** The name to use for `&` expansion in selectors. Maybe empty for at-rules like `@import`, `@font-face`, `@media`, ... */ /**
  1907. * Find the array index of where to add an element to keep it sorted.
  1908. *
  1909. * @returns The insertion index
  1910. */
  1911. function sortedInsertionIndex(array, element) {
  1912. // Find position using binary search
  1913. // eslint-disable-next-line no-var
  1914. for (var low = 0, high = array.length; low < high;) {
  1915. let pivot = high + low >> 1;
  1916. 0 >= compareTwindRules(array[pivot], element) ? low = pivot + 1 : high = pivot;
  1917. }
  1918. return high;
  1919. }
  1920. function compareTwindRules(a, b) {
  1921. // base and overrides (css) layers are kept in order they are declared
  1922. let layer = a.p & Layer.o;
  1923. return layer == (b.p & Layer.o) && (layer == Layer.b || layer == Layer.o) ? 0 : a.p - b.p || a.o - b.o || collator.compare(byModifier(a.n), byModifier(b.n)) || collator.compare(byName(a.n), byName(b.n));
  1924. }
  1925. function byModifier(s) {
  1926. return (s || '').split(/:/).pop().split('/').pop() || '\x00';
  1927. }
  1928. function byName(s) {
  1929. return (s || '').replace(/\W/g, c => String.fromCharCode(127 + c.charCodeAt(0))) + '\x00';
  1930. }
  1931. function parseColorComponent(chars, factor) {
  1932. return Math.round(parseInt(chars, 16) * factor);
  1933. }
  1934. /**
  1935. * @internal
  1936. * @param color
  1937. * @param options
  1938. * @returns
  1939. */
  1940. function toColorValue(color, options = {}) {
  1941. if ('function' == typeof color) return color(options);
  1942. let {
  1943. opacityValue = '1',
  1944. opacityVariable
  1945. } = options,
  1946. opacity = opacityVariable ? `var(${opacityVariable})` : opacityValue;
  1947. if (color.includes('<alpha-value>')) return color.replace('<alpha-value>', opacity);
  1948. // rgb hex: #0123 and #001122
  1949. if ('#' == color[0] && (4 == color.length || 7 == color.length)) {
  1950. let size = (color.length - 1) / 3,
  1951. factor = [17, 1, 0.062272][size - 1];
  1952. return `rgba(${[parseColorComponent(color.substr(1, size), factor), parseColorComponent(color.substr(1 + size, size), factor), parseColorComponent(color.substr(1 + 2 * size, size), factor), opacity]})`;
  1953. }
  1954. return '1' == opacity ? color : '0' == opacity ? '#0000' :
  1955. // convert rgb and hsl to alpha variant
  1956. color.replace(/^(rgb|hsl)(\([^)]+)\)$/, `$1a$2,${opacity})`);
  1957. }
  1958. function serialize(style, rule, context, precedence, conditions = []) {
  1959. return function serialize$(style, {
  1960. n: name,
  1961. p: precedence,
  1962. r: conditions = [],
  1963. i: important
  1964. }, context) {
  1965. let rules = [],
  1966. // The generated declaration block eg body of the css rule
  1967. declarations = '',
  1968. // This ensures that 'border-top-width' has a higher precedence than 'border-top'
  1969. maxPropertyPrecedence = 0,
  1970. // More specific utilities have less declarations and a higher precedence
  1971. numberOfDeclarations = 0;
  1972. for (let key in style || {}) {
  1973. var layer,
  1974. // https://github.com/kripod/otion/blob/main/packages/otion/src/propertyMatchers.ts
  1975. // "+1": [
  1976. // /* ^border-.*(w|c|sty) */
  1977. // "border-.*(width,color,style)",
  1978. // /* ^[tlbr].{2,4}m?$ */
  1979. // "top",
  1980. // "left",
  1981. // "bottom",
  1982. // "right",
  1983. // /* ^c.{7}$ */
  1984. // "continue",
  1985. // /* ^c.{8}$ */
  1986. // "container",
  1987. // ],
  1988. // "-1": [
  1989. // /* ^[fl].{5}l */
  1990. // "flex-flow",
  1991. // "line-clamp",
  1992. // /* ^g.{8}$ */
  1993. // "grid-area",
  1994. // /* ^pl */
  1995. // "place-content",
  1996. // "place-items",
  1997. // "place-self",
  1998. // ],
  1999. // group: 1 => +1
  2000. // group: 2 => -1
  2001. // 0 - 15 => 4 bits
  2002. // Ignore vendor prefixed and custom properties
  2003. property;
  2004. let value = style[key];
  2005. if ('@' == key[0]) {
  2006. // at rules: https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule
  2007. if (!value) continue;
  2008. // @apply ...;
  2009. if ('a' == key[1]) {
  2010. rules.push(...translateWith(name, precedence, parse('' + value), context, precedence, conditions, important, true));
  2011. continue;
  2012. }
  2013. // @layer <layer>
  2014. if ('l' == key[1]) {
  2015. for (let css of asArray(value)) rules.push(...serialize$(css, {
  2016. n: name,
  2017. p: (layer = Layer[key[7]],
  2018. // Set layer (first reset, than set)
  2019. precedence & ~Layer.o | layer),
  2020. r: 'd' == key[7] ? [] : conditions,
  2021. i: important
  2022. }, context));
  2023. continue;
  2024. }
  2025. // @import
  2026. if ('i' == key[1]) {
  2027. rules.push(...asArray(value).map(value => ({
  2028. // before all layers
  2029. p: -1,
  2030. o: 0,
  2031. r: [],
  2032. d: key + ' ' + value
  2033. })));
  2034. continue;
  2035. }
  2036. // @keyframes
  2037. if ('k' == key[1]) {
  2038. // Use defaults layer
  2039. rules.push({
  2040. p: Layer.d,
  2041. o: 0,
  2042. r: [key],
  2043. d: serialize$(value, {
  2044. p: Layer.d
  2045. }, context).map(stringify$1).join('')
  2046. });
  2047. continue;
  2048. }
  2049. // @font-face
  2050. // TODO @font-feature-values
  2051. if ('f' == key[1]) {
  2052. // Use defaults layer
  2053. rules.push(...asArray(value).map(value => ({
  2054. p: Layer.d,
  2055. o: 0,
  2056. r: [key],
  2057. d: serialize$(value, {
  2058. p: Layer.d
  2059. }, context).map(stringify$1).join('')
  2060. })));
  2061. continue;
  2062. }
  2063. }
  2064. // -> All other are handled below; same as selector
  2065. // @media
  2066. // @supports
  2067. // selector
  2068. if ('object' != typeof value || Array.isArray(value)) {
  2069. if ('label' == key && value) name = value + hash(JSON.stringify([precedence, important, style]));else if (value || 0 === value) {
  2070. // property -> hyphenate
  2071. key = key.replace(/[A-Z]/g, _ => '-' + _.toLowerCase());
  2072. // Update precedence
  2073. numberOfDeclarations += 1;
  2074. maxPropertyPrecedence = Math.max(maxPropertyPrecedence, '-' == (property = key)[0] ? 0 : seperatorPrecedence(property) + (/^(?:(border-(?!w|c|sty)|[tlbr].{2,4}m?$|c.{7,8}$)|([fl].{5}l|g.{8}$|pl))/.test(property) ? +!!RegExp.$1 || /* +1 */-!!RegExp.$2 : /* -1 */0) + 1);
  2075. declarations += (declarations ? ';' : '') + asArray(value).map(value => context.s(key,
  2076. // support theme(...) function in values
  2077. // calc(100vh - theme('spacing.12'))
  2078. resolveThemeFunction('' + value, context.theme) + (important ? ' !important' : ''))).join(';');
  2079. }
  2080. } else
  2081. // at-rule or non-global selector
  2082. if ('@' == key[0] || key.includes('&')) {
  2083. let rulePrecedence = precedence;
  2084. if ('@' == key[0]) {
  2085. // Handle `@media screen(sm)` and `@media (screen(sm) or ...)`
  2086. key = key.replace(/\bscreen\(([^)]+)\)/g, (_, screenKey) => {
  2087. let screen = context.theme('screens', screenKey);
  2088. return screen ? (rulePrecedence |= 67108864, /* Shifts.screens */mql(screen, '')) : _;
  2089. });
  2090. rulePrecedence |= atRulePrecedence(key);
  2091. }
  2092. rules.push(...serialize$(value, {
  2093. n: name,
  2094. p: rulePrecedence,
  2095. r: [...conditions, key],
  2096. i: important
  2097. }, context));
  2098. } else
  2099. // global selector
  2100. rules.push(...serialize$(value, {
  2101. p: precedence,
  2102. r: [...conditions, key]
  2103. }, context));
  2104. }
  2105. return (
  2106. // PERF: prevent unshift using `rules = [{}]` above and then `rules[0] = {...}`
  2107. rules.unshift({
  2108. n: name,
  2109. p: precedence,
  2110. o:
  2111. // number of declarations (descending)
  2112. Math.max(0, 15 - numberOfDeclarations) +
  2113. // greatest precedence of properties
  2114. // if there is no property precedence this is most likely a custom property only declaration
  2115. // these have the highest precedence
  2116. 1.5 * Math.min(maxPropertyPrecedence || 15, 15),
  2117. r: conditions,
  2118. // stringified declarations
  2119. d: declarations
  2120. }), rules.sort(compareTwindRules)
  2121. );
  2122. }(style, convert(rule, context, precedence, conditions), context);
  2123. }
  2124. function resolveThemeFunction(value, theme) {
  2125. // support theme(...) function in values
  2126. // calc(100vh - theme('spacing.12'))
  2127. // theme('borderColor.DEFAULT', 'currentColor')
  2128. // PERF: check for theme before running the regexp
  2129. // if (value.includes('theme')) {
  2130. return value.replace(/theme\((["'`])?(.+?)\1(?:\s*,\s*(["'`])?(.+?)\3)?\)/g, (_, __, key, ___, defaultValue = '') => {
  2131. let value = theme(key, defaultValue);
  2132. return 'function' == typeof value && /color|fill|stroke/i.test(key) ? toColorValue(value) : '' + asArray(value).filter(v => Object(v) !== v);
  2133. });
  2134. }
  2135. // }
  2136. // return value
  2137. function merge(rules, name) {
  2138. let current;
  2139. // merge:
  2140. // - same conditions
  2141. // - replace name with hash of name + condititions + declarations
  2142. // - precedence:
  2143. // - combine bits or use max precendence
  2144. // - set layer bit to merged
  2145. let result = [];
  2146. for (let rule of rules)
  2147. // only merge rules with declarations and names (eg no global rules)
  2148. if (rule.d && rule.n) {
  2149. if (current?.p == rule.p && '' + current.r == '' + rule.r) {
  2150. current.c = [current.c, rule.c].filter(Boolean).join(' ');
  2151. current.d = current.d + ';' + rule.d;
  2152. } else
  2153. // only set name for named rules eg not for global or className propagation rules
  2154. result.push(current = {
  2155. ...rule,
  2156. n: rule.n && name
  2157. });
  2158. } else result.push({
  2159. ...rule,
  2160. n: rule.n && name
  2161. });
  2162. return result;
  2163. }
  2164. function translate(rules, context, precedence = Layer.u, conditions, important) {
  2165. // Sorted by precedence
  2166. let result = [];
  2167. for (let rule of rules) for (let cssRule of function (rule, context, precedence, conditions, important) {
  2168. rule = {
  2169. ...rule,
  2170. i: rule.i || important
  2171. };
  2172. let resolved = function (rule, context) {
  2173. let factory = registry.get(rule.n);
  2174. return factory ? factory(rule, context) : context.r(rule.n, 'dark' == rule.v[0]);
  2175. }(rule, context);
  2176. return resolved ?
  2177. // a list of class names
  2178. 'string' == typeof resolved ? (({
  2179. r: conditions,
  2180. p: precedence
  2181. } = convert(rule, context, precedence, conditions)), merge(translate(parse(resolved), context, precedence, conditions, rule.i), rule.n)) : Array.isArray(resolved) ? resolved.map(rule => {
  2182. var /* Shifts.layer */ /*
  2183. To have a predictable styling the styles must be ordered.
  2184. This order is represented by a precedence number. The lower values
  2185. are inserted before higher values. Meaning higher precedence styles
  2186. overwrite lower precedence styles.
  2187. Each rule has some traits that are put into a bit set which form
  2188. the precedence:
  2189. | bits | trait |
  2190. | ---- | ---------------------------------------------------- |
  2191. | 1 | dark mode |
  2192. | 2 | layer: preflight, global, components, utilities, css |
  2193. | 1 | screens: is this a responsive variation of a rule |
  2194. | 5 | responsive based on min-width |
  2195. | 4 | at-rules |
  2196. | 18 | pseudo and group variants |
  2197. | 4 | number of declarations (descending) |
  2198. | 4 | greatest precedence of properties |
  2199. **Dark Mode: 1 bit**
  2200. Flag for dark mode rules.
  2201. **Layer: 3 bits**
  2202. - defaults = 0: The preflight styles and any base styles registered by plugins.
  2203. - base = 1: The global styles registered by plugins.
  2204. - components = 2
  2205. - variants = 3
  2206. - compounds = 4
  2207. - aliases = 5
  2208. - utilities = 6: Utility classes and any utility classes registered by plugins.
  2209. - css = 7: Styles generated by css
  2210. **Screens: 1 bit**
  2211. Flag for screen variants. They may not always have a `min-width` to be detected by _Responsive_ below.
  2212. **Responsive: 4 bits**
  2213. Based on extracted `min-width` value:
  2214. - 576px -> 3
  2215. - 1536px -> 10
  2216. - 36rem -> 3
  2217. - 96rem -> 9
  2218. **At-Rules: 4 bits**
  2219. Based on the count of special chars (`-:,`) within the at-rule.
  2220. **Pseudo and group variants: 18 bits**
  2221. Ensures predictable order of pseudo classes.
  2222. - https://bitsofco.de/when-do-the-hover-focus-and-active-pseudo-classes-apply/#orderofstyleshoverthenfocusthenactive
  2223. - https://developer.mozilla.org/docs/Web/CSS/:active#Active_links
  2224. - https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/defaultConfig.stub.js#L718
  2225. **Number of declarations (descending): 4 bits**
  2226. Allows single declaration styles to overwrite styles from multi declaration styles.
  2227. **Greatest precedence of properties: 4 bits**
  2228. Ensure shorthand properties are inserted before longhand properties; eg longhand override shorthand
  2229. */precedence1, layer;
  2230. return {
  2231. o: 0,
  2232. ...rule,
  2233. r: [...asArray(conditions), ...asArray(rule.r)],
  2234. p: (precedence1 = precedence, layer = rule.p ?? precedence, precedence1 & ~Layer.o | layer)
  2235. };
  2236. }) : serialize(resolved, rule, context, precedence, conditions) :
  2237. // propagate className as is
  2238. [{
  2239. c: toClassName(rule),
  2240. p: 0,
  2241. o: 0,
  2242. r: []
  2243. }];
  2244. }(rule, context, precedence, conditions, important)) result.splice(sortedInsertionIndex(result, cssRule), 0, cssRule);
  2245. return result;
  2246. }
  2247. function translateWith(name, layer, rules, context, precedence, conditions, important, useOrderOfRules) {
  2248. return merge((useOrderOfRules ? rules.flatMap(rule => translate([rule], context, precedence, conditions, important)) : translate(rules, context, precedence, conditions, important)).map(rule => {
  2249. return (
  2250. // do not move defaults
  2251. // move only rules with a name unless they are in the base layer
  2252. rule.p & Layer.o && (rule.n || layer == Layer.b) ? {
  2253. ...rule,
  2254. p: rule.p & ~Layer.o | layer,
  2255. o: 0
  2256. } : rule
  2257. );
  2258. }), name);
  2259. }
  2260. function define(className, layer, rules, useOrderOfRules) {
  2261. var factory;
  2262. return factory = (rule, context) => {
  2263. let {
  2264. n: name,
  2265. p: precedence,
  2266. r: conditions,
  2267. i: important
  2268. } = convert(rule, context, layer);
  2269. return rules && translateWith(name, layer, rules, context, precedence, conditions, important, useOrderOfRules);
  2270. }, registry.set(className, factory), className;
  2271. }
  2272. /**
  2273. * The utility name including `-` if set, but without `!` and variants
  2274. */ /**
  2275. * All variants without trailing colon: `hover`, `after:`, `[...]`
  2276. */ /**
  2277. * Something like `!underline` or `!bg-red-500` or `!red-500`
  2278. */
  2279. function createRule(active, current, loc) {
  2280. if ('(' != active[active.length - 1]) {
  2281. let variants = [],
  2282. important = false,
  2283. negated = false,
  2284. name = '';
  2285. for (let value of active) if (!('(' == value || /[~@]$/.test(value))) {
  2286. if ('!' == value[0]) {
  2287. value = value.slice(1);
  2288. important = !important;
  2289. }
  2290. if (value.endsWith(':')) {
  2291. variants['dark:' == value ? 'unshift' : 'push'](value.slice(0, -1));
  2292. continue;
  2293. }
  2294. if ('-' == value[0]) {
  2295. value = value.slice(1);
  2296. negated = !negated;
  2297. }
  2298. value.endsWith('-') && (value = value.slice(0, -1));
  2299. value && '&' != value && (name += (name && '-') + value);
  2300. }
  2301. if (name) {
  2302. negated && (name = '-' + name);
  2303. current[0].push({
  2304. n: name,
  2305. v: variants.filter(uniq),
  2306. i: important
  2307. });
  2308. }
  2309. }
  2310. }
  2311. function uniq(value, index, values) {
  2312. return values.indexOf(value) == index;
  2313. }
  2314. let cache = new Map();
  2315. /**
  2316. * @internal
  2317. * @param token
  2318. * @returns
  2319. */
  2320. function parse(token) {
  2321. let parsed = cache.get(token);
  2322. if (!parsed) {
  2323. // Stack of active groupings (`(`), variants, or nested (`~` or `@`)
  2324. let active = [],
  2325. // Stack of current rule list to put new rules in
  2326. // the first `0` element is the current list
  2327. current = [[]],
  2328. startIndex = 0,
  2329. skip = 0,
  2330. comment = null,
  2331. position = 0,
  2332. // eslint-disable-next-line no-inner-declarations
  2333. commit = (isRule, endOffset = 0) => {
  2334. if (startIndex != position) {
  2335. active.push(token.slice(startIndex, position + endOffset));
  2336. isRule && createRule(active, current);
  2337. }
  2338. startIndex = position + 1;
  2339. };
  2340. for (; position < token.length; position++) {
  2341. let char = token[position];
  2342. if (skip) '\\' != token[position - 1] && (skip += +('[' == char) || -(']' == char));else if ('[' == char)
  2343. // start to skip
  2344. skip += 1;else if (comment) {
  2345. if ('\\' != token[position - 1] && comment.test(token.slice(position))) {
  2346. comment = null;
  2347. startIndex = position + RegExp.lastMatch.length;
  2348. }
  2349. } else if ('/' == char && '\\' != token[position - 1] && ('*' == token[position + 1] || '/' == token[position + 1]))
  2350. // multiline or single line comment
  2351. comment = '*' == token[position + 1] ? /^\*\// : /^[\r\n]/;else if ('(' == char) {
  2352. // hover:(...) or utilitity-(...)
  2353. commit();
  2354. active.push(char);
  2355. } else if (':' == char) ':' != token[position + 1] && commit(false, 1);else if (/[\s,)]/.test(char)) {
  2356. // whitespace, comma or closing brace
  2357. commit(true);
  2358. let lastGroup = active.lastIndexOf('(');
  2359. if (')' == char) {
  2360. // Close nested block
  2361. let nested = active[lastGroup - 1];
  2362. if (/[~@]$/.test(nested)) {
  2363. let rules = current.shift();
  2364. active.length = lastGroup;
  2365. // remove variants that are already applied through active
  2366. createRule([...active, '#'], current);
  2367. let {
  2368. v
  2369. } = current[0].pop();
  2370. for (let rule of rules)
  2371. // if a rule has dark we need to splice after the first entry eg dark
  2372. rule.v.splice(+('dark' == rule.v[0]) - +('dark' == v[0]), v.length);
  2373. createRule([...active, define(
  2374. // named nested
  2375. nested.length > 1 ? nested.slice(0, -1) + hash(JSON.stringify([nested, rules])) : nested + '(' + format(rules) + ')', Layer.a, rules, /@$/.test(nested))], current);
  2376. }
  2377. lastGroup = active.lastIndexOf('(', lastGroup - 1);
  2378. }
  2379. active.length = lastGroup + 1;
  2380. } else /[~@]/.test(char) && '(' == token[position + 1] &&
  2381. // start nested block
  2382. // ~(...) or button~(...)
  2383. // @(...) or button@(...)
  2384. current.unshift([]);
  2385. }
  2386. // Consume remaining stack
  2387. commit(true);
  2388. cache.set(token, parsed = current[0]);
  2389. }
  2390. return parsed;
  2391. }
  2392. /** The found theme value */ // indirection wrapper to remove autocomplete functions from production bundles
  2393. /**
  2394. * @group Configuration
  2395. * @param pattern
  2396. */ /**
  2397. * @group Configuration
  2398. * @param pattern
  2399. * @param resolver
  2400. */ /**
  2401. * @group Configuration
  2402. * @param pattern
  2403. * @param resolve
  2404. */ // eslint-disable-next-line @typescript-eslint/ban-types
  2405. /**
  2406. * @group Configuration
  2407. * @param pattern
  2408. * @param resolve
  2409. * @param convert
  2410. */
  2411. function match(pattern,
  2412. // eslint-disable-next-line @typescript-eslint/ban-types
  2413. resolve, convert) {
  2414. return [pattern, fromMatch(resolve, convert)];
  2415. }
  2416. /**
  2417. * @group Configuration
  2418. * @internal
  2419. * @deprecated Use {@link match} instead.
  2420. */ /**
  2421. * @group Configuration
  2422. * @internal
  2423. * @deprecated Use {@link match} instead.
  2424. */ /**
  2425. * @group Configuration
  2426. * @internal
  2427. * @deprecated Use {@link match} instead.
  2428. */ /**
  2429. * @group Configuration
  2430. * @internal
  2431. * @deprecated Use {@link match} instead.
  2432. */
  2433. function fromMatch(resolve, convert) {
  2434. return 'function' == typeof resolve ? resolve : 'string' == typeof resolve && /^[\w-]+$/.test(resolve) ?
  2435. // a CSS property alias
  2436. (match, context) => ({
  2437. [resolve]: convert ? convert(match, context) : maybeNegate(match, 1)
  2438. }) : match =>
  2439. // CSSObject, shortcut or apply
  2440. resolve || {
  2441. [match[1]]: maybeNegate(match, 2)
  2442. };
  2443. }
  2444. function maybeNegate(match, offset, value = match.slice(offset).find(Boolean) || match.$$ || match.input) {
  2445. return '-' == match.input[0] ? `calc(${value} * -1)` : value;
  2446. }
  2447. /**
  2448. * @group Configuration
  2449. * @param pattern
  2450. * @param section
  2451. * @param resolve
  2452. * @param convert
  2453. * @returns
  2454. */
  2455. function matchTheme(pattern, /** Theme section to use (default: `$1` — The first matched group) */section, /** The css property (default: value of {@link section}) */resolve, convert) {
  2456. return [pattern, fromTheme(section, resolve, convert)];
  2457. }
  2458. /**
  2459. * @group Configuration
  2460. * @internal
  2461. * @deprecated Use {@link matchTheme} instead.
  2462. * @param section
  2463. * @param resolve
  2464. * @param convert
  2465. * @returns
  2466. */
  2467. function fromTheme( /** Theme section to use (default: `$1` — The first matched group) */section, /** The css property (default: value of {@link section}) */resolve, convert) {
  2468. let factory = 'string' == typeof resolve ? (match, context) => ({
  2469. [resolve]: convert ? convert(match, context) : match._
  2470. }) : resolve || (({
  2471. 1: $1,
  2472. _
  2473. }, context, section) => ({
  2474. [$1 || section]: _
  2475. }));
  2476. return (match, context) => {
  2477. let themeSection = camelize(section || match[1]),
  2478. value = context.theme(themeSection, match.$$) ?? arbitrary(match.$$, themeSection, context);
  2479. if (null != value) return match._ = maybeNegate(match, 0, value), factory(match, context, themeSection);
  2480. };
  2481. }
  2482. /** Theme section to use (default: `$0.replace('-', 'Color')` — The matched string with `Color` appended) */ /** The css property (default: value of {@link section}) */ /** `--tw-${$0}opacity` -> '--tw-text-opacity' */ /** `section.replace('Color', 'Opacity')` -> 'textOpacity' */ /**
  2483. * @group Configuration
  2484. * @param pattern
  2485. * @param options
  2486. * @param resolve
  2487. * @returns
  2488. */
  2489. function matchColor(pattern, options = {}, resolve) {
  2490. return [pattern, colorFromTheme(options, resolve)];
  2491. }
  2492. /**
  2493. * @group Configuration
  2494. * @internal
  2495. * @deprecated Use {@link matchColor} instead.
  2496. * @param options
  2497. * @param resolve
  2498. * @returns
  2499. */
  2500. function colorFromTheme(options = {}, resolve) {
  2501. return (match, context) => {
  2502. // text- -> textColor
  2503. // ring-offset(?:-|$) -> ringOffsetColor
  2504. let {
  2505. section = camelize(match[0]).replace('-', '') + 'Color'
  2506. } = options,
  2507. // extract color and opacity
  2508. // rose-500 -> ['rose-500']
  2509. // [hsl(0_100%_/_50%)] -> ['[hsl(0_100%_/_50%)]']
  2510. // indigo-500/100 -> ['indigo-500', '100']
  2511. // [hsl(0_100%_/_50%)]/[.25] -> ['[hsl(0_100%_/_50%)]', '[.25]']
  2512. [colorMatch, opacityMatch] = parseValue(match.$$);
  2513. if (!colorMatch) return;
  2514. let colorValue = context.theme(section, colorMatch) || arbitrary(colorMatch, section, context);
  2515. if (!colorValue || 'object' == typeof colorValue) return;
  2516. let {
  2517. // text- -> --tw-text-opacity
  2518. // ring-offset(?:-|$) -> --tw-ring-offset-opacity
  2519. // TODO move this default into preset-tailwind?
  2520. opacityVariable = `--tw-${match[0].replace(/-$/, '')}-opacity`,
  2521. opacitySection = section.replace('Color', 'Opacity'),
  2522. property = section,
  2523. selector
  2524. } = options,
  2525. opacityValue = context.theme(opacitySection, opacityMatch || 'DEFAULT') || opacityMatch && arbitrary(opacityMatch, opacitySection, context),
  2526. // if (typeof color != 'string') {
  2527. // console.warn(`Invalid color ${colorMatch} (from ${match.input}):`, color)
  2528. // return
  2529. // }
  2530. create = resolve || (({
  2531. _
  2532. }) => {
  2533. let properties = toCSS(property, _);
  2534. return selector ? {
  2535. [selector]: properties
  2536. } : properties;
  2537. });
  2538. match._ = {
  2539. value: toColorValue(colorValue, {
  2540. opacityVariable: opacityVariable || void 0,
  2541. opacityValue: opacityValue || void 0
  2542. }),
  2543. color: options => toColorValue(colorValue, options),
  2544. opacityVariable: opacityVariable || void 0,
  2545. opacityValue: opacityValue || void 0
  2546. };
  2547. let properties = create(match, context);
  2548. // auto support dark mode colors
  2549. if (!match.dark) {
  2550. let darkColorValue = context.d(section, colorMatch, colorValue);
  2551. if (darkColorValue && darkColorValue !== colorValue) {
  2552. match._ = {
  2553. value: toColorValue(darkColorValue, {
  2554. opacityVariable: opacityVariable || void 0,
  2555. opacityValue: opacityValue || '1'
  2556. }),
  2557. color: options => toColorValue(darkColorValue, options),
  2558. opacityVariable: opacityVariable || void 0,
  2559. opacityValue: opacityValue || void 0
  2560. };
  2561. properties = {
  2562. '&': properties,
  2563. [context.v('dark')]: create(match, context)
  2564. };
  2565. }
  2566. }
  2567. return properties;
  2568. };
  2569. }
  2570. /**
  2571. * @internal
  2572. * @param input
  2573. */
  2574. function parseValue(input) {
  2575. // extract color and opacity
  2576. // rose-500 -> ['rose-500']
  2577. // [hsl(0_100%_/_50%)] -> ['[hsl(0_100%_/_50%)]']
  2578. // indigo-500/100 -> ['indigo-500', '100']
  2579. // [hsl(0_100%_/_50%)]/[.25] -> ['[hsl(0_100%_/_50%)]', '[.25]']
  2580. return (input.match(/^(\[[^\]]+]|[^/]+?)(?:\/(.+))?$/) || []).slice(1);
  2581. }
  2582. /**
  2583. * @internal
  2584. * @param property
  2585. * @param value
  2586. * @returns
  2587. */
  2588. function toCSS(property, value) {
  2589. let properties = {};
  2590. if ('string' == typeof value) properties[property] = value;else {
  2591. value.opacityVariable && value.value.includes(value.opacityVariable) && (properties[value.opacityVariable] = value.opacityValue || '1');
  2592. properties[property] = value.value;
  2593. }
  2594. return properties;
  2595. }
  2596. /**
  2597. * @internal
  2598. * @param value
  2599. * @param section
  2600. * @param context
  2601. * @returns
  2602. */
  2603. function arbitrary(value, section, context) {
  2604. if ('[' == value[0] && ']' == value.slice(-1)) {
  2605. value = normalize(resolveThemeFunction(value.slice(1, -1), context.theme));
  2606. if (!section) return value;
  2607. if (
  2608. // Respect type hints from the user on ambiguous arbitrary values - https://tailwindcss.com/docs/adding-custom-styles#resolving-ambiguities
  2609. !(
  2610. // If this is a color section and the value is a hex color, color function or color name
  2611. /color|fill|stroke/i.test(section) && !(/^color:/.test(value) || /^(#|((hsl|rgb)a?|hwb|lab|lch|color)\(|[a-z]+$)/.test(value)) ||
  2612. // url(, [a-z]-gradient(, image(, cross-fade(, image-set(
  2613. /image/i.test(section) && !(/^image:/.test(value) || /^[a-z-]+\(/.test(value)) ||
  2614. // font-*
  2615. // - fontWeight (type: ['lookup', 'number', 'any'])
  2616. // - fontFamily (type: ['lookup', 'generic-name', 'family-name'])
  2617. /weight/i.test(section) && !(/^(number|any):/.test(value) || /^\d+$/.test(value)) ||
  2618. // bg-*
  2619. // - backgroundPosition (type: ['lookup', ['position', { preferOnConflict: true }]])
  2620. // - backgroundSize (type: ['lookup', 'length', 'percentage', 'size'])
  2621. /position/i.test(section) && /^(length|size):/.test(value)))
  2622. // remove arbitrary type prefix — we do not need it but user may use it
  2623. // https://github.com/tailwindlabs/tailwindcss/blob/master/src/util/dataTypes.js
  2624. // url, number, percentage, length, line-width, shadow, color, image, gradient, position, family-name, lookup, any, generic-name, absolute-size, relative-size
  2625. return value.replace(/^[a-z-]+:/, '');
  2626. }
  2627. }
  2628. function camelize(value) {
  2629. return value.replace(/-./g, x => x[1].toUpperCase());
  2630. }
  2631. /**
  2632. * @internal
  2633. * @param value
  2634. * @returns
  2635. */
  2636. function normalize(value) {
  2637. return (
  2638. // Keep raw strings if it starts with `url(`
  2639. value.includes('url(') ? value.replace(/(.*?)(url\(.*?\))(.*?)/g, (_, before = '', url, after = '') => normalize(before) + url + normalize(after)) : value.
  2640. // Convert `_` to ` `, except for escaped underscores `\_`
  2641. replace(/(^|[^\\])_+/g, (fullMatch, characterBefore) => characterBefore + ' '.repeat(fullMatch.length - characterBefore.length)).replace(/\\_/g, '_').
  2642. // Add spaces around operators inside math functions like calc() that do not follow an operator
  2643. // or '('.
  2644. replace(/(calc|min|max|clamp)\(.+\)/g, match => match.replace(/(-?\d*\.?\d(?!\b-.+[,)](?![^+\-/*])\D)(?:%|[a-z]+)?|\))([+\-/*])/g, '$1 $2 '))
  2645. );
  2646. }
  2647. /**
  2648. * @group Configuration
  2649. * @param param0
  2650. * @returns
  2651. */
  2652. function defineConfig({
  2653. presets = [],
  2654. ...userConfig
  2655. }) {
  2656. // most user config values go first to have precendence over preset config
  2657. // only `preflight` and `theme` are applied as last preset to override all presets
  2658. let config = {
  2659. darkMode: void 0,
  2660. darkColor: void 0,
  2661. preflight: false !== userConfig.preflight && [],
  2662. theme: {},
  2663. variants: asArray(userConfig.variants),
  2664. rules: asArray(userConfig.rules),
  2665. ignorelist: asArray(userConfig.ignorelist),
  2666. hash: void 0,
  2667. stringify: (property, value) => property + ':' + value,
  2668. finalize: []
  2669. };
  2670. for (let preset of asArray([...presets, {
  2671. darkMode: userConfig.darkMode,
  2672. darkColor: userConfig.darkColor,
  2673. preflight: false !== userConfig.preflight && asArray(userConfig.preflight),
  2674. theme: userConfig.theme,
  2675. hash: userConfig.hash,
  2676. stringify: userConfig.stringify,
  2677. finalize: userConfig.finalize
  2678. }])) {
  2679. let {
  2680. preflight,
  2681. darkMode = config.darkMode,
  2682. darkColor = config.darkColor,
  2683. theme,
  2684. variants,
  2685. rules,
  2686. ignorelist,
  2687. hash = config.hash,
  2688. stringify = config.stringify,
  2689. finalize
  2690. } = 'function' == typeof preset ? preset(config) : preset;
  2691. config = {
  2692. // values defined by user or previous presets take precedence
  2693. preflight: false !== config.preflight && false !== preflight && [...config.preflight, ...asArray(preflight)],
  2694. darkMode,
  2695. darkColor,
  2696. theme: {
  2697. ...config.theme,
  2698. ...theme,
  2699. extend: {
  2700. ...config.theme.extend,
  2701. ...theme?.extend
  2702. }
  2703. },
  2704. variants: [...config.variants, ...asArray(variants)],
  2705. rules: [...config.rules, ...asArray(rules)],
  2706. ignorelist: [...config.ignorelist, ...asArray(ignorelist)],
  2707. hash,
  2708. stringify,
  2709. finalize: [...config.finalize, ...asArray(finalize)]
  2710. };
  2711. }
  2712. return config;
  2713. }
  2714. function find(value, list, cache, getResolver, context, isDark) {
  2715. for (let item of list) {
  2716. let resolver = cache.get(item);
  2717. resolver || cache.set(item, resolver = getResolver(item));
  2718. let resolved = resolver(value, context, isDark);
  2719. if (resolved) return resolved;
  2720. }
  2721. }
  2722. function getVariantResolver(variant) {
  2723. var resolve;
  2724. return createResolve(variant[0], 'function' == typeof (resolve = variant[1]) ? resolve : () => resolve);
  2725. }
  2726. function getRuleResolver(rule) {
  2727. var resolve, convert;
  2728. return Array.isArray(rule) ? createResolve(rule[0], fromMatch(rule[1], rule[2])) : createResolve(rule, fromMatch(resolve, convert));
  2729. }
  2730. function createResolve(patterns, resolve) {
  2731. return createRegExpExecutor(patterns, (value, condition, context, isDark) => {
  2732. let match = condition.exec(value);
  2733. if (match) return (
  2734. // MATCH.$_ = value
  2735. match.$$ = value.slice(match[0].length), match.dark = isDark, resolve(match, context)
  2736. );
  2737. });
  2738. }
  2739. function createRegExpExecutor(patterns, run) {
  2740. let conditions = asArray(patterns).map(toCondition);
  2741. return (value, context, isDark) => {
  2742. for (let condition of conditions) {
  2743. let result = run(value, condition, context, isDark);
  2744. if (result) return result;
  2745. }
  2746. };
  2747. }
  2748. function toCondition(value) {
  2749. // "visible" -> /^visible$/
  2750. // "(float)-(left|right|none)" -> /^(float)-(left|right|none)$/
  2751. // "auto-rows-" -> /^auto-rows-/
  2752. // "gap(-|$)" -> /^gap(-|$)/
  2753. return 'string' == typeof value ? RegExp('^' + value + (value.includes('$') || '-' == value.slice(-1) ? '' : '$')) : value;
  2754. }
  2755. /**
  2756. * @group Runtime
  2757. * @param config
  2758. * @param sheet
  2759. */
  2760. function twind(userConfig, sheet) {
  2761. let config = defineConfig(userConfig),
  2762. context = function ({
  2763. theme,
  2764. darkMode,
  2765. darkColor = noop,
  2766. variants,
  2767. rules,
  2768. hash: hash$1,
  2769. stringify,
  2770. ignorelist,
  2771. finalize
  2772. }) {
  2773. // Used to cache resolved rule values
  2774. let variantCache = new Map(),
  2775. // lazy created resolve functions
  2776. variantResolvers = new Map(),
  2777. // Used to cache resolved rule values
  2778. ruleCache = new Map(),
  2779. // lazy created resolve functions
  2780. ruleResolvers = new Map(),
  2781. ignored = createRegExpExecutor(ignorelist, (value, condition) => condition.test(value));
  2782. // add dark as last variant to allow user to override it
  2783. // we can modify variants as it has been passed through defineConfig which already made a copy
  2784. variants.push(['dark', Array.isArray(darkMode) || 'class' == darkMode ? `${asArray(darkMode)[1] || '.dark'} &` : 'string' == typeof darkMode && 'media' != darkMode ? darkMode :
  2785. // a custom selector
  2786. '@media (prefers-color-scheme:dark)']);
  2787. let h = 'function' == typeof hash$1 ? value => hash$1(value, hash) : hash$1 ? hash : identity;
  2788. h !== identity && finalize.push(rule => ({
  2789. ...rule,
  2790. n: rule.n && h(rule.n),
  2791. d: rule.d?.replace(/--(tw(?:-[\w-]+)?)\b/g, (_, property) => '--' + h(property).replace('#', ''))
  2792. }));
  2793. let ctx = {
  2794. theme: function ({
  2795. extend = {},
  2796. ...base
  2797. }) {
  2798. let resolved = {},
  2799. resolveContext = {
  2800. get colors() {
  2801. return theme('colors');
  2802. },
  2803. theme,
  2804. // Stub implementation as negated values are automatically infered and do _not_ need to be in the theme
  2805. negative() {
  2806. return {};
  2807. },
  2808. breakpoints(screens) {
  2809. let breakpoints = {};
  2810. for (let key in screens) 'string' == typeof screens[key] && (breakpoints['screen-' + key] = screens[key]);
  2811. return breakpoints;
  2812. }
  2813. };
  2814. return theme;
  2815. function theme(sectionKey, key, defaultValue, opacityValue) {
  2816. if (sectionKey) {
  2817. ({
  2818. 1: sectionKey,
  2819. 2: opacityValue
  2820. } =
  2821. // eslint-disable-next-line no-sparse-arrays
  2822. /^(\S+?)(?:\s*\/\s*([^/]+))?$/.exec(sectionKey) || [, sectionKey]);
  2823. if (/[.[]/.test(sectionKey)) {
  2824. let path = [];
  2825. // dotted deep access: colors.gray.500 or spacing[2.5]
  2826. sectionKey.replace(/\[([^\]]+)\]|([^.[]+)/g, (_, $1, $2 = $1) => path.push($2));
  2827. sectionKey = path.shift();
  2828. defaultValue = key;
  2829. key = path.join('-');
  2830. }
  2831. let section = resolved[sectionKey] ||
  2832. // two-step deref to allow extend section to reference base section
  2833. Object.assign(Object.assign(
  2834. // Make sure to not get into recursive calls
  2835. resolved[sectionKey] = {}, deref(base, sectionKey)), deref(extend, sectionKey));
  2836. if (null == key) return section;
  2837. key || (key = 'DEFAULT');
  2838. let value = section[key] ?? key.split('-').reduce((obj, prop) => obj?.[prop], section) ?? defaultValue;
  2839. return opacityValue ? toColorValue(value, {
  2840. opacityValue: resolveThemeFunction(opacityValue, theme)
  2841. }) : value;
  2842. }
  2843. // Collect the whole theme
  2844. let result = {};
  2845. for (let section1 of [...Object.keys(base), ...Object.keys(extend)]) result[section1] = theme(section1);
  2846. return result;
  2847. }
  2848. function deref(source, section) {
  2849. let value = source[section];
  2850. return ('function' == typeof value && (value = value(resolveContext)), value && /color|fill|stroke/i.test(section)) ? function flattenColorPalette(colors, path = []) {
  2851. let flattend = {};
  2852. for (let key in colors) {
  2853. let value = colors[key],
  2854. keyPath = [...path, key];
  2855. flattend[keyPath.join('-')] = value;
  2856. if ('DEFAULT' == key) {
  2857. keyPath = path;
  2858. flattend[path.join('-')] = value;
  2859. }
  2860. 'object' == typeof value && Object.assign(flattend, flattenColorPalette(value, keyPath));
  2861. }
  2862. return flattend;
  2863. }(value) : value;
  2864. }
  2865. }(theme),
  2866. e: escape,
  2867. h,
  2868. s(property, value) {
  2869. return stringify(property, value, ctx);
  2870. },
  2871. d(section, key, color) {
  2872. return darkColor(section, key, ctx, color);
  2873. },
  2874. v(value) {
  2875. return variantCache.has(value) || variantCache.set(value, find(value, variants, variantResolvers, getVariantResolver, ctx) || '&:' + value), variantCache.get(value);
  2876. },
  2877. r(className, isDark) {
  2878. let key = JSON.stringify([className, isDark]);
  2879. return ruleCache.has(key) || ruleCache.set(key, !ignored(className, ctx) && find(className, rules, ruleResolvers, getRuleResolver, ctx, isDark)), ruleCache.get(key);
  2880. },
  2881. f(rule) {
  2882. return finalize.reduce((rule, p) => p(rule, ctx), rule);
  2883. }
  2884. };
  2885. return ctx;
  2886. }(config),
  2887. // Map of tokens to generated className
  2888. cache = new Map(),
  2889. // An array of precedence by index within the sheet
  2890. // always sorted
  2891. sortedPrecedences = [],
  2892. // Cache for already inserted css rules
  2893. // to prevent double insertions
  2894. insertedRules = new Set();
  2895. sheet.resume(className => cache.set(className, className), (cssText, rule) => {
  2896. sheet.insert(cssText, sortedPrecedences.length, rule);
  2897. sortedPrecedences.push(rule);
  2898. insertedRules.add(cssText);
  2899. });
  2900. function insert(rule) {
  2901. let finalRule = context.f(rule),
  2902. cssText = stringify$1(finalRule);
  2903. // If not already inserted
  2904. if (cssText && !insertedRules.has(cssText)) {
  2905. // Mark rule as inserted
  2906. insertedRules.add(cssText);
  2907. // Find the correct position
  2908. let index = sortedInsertionIndex(sortedPrecedences, rule);
  2909. // Insert
  2910. sheet.insert(cssText, index, rule);
  2911. // Update sorted index
  2912. sortedPrecedences.splice(index, 0, rule);
  2913. }
  2914. return finalRule.n;
  2915. }
  2916. return Object.defineProperties(function tw(tokens) {
  2917. if (!cache.size) for (let preflight of asArray(config.preflight)) {
  2918. 'function' == typeof preflight && (preflight = preflight(context));
  2919. preflight && ('string' == typeof preflight ? translateWith('', Layer.b, parse(preflight), context, Layer.b, [], false, true) : serialize(preflight, {}, context, Layer.b)).forEach(insert);
  2920. }
  2921. tokens = '' + tokens;
  2922. let className = cache.get(tokens);
  2923. if (!className) {
  2924. let classNames = new Set();
  2925. for (let rule of translate(parse(tokens), context)) classNames.add(rule.c).add(insert(rule));
  2926. className = [...classNames].filter(Boolean).join(' ');
  2927. // Remember the generated class name
  2928. cache.set(tokens, className).set(className, className);
  2929. }
  2930. return className;
  2931. }, Object.getOwnPropertyDescriptors({
  2932. get target() {
  2933. return sheet.target;
  2934. },
  2935. theme: context.theme,
  2936. config,
  2937. snapshot() {
  2938. let restoreSheet = sheet.snapshot(),
  2939. insertedRules$ = new Set(insertedRules),
  2940. cache$ = new Map(cache),
  2941. sortedPrecedences$ = [...sortedPrecedences];
  2942. return () => {
  2943. restoreSheet();
  2944. insertedRules = insertedRules$;
  2945. cache = cache$;
  2946. sortedPrecedences = sortedPrecedences$;
  2947. };
  2948. },
  2949. clear() {
  2950. sheet.clear();
  2951. insertedRules = new Set();
  2952. cache = new Map();
  2953. sortedPrecedences = [];
  2954. },
  2955. destroy() {
  2956. this.clear();
  2957. sheet.destroy();
  2958. }
  2959. }));
  2960. }
  2961. /**
  2962. * Simplified MutationRecord which allows us to pass an
  2963. * ArrayLike (compatible with Array and NodeList) `addedNodes` and
  2964. * omit other properties we are not interested in.
  2965. */
  2966. function getStyleElement(selector) {
  2967. let style = document.querySelector(selector || 'style[data-twind=""]');
  2968. if (!style || 'STYLE' != style.tagName) {
  2969. style = document.createElement('style');
  2970. document.head.prepend(style);
  2971. }
  2972. return style.dataset.twind = 'claimed', style;
  2973. }
  2974. /**
  2975. * @group Sheets
  2976. * @param element
  2977. * @returns
  2978. */
  2979. function dom(element) {
  2980. let target = element && 'string' != typeof element ? element : getStyleElement(element);
  2981. return {
  2982. target,
  2983. snapshot() {
  2984. // collect current rules
  2985. let rules = Array.from(target.childNodes, node => node.textContent);
  2986. return () => {
  2987. // remove all existing rules
  2988. this.clear();
  2989. // add all snapshot rules back
  2990. // eslint-disable-next-line @typescript-eslint/unbound-method
  2991. rules.forEach(this.insert);
  2992. };
  2993. },
  2994. clear() {
  2995. target.textContent = '';
  2996. },
  2997. destroy() {
  2998. target.remove();
  2999. },
  3000. insert(cssText, index) {
  3001. target.insertBefore(document.createTextNode(cssText), target.childNodes[index] || null);
  3002. },
  3003. resume: noop
  3004. };
  3005. }
  3006.  
  3007. 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(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}
  3008.  
  3009. let CSSPrefixFlags = [['-webkit-', 1],
  3010. // 0b001
  3011. ['-moz-', 2],
  3012. // 0b010
  3013. ['-ms-', 4]];
  3014. // 0b100
  3015. function presetAutoprefix() {
  3016. return ({
  3017. stringify
  3018. }) => ({
  3019. stringify(property, value, context) {
  3020. let cssText = '',
  3021. // Resolve aliases, e.g. `gap` -> `grid-gap`
  3022. propertyAlias = r(property);
  3023. propertyAlias && (cssText += stringify(propertyAlias, value, context) + ';');
  3024. // Prefix properties, e.g. `backdrop-filter` -> `-webkit-backdrop-filter`
  3025. let propertyFlags = a(property),
  3026. valueFlags = t(property, value);
  3027. for (let prefix of CSSPrefixFlags) {
  3028. propertyFlags & prefix[1] && (cssText += stringify(prefix[0] + property, value, context) + ';');
  3029. valueFlags & prefix[1] && (cssText += stringify(property, prefix[0] + value, context) + ';');
  3030. }
  3031. /* Include the standardized declaration last */ /* https://css-tricks.com/ordering-css3-properties/ */
  3032. return cssText + stringify(property, value, context);
  3033. }
  3034. });
  3035. }
  3036.  
  3037. /**
  3038. * @module @twind/preset-tailwind/baseTheme
  3039. */ /**
  3040. * @experimental
  3041. */let theme = {
  3042. screens: {
  3043. sm: '640px',
  3044. md: '768px',
  3045. lg: '1024px',
  3046. xl: '1280px',
  3047. '2xl': '1536px'
  3048. },
  3049. columns: {
  3050. auto: 'auto',
  3051. // Handled by plugin,
  3052. // 1: '1',
  3053. // 2: '2',
  3054. // 3: '3',
  3055. // 4: '4',
  3056. // 5: '5',
  3057. // 6: '6',
  3058. // 7: '7',
  3059. // 8: '8',
  3060. // 9: '9',
  3061. // 10: '10',
  3062. // 11: '11',
  3063. // 12: '12',
  3064. '3xs': '16rem',
  3065. '2xs': '18rem',
  3066. xs: '20rem',
  3067. sm: '24rem',
  3068. md: '28rem',
  3069. lg: '32rem',
  3070. xl: '36rem',
  3071. '2xl': '42rem',
  3072. '3xl': '48rem',
  3073. '4xl': '56rem',
  3074. '5xl': '64rem',
  3075. '6xl': '72rem',
  3076. '7xl': '80rem'
  3077. },
  3078. spacing: {
  3079. px: '1px',
  3080. 0: '0px',
  3081. ... /* #__PURE__ */linear(4, 'rem', 4, 0.5, 0.5),
  3082. // 0.5: '0.125rem',
  3083. // 1: '0.25rem',
  3084. // 1.5: '0.375rem',
  3085. // 2: '0.5rem',
  3086. // 2.5: '0.625rem',
  3087. // 3: '0.75rem',
  3088. // 3.5: '0.875rem',
  3089. // 4: '1rem',
  3090. ... /* #__PURE__ */linear(12, 'rem', 4, 5),
  3091. // 5: '1.25rem',
  3092. // 6: '1.5rem',
  3093. // 7: '1.75rem',
  3094. // 8: '2rem',
  3095. // 9: '2.25rem',
  3096. // 10: '2.5rem',
  3097. // 11: '2.75rem',
  3098. // 12: '3rem',
  3099. 14: '3.5rem',
  3100. ... /* #__PURE__ */linear(64, 'rem', 4, 16, 4),
  3101. // 16: '4rem',
  3102. // 20: '5rem',
  3103. // 24: '6rem',
  3104. // 28: '7rem',
  3105. // 32: '8rem',
  3106. // 36: '9rem',
  3107. // 40: '10rem',
  3108. // 44: '11rem',
  3109. // 48: '12rem',
  3110. // 52: '13rem',
  3111. // 56: '14rem',
  3112. // 60: '15rem',
  3113. // 64: '16rem',
  3114. 72: '18rem',
  3115. 80: '20rem',
  3116. 96: '24rem'
  3117. },
  3118. durations: {
  3119. 75: '75ms',
  3120. 100: '100ms',
  3121. 150: '150ms',
  3122. 200: '200ms',
  3123. 300: '300ms',
  3124. 500: '500ms',
  3125. 700: '700ms',
  3126. 1000: '1000ms'
  3127. },
  3128. animation: {
  3129. none: 'none',
  3130. spin: 'spin 1s linear infinite',
  3131. ping: 'ping 1s cubic-bezier(0,0,0.2,1) infinite',
  3132. pulse: 'pulse 2s cubic-bezier(0.4,0,0.6,1) infinite',
  3133. bounce: 'bounce 1s infinite'
  3134. },
  3135. aspectRatio: {
  3136. auto: 'auto',
  3137. square: '1/1',
  3138. video: '16/9'
  3139. },
  3140. backdropBlur: /* #__PURE__ */alias('blur'),
  3141. backdropBrightness: /* #__PURE__ */alias('brightness'),
  3142. backdropContrast: /* #__PURE__ */alias('contrast'),
  3143. backdropGrayscale: /* #__PURE__ */alias('grayscale'),
  3144. backdropHueRotate: /* #__PURE__ */alias('hueRotate'),
  3145. backdropInvert: /* #__PURE__ */alias('invert'),
  3146. backdropOpacity: /* #__PURE__ */alias('opacity'),
  3147. backdropSaturate: /* #__PURE__ */alias('saturate'),
  3148. backdropSepia: /* #__PURE__ */alias('sepia'),
  3149. backgroundColor: /* #__PURE__ */alias('colors'),
  3150. backgroundImage: {
  3151. none: 'none'
  3152. },
  3153. // These are built-in
  3154. // 'gradient-to-t': 'linear-gradient(to top, var(--tw-gradient-stops))',
  3155. // 'gradient-to-tr': 'linear-gradient(to top right, var(--tw-gradient-stops))',
  3156. // 'gradient-to-r': 'linear-gradient(to right, var(--tw-gradient-stops))',
  3157. // 'gradient-to-br': 'linear-gradient(to bottom right, var(--tw-gradient-stops))',
  3158. // 'gradient-to-b': 'linear-gradient(to bottom, var(--tw-gradient-stops))',
  3159. // 'gradient-to-bl': 'linear-gradient(to bottom left, var(--tw-gradient-stops))',
  3160. // 'gradient-to-l': 'linear-gradient(to left, var(--tw-gradient-stops))',
  3161. // 'gradient-to-tl': 'linear-gradient(to top left, var(--tw-gradient-stops))',
  3162. backgroundOpacity: /* #__PURE__ */alias('opacity'),
  3163. // backgroundPosition: {
  3164. // // The following are already handled by the plugin:
  3165. // // center, right, left, bottom, top
  3166. // // 'bottom-10px-right-20px' -> bottom 10px right 20px
  3167. // },
  3168. backgroundSize: {
  3169. auto: 'auto',
  3170. cover: 'cover',
  3171. contain: 'contain'
  3172. },
  3173. blur: {
  3174. none: 'none',
  3175. 0: '0',
  3176. sm: '4px',
  3177. DEFAULT: '8px',
  3178. md: '12px',
  3179. lg: '16px',
  3180. xl: '24px',
  3181. '2xl': '40px',
  3182. '3xl': '64px'
  3183. },
  3184. brightness: {
  3185. ... /* #__PURE__ */linear(200, '', 100, 0, 50),
  3186. // 0: '0',
  3187. // 50: '.5',
  3188. // 150: '1.5',
  3189. // 200: '2',
  3190. ... /* #__PURE__ */linear(110, '', 100, 90, 5),
  3191. // 90: '.9',
  3192. // 95: '.95',
  3193. // 100: '1',
  3194. // 105: '1.05',
  3195. // 110: '1.1',
  3196. 75: '0.75',
  3197. 125: '1.25'
  3198. },
  3199. borderColor: ({
  3200. theme
  3201. }) => ({
  3202. DEFAULT: theme('colors.gray.200', 'currentColor'),
  3203. ...theme('colors')
  3204. }),
  3205. borderOpacity: /* #__PURE__ */alias('opacity'),
  3206. borderRadius: {
  3207. none: '0px',
  3208. sm: '0.125rem',
  3209. DEFAULT: '0.25rem',
  3210. md: '0.375rem',
  3211. lg: '0.5rem',
  3212. xl: '0.75rem',
  3213. '2xl': '1rem',
  3214. '3xl': '1.5rem',
  3215. '1/2': '50%',
  3216. full: '9999px'
  3217. },
  3218. borderSpacing: /* #__PURE__ */alias('spacing'),
  3219. borderWidth: {
  3220. DEFAULT: '1px',
  3221. ... /* #__PURE__ */exponential(8, 'px')
  3222. },
  3223. // 0: '0px',
  3224. // 2: '2px',
  3225. // 4: '4px',
  3226. // 8: '8px',
  3227. boxShadow: {
  3228. sm: '0 1px 2px 0 rgba(0,0,0,0.05)',
  3229. DEFAULT: '0 1px 3px 0 rgba(0,0,0,0.1), 0 1px 2px -1px rgba(0,0,0,0.1)',
  3230. md: '0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -2px rgba(0,0,0,0.1)',
  3231. lg: '0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1)',
  3232. xl: '0 20px 25px -5px rgba(0,0,0,0.1), 0 8px 10px -6px rgba(0,0,0,0.1)',
  3233. '2xl': '0 25px 50px -12px rgba(0,0,0,0.25)',
  3234. inner: 'inset 0 2px 4px 0 rgba(0,0,0,0.05)',
  3235. none: '0 0 #0000'
  3236. },
  3237. boxShadowColor: alias('colors'),
  3238. // container: {},
  3239. // cursor: {
  3240. // // Default values are handled by plugin
  3241. // },
  3242. caretColor: /* #__PURE__ */alias('colors'),
  3243. accentColor: ({
  3244. theme
  3245. }) => ({
  3246. auto: 'auto',
  3247. ...theme('colors')
  3248. }),
  3249. contrast: {
  3250. ... /* #__PURE__ */linear(200, '', 100, 0, 50),
  3251. // 0: '0',
  3252. // 50: '.5',
  3253. // 150: '1.5',
  3254. // 200: '2',
  3255. 75: '0.75',
  3256. 125: '1.25'
  3257. },
  3258. content: {
  3259. none: 'none'
  3260. },
  3261. divideColor: /* #__PURE__ */alias('borderColor'),
  3262. divideOpacity: /* #__PURE__ */alias('borderOpacity'),
  3263. divideWidth: /* #__PURE__ */alias('borderWidth'),
  3264. dropShadow: {
  3265. sm: '0 1px 1px rgba(0,0,0,0.05)',
  3266. DEFAULT: ['0 1px 2px rgba(0,0,0,0.1)', '0 1px 1px rgba(0,0,0,0.06)'],
  3267. md: ['0 4px 3px rgba(0,0,0,0.07)', '0 2px 2px rgba(0,0,0,0.06)'],
  3268. lg: ['0 10px 8px rgba(0,0,0,0.04)', '0 4px 3px rgba(0,0,0,0.1)'],
  3269. xl: ['0 20px 13px rgba(0,0,0,0.03)', '0 8px 5px rgba(0,0,0,0.08)'],
  3270. '2xl': '0 25px 25px rgba(0,0,0,0.15)',
  3271. none: '0 0 #0000'
  3272. },
  3273. fill: ({
  3274. theme
  3275. }) => ({
  3276. ...theme('colors'),
  3277. none: 'none'
  3278. }),
  3279. grayscale: {
  3280. DEFAULT: '100%',
  3281. 0: '0'
  3282. },
  3283. hueRotate: {
  3284. 0: '0deg',
  3285. 15: '15deg',
  3286. 30: '30deg',
  3287. 60: '60deg',
  3288. 90: '90deg',
  3289. 180: '180deg'
  3290. },
  3291. invert: {
  3292. DEFAULT: '100%',
  3293. 0: '0'
  3294. },
  3295. flex: {
  3296. 1: '1 1 0%',
  3297. auto: '1 1 auto',
  3298. initial: '0 1 auto',
  3299. none: 'none'
  3300. },
  3301. flexBasis: ({
  3302. theme
  3303. }) => ({
  3304. ...theme('spacing'),
  3305. ...ratios(2, 6),
  3306. // '1/2': '50%',
  3307. // '1/3': '33.333333%',
  3308. // '2/3': '66.666667%',
  3309. // '1/4': '25%',
  3310. // '2/4': '50%',
  3311. // '3/4': '75%',
  3312. // '1/5': '20%',
  3313. // '2/5': '40%',
  3314. // '3/5': '60%',
  3315. // '4/5': '80%',
  3316. // '1/6': '16.666667%',
  3317. // '2/6': '33.333333%',
  3318. // '3/6': '50%',
  3319. // '4/6': '66.666667%',
  3320. // '5/6': '83.333333%',
  3321. ...ratios(12, 12),
  3322. // '1/12': '8.333333%',
  3323. // '2/12': '16.666667%',
  3324. // '3/12': '25%',
  3325. // '4/12': '33.333333%',
  3326. // '5/12': '41.666667%',
  3327. // '6/12': '50%',
  3328. // '7/12': '58.333333%',
  3329. // '8/12': '66.666667%',
  3330. // '9/12': '75%',
  3331. // '10/12': '83.333333%',
  3332. // '11/12': '91.666667%',
  3333. auto: 'auto',
  3334. full: '100%'
  3335. }),
  3336. flexGrow: {
  3337. DEFAULT: 1,
  3338. 0: 0
  3339. },
  3340. flexShrink: {
  3341. DEFAULT: 1,
  3342. 0: 0
  3343. },
  3344. fontFamily: {
  3345. 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(','),
  3346. serif: 'ui-serif,Georgia,Cambria,"Times New Roman",Times,serif'.split(','),
  3347. mono: 'ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace'.split(',')
  3348. },
  3349. fontSize: {
  3350. xs: ['0.75rem', '1rem'],
  3351. sm: ['0.875rem', '1.25rem'],
  3352. base: ['1rem', '1.5rem'],
  3353. lg: ['1.125rem', '1.75rem'],
  3354. xl: ['1.25rem', '1.75rem'],
  3355. '2xl': ['1.5rem', '2rem'],
  3356. '3xl': ['1.875rem', '2.25rem'],
  3357. '4xl': ['2.25rem', '2.5rem'],
  3358. '5xl': ['3rem', '1'],
  3359. '6xl': ['3.75rem', '1'],
  3360. '7xl': ['4.5rem', '1'],
  3361. '8xl': ['6rem', '1'],
  3362. '9xl': ['8rem', '1']
  3363. },
  3364. fontWeight: {
  3365. thin: '100',
  3366. extralight: '200',
  3367. light: '300',
  3368. normal: '400',
  3369. medium: '500',
  3370. semibold: '600',
  3371. bold: '700',
  3372. extrabold: '800',
  3373. black: '900'
  3374. },
  3375. gap: /* #__PURE__ */alias('spacing'),
  3376. gradientColorStops: /* #__PURE__ */alias('colors'),
  3377. gridAutoColumns: {
  3378. auto: 'auto',
  3379. min: 'min-content',
  3380. max: 'max-content',
  3381. fr: 'minmax(0,1fr)'
  3382. },
  3383. gridAutoRows: {
  3384. auto: 'auto',
  3385. min: 'min-content',
  3386. max: 'max-content',
  3387. fr: 'minmax(0,1fr)'
  3388. },
  3389. gridColumn: {
  3390. // span-X is handled by the plugin: span-1 -> span 1 / span 1
  3391. auto: 'auto',
  3392. 'span-full': '1 / -1'
  3393. },
  3394. // gridColumnEnd: {
  3395. // // Defaults handled by plugin
  3396. // },
  3397. // gridColumnStart: {
  3398. // // Defaults handled by plugin
  3399. // },
  3400. gridRow: {
  3401. // span-X is handled by the plugin: span-1 -> span 1 / span 1
  3402. auto: 'auto',
  3403. 'span-full': '1 / -1'
  3404. },
  3405. // gridRowStart: {
  3406. // // Defaults handled by plugin
  3407. // },
  3408. // gridRowEnd: {
  3409. // // Defaults handled by plugin
  3410. // },
  3411. gridTemplateColumns: {
  3412. // numbers are handled by the plugin: 1 -> repeat(1, minmax(0, 1fr))
  3413. none: 'none'
  3414. },
  3415. gridTemplateRows: {
  3416. // numbers are handled by the plugin: 1 -> repeat(1, minmax(0, 1fr))
  3417. none: 'none'
  3418. },
  3419. height: ({
  3420. theme
  3421. }) => ({
  3422. ...theme('spacing'),
  3423. ...ratios(2, 6),
  3424. // '1/2': '50%',
  3425. // '1/3': '33.333333%',
  3426. // '2/3': '66.666667%',
  3427. // '1/4': '25%',
  3428. // '2/4': '50%',
  3429. // '3/4': '75%',
  3430. // '1/5': '20%',
  3431. // '2/5': '40%',
  3432. // '3/5': '60%',
  3433. // '4/5': '80%',
  3434. // '1/6': '16.666667%',
  3435. // '2/6': '33.333333%',
  3436. // '3/6': '50%',
  3437. // '4/6': '66.666667%',
  3438. // '5/6': '83.333333%',
  3439. min: 'min-content',
  3440. max: 'max-content',
  3441. fit: 'fit-content',
  3442. auto: 'auto',
  3443. full: '100%',
  3444. screen: '100vh'
  3445. }),
  3446. inset: ({
  3447. theme
  3448. }) => ({
  3449. ...theme('spacing'),
  3450. ...ratios(2, 4),
  3451. // '1/2': '50%',
  3452. // '1/3': '33.333333%',
  3453. // '2/3': '66.666667%',
  3454. // '1/4': '25%',
  3455. // '2/4': '50%',
  3456. // '3/4': '75%',
  3457. auto: 'auto',
  3458. full: '100%'
  3459. }),
  3460. keyframes: {
  3461. spin: {
  3462. from: {
  3463. transform: 'rotate(0deg)'
  3464. },
  3465. to: {
  3466. transform: 'rotate(360deg)'
  3467. }
  3468. },
  3469. ping: {
  3470. '0%': {
  3471. transform: 'scale(1)',
  3472. opacity: '1'
  3473. },
  3474. '75%,100%': {
  3475. transform: 'scale(2)',
  3476. opacity: '0'
  3477. }
  3478. },
  3479. pulse: {
  3480. '0%,100%': {
  3481. opacity: '1'
  3482. },
  3483. '50%': {
  3484. opacity: '.5'
  3485. }
  3486. },
  3487. bounce: {
  3488. '0%, 100%': {
  3489. transform: 'translateY(-25%)',
  3490. animationTimingFunction: 'cubic-bezier(0.8,0,1,1)'
  3491. },
  3492. '50%': {
  3493. transform: 'none',
  3494. animationTimingFunction: 'cubic-bezier(0,0,0.2,1)'
  3495. }
  3496. }
  3497. },
  3498. letterSpacing: {
  3499. tighter: '-0.05em',
  3500. tight: '-0.025em',
  3501. normal: '0em',
  3502. wide: '0.025em',
  3503. wider: '0.05em',
  3504. widest: '0.1em'
  3505. },
  3506. lineHeight: {
  3507. ... /* #__PURE__ */linear(10, 'rem', 4, 3),
  3508. // 3: '.75rem',
  3509. // 4: '1rem',
  3510. // 5: '1.25rem',
  3511. // 6: '1.5rem',
  3512. // 7: '1.75rem',
  3513. // 8: '2rem',
  3514. // 9: '2.25rem',
  3515. // 10: '2.5rem',
  3516. none: '1',
  3517. tight: '1.25',
  3518. snug: '1.375',
  3519. normal: '1.5',
  3520. relaxed: '1.625',
  3521. loose: '2'
  3522. },
  3523. // listStyleType: {
  3524. // // Defaults handled by plugin
  3525. // },
  3526. margin: ({
  3527. theme
  3528. }) => ({
  3529. auto: 'auto',
  3530. ...theme('spacing')
  3531. }),
  3532. maxHeight: ({
  3533. theme
  3534. }) => ({
  3535. full: '100%',
  3536. min: 'min-content',
  3537. max: 'max-content',
  3538. fit: 'fit-content',
  3539. screen: '100vh',
  3540. ...theme('spacing')
  3541. }),
  3542. maxWidth: ({
  3543. theme,
  3544. breakpoints
  3545. }) => ({
  3546. ...breakpoints(theme('screens')),
  3547. none: 'none',
  3548. 0: '0rem',
  3549. xs: '20rem',
  3550. sm: '24rem',
  3551. md: '28rem',
  3552. lg: '32rem',
  3553. xl: '36rem',
  3554. '2xl': '42rem',
  3555. '3xl': '48rem',
  3556. '4xl': '56rem',
  3557. '5xl': '64rem',
  3558. '6xl': '72rem',
  3559. '7xl': '80rem',
  3560. full: '100%',
  3561. min: 'min-content',
  3562. max: 'max-content',
  3563. fit: 'fit-content',
  3564. prose: '65ch'
  3565. }),
  3566. minHeight: {
  3567. 0: '0px',
  3568. full: '100%',
  3569. min: 'min-content',
  3570. max: 'max-content',
  3571. fit: 'fit-content',
  3572. screen: '100vh'
  3573. },
  3574. minWidth: {
  3575. 0: '0px',
  3576. full: '100%',
  3577. min: 'min-content',
  3578. max: 'max-content',
  3579. fit: 'fit-content'
  3580. },
  3581. // objectPosition: {
  3582. // // The plugins joins all arguments by default
  3583. // },
  3584. opacity: {
  3585. ... /* #__PURE__ */linear(100, '', 100, 0, 10),
  3586. // 0: '0',
  3587. // 10: '0.1',
  3588. // 20: '0.2',
  3589. // 30: '0.3',
  3590. // 40: '0.4',
  3591. // 60: '0.6',
  3592. // 70: '0.7',
  3593. // 80: '0.8',
  3594. // 90: '0.9',
  3595. // 100: '1',
  3596. 5: '0.05',
  3597. 25: '0.25',
  3598. 75: '0.75',
  3599. 95: '0.95'
  3600. },
  3601. order: {
  3602. // Handled by plugin
  3603. // 1: '1',
  3604. // 2: '2',
  3605. // 3: '3',
  3606. // 4: '4',
  3607. // 5: '5',
  3608. // 6: '6',
  3609. // 7: '7',
  3610. // 8: '8',
  3611. // 9: '9',
  3612. // 10: '10',
  3613. // 11: '11',
  3614. // 12: '12',
  3615. first: '-9999',
  3616. last: '9999',
  3617. none: '0'
  3618. },
  3619. padding: /* #__PURE__ */alias('spacing'),
  3620. placeholderColor: /* #__PURE__ */alias('colors'),
  3621. placeholderOpacity: /* #__PURE__ */alias('opacity'),
  3622. outlineColor: /* #__PURE__ */alias('colors'),
  3623. outlineOffset: /* #__PURE__ */exponential(8, 'px'),
  3624. // 0: '0px',
  3625. // 1: '1px',
  3626. // 2: '2px',
  3627. // 4: '4px',
  3628. // 8: '8px',,
  3629. outlineWidth: /* #__PURE__ */exponential(8, 'px'),
  3630. // 0: '0px',
  3631. // 1: '1px',
  3632. // 2: '2px',
  3633. // 4: '4px',
  3634. // 8: '8px',,
  3635. ringColor: ({
  3636. theme
  3637. }) => ({
  3638. ...theme('colors'),
  3639. DEFAULT: '#3b82f6'
  3640. }),
  3641. ringOffsetColor: /* #__PURE__ */alias('colors'),
  3642. ringOffsetWidth: /* #__PURE__ */exponential(8, 'px'),
  3643. // 0: '0px',
  3644. // 1: '1px',
  3645. // 2: '2px',
  3646. // 4: '4px',
  3647. // 8: '8px',,
  3648. ringOpacity: ({
  3649. theme
  3650. }) => ({
  3651. ...theme('opacity'),
  3652. DEFAULT: '0.5'
  3653. }),
  3654. ringWidth: {
  3655. DEFAULT: '3px',
  3656. ... /* #__PURE__ */exponential(8, 'px')
  3657. },
  3658. // 0: '0px',
  3659. // 1: '1px',
  3660. // 2: '2px',
  3661. // 4: '4px',
  3662. // 8: '8px',
  3663. rotate: {
  3664. ... /* #__PURE__ */exponential(2, 'deg'),
  3665. // 0: '0deg',
  3666. // 1: '1deg',
  3667. // 2: '2deg',
  3668. ... /* #__PURE__ */exponential(12, 'deg', 3),
  3669. // 3: '3deg',
  3670. // 6: '6deg',
  3671. // 12: '12deg',
  3672. ... /* #__PURE__ */exponential(180, 'deg', 45)
  3673. },
  3674. // 45: '45deg',
  3675. // 90: '90deg',
  3676. // 180: '180deg',
  3677. saturate: /* #__PURE__ */linear(200, '', 100, 0, 50),
  3678. // 0: '0',
  3679. // 50: '.5',
  3680. // 100: '1',
  3681. // 150: '1.5',
  3682. // 200: '2',
  3683. scale: {
  3684. ... /* #__PURE__ */linear(150, '', 100, 0, 50),
  3685. // 0: '0',
  3686. // 50: '.5',
  3687. // 150: '1.5',
  3688. ... /* #__PURE__ */linear(110, '', 100, 90, 5),
  3689. // 90: '.9',
  3690. // 95: '.95',
  3691. // 100: '1',
  3692. // 105: '1.05',
  3693. // 110: '1.1',
  3694. 75: '0.75',
  3695. 125: '1.25'
  3696. },
  3697. scrollMargin: /* #__PURE__ */alias('spacing'),
  3698. scrollPadding: /* #__PURE__ */alias('spacing'),
  3699. sepia: {
  3700. 0: '0',
  3701. DEFAULT: '100%'
  3702. },
  3703. skew: {
  3704. ... /* #__PURE__ */exponential(2, 'deg'),
  3705. // 0: '0deg',
  3706. // 1: '1deg',
  3707. // 2: '2deg',
  3708. ... /* #__PURE__ */exponential(12, 'deg', 3)
  3709. },
  3710. // 3: '3deg',
  3711. // 6: '6deg',
  3712. // 12: '12deg',
  3713. space: /* #__PURE__ */alias('spacing'),
  3714. stroke: ({
  3715. theme
  3716. }) => ({
  3717. ...theme('colors'),
  3718. none: 'none'
  3719. }),
  3720. strokeWidth: /* #__PURE__ */linear(2),
  3721. // 0: '0',
  3722. // 1: '1',
  3723. // 2: '2',,
  3724. textColor: /* #__PURE__ */alias('colors'),
  3725. textDecorationColor: /* #__PURE__ */alias('colors'),
  3726. textDecorationThickness: {
  3727. 'from-font': 'from-font',
  3728. auto: 'auto',
  3729. ... /* #__PURE__ */exponential(8, 'px')
  3730. },
  3731. // 0: '0px',
  3732. // 1: '1px',
  3733. // 2: '2px',
  3734. // 4: '4px',
  3735. // 8: '8px',
  3736. textUnderlineOffset: {
  3737. auto: 'auto',
  3738. ... /* #__PURE__ */exponential(8, 'px')
  3739. },
  3740. // 0: '0px',
  3741. // 1: '1px',
  3742. // 2: '2px',
  3743. // 4: '4px',
  3744. // 8: '8px',
  3745. textIndent: /* #__PURE__ */alias('spacing'),
  3746. textOpacity: /* #__PURE__ */alias('opacity'),
  3747. // transformOrigin: {
  3748. // // The following are already handled by the plugin:
  3749. // // center, right, left, bottom, top
  3750. // // 'bottom-10px-right-20px' -> bottom 10px right 20px
  3751. // },
  3752. transitionDuration: ({
  3753. theme
  3754. }) => ({
  3755. ...theme('durations'),
  3756. DEFAULT: '150ms'
  3757. }),
  3758. transitionDelay: /* #__PURE__ */alias('durations'),
  3759. transitionProperty: {
  3760. none: 'none',
  3761. all: 'all',
  3762. DEFAULT: 'color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter',
  3763. colors: 'color,background-color,border-color,text-decoration-color,fill,stroke',
  3764. opacity: 'opacity',
  3765. shadow: 'box-shadow',
  3766. transform: 'transform'
  3767. },
  3768. transitionTimingFunction: {
  3769. DEFAULT: 'cubic-bezier(0.4,0,0.2,1)',
  3770. linear: 'linear',
  3771. in: 'cubic-bezier(0.4,0,1,1)',
  3772. out: 'cubic-bezier(0,0,0.2,1)',
  3773. 'in-out': 'cubic-bezier(0.4,0,0.2,1)'
  3774. },
  3775. translate: ({
  3776. theme
  3777. }) => ({
  3778. ...theme('spacing'),
  3779. ...ratios(2, 4),
  3780. // '1/2': '50%',
  3781. // '1/3': '33.333333%',
  3782. // '2/3': '66.666667%',
  3783. // '1/4': '25%',
  3784. // '2/4': '50%',
  3785. // '3/4': '75%',
  3786. full: '100%'
  3787. }),
  3788. width: ({
  3789. theme
  3790. }) => ({
  3791. min: 'min-content',
  3792. max: 'max-content',
  3793. fit: 'fit-content',
  3794. screen: '100vw',
  3795. ...theme('flexBasis')
  3796. }),
  3797. willChange: {
  3798. scroll: 'scroll-position'
  3799. },
  3800. // other options handled by rules
  3801. // auto: 'auto',
  3802. // contents: 'contents',
  3803. // transform: 'transform',
  3804. zIndex: {
  3805. ... /* #__PURE__ */linear(50, '', 1, 0, 10),
  3806. // 0: '0',
  3807. // 10: '10',
  3808. // 20: '20',
  3809. // 30: '30',
  3810. // 40: '40',
  3811. // 50: '50',
  3812. auto: 'auto'
  3813. }
  3814. };
  3815. // '1/2': '50%',
  3816. // '1/3': '33.333333%',
  3817. // '2/3': '66.666667%',
  3818. // '1/4': '25%',
  3819. // '2/4': '50%',
  3820. // '3/4': '75%',
  3821. // '1/5': '20%',
  3822. // '2/5': '40%',
  3823. // '3/5': '60%',
  3824. // '4/5': '80%',
  3825. // '1/6': '16.666667%',
  3826. // '2/6': '33.333333%',
  3827. // '3/6': '50%',
  3828. // '4/6': '66.666667%',
  3829. // '5/6': '83.333333%',
  3830. function ratios(start, end) {
  3831. let result = {};
  3832. do
  3833. // XXX: using var to avoid strange bug when generating cjs where `= 1` is removed
  3834. // eslint-disable-next-line no-var
  3835. for (var dividend = 1; dividend < start; dividend++) result[`${dividend}/${start}`] = Number((dividend / start * 100).toFixed(6)) + '%'; while (++start <= end);
  3836. return result;
  3837. }
  3838. // 0: '0px',
  3839. // 2: '2px',
  3840. // 4: '4px',
  3841. // 8: '8px',
  3842. function exponential(stop, unit, start = 0) {
  3843. let result = {};
  3844. for (; start <= stop; start = 2 * start || 1) result[start] = start + unit;
  3845. return result;
  3846. }
  3847. // 3: '.75rem',
  3848. // 4: '1rem',
  3849. // 5: '1.25rem',
  3850. // 6: '1.5rem',
  3851. // 7: '1.75rem',
  3852. // 8: '2rem',
  3853. // 9: '2.25rem',
  3854. // 10: '2.5rem',
  3855. function linear(stop, unit = '', divideBy = 1, start = 0, step = 1, result = {})
  3856. // eslint-disable-next-line max-params
  3857. {
  3858. for (; start <= stop; start += step) result[start] = start / divideBy + unit;
  3859. return result;
  3860. }
  3861. function alias(section) {
  3862. return ({
  3863. theme
  3864. }) => theme(section);
  3865. }
  3866.  
  3867. let preflight = {
  3868. /*
  3869. 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
  3870. 2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
  3871. */
  3872. '*,::before,::after': {
  3873. boxSizing: 'border-box',
  3874. /* 1 */borderWidth: '0',
  3875. /* 2 */borderStyle: 'solid',
  3876. /* 2 */borderColor: 'theme(borderColor.DEFAULT, currentColor)'
  3877. },
  3878. /* 2 */'::before,::after': {
  3879. '--tw-content': "''"
  3880. },
  3881. /*
  3882. 1. Use a consistent sensible line-height in all browsers.
  3883. 2. Prevent adjustments of font size after orientation changes in iOS.
  3884. 3. Use a more readable tab size.
  3885. 4. Use the user's configured `sans` font-family by default.
  3886. 5. Use the user's configured `sans` font-feature-settings by default.
  3887. */
  3888. html: {
  3889. lineHeight: 1.5,
  3890. /* 1 */WebkitTextSizeAdjust: '100%',
  3891. /* 2 */MozTabSize: '4',
  3892. /* 3 */tabSize: 4,
  3893. /* 3 */fontFamily: `theme(fontFamily.sans, ${theme.fontFamily.sans})`,
  3894. /* 4 */fontFeatureSettings: 'theme(fontFamily.sans[1].fontFeatureSettings, normal)'
  3895. },
  3896. /* 5 */ /*
  3897. 1. Remove the margin in all browsers.
  3898. 2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
  3899. */body: {
  3900. margin: '0',
  3901. /* 1 */lineHeight: 'inherit'
  3902. },
  3903. /* 2 */ /*
  3904. 1. Add the correct height in Firefox.
  3905. 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
  3906. 3. Ensure horizontal rules are visible by default.
  3907. */hr: {
  3908. height: '0',
  3909. /* 1 */color: 'inherit',
  3910. /* 2 */borderTopWidth: '1px'
  3911. },
  3912. /* 3 */ /*
  3913. Add the correct text decoration in Chrome, Edge, and Safari.
  3914. */'abbr:where([title])': {
  3915. textDecoration: 'underline dotted'
  3916. },
  3917. /*
  3918. Remove the default font size and weight for headings.
  3919. */
  3920. 'h1,h2,h3,h4,h5,h6': {
  3921. fontSize: 'inherit',
  3922. fontWeight: 'inherit'
  3923. },
  3924. /*
  3925. Reset links to optimize for opt-in styling instead of opt-out.
  3926. */
  3927. a: {
  3928. color: 'inherit',
  3929. textDecoration: 'inherit'
  3930. },
  3931. /*
  3932. Add the correct font weight in Edge and Safari.
  3933. */
  3934. 'b,strong': {
  3935. fontWeight: 'bolder'
  3936. },
  3937. /*
  3938. 1. Use the user's configured `mono` font family by default.
  3939. 2. Use the user's configured `mono` font-feature-settings by default.
  3940. 3. Correct the odd `em` font sizing in all browsers.
  3941. */
  3942. 'code,kbd,samp,pre': {
  3943. fontFamily: `theme(fontFamily.mono, ${theme.fontFamily.mono})`,
  3944. fontFeatureSettings: 'theme(fontFamily.mono[1].fontFeatureSettings, normal)',
  3945. fontSize: '1em'
  3946. },
  3947. /*
  3948. Add the correct font size in all browsers.
  3949. */
  3950. small: {
  3951. fontSize: '80%'
  3952. },
  3953. /*
  3954. Prevent `sub` and `sup` elements from affecting the line height in all browsers.
  3955. */
  3956. 'sub,sup': {
  3957. fontSize: '75%',
  3958. lineHeight: 0,
  3959. position: 'relative',
  3960. verticalAlign: 'baseline'
  3961. },
  3962. sub: {
  3963. bottom: '-0.25em'
  3964. },
  3965. sup: {
  3966. top: '-0.5em'
  3967. },
  3968. /*
  3969. 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
  3970. 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
  3971. 3. Remove gaps between table borders by default.
  3972. */
  3973. table: {
  3974. textIndent: '0',
  3975. /* 1 */borderColor: 'inherit',
  3976. /* 2 */borderCollapse: 'collapse'
  3977. },
  3978. /* 3 */ /*
  3979. 1. Change the font styles in all browsers.
  3980. 2. Remove the margin in Firefox and Safari.
  3981. 3. Remove default padding in all browsers.
  3982. */'button,input,optgroup,select,textarea': {
  3983. fontFamily: 'inherit',
  3984. /* 1 */fontSize: '100%',
  3985. /* 1 */lineHeight: 'inherit',
  3986. /* 1 */color: 'inherit',
  3987. /* 1 */margin: '0',
  3988. /* 2 */padding: '0'
  3989. },
  3990. /* 3 */ /*
  3991. Remove the inheritance of text transform in Edge and Firefox.
  3992. */'button,select': {
  3993. textTransform: 'none'
  3994. },
  3995. /*
  3996. 1. Correct the inability to style clickable types in iOS and Safari.
  3997. 2. Remove default button styles.
  3998. */
  3999. "button,[type='button'],[type='reset'],[type='submit']": {
  4000. WebkitAppearance: 'button',
  4001. /* 1 */backgroundColor: 'transparent',
  4002. /* 2 */backgroundImage: 'none'
  4003. },
  4004. /* 4 */ /*
  4005. Use the modern Firefox focus style for all focusable elements.
  4006. */':-moz-focusring': {
  4007. outline: 'auto'
  4008. },
  4009. /*
  4010. Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
  4011. */
  4012. ':-moz-ui-invalid': {
  4013. boxShadow: 'none'
  4014. },
  4015. /*
  4016. Add the correct vertical alignment in Chrome and Firefox.
  4017. */
  4018. progress: {
  4019. verticalAlign: 'baseline'
  4020. },
  4021. /*
  4022. Correct the cursor style of increment and decrement buttons in Safari.
  4023. */
  4024. '::-webkit-inner-spin-button,::-webkit-outer-spin-button': {
  4025. height: 'auto'
  4026. },
  4027. /*
  4028. 1. Correct the odd appearance in Chrome and Safari.
  4029. 2. Correct the outline style in Safari.
  4030. */
  4031. "[type='search']": {
  4032. WebkitAppearance: 'textfield',
  4033. /* 1 */outlineOffset: '-2px'
  4034. },
  4035. /* 2 */ /*
  4036. Remove the inner padding in Chrome and Safari on macOS.
  4037. */'::-webkit-search-decoration': {
  4038. WebkitAppearance: 'none'
  4039. },
  4040. /*
  4041. 1. Correct the inability to style clickable types in iOS and Safari.
  4042. 2. Change font properties to `inherit` in Safari.
  4043. */
  4044. '::-webkit-file-upload-button': {
  4045. WebkitAppearance: 'button',
  4046. /* 1 */font: 'inherit'
  4047. },
  4048. /* 2 */ /*
  4049. Add the correct display in Chrome and Safari.
  4050. */summary: {
  4051. display: 'list-item'
  4052. },
  4053. /*
  4054. Removes the default spacing and border for appropriate elements.
  4055. */
  4056. 'blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre': {
  4057. margin: '0'
  4058. },
  4059. fieldset: {
  4060. margin: '0',
  4061. padding: '0'
  4062. },
  4063. legend: {
  4064. padding: '0'
  4065. },
  4066. 'ol,ul,menu': {
  4067. listStyle: 'none',
  4068. margin: '0',
  4069. padding: '0'
  4070. },
  4071. /*
  4072. Prevent resizing textareas horizontally by default.
  4073. */
  4074. textarea: {
  4075. resize: 'vertical'
  4076. },
  4077. /*
  4078. 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
  4079. 2. Set the default placeholder color to the user's configured gray 400 color.
  4080. */
  4081. 'input::placeholder,textarea::placeholder': {
  4082. opacity: 1,
  4083. /* 1 */color: 'theme(colors.gray.400, #9ca3af)'
  4084. },
  4085. /* 2 */ /*
  4086. Set the default cursor for buttons.
  4087. */'button,[role="button"]': {
  4088. cursor: 'pointer'
  4089. },
  4090. /*
  4091. Make sure disabled buttons don't get the pointer cursor.
  4092. */
  4093. ':disabled': {
  4094. cursor: 'default'
  4095. },
  4096. /*
  4097. 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
  4098. 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
  4099. This can trigger a poorly considered lint error in some tools but is included by design.
  4100. */
  4101. 'img,svg,video,canvas,audio,iframe,embed,object': {
  4102. display: 'block',
  4103. /* 1 */verticalAlign: 'middle'
  4104. },
  4105. /* 2 */ /*
  4106. Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
  4107. */'img,video': {
  4108. maxWidth: '100%',
  4109. height: 'auto'
  4110. },
  4111. /* Make elements with the HTML hidden attribute stay hidden by default */'[hidden]': {
  4112. display: 'none'
  4113. }
  4114. };
  4115.  
  4116. // indirection wrapper to remove autocomplete functions from production bundles
  4117. let rules = [/* arbitrary properties: [paint-order:markers] */match('\\[([-\\w]+):(.+)]', ({
  4118. 1: $1,
  4119. 2: $2
  4120. }, context) => ({
  4121. '@layer overrides': {
  4122. '&': {
  4123. [$1]: arbitrary(`[${$2}]`, '', context)
  4124. }
  4125. }
  4126. })), /* Styling based on parent and peer state */match('(group|peer)([~/][^-[]+)?', ({
  4127. input
  4128. }, {
  4129. h
  4130. }) => [{
  4131. c: h(input)
  4132. }]), /* LAYOUT */matchTheme('aspect-', 'aspectRatio'), match('container', (_, {
  4133. theme
  4134. }) => {
  4135. let {
  4136. screens = theme('screens'),
  4137. center,
  4138. padding
  4139. } = theme('container'),
  4140. rules = {
  4141. width: '100%',
  4142. marginRight: center && 'auto',
  4143. marginLeft: center && 'auto',
  4144. ...paddingFor('xs')
  4145. };
  4146. for (let screen in screens) {
  4147. let value = screens[screen];
  4148. 'string' == typeof value && (rules[mql(value)] = {
  4149. '&': {
  4150. maxWidth: value,
  4151. ...paddingFor(screen)
  4152. }
  4153. });
  4154. }
  4155. return rules;
  4156. function paddingFor(screen) {
  4157. let value = padding && ('string' == typeof padding ? padding : padding[screen] || padding.DEFAULT);
  4158. if (value) return {
  4159. paddingRight: value,
  4160. paddingLeft: value
  4161. };
  4162. }
  4163. }),
  4164. // Content
  4165. matchTheme('content-', 'content', ({
  4166. _
  4167. }) => ({
  4168. '--tw-content': _,
  4169. content: 'var(--tw-content)'
  4170. })),
  4171. // Box Decoration Break
  4172. match('(?:box-)?decoration-(slice|clone)', 'boxDecorationBreak'),
  4173. // Box Sizing
  4174. match('box-(border|content)', 'boxSizing', ({
  4175. 1: $1
  4176. }) => $1 + '-box'),
  4177. // Display
  4178. match('hidden', {
  4179. display: 'none'
  4180. }),
  4181. // Table Layout
  4182. match('table-(auto|fixed)', 'tableLayout'), match(['(block|flex|table|grid|inline|contents|flow-root|list-item)', '(inline-(block|flex|table|grid))', '(table-(caption|cell|column|row|(column|row|footer|header)-group))'], 'display'),
  4183. // Floats
  4184. '(float)-(left|right|none)',
  4185. // Clear
  4186. '(clear)-(left|right|none|both)',
  4187. // Overflow
  4188. '(overflow(?:-[xy])?)-(auto|hidden|clip|visible|scroll)',
  4189. // Isolation
  4190. '(isolation)-(auto)',
  4191. // Isolation
  4192. match('isolate', 'isolation'),
  4193. // Object Fit
  4194. match('object-(contain|cover|fill|none|scale-down)', 'objectFit'),
  4195. // Object Position
  4196. matchTheme('object-', 'objectPosition'), match('object-(top|bottom|center|(left|right)(-(top|bottom))?)', 'objectPosition', spacify),
  4197. // Overscroll Behavior
  4198. match('overscroll(-[xy])?-(auto|contain|none)', ({
  4199. 1: $1 = '',
  4200. 2: $2
  4201. }) => ({
  4202. ['overscroll-behavior' + $1]: $2
  4203. })),
  4204. // Position
  4205. match('(static|fixed|absolute|relative|sticky)', 'position'),
  4206. // Top / Right / Bottom / Left
  4207. matchTheme('-?inset(-[xy])?(?:$|-)', 'inset', ({
  4208. 1: $1,
  4209. _
  4210. }) => ({
  4211. top: '-x' != $1 && _,
  4212. right: '-y' != $1 && _,
  4213. bottom: '-x' != $1 && _,
  4214. left: '-y' != $1 && _
  4215. })), matchTheme('-?(top|bottom|left|right)(?:$|-)', 'inset'),
  4216. // Visibility
  4217. match('(visible|collapse)', 'visibility'), match('invisible', {
  4218. visibility: 'hidden'
  4219. }),
  4220. // Z-Index
  4221. matchTheme('-?z-', 'zIndex'), /* FLEXBOX */ // Flex Direction
  4222. match('flex-((row|col)(-reverse)?)', 'flexDirection', columnify), match('flex-(wrap|wrap-reverse|nowrap)', 'flexWrap'), matchTheme('(flex-(?:grow|shrink))(?:$|-)'), /*, 'flex-grow' | flex-shrink */matchTheme('(flex)-'), /*, 'flex' */matchTheme('grow(?:$|-)', 'flexGrow'), matchTheme('shrink(?:$|-)', 'flexShrink'), matchTheme('basis-', 'flexBasis'), matchTheme('-?(order)-'), /*, 'order' */'-?(order)-(\\d+)', /* GRID */ // Grid Template Columns
  4223. matchTheme('grid-cols-', 'gridTemplateColumns'), match('grid-cols-(\\d+)', 'gridTemplateColumns', gridTemplate),
  4224. // Grid Column Start / End
  4225. matchTheme('col-', 'gridColumn'), match('col-(span)-(\\d+)', 'gridColumn', span), matchTheme('col-start-', 'gridColumnStart'), match('col-start-(auto|\\d+)', 'gridColumnStart'), matchTheme('col-end-', 'gridColumnEnd'), match('col-end-(auto|\\d+)', 'gridColumnEnd'),
  4226. // Grid Template Rows
  4227. matchTheme('grid-rows-', 'gridTemplateRows'), match('grid-rows-(\\d+)', 'gridTemplateRows', gridTemplate),
  4228. // Grid Row Start / End
  4229. matchTheme('row-', 'gridRow'), match('row-(span)-(\\d+)', 'gridRow', span), matchTheme('row-start-', 'gridRowStart'), match('row-start-(auto|\\d+)', 'gridRowStart'), matchTheme('row-end-', 'gridRowEnd'), match('row-end-(auto|\\d+)', 'gridRowEnd'),
  4230. // Grid Auto Flow
  4231. match('grid-flow-((row|col)(-dense)?)', 'gridAutoFlow', match => spacify(columnify(match))), match('grid-flow-(dense)', 'gridAutoFlow'),
  4232. // Grid Auto Columns
  4233. matchTheme('auto-cols-', 'gridAutoColumns'),
  4234. // Grid Auto Rows
  4235. matchTheme('auto-rows-', 'gridAutoRows'),
  4236. // Gap
  4237. matchTheme('gap-x(?:$|-)', 'gap', 'columnGap'), matchTheme('gap-y(?:$|-)', 'gap', 'rowGap'), matchTheme('gap(?:$|-)', 'gap'), /* BOX ALIGNMENT */ // Justify Items
  4238. // Justify Self
  4239. '(justify-(?:items|self))-',
  4240. // Justify Content
  4241. match('justify-', 'justifyContent', convertContentValue),
  4242. // Align Content
  4243. // Align Items
  4244. // Align Self
  4245. match('(content|items|self)-', match => ({
  4246. ['align-' + match[1]]: convertContentValue(match)
  4247. })),
  4248. // Place Content
  4249. // Place Items
  4250. // Place Self
  4251. match('(place-(content|items|self))-', ({
  4252. 1: $1,
  4253. $$
  4254. }) => ({
  4255. [$1]: ('wun'.includes($$[3]) ? 'space-' : '') + $$
  4256. })), /* SPACING */ // Padding
  4257. matchTheme('p([xytrbl])?(?:$|-)', 'padding', edge('padding')),
  4258. // Margin
  4259. matchTheme('-?m([xytrbl])?(?:$|-)', 'margin', edge('margin')),
  4260. // Space Between
  4261. matchTheme('-?space-(x|y)(?:$|-)', 'space', ({
  4262. 1: $1,
  4263. _
  4264. }) => ({
  4265. '&>:not([hidden])~:not([hidden])': {
  4266. [`--tw-space-${$1}-reverse`]: '0',
  4267. ['margin-' + {
  4268. y: 'top',
  4269. x: 'left'
  4270. }[$1]]: `calc(${_} * calc(1 - var(--tw-space-${$1}-reverse)))`,
  4271. ['margin-' + {
  4272. y: 'bottom',
  4273. x: 'right'
  4274. }[$1]]: `calc(${_} * var(--tw-space-${$1}-reverse))`
  4275. }
  4276. })), match('space-(x|y)-reverse', ({
  4277. 1: $1
  4278. }) => ({
  4279. '&>:not([hidden])~:not([hidden])': {
  4280. [`--tw-space-${$1}-reverse`]: '1'
  4281. }
  4282. })), /* SIZING */ // Width
  4283. matchTheme('w-', 'width'),
  4284. // Min-Width
  4285. matchTheme('min-w-', 'minWidth'),
  4286. // Max-Width
  4287. matchTheme('max-w-', 'maxWidth'),
  4288. // Height
  4289. matchTheme('h-', 'height'),
  4290. // Min-Height
  4291. matchTheme('min-h-', 'minHeight'),
  4292. // Max-Height
  4293. matchTheme('max-h-', 'maxHeight'), /* TYPOGRAPHY */ // Font Weight
  4294. matchTheme('font-', 'fontWeight'),
  4295. // Font Family
  4296. matchTheme('font-', 'fontFamily', ({
  4297. _
  4298. }) => {
  4299. return 'string' == typeof (_ = asArray(_))[1] ? {
  4300. fontFamily: join(_)
  4301. } : {
  4302. fontFamily: join(_[0]),
  4303. ..._[1]
  4304. };
  4305. }),
  4306. // Font Smoothing
  4307. match('antialiased', {
  4308. WebkitFontSmoothing: 'antialiased',
  4309. MozOsxFontSmoothing: 'grayscale'
  4310. }), match('subpixel-antialiased', {
  4311. WebkitFontSmoothing: 'auto',
  4312. MozOsxFontSmoothing: 'auto'
  4313. }),
  4314. // Font Style
  4315. match('italic', 'fontStyle'), match('not-italic', {
  4316. fontStyle: 'normal'
  4317. }),
  4318. // Font Variant Numeric
  4319. match('(ordinal|slashed-zero|(normal|lining|oldstyle|proportional|tabular)-nums|(diagonal|stacked)-fractions)', ({
  4320. 1: $1,
  4321. 2: $2 = '',
  4322. 3: $3
  4323. }) =>
  4324. // normal-nums
  4325. 'normal' == $2 ? {
  4326. fontVariantNumeric: 'normal'
  4327. } : {
  4328. ['--tw-' + ($3 ?
  4329. // diagonal-fractions, stacked-fractions
  4330. 'numeric-fraction' : 'pt'.includes($2[0]) ?
  4331. // proportional-nums, tabular-nums
  4332. 'numeric-spacing' : $2 ?
  4333. // lining-nums, oldstyle-nums
  4334. 'numeric-figure' :
  4335. // ordinal, slashed-zero
  4336. $1)]: $1,
  4337. fontVariantNumeric: 'var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)',
  4338. ...asDefaults({
  4339. '--tw-ordinal': 'var(--tw-empty,/*!*/ /*!*/)',
  4340. '--tw-slashed-zero': 'var(--tw-empty,/*!*/ /*!*/)',
  4341. '--tw-numeric-figure': 'var(--tw-empty,/*!*/ /*!*/)',
  4342. '--tw-numeric-spacing': 'var(--tw-empty,/*!*/ /*!*/)',
  4343. '--tw-numeric-fraction': 'var(--tw-empty,/*!*/ /*!*/)'
  4344. })
  4345. }),
  4346. // Letter Spacing
  4347. matchTheme('tracking-', 'letterSpacing'),
  4348. // Line Height
  4349. matchTheme('leading-', 'lineHeight'),
  4350. // List Style Position
  4351. match('list-(inside|outside)', 'listStylePosition'),
  4352. // List Style Type
  4353. matchTheme('list-', 'listStyleType'), match('list-', 'listStyleType'),
  4354. // Placeholder Opacity
  4355. matchTheme('placeholder-opacity-', 'placeholderOpacity', ({
  4356. _
  4357. }) => ({
  4358. '&::placeholder': {
  4359. '--tw-placeholder-opacity': _
  4360. }
  4361. })),
  4362. // Placeholder Color
  4363. matchColor('placeholder-', {
  4364. property: 'color',
  4365. selector: '&::placeholder'
  4366. }),
  4367. // Text Alignment
  4368. match('text-(left|center|right|justify|start|end)', 'textAlign'), match('text-(ellipsis|clip)', 'textOverflow'),
  4369. // Text Opacity
  4370. matchTheme('text-opacity-', 'textOpacity', '--tw-text-opacity'),
  4371. // Text Color
  4372. matchColor('text-', {
  4373. property: 'color'
  4374. }),
  4375. // Font Size
  4376. matchTheme('text-', 'fontSize', ({
  4377. _
  4378. }) => 'string' == typeof _ ? {
  4379. fontSize: _
  4380. } : {
  4381. fontSize: _[0],
  4382. ...('string' == typeof _[1] ? {
  4383. lineHeight: _[1]
  4384. } : _[1])
  4385. }),
  4386. // Text Indent
  4387. matchTheme('indent-', 'textIndent'),
  4388. // Text Decoration
  4389. match('(overline|underline|line-through)', 'textDecorationLine'), match('no-underline', {
  4390. textDecorationLine: 'none'
  4391. }),
  4392. // Text Underline offset
  4393. matchTheme('underline-offset-', 'textUnderlineOffset'),
  4394. // Text Decoration Color
  4395. matchColor('decoration-', {
  4396. section: 'textDecorationColor',
  4397. opacityVariable: false,
  4398. opacitySection: 'opacity'
  4399. }),
  4400. // Text Decoration Thickness
  4401. matchTheme('decoration-', 'textDecorationThickness'),
  4402. // Text Decoration Style
  4403. match('decoration-', 'textDecorationStyle'),
  4404. // Text Transform
  4405. match('(uppercase|lowercase|capitalize)', 'textTransform'), match('normal-case', {
  4406. textTransform: 'none'
  4407. }),
  4408. // Text Overflow
  4409. match('truncate', {
  4410. overflow: 'hidden',
  4411. whiteSpace: 'nowrap',
  4412. textOverflow: 'ellipsis'
  4413. }),
  4414. // Vertical Alignment
  4415. match('align-', 'verticalAlign'),
  4416. // Whitespace
  4417. match('whitespace-', 'whiteSpace'),
  4418. // Word Break
  4419. match('break-normal', {
  4420. wordBreak: 'normal',
  4421. overflowWrap: 'normal'
  4422. }), match('break-words', {
  4423. overflowWrap: 'break-word'
  4424. }), match('break-all', {
  4425. wordBreak: 'break-all'
  4426. }), match('break-keep', {
  4427. wordBreak: 'keep-all'
  4428. }),
  4429. // Caret Color
  4430. matchColor('caret-', {
  4431. // section: 'caretColor',
  4432. opacityVariable: false,
  4433. opacitySection: 'opacity'
  4434. }),
  4435. // Accent Color
  4436. matchColor('accent-', {
  4437. // section: 'accentColor',
  4438. opacityVariable: false,
  4439. opacitySection: 'opacity'
  4440. }),
  4441. // Gradient Color Stops
  4442. match('bg-gradient-to-([trbl]|[tb][rl])', 'backgroundImage', ({
  4443. 1: $1
  4444. }) => `linear-gradient(to ${position($1, ' ')},var(--tw-gradient-stops))`), matchColor('from-', {
  4445. section: 'gradientColorStops',
  4446. opacityVariable: false,
  4447. opacitySection: 'opacity'
  4448. }, ({
  4449. _
  4450. }) => ({
  4451. '--tw-gradient-from': _.value,
  4452. '--tw-gradient-to': _.color({
  4453. opacityValue: '0'
  4454. }),
  4455. '--tw-gradient-stops': "var(--tw-gradient-from),var(--tw-gradient-to)"
  4456. })), matchColor('via-', {
  4457. section: 'gradientColorStops',
  4458. opacityVariable: false,
  4459. opacitySection: 'opacity'
  4460. }, ({
  4461. _
  4462. }) => ({
  4463. '--tw-gradient-to': _.color({
  4464. opacityValue: '0'
  4465. }),
  4466. '--tw-gradient-stops': `var(--tw-gradient-from),${_.value},var(--tw-gradient-to)`
  4467. })), matchColor('to-', {
  4468. section: 'gradientColorStops',
  4469. property: '--tw-gradient-to',
  4470. opacityVariable: false,
  4471. opacitySection: 'opacity'
  4472. }), /* BACKGROUNDS */ // Background Attachment
  4473. match('bg-(fixed|local|scroll)', 'backgroundAttachment'),
  4474. // Background Origin
  4475. match('bg-origin-(border|padding|content)', 'backgroundOrigin', ({
  4476. 1: $1
  4477. }) => $1 + '-box'),
  4478. // Background Repeat
  4479. match(['bg-(no-repeat|repeat(-[xy])?)', 'bg-repeat-(round|space)'], 'backgroundRepeat'),
  4480. // Background Blend Mode
  4481. match('bg-blend-', 'backgroundBlendMode'),
  4482. // Background Clip
  4483. match('bg-clip-(border|padding|content|text)', 'backgroundClip', ({
  4484. 1: $1
  4485. }) => $1 + ('text' == $1 ? '' : '-box')),
  4486. // Background Opacity
  4487. matchTheme('bg-opacity-', 'backgroundOpacity', '--tw-bg-opacity'),
  4488. // Background Color
  4489. // bg-${backgroundColor}/${backgroundOpacity}
  4490. matchColor('bg-', {
  4491. section: 'backgroundColor'
  4492. }),
  4493. // Background Image
  4494. // supported arbitrary types are: length, color, angle, list
  4495. matchTheme('bg-', 'backgroundImage'),
  4496. // Background Position
  4497. matchTheme('bg-', 'backgroundPosition'), match('bg-(top|bottom|center|(left|right)(-(top|bottom))?)', 'backgroundPosition', spacify),
  4498. // Background Size
  4499. matchTheme('bg-', 'backgroundSize'), /* BORDERS */ // Border Radius
  4500. matchTheme('rounded(?:$|-)', 'borderRadius'), matchTheme('rounded-([trbl]|[tb][rl])(?:$|-)', 'borderRadius', ({
  4501. 1: $1,
  4502. _
  4503. }) => {
  4504. let corners = {
  4505. t: ['tl', 'tr'],
  4506. r: ['tr', 'br'],
  4507. b: ['bl', 'br'],
  4508. l: ['bl', 'tl']
  4509. }[$1] || [$1, $1];
  4510. return {
  4511. [`border-${position(corners[0])}-radius`]: _,
  4512. [`border-${position(corners[1])}-radius`]: _
  4513. };
  4514. }),
  4515. // Border Collapse
  4516. match('border-(collapse|separate)', 'borderCollapse'),
  4517. // Border Opacity
  4518. matchTheme('border-opacity(?:$|-)', 'borderOpacity', '--tw-border-opacity'),
  4519. // Border Style
  4520. match('border-(solid|dashed|dotted|double|none)', 'borderStyle'),
  4521. // Border Spacing
  4522. matchTheme('border-spacing(-[xy])?(?:$|-)', 'borderSpacing', ({
  4523. 1: $1,
  4524. _
  4525. }) => ({
  4526. ...asDefaults({
  4527. '--tw-border-spacing-x': '0',
  4528. '--tw-border-spacing-y': '0'
  4529. }),
  4530. ['--tw-border-spacing' + ($1 || '-x')]: _,
  4531. ['--tw-border-spacing' + ($1 || '-y')]: _,
  4532. 'border-spacing': 'var(--tw-border-spacing-x) var(--tw-border-spacing-y)'
  4533. })),
  4534. // Border Color
  4535. matchColor('border-([xytrbl])-', {
  4536. section: 'borderColor'
  4537. }, edge('border', 'Color')), matchColor('border-'),
  4538. // Border Width
  4539. matchTheme('border-([xytrbl])(?:$|-)', 'borderWidth', edge('border', 'Width')), matchTheme('border(?:$|-)', 'borderWidth'),
  4540. // Divide Opacity
  4541. matchTheme('divide-opacity(?:$|-)', 'divideOpacity', ({
  4542. _
  4543. }) => ({
  4544. '&>:not([hidden])~:not([hidden])': {
  4545. '--tw-divide-opacity': _
  4546. }
  4547. })),
  4548. // Divide Style
  4549. match('divide-(solid|dashed|dotted|double|none)', ({
  4550. 1: $1
  4551. }) => ({
  4552. '&>:not([hidden])~:not([hidden])': {
  4553. borderStyle: $1
  4554. }
  4555. })),
  4556. // Divide Width
  4557. match('divide-([xy]-reverse)', ({
  4558. 1: $1
  4559. }) => ({
  4560. '&>:not([hidden])~:not([hidden])': {
  4561. ['--tw-divide-' + $1]: '1'
  4562. }
  4563. })), matchTheme('divide-([xy])(?:$|-)', 'divideWidth', ({
  4564. 1: $1,
  4565. _
  4566. }) => {
  4567. let edges = {
  4568. x: 'lr',
  4569. y: 'tb'
  4570. }[$1];
  4571. return {
  4572. '&>:not([hidden])~:not([hidden])': {
  4573. [`--tw-divide-${$1}-reverse`]: '0',
  4574. [`border-${position(edges[0])}Width`]: `calc(${_} * calc(1 - var(--tw-divide-${$1}-reverse)))`,
  4575. [`border-${position(edges[1])}Width`]: `calc(${_} * var(--tw-divide-${$1}-reverse))`
  4576. }
  4577. };
  4578. }),
  4579. // Divide Color
  4580. matchColor('divide-', {
  4581. // section: $0.replace('-', 'Color') -> 'divideColor'
  4582. property: 'borderColor',
  4583. // opacityVariable: '--tw-border-opacity',
  4584. // opacitySection: section.replace('Color', 'Opacity') -> 'divideOpacity'
  4585. selector: '&>:not([hidden])~:not([hidden])'
  4586. }),
  4587. // Ring Offset Opacity
  4588. matchTheme('ring-opacity(?:$|-)', 'ringOpacity', '--tw-ring-opacity'),
  4589. // Ring Offset Color
  4590. matchColor('ring-offset-', {
  4591. // section: 'ringOffsetColor',
  4592. property: '--tw-ring-offset-color',
  4593. opacityVariable: false
  4594. }),
  4595. // opacitySection: section.replace('Color', 'Opacity') -> 'ringOffsetOpacity'
  4596. // Ring Offset Width
  4597. matchTheme('ring-offset(?:$|-)', 'ringOffsetWidth', '--tw-ring-offset-width'),
  4598. // Ring Inset
  4599. match('ring-inset', {
  4600. '--tw-ring-inset': 'inset'
  4601. }),
  4602. // Ring Color
  4603. matchColor('ring-', {
  4604. // section: 'ringColor',
  4605. property: '--tw-ring-color'
  4606. }),
  4607. // opacityVariable: '--tw-ring-opacity',
  4608. // opacitySection: section.replace('Color', 'Opacity') -> 'ringOpacity'
  4609. // Ring Width
  4610. matchTheme('ring(?:$|-)', 'ringWidth', ({
  4611. _
  4612. }, {
  4613. theme
  4614. }) => ({
  4615. ...asDefaults({
  4616. '--tw-ring-offset-shadow': '0 0 #0000',
  4617. '--tw-ring-shadow': '0 0 #0000',
  4618. '--tw-shadow': '0 0 #0000',
  4619. '--tw-shadow-colored': '0 0 #0000',
  4620. // Within own declaration to have the defaults above to be merged with defaults from shadow
  4621. '&': {
  4622. '--tw-ring-inset': 'var(--tw-empty,/*!*/ /*!*/)',
  4623. '--tw-ring-offset-width': theme('ringOffsetWidth', '', '0px'),
  4624. '--tw-ring-offset-color': toColorValue(theme('ringOffsetColor', '', '#fff')),
  4625. '--tw-ring-color': toColorValue(theme('ringColor', '', '#93c5fd'), {
  4626. opacityVariable: '--tw-ring-opacity'
  4627. }),
  4628. '--tw-ring-opacity': theme('ringOpacity', '', '0.5')
  4629. }
  4630. }),
  4631. '--tw-ring-offset-shadow': "var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)",
  4632. '--tw-ring-shadow': `var(--tw-ring-inset) 0 0 0 calc(${_} + var(--tw-ring-offset-width)) var(--tw-ring-color)`,
  4633. boxShadow: "var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)"
  4634. })), /* EFFECTS */ // Box Shadow Color
  4635. matchColor('shadow-', {
  4636. section: 'boxShadowColor',
  4637. opacityVariable: false,
  4638. opacitySection: 'opacity'
  4639. }, ({
  4640. _
  4641. }) => ({
  4642. '--tw-shadow-color': _.value,
  4643. '--tw-shadow': 'var(--tw-shadow-colored)'
  4644. })),
  4645. // Box Shadow
  4646. matchTheme('shadow(?:$|-)', 'boxShadow', ({
  4647. _
  4648. }) => ({
  4649. ...asDefaults({
  4650. '--tw-ring-offset-shadow': '0 0 #0000',
  4651. '--tw-ring-shadow': '0 0 #0000',
  4652. '--tw-shadow': '0 0 #0000',
  4653. '--tw-shadow-colored': '0 0 #0000'
  4654. }),
  4655. '--tw-shadow': join(_),
  4656. // replace all colors with reference to --tw-shadow-colored
  4657. // this matches colors after non-comma char (keyword, offset) before comma or the end
  4658. '--tw-shadow-colored': join(_).replace(/([^,]\s+)(?:#[a-f\d]+|(?:(?:hsl|rgb)a?|hwb|lab|lch|color|var)\(.+?\)|[a-z]+)(,|$)/g, '$1var(--tw-shadow-color)$2'),
  4659. boxShadow: "var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)"
  4660. })),
  4661. // Opacity
  4662. matchTheme('(opacity)-'), /*, 'opacity' */ // Mix Blend Mode
  4663. match('mix-blend-', 'mixBlendMode'), /* FILTERS */...filter(), ...filter('backdrop-'), /* TRANSITIONS AND ANIMATION */ // Transition Property
  4664. matchTheme('transition(?:$|-)', 'transitionProperty', (match, {
  4665. theme
  4666. }) => ({
  4667. transitionProperty: join(match),
  4668. transitionTimingFunction: 'none' == match._ ? void 0 : join(theme('transitionTimingFunction', '')),
  4669. transitionDuration: 'none' == match._ ? void 0 : join(theme('transitionDuration', ''))
  4670. })),
  4671. // Transition Duration
  4672. matchTheme('duration(?:$|-)', 'transitionDuration', 'transitionDuration', join),
  4673. // Transition Timing Function
  4674. matchTheme('ease(?:$|-)', 'transitionTimingFunction', 'transitionTimingFunction', join),
  4675. // Transition Delay
  4676. matchTheme('delay(?:$|-)', 'transitionDelay', 'transitionDelay', join), matchTheme('animate(?:$|-)', 'animation', (match, {
  4677. theme,
  4678. h,
  4679. e
  4680. }) => {
  4681. let animation = join(match),
  4682. // Try to auto inject keyframes
  4683. parts = animation.split(' '),
  4684. keyframeValues = theme('keyframes', parts[0]);
  4685. return keyframeValues ? {
  4686. ['@keyframes ' + (parts[0] = e(h(parts[0])))]: keyframeValues,
  4687. animation: parts.join(' ')
  4688. } : {
  4689. animation
  4690. };
  4691. }), /* TRANSFORMS */ // Transform
  4692. '(transform)-(none)', match('transform', tranformDefaults), match('transform-(cpu|gpu)', ({
  4693. 1: $1
  4694. }) => ({
  4695. '--tw-transform': transformValue('gpu' == $1)
  4696. })),
  4697. // Scale
  4698. matchTheme('scale(-[xy])?-', 'scale', ({
  4699. 1: $1,
  4700. _
  4701. }) => ({
  4702. ['--tw-scale' + ($1 || '-x')]: _,
  4703. ['--tw-scale' + ($1 || '-y')]: _,
  4704. ...tranformDefaults()
  4705. })),
  4706. // Rotate
  4707. matchTheme('-?(rotate)-', 'rotate', transform),
  4708. // Translate
  4709. matchTheme('-?(translate-[xy])-', 'translate', transform),
  4710. // Skew
  4711. matchTheme('-?(skew-[xy])-', 'skew', transform),
  4712. // Transform Origin
  4713. match('origin-(center|((top|bottom)(-(left|right))?)|left|right)', 'transformOrigin', spacify), /* INTERACTIVITY */ // Appearance
  4714. '(appearance)-',
  4715. // Columns
  4716. matchTheme('(columns)-'), /*, 'columns' */'(columns)-(\\d+)',
  4717. // Break Before, After and Inside
  4718. '(break-(?:before|after|inside))-',
  4719. // Cursor
  4720. matchTheme('(cursor)-'), /*, 'cursor' */'(cursor)-',
  4721. // Scroll Snap Type
  4722. match('snap-(none)', 'scroll-snap-type'), match('snap-(x|y|both)', ({
  4723. 1: $1
  4724. }) => ({
  4725. ...asDefaults({
  4726. '--tw-scroll-snap-strictness': 'proximity'
  4727. }),
  4728. 'scroll-snap-type': $1 + ' var(--tw-scroll-snap-strictness)'
  4729. })), match('snap-(mandatory|proximity)', '--tw-scroll-snap-strictness'),
  4730. // Scroll Snap Align
  4731. match('snap-(?:(start|end|center)|align-(none))', 'scroll-snap-align'),
  4732. // Scroll Snap Stop
  4733. match('snap-(normal|always)', 'scroll-snap-stop'), match('scroll-(auto|smooth)', 'scroll-behavior'),
  4734. // Scroll Margin
  4735. // Padding
  4736. matchTheme('scroll-p([xytrbl])?(?:$|-)', 'padding', edge('scroll-padding')),
  4737. // Margin
  4738. matchTheme('-?scroll-m([xytrbl])?(?:$|-)', 'scroll-margin', edge('scroll-margin')),
  4739. // Touch Action
  4740. match('touch-(auto|none|manipulation)', 'touch-action'), match('touch-(pinch-zoom|pan-(?:(x|left|right)|(y|up|down)))', ({
  4741. 1: $1,
  4742. 2: $2,
  4743. 3: $3
  4744. }) => ({
  4745. ...asDefaults({
  4746. '--tw-pan-x': 'var(--tw-empty,/*!*/ /*!*/)',
  4747. '--tw-pan-y': 'var(--tw-empty,/*!*/ /*!*/)',
  4748. '--tw-pinch-zoom': 'var(--tw-empty,/*!*/ /*!*/)',
  4749. '--tw-touch-action': 'var(--tw-pan-x) var(--tw-pan-y) var(--tw-pinch-zoom)'
  4750. }),
  4751. // x, left, right -> pan-x
  4752. // y, up, down -> pan-y
  4753. // -> pinch-zoom
  4754. [`--tw-${$2 ? 'pan-x' : $3 ? 'pan-y' : $1}`]: $1,
  4755. 'touch-action': 'var(--tw-touch-action)'
  4756. })),
  4757. // Outline Style
  4758. match('outline-none', {
  4759. outline: '2px solid transparent',
  4760. 'outline-offset': '2px'
  4761. }), match('outline', {
  4762. outlineStyle: 'solid'
  4763. }), match('outline-(dashed|dotted|double)', 'outlineStyle'),
  4764. // Outline Offset
  4765. matchTheme('-?(outline-offset)-'), /*, 'outlineOffset'*/ // Outline Color
  4766. matchColor('outline-', {
  4767. opacityVariable: false,
  4768. opacitySection: 'opacity'
  4769. }),
  4770. // Outline Width
  4771. matchTheme('outline-', 'outlineWidth'),
  4772. // Pointer Events
  4773. '(pointer-events)-',
  4774. // Will Change
  4775. matchTheme('(will-change)-'), /*, 'willChange' */'(will-change)-',
  4776. // Resize
  4777. ['resize(?:-(none|x|y))?', 'resize', ({
  4778. 1: $1
  4779. }) => ({
  4780. x: 'horizontal',
  4781. y: 'vertical'
  4782. })[$1] || $1 || 'both'],
  4783. // User Select
  4784. match('select-(none|text|all|auto)', 'userSelect'), /* SVG */ // Fill, Stroke
  4785. matchColor('fill-', {
  4786. section: 'fill',
  4787. opacityVariable: false,
  4788. opacitySection: 'opacity'
  4789. }), matchColor('stroke-', {
  4790. section: 'stroke',
  4791. opacityVariable: false,
  4792. opacitySection: 'opacity'
  4793. }),
  4794. // Stroke Width
  4795. matchTheme('stroke-', 'strokeWidth'), /* ACCESSIBILITY */ // Screen Readers
  4796. match('sr-only', {
  4797. position: 'absolute',
  4798. width: '1px',
  4799. height: '1px',
  4800. padding: '0',
  4801. margin: '-1px',
  4802. overflow: 'hidden',
  4803. whiteSpace: 'nowrap',
  4804. clip: 'rect(0,0,0,0)',
  4805. borderWidth: '0'
  4806. }), match('not-sr-only', {
  4807. position: 'static',
  4808. width: 'auto',
  4809. height: 'auto',
  4810. padding: '0',
  4811. margin: '0',
  4812. overflow: 'visible',
  4813. whiteSpace: 'normal',
  4814. clip: 'auto'
  4815. })];
  4816. function spacify(value) {
  4817. return ('string' == typeof value ? value : value[1]).replace(/-/g, ' ').trim();
  4818. }
  4819. function columnify(value) {
  4820. return ('string' == typeof value ? value : value[1]).replace('col', 'column');
  4821. }
  4822. function position(shorthand, separator = '-') {
  4823. let longhand = [];
  4824. for (let short of shorthand) longhand.push({
  4825. t: 'top',
  4826. r: 'right',
  4827. b: 'bottom',
  4828. l: 'left'
  4829. }[short]);
  4830. return longhand.join(separator);
  4831. }
  4832. function join(value) {
  4833. return value && '' + (value._ || value);
  4834. }
  4835. function convertContentValue({
  4836. $$
  4837. }) {
  4838. return ({
  4839. // /* aut*/ o: '',
  4840. /* sta*/
  4841. r: /*t*/'flex-',
  4842. /* end*/'': 'flex-',
  4843. // /* cen*/ t /*er*/: '',
  4844. /* bet*/
  4845. w: /*een*/'space-',
  4846. /* aro*/u: /*nd*/'space-',
  4847. /* eve*/n: /*ly*/'space-'
  4848. }[$$[3] || ''] || '') + $$;
  4849. }
  4850. function edge(propertyPrefix, propertySuffix = '') {
  4851. return ({
  4852. 1: $1,
  4853. _
  4854. }) => {
  4855. let edges = {
  4856. x: 'lr',
  4857. y: 'tb'
  4858. }[$1] || $1 + $1;
  4859. return edges ? {
  4860. ...toCSS(propertyPrefix + '-' + position(edges[0]) + propertySuffix, _),
  4861. ...toCSS(propertyPrefix + '-' + position(edges[1]) + propertySuffix, _)
  4862. } : toCSS(propertyPrefix + propertySuffix, _);
  4863. };
  4864. }
  4865. function filter(prefix = '') {
  4866. let filters = ['blur', 'brightness', 'contrast', 'grayscale', 'hue-rotate', 'invert', prefix && 'opacity', 'saturate', 'sepia', !prefix && 'drop-shadow'].filter(Boolean),
  4867. defaults = {};
  4868. // first create properties defaults
  4869. for (let key of filters) defaults[`--tw-${prefix}${key}`] = 'var(--tw-empty,/*!*/ /*!*/)';
  4870. return defaults = {
  4871. // move defaults
  4872. ...asDefaults(defaults),
  4873. // add default filter which allows standalone usage
  4874. [`${prefix}filter`]: filters.map(key => `var(--tw-${prefix}${key})`).join(' ')
  4875. }, [`(${prefix}filter)-(none)`, match(`${prefix}filter`, defaults), ...filters.map(key => matchTheme(
  4876. // hue-rotate can be negated
  4877. `${'h' == key[0] ? '-?' : ''}(${prefix}${key})(?:$|-)`, key, ({
  4878. 1: $1,
  4879. _
  4880. }) => ({
  4881. [`--tw-${$1}`]: asArray(_).map(value => `${key}(${value})`).join(' '),
  4882. ...defaults
  4883. })))];
  4884. }
  4885. function transform({
  4886. 1: $1,
  4887. _
  4888. }) {
  4889. return {
  4890. ['--tw-' + $1]: _,
  4891. ...tranformDefaults()
  4892. };
  4893. }
  4894. function tranformDefaults() {
  4895. return {
  4896. ...asDefaults({
  4897. '--tw-translate-x': '0',
  4898. '--tw-translate-y': '0',
  4899. '--tw-rotate': '0',
  4900. '--tw-skew-x': '0',
  4901. '--tw-skew-y': '0',
  4902. '--tw-scale-x': '1',
  4903. '--tw-scale-y': '1',
  4904. '--tw-transform': transformValue()
  4905. }),
  4906. transform: 'var(--tw-transform)'
  4907. };
  4908. }
  4909. function transformValue(gpu) {
  4910. return [gpu ?
  4911. // -gpu
  4912. 'translate3d(var(--tw-translate-x),var(--tw-translate-y),0)' : 'translateX(var(--tw-translate-x)) translateY(var(--tw-translate-y))', 'rotate(var(--tw-rotate))', 'skewX(var(--tw-skew-x))', 'skewY(var(--tw-skew-y))', 'scaleX(var(--tw-scale-x))', 'scaleY(var(--tw-scale-y))'].join(' ');
  4913. }
  4914. function span({
  4915. 1: $1,
  4916. 2: $2
  4917. }) {
  4918. return `${$1} ${$2} / ${$1} ${$2}`;
  4919. }
  4920. function gridTemplate({
  4921. 1: $1
  4922. }) {
  4923. return `repeat(${$1},minmax(0,1fr))`;
  4924. }
  4925. function asDefaults(props) {
  4926. return {
  4927. '@layer defaults': {
  4928. '*,::before,::after': props,
  4929. '::backdrop': props
  4930. }
  4931. };
  4932. }
  4933.  
  4934. // indirection wrapper to remove autocomplete functions from production bundles
  4935. let variants = [['sticky', '@supports ((position: -webkit-sticky) or (position:sticky))'], ['motion-reduce', '@media (prefers-reduced-motion:reduce)'], ['motion-safe', '@media (prefers-reduced-motion:no-preference)'], ['print', '@media print'], ['(portrait|landscape)', ({
  4936. 1: $1
  4937. }) => `@media (orientation:${$1})`], ['contrast-(more|less)', ({
  4938. 1: $1
  4939. }) => `@media (prefers-contrast:${$1})`], ['(first-(letter|line)|placeholder|backdrop|before|after)', ({
  4940. 1: $1
  4941. }) => `&::${$1}`], ['(marker|selection)', ({
  4942. 1: $1
  4943. }) => `& *::${$1},&::${$1}`], ['file', '&::file-selector-button'], ['(first|last|only)', ({
  4944. 1: $1
  4945. }) => `&:${$1}-child`], ['even', '&:nth-child(2n)'], ['odd', '&:nth-child(odd)'], ['open', '&[open]'],
  4946. // All other pseudo classes are already supported by twind
  4947. ['(aria|data)-', ({
  4948. 1: $1,
  4949. /* aria or data */$$
  4950. }, /* everything after the dash */context) => $$ && `&[${$1}-${// aria-asc or data-checked -> from theme
  4951. context.theme($1, $$) ||
  4952. // aria-[...] or data-[...]
  4953. arbitrary($$, '', context) ||
  4954. // default handling
  4955. `${$$}="true"`}]`], /* Styling based on parent and peer state */ // Groups classes like: group-focus and group-hover
  4956. // these need to add a marker selector with the pseudo class
  4957. // => '.group:focus .group-focus:selector'
  4958. ['((group|peer)(~[^-[]+)?)(-\\[(.+)]|[-[].+?)(\\/.+)?', ({
  4959. 2: type,
  4960. 3: name = '',
  4961. 4: $4,
  4962. 5: $5 = '',
  4963. 6: label = name
  4964. }, {
  4965. e,
  4966. h,
  4967. v
  4968. }) => {
  4969. let selector = normalize($5) || ('[' == $4[0] ? $4 : v($4.slice(1)));
  4970. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  4971. return `${(selector.includes('&') ? selector : '&' + selector).replace(/&/g, `:merge(.${e(h(type + label))})`)}${'p' == type[0] ? '~' : ' '}&`;
  4972. }],
  4973. // direction variants
  4974. ['(ltr|rtl)', ({
  4975. 1: $1
  4976. }) => `[dir="${$1}"] &`], ['supports-', ({
  4977. $$
  4978. }, /* everything after the dash */context) => {
  4979. $$ && ($$ = context.theme('supports', $$) || arbitrary($$, '', context));
  4980. if ($$) return $$.includes(':') || ($$ += ':var(--tw)'), /^\w*\s*\(/.test($$) || ($$ = `(${$$})`),
  4981. // Chrome has a bug where `(condtion1)or(condition2)` is not valid
  4982. // But `(condition1) or (condition2)` is supported.
  4983. `@supports ${$$.replace(/\b(and|or|not)\b/g, ' $1 ').trim()}`;
  4984. }], ['max-', ({
  4985. $$
  4986. }, context) => {
  4987. $$ && ($$ = context.theme('screens', $$) || arbitrary($$, '', context));
  4988. if ('string' == typeof $$) return `@media not all and (min-width:${$$})`;
  4989. }], ['min-', ({
  4990. $$
  4991. }, context) => {
  4992. return $$ && ($$ = arbitrary($$, '', context)), $$ && `@media (min-width:${$$})`;
  4993. }],
  4994. // Arbitrary variants
  4995. [/^\[(.+)]$/, ({
  4996. 1: $1
  4997. }) => /[&@]/.test($1) && normalize($1).replace(/[}]+$/, '').split('{')]];
  4998.  
  4999. /** Allows to disable to tailwind preflight (default: `false` eg include the tailwind preflight ) */ /**
  5000. * @experimental
  5001. */
  5002. function presetTailwindBase({
  5003. colors,
  5004. disablePreflight
  5005. } = {}) {
  5006. return {
  5007. // allow other preflight to run
  5008. preflight: disablePreflight ? void 0 : preflight,
  5009. theme: {
  5010. ...theme,
  5011. colors: {
  5012. inherit: 'inherit',
  5013. current: 'currentColor',
  5014. transparent: 'transparent',
  5015. black: '#000',
  5016. white: '#fff',
  5017. ...colors
  5018. }
  5019. },
  5020. variants,
  5021. rules,
  5022. finalize(rule) {
  5023. return (
  5024. // automatically add `content: ''` to before and after so you don’t have to specify it unless you want a different value
  5025. // ignore global, preflight, and auto added rules
  5026. rule.n &&
  5027. // only if there are declarations
  5028. rule.d &&
  5029. // and it has a ::before or ::after selector
  5030. rule.r.some(r => /^&::(before|after)$/.test(r)) &&
  5031. // there is no content property yet
  5032. !/(^|;)content:/.test(rule.d) ? {
  5033. ...rule,
  5034. d: 'content:var(--tw-content);' + rule.d
  5035. } : rule
  5036. );
  5037. }
  5038. };
  5039. }
  5040.  
  5041. // Source from https://github.com/tailwindlabs/tailwindcss/blob/master/src/public/colors.js
  5042. /**
  5043. * @module @twind/preset-tailwind/colors
  5044. */let slate = {
  5045. 50: '#f8fafc',
  5046. 100: '#f1f5f9',
  5047. 200: '#e2e8f0',
  5048. 300: '#cbd5e1',
  5049. 400: '#94a3b8',
  5050. 500: '#64748b',
  5051. 600: '#475569',
  5052. 700: '#334155',
  5053. 800: '#1e293b',
  5054. 900: '#0f172a'
  5055. },
  5056. gray = {
  5057. 50: '#f9fafb',
  5058. 100: '#f3f4f6',
  5059. 200: '#e5e7eb',
  5060. 300: '#d1d5db',
  5061. 400: '#9ca3af',
  5062. 500: '#6b7280',
  5063. 600: '#4b5563',
  5064. 700: '#374151',
  5065. 800: '#1f2937',
  5066. 900: '#111827'
  5067. },
  5068. zinc = {
  5069. 50: '#fafafa',
  5070. 100: '#f4f4f5',
  5071. 200: '#e4e4e7',
  5072. 300: '#d4d4d8',
  5073. 400: '#a1a1aa',
  5074. 500: '#71717a',
  5075. 600: '#52525b',
  5076. 700: '#3f3f46',
  5077. 800: '#27272a',
  5078. 900: '#18181b'
  5079. },
  5080. neutral = {
  5081. 50: '#fafafa',
  5082. 100: '#f5f5f5',
  5083. 200: '#e5e5e5',
  5084. 300: '#d4d4d4',
  5085. 400: '#a3a3a3',
  5086. 500: '#737373',
  5087. 600: '#525252',
  5088. 700: '#404040',
  5089. 800: '#262626',
  5090. 900: '#171717'
  5091. },
  5092. stone = {
  5093. 50: '#fafaf9',
  5094. 100: '#f5f5f4',
  5095. 200: '#e7e5e4',
  5096. 300: '#d6d3d1',
  5097. 400: '#a8a29e',
  5098. 500: '#78716c',
  5099. 600: '#57534e',
  5100. 700: '#44403c',
  5101. 800: '#292524',
  5102. 900: '#1c1917'
  5103. },
  5104. red = {
  5105. 50: '#fef2f2',
  5106. 100: '#fee2e2',
  5107. 200: '#fecaca',
  5108. 300: '#fca5a5',
  5109. 400: '#f87171',
  5110. 500: '#ef4444',
  5111. 600: '#dc2626',
  5112. 700: '#b91c1c',
  5113. 800: '#991b1b',
  5114. 900: '#7f1d1d'
  5115. },
  5116. orange = {
  5117. 50: '#fff7ed',
  5118. 100: '#ffedd5',
  5119. 200: '#fed7aa',
  5120. 300: '#fdba74',
  5121. 400: '#fb923c',
  5122. 500: '#f97316',
  5123. 600: '#ea580c',
  5124. 700: '#c2410c',
  5125. 800: '#9a3412',
  5126. 900: '#7c2d12'
  5127. },
  5128. amber = {
  5129. 50: '#fffbeb',
  5130. 100: '#fef3c7',
  5131. 200: '#fde68a',
  5132. 300: '#fcd34d',
  5133. 400: '#fbbf24',
  5134. 500: '#f59e0b',
  5135. 600: '#d97706',
  5136. 700: '#b45309',
  5137. 800: '#92400e',
  5138. 900: '#78350f'
  5139. },
  5140. yellow = {
  5141. 50: '#fefce8',
  5142. 100: '#fef9c3',
  5143. 200: '#fef08a',
  5144. 300: '#fde047',
  5145. 400: '#facc15',
  5146. 500: '#eab308',
  5147. 600: '#ca8a04',
  5148. 700: '#a16207',
  5149. 800: '#854d0e',
  5150. 900: '#713f12'
  5151. },
  5152. lime = {
  5153. 50: '#f7fee7',
  5154. 100: '#ecfccb',
  5155. 200: '#d9f99d',
  5156. 300: '#bef264',
  5157. 400: '#a3e635',
  5158. 500: '#84cc16',
  5159. 600: '#65a30d',
  5160. 700: '#4d7c0f',
  5161. 800: '#3f6212',
  5162. 900: '#365314'
  5163. },
  5164. green = {
  5165. 50: '#f0fdf4',
  5166. 100: '#dcfce7',
  5167. 200: '#bbf7d0',
  5168. 300: '#86efac',
  5169. 400: '#4ade80',
  5170. 500: '#22c55e',
  5171. 600: '#16a34a',
  5172. 700: '#15803d',
  5173. 800: '#166534',
  5174. 900: '#14532d'
  5175. },
  5176. emerald = {
  5177. 50: '#ecfdf5',
  5178. 100: '#d1fae5',
  5179. 200: '#a7f3d0',
  5180. 300: '#6ee7b7',
  5181. 400: '#34d399',
  5182. 500: '#10b981',
  5183. 600: '#059669',
  5184. 700: '#047857',
  5185. 800: '#065f46',
  5186. 900: '#064e3b'
  5187. },
  5188. teal = {
  5189. 50: '#f0fdfa',
  5190. 100: '#ccfbf1',
  5191. 200: '#99f6e4',
  5192. 300: '#5eead4',
  5193. 400: '#2dd4bf',
  5194. 500: '#14b8a6',
  5195. 600: '#0d9488',
  5196. 700: '#0f766e',
  5197. 800: '#115e59',
  5198. 900: '#134e4a'
  5199. },
  5200. cyan = {
  5201. 50: '#ecfeff',
  5202. 100: '#cffafe',
  5203. 200: '#a5f3fc',
  5204. 300: '#67e8f9',
  5205. 400: '#22d3ee',
  5206. 500: '#06b6d4',
  5207. 600: '#0891b2',
  5208. 700: '#0e7490',
  5209. 800: '#155e75',
  5210. 900: '#164e63'
  5211. },
  5212. sky = {
  5213. 50: '#f0f9ff',
  5214. 100: '#e0f2fe',
  5215. 200: '#bae6fd',
  5216. 300: '#7dd3fc',
  5217. 400: '#38bdf8',
  5218. 500: '#0ea5e9',
  5219. 600: '#0284c7',
  5220. 700: '#0369a1',
  5221. 800: '#075985',
  5222. 900: '#0c4a6e'
  5223. },
  5224. blue = {
  5225. 50: '#eff6ff',
  5226. 100: '#dbeafe',
  5227. 200: '#bfdbfe',
  5228. 300: '#93c5fd',
  5229. 400: '#60a5fa',
  5230. 500: '#3b82f6',
  5231. 600: '#2563eb',
  5232. 700: '#1d4ed8',
  5233. 800: '#1e40af',
  5234. 900: '#1e3a8a'
  5235. },
  5236. indigo = {
  5237. 50: '#eef2ff',
  5238. 100: '#e0e7ff',
  5239. 200: '#c7d2fe',
  5240. 300: '#a5b4fc',
  5241. 400: '#818cf8',
  5242. 500: '#6366f1',
  5243. 600: '#4f46e5',
  5244. 700: '#4338ca',
  5245. 800: '#3730a3',
  5246. 900: '#312e81'
  5247. },
  5248. violet = {
  5249. 50: '#f5f3ff',
  5250. 100: '#ede9fe',
  5251. 200: '#ddd6fe',
  5252. 300: '#c4b5fd',
  5253. 400: '#a78bfa',
  5254. 500: '#8b5cf6',
  5255. 600: '#7c3aed',
  5256. 700: '#6d28d9',
  5257. 800: '#5b21b6',
  5258. 900: '#4c1d95'
  5259. },
  5260. purple = {
  5261. 50: '#faf5ff',
  5262. 100: '#f3e8ff',
  5263. 200: '#e9d5ff',
  5264. 300: '#d8b4fe',
  5265. 400: '#c084fc',
  5266. 500: '#a855f7',
  5267. 600: '#9333ea',
  5268. 700: '#7e22ce',
  5269. 800: '#6b21a8',
  5270. 900: '#581c87'
  5271. },
  5272. fuchsia = {
  5273. 50: '#fdf4ff',
  5274. 100: '#fae8ff',
  5275. 200: '#f5d0fe',
  5276. 300: '#f0abfc',
  5277. 400: '#e879f9',
  5278. 500: '#d946ef',
  5279. 600: '#c026d3',
  5280. 700: '#a21caf',
  5281. 800: '#86198f',
  5282. 900: '#701a75'
  5283. },
  5284. pink = {
  5285. 50: '#fdf2f8',
  5286. 100: '#fce7f3',
  5287. 200: '#fbcfe8',
  5288. 300: '#f9a8d4',
  5289. 400: '#f472b6',
  5290. 500: '#ec4899',
  5291. 600: '#db2777',
  5292. 700: '#be185d',
  5293. 800: '#9d174d',
  5294. 900: '#831843'
  5295. },
  5296. rose = {
  5297. 50: '#fff1f2',
  5298. 100: '#ffe4e6',
  5299. 200: '#fecdd3',
  5300. 300: '#fda4af',
  5301. 400: '#fb7185',
  5302. 500: '#f43f5e',
  5303. 600: '#e11d48',
  5304. 700: '#be123c',
  5305. 800: '#9f1239',
  5306. 900: '#881337'
  5307. },
  5308. // get lightBlue() {
  5309. // warn({ version: 'v2.2', from: 'lightBlue', to: 'sky' })
  5310. // return this.sky
  5311. // }
  5312. // get warmGray() {
  5313. // warn({ version: 'v3.0', from: 'warmGray', to: 'stone' })
  5314. // return this.stone
  5315. // }
  5316. // get trueGray() {
  5317. // warn({ version: 'v3.0', from: 'trueGray', to: 'neutral' })
  5318. // return this.neutral
  5319. // }
  5320. // get coolGray() {
  5321. // warn({ version: 'v3.0', from: 'coolGray', to: 'gray' })
  5322. // return this.gray
  5323. // }
  5324. // get blueGray() {
  5325. // warn({ version: 'v3.0', from: 'blueGray', to: 'slate' })
  5326. // return this.slate
  5327. // }
  5328. colors = {
  5329. __proto__: null,
  5330. slate,
  5331. gray,
  5332. zinc,
  5333. neutral,
  5334. stone,
  5335. red,
  5336. orange,
  5337. amber,
  5338. yellow,
  5339. lime,
  5340. green,
  5341. emerald,
  5342. teal,
  5343. cyan,
  5344. sky,
  5345. blue,
  5346. indigo,
  5347. violet,
  5348. purple,
  5349. fuchsia,
  5350. pink,
  5351. rose
  5352. };
  5353.  
  5354. /** Allows to disable to tailwind preflight (default: `false` eg include the tailwind preflight ) */
  5355. function presetTailwind({
  5356. disablePreflight
  5357. } = {}) {
  5358. return presetTailwindBase({
  5359. colors,
  5360. disablePreflight
  5361. });
  5362. }
  5363.  
  5364. const tw = twind({
  5365. preflight: false,
  5366. hash: (className, defaultHash) => {
  5367. return `tw-${defaultHash(className).slice(1)}`;
  5368. },
  5369. presets: [presetAutoprefix(), presetTailwind({
  5370. disablePreflight: true
  5371. })]
  5372. }, dom());
  5373.  
  5374. const _tmpl$$c = /*#__PURE__*/template(`<div><div> edition, v</div><div></div><div></div><div><button>`),
  5375. _tmpl$2$3 = /*#__PURE__*/template(`<a target="_blank" rel="noopener noreferrer">`),
  5376. _tmpl$3$3 = /*#__PURE__*/template(`<div>`),
  5377. _tmpl$4$3 = /*#__PURE__*/template(`<div><div></div><div><select>`),
  5378. _tmpl$5$3 = /*#__PURE__*/template(`<option>`);
  5379. const detectResOptionsMap = {
  5380. S: () => "1024px",
  5381. M: () => "1536px",
  5382. L: () => "2048px",
  5383. X: () => "2560px"
  5384. };
  5385. const detectResOptions = Object.keys(detectResOptionsMap);
  5386. const renderTextDirOptionsMap = {
  5387. auto: t$1("settings.render-text-orientation-options.auto"),
  5388. h: t$1("settings.render-text-orientation-options.horizontal"),
  5389. v: t$1("settings.render-text-orientation-options.vertical")
  5390. };
  5391. const renderTextDirOptions = Object.keys(renderTextDirOptionsMap);
  5392. const textDetectorOptionsMap = {
  5393. default: t$1("settings.text-detector-options.default"),
  5394. ctd: () => "Comic Text Detector"
  5395. };
  5396. const textDetectorOptions = Object.keys(textDetectorOptionsMap);
  5397. const translatorOptionsMap = {
  5398. "gpt3.5": () => "GPT-3.5",
  5399. "youdao": () => "Youdao",
  5400. "baidu": () => "Baidu",
  5401. "google": () => "Google",
  5402. "deepl": () => "DeepL",
  5403. "papago": () => "Papago",
  5404. "offline": () => "Sugoi / NLLB",
  5405. "none": t$1("settings.translator-options.none")
  5406. };
  5407. const translatorOptions = Object.keys(translatorOptionsMap);
  5408. const targetLangOptionsMap = {
  5409. "": t$1("settings.target-language-options.auto"),
  5410. "CHS": () => "简体中文",
  5411. "CHT": () => "繁體中文",
  5412. "JPN": () => "日本語",
  5413. "ENG": () => "English",
  5414. "KOR": () => "한국어",
  5415. "VIN": () => "Tiếng Việt",
  5416. "CSY": () => "čeština",
  5417. "NLD": () => "Nederlands",
  5418. "FRA": () => "français",
  5419. "DEU": () => "Deutsch",
  5420. "HUN": () => "magyar nyelv",
  5421. "ITA": () => "italiano",
  5422. "PLK": () => "polski",
  5423. "PTB": () => "português",
  5424. "ROM": () => "limba română",
  5425. "RUS": () => "русский язык",
  5426. "UKR": () => "українська мова",
  5427. "ESP": () => "español",
  5428. "TRK": () => "Türk dili"
  5429. };
  5430. const scriptLangOptionsMap = {
  5431. "": t$1("settings.script-language-options.auto"),
  5432. "zh-CN": () => "简体中文",
  5433. "en-US": () => "English"
  5434. };
  5435. const keepInstancesOptionsMap = {
  5436. "until-reload": t$1("settings.keep-instances-options.until-reload"),
  5437. "until-navigate": t$1("settings.keep-instances-options.until-navigate")
  5438. };
  5439. const Settings = props => {
  5440. const itemOrientation = () => props.itemOrientation ?? "vertical";
  5441. const textStyle = () => props.textStyle ?? {};
  5442. return (() => {
  5443. const _el$ = _tmpl$$c(),
  5444. _el$2 = _el$.firstChild,
  5445. _el$3 = _el$2.firstChild,
  5446. _el$4 = _el$2.nextSibling,
  5447. _el$5 = _el$4.nextSibling,
  5448. _el$6 = _el$5.nextSibling,
  5449. _el$7 = _el$6.firstChild;
  5450. insert(_el$2, EDITION, _el$3);
  5451. insert(_el$2, VERSION, null);
  5452. insert(_el$4, t$1("sponsor.text"));
  5453. insert(_el$5, createComponent(For, {
  5454. each: [["ko-fi", "https://ko-fi.com/voilelabs"], ["Patreon", "https://patreon.com/voilelabs"], ["爱发电", "https://afdian.net/@voilelabs"]],
  5455. children: ([name, url]) => [" ", (() => {
  5456. const _el$8 = _tmpl$2$3();
  5457. setAttribute(_el$8, "href", url);
  5458. insert(_el$8, name);
  5459. createRenderEffect(() => className(_el$8, tw("no-underline text-blue-600")));
  5460. return _el$8;
  5461. })()]
  5462. }));
  5463. insert(_el$, createComponent(For, {
  5464. get each() {
  5465. return [[t$1("settings.detection-resolution"), detectionResolution, setDetectionResolution, detectResOptionsMap, t$1("settings.detection-resolution-desc")], [t$1("settings.text-detector"), textDetector, setTextDetector, textDetectorOptionsMap, t$1("settings.text-detector-desc")], [t$1("settings.translator"), translatorService, setTranslatorService, translatorOptionsMap, t$1("settings.translator-desc")], [t$1("settings.render-text-orientation"), renderTextOrientation, setRenderTextOrientation, renderTextDirOptionsMap, t$1("settings.render-text-orientation-desc")], [t$1("settings.target-language"), targetLang, setTargetLang, targetLangOptionsMap, t$1("settings.target-language-desc")], [t$1("settings.script-language"), scriptLang, setScriptLang, scriptLangOptionsMap, t$1("settings.script-language-desc")], [t$1("settings.keep-instances"), keepInstances, setKeepInstances, keepInstancesOptionsMap, t$1("settings.keep-instances-desc")]];
  5466. },
  5467. children: ([title, opt, setOpt, optMap, desc]) => (() => {
  5468. const _el$9 = _tmpl$4$3(),
  5469. _el$10 = _el$9.firstChild,
  5470. _el$11 = _el$10.nextSibling,
  5471. _el$12 = _el$11.firstChild;
  5472. insert(_el$10, title);
  5473. _el$12.addEventListener("change", e => setOpt(e.target.value));
  5474. insert(_el$12, () => Object.entries(optMap).map(([value, label]) => (() => {
  5475. const _el$14 = _tmpl$5$3();
  5476. _el$14.value = value;
  5477. insert(_el$14, label);
  5478. return _el$14;
  5479. })()));
  5480. insert(_el$11, createComponent(Show, {
  5481. get when() {
  5482. return desc();
  5483. },
  5484. get children() {
  5485. const _el$13 = _tmpl$3$3();
  5486. insert(_el$13, desc);
  5487. createRenderEffect(() => className(_el$13, tw("text-sm")));
  5488. return _el$13;
  5489. }
  5490. }), null);
  5491. createRenderEffect(_p$ => {
  5492. const _v$ = itemOrientation() === "horizontal" ? tw("flex items-center") : "",
  5493. _v$2 = textStyle();
  5494. _v$ !== _p$._v$ && className(_el$9, _p$._v$ = _v$);
  5495. _p$._v$2 = style(_el$10, _v$2, _p$._v$2);
  5496. return _p$;
  5497. }, {
  5498. _v$: undefined,
  5499. _v$2: undefined
  5500. });
  5501. createRenderEffect(() => _el$12.value = opt());
  5502. return _el$9;
  5503. })()
  5504. }), _el$6);
  5505. _el$7.addEventListener("click", e => {
  5506. e.stopPropagation();
  5507. e.preventDefault();
  5508. setDetectionResolution(null);
  5509. setTextDetector(null);
  5510. setTranslatorService(null);
  5511. setRenderTextOrientation(null);
  5512. setTargetLang(null);
  5513. setScriptLang(null);
  5514. });
  5515. insert(_el$7, t$1("settings.reset"));
  5516. createRenderEffect(() => className(_el$, tw("flex flex-col gap-2")));
  5517. return _el$;
  5518. })();
  5519. };
  5520.  
  5521. function formatSize(bytes) {
  5522. const k = 1024;
  5523. const sizes = ["B", "KB", "MB", "GB", "TB"];
  5524. if (bytes === 0) return "0B";
  5525. const i = Math.floor(Math.log(bytes) / Math.log(k));
  5526. return `${(bytes / k ** i).toFixed(2)}${sizes[i]}`;
  5527. }
  5528. function formatProgress(loaded, total) {
  5529. return `${formatSize(loaded)}/${formatSize(total)}`;
  5530. }
  5531. function assert(condition, message) {
  5532. if (!condition) throw new Error(message);
  5533. }
  5534.  
  5535. async function resizeToSubmit(blob, suffix) {
  5536. const blobUrl = URL.createObjectURL(blob);
  5537. const img = await new Promise((resolve, reject) => {
  5538. const img2 = new Image();
  5539. img2.onload = () => resolve(img2);
  5540. img2.onerror = err => reject(err);
  5541. img2.src = blobUrl;
  5542. });
  5543. URL.revokeObjectURL(blobUrl);
  5544. const w = img.width;
  5545. const h = img.height;
  5546. if (w <= 4096 && h <= 4096) return {
  5547. blob,
  5548. suffix
  5549. };
  5550. const scale = Math.min(4096 / w, 4096 / h);
  5551. const width = Math.floor(w * scale);
  5552. const height = Math.floor(h * scale);
  5553. const canvas = document.createElement("canvas");
  5554. canvas.width = width;
  5555. canvas.height = height;
  5556. const ctx = canvas.getContext("2d");
  5557. ctx.imageSmoothingQuality = "high";
  5558. ctx.drawImage(img, 0, 0, width, height);
  5559. const newBlob = await new Promise((resolve, reject) => {
  5560. canvas.toBlob(blob2 => {
  5561. if (blob2) resolve(blob2);else reject(new Error("Canvas toBlob failed"));
  5562. }, "image/png");
  5563. });
  5564. return {
  5565. blob: newBlob,
  5566. suffix: "png"
  5567. };
  5568. }
  5569. async function submitTranslate(blob, suffix, listeners = {}, optionsOverwrite) {
  5570. const {
  5571. onProgress,
  5572. onFinal
  5573. } = listeners;
  5574. const formData = new FormData();
  5575. formData.append("file", blob, `image.${suffix}`);
  5576. formData.append("target_language", targetLang() || BCP47ToISO639(realLang()));
  5577. formData.append("detector", optionsOverwrite?.textDetector ?? textDetector());
  5578. formData.append("direction", optionsOverwrite?.renderTextOrientation ?? renderTextOrientation());
  5579. formData.append("translator", optionsOverwrite?.translator ?? translatorService());
  5580. formData.append("size", optionsOverwrite?.detectionResolution ?? detectionResolution());
  5581. formData.append("retry", optionsOverwrite?.forceRetry ? "true" : "false");
  5582. const result = await GMP.xmlHttpRequest({
  5583. method: "POST",
  5584. url: "https://api.cotrans.touhou.ai/task/upload/v1",
  5585. // @ts-expect-error FormData is supported
  5586. data: formData,
  5587. upload: {
  5588. onprogress: onProgress || onFinal ? e => {
  5589. if (e.lengthComputable) {
  5590. if (e.loaded >= e.total - 16) {
  5591. onFinal?.();
  5592. } else {
  5593. const p = formatProgress(e.loaded, e.total);
  5594. onProgress?.(p);
  5595. }
  5596. }
  5597. } : void 0
  5598. }
  5599. });
  5600. return JSON.parse(result.responseText);
  5601. }
  5602. function getStatusText(msg) {
  5603. if (msg.type === "pending") return t$1("common.status.pending-pos", {
  5604. pos: msg.pos
  5605. });
  5606. if (msg.type === "status") return t$1(`common.status.${msg.status}`);
  5607. return t$1("common.status.default");
  5608. }
  5609. function pullTranslationStatus(id, cb) {
  5610. const ws = new WebSocket(`wss://api.cotrans.touhou.ai/task/${id}/event/v1`);
  5611. return new Promise((resolve, reject) => {
  5612. ws.onmessage = e => {
  5613. const msg = JSON.parse(e.data);
  5614. if (msg.type === "result") resolve(msg.result);else if (msg.type === "error") reject(t$1("common.status.error-with-id", {
  5615. id: msg.error_id
  5616. }));else cb(getStatusText(msg));
  5617. };
  5618. });
  5619. }
  5620. async function pullTranslationStatusPolling(id, cb) {
  5621. while (true) {
  5622. const res = await GMP.xmlHttpRequest({
  5623. method: "GET",
  5624. url: `https://api.cotrans.touhou.ai/task/${id}/status/v1`
  5625. });
  5626. const msg = JSON.parse(res.responseText);
  5627. if (msg.type === "result") return msg.result;else if (msg.type === "error") throw t$1("common.status.error-with-id", {
  5628. id: msg.error_id
  5629. });else cb(getStatusText(msg));
  5630. await new Promise(resolve => setTimeout(resolve, 1e3));
  5631. }
  5632. }
  5633. async function downloadBlob(url, listeners = {}) {
  5634. const {
  5635. onProgress
  5636. } = listeners;
  5637. const res = await GMP.xmlHttpRequest({
  5638. method: "GET",
  5639. responseType: "blob",
  5640. url,
  5641. onprogress: onProgress ? e => {
  5642. if (e.lengthComputable) {
  5643. const p = formatProgress(e.loaded, e.total);
  5644. onProgress(p);
  5645. }
  5646. } : void 0
  5647. });
  5648. return res.response;
  5649. }
  5650.  
  5651. const _tmpl$$b = /*#__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">`);
  5652. const IconCarbonTranslate = ((props = {}) => (() => {
  5653. const _el$ = _tmpl$$b();
  5654. spread(_el$, props, true, true);
  5655. return _el$;
  5656. })());
  5657.  
  5658. const _tmpl$$a = /*#__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">`);
  5659. const IconCarbonReset = ((props = {}) => (() => {
  5660. const _el$ = _tmpl$$a();
  5661. spread(_el$, props, true, true);
  5662. return _el$;
  5663. })());
  5664.  
  5665. const _tmpl$$9 = /*#__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">`);
  5666. const IconCarbonChevronRight = ((props = {}) => (() => {
  5667. const _el$ = _tmpl$$9();
  5668. spread(_el$, props, true, true);
  5669. return _el$;
  5670. })());
  5671.  
  5672. const _tmpl$$8 = /*#__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">`);
  5673. const IconCarbonChevronLeft = ((props = {}) => (() => {
  5674. const _el$ = _tmpl$$8();
  5675. spread(_el$, props, true, true);
  5676. return _el$;
  5677. })());
  5678.  
  5679. const _tmpl$$7 = /*#__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">`);
  5680. const IconCarbonChevronDown = ((props = {}) => (() => {
  5681. const _el$ = _tmpl$$7();
  5682. spread(_el$, props, true, true);
  5683. return _el$;
  5684. })());
  5685.  
  5686. const _tmpl$$6 = /*#__PURE__*/template(`<div>`),
  5687. _tmpl$2$2 = /*#__PURE__*/template(`<div><div>`),
  5688. _tmpl$3$2 = /*#__PURE__*/template(`<div><label><input type="checkbox">`),
  5689. _tmpl$4$2 = /*#__PURE__*/template(`<div><div><div><div></div></div></div><div>`),
  5690. _tmpl$5$2 = /*#__PURE__*/template(`<div><div></div><div><select>`),
  5691. _tmpl$6 = /*#__PURE__*/template(`<option>`),
  5692. _tmpl$7 = /*#__PURE__*/template(`<div data-transall="true">`);
  5693. function mount$4() {
  5694. const images = /* @__PURE__ */new Set();
  5695. const instances = new ReactiveMap();
  5696. const translatedMap = /* @__PURE__ */new Map();
  5697. const translateEnabledMap = /* @__PURE__ */new Map();
  5698. function findImageNodes(node) {
  5699. 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"));
  5700. }
  5701. function rescanImages() {
  5702. const imageNodes = findImageNodes(document.body);
  5703. const removedImages = new Set(images);
  5704. for (const node of imageNodes) {
  5705. removedImages.delete(node);
  5706. if (images.has(node)) continue;
  5707. try {
  5708. instances.set(node, createRoot(dispose => {
  5709. const instance = createInstance(node);
  5710. return {
  5711. ...instance,
  5712. dispose
  5713. };
  5714. }));
  5715. images.add(node);
  5716. } catch (e) {}
  5717. }
  5718. for (const node of removedImages) {
  5719. if (!instances.has(node)) continue;
  5720. const instance = instances.get(node);
  5721. instance.dispose();
  5722. instances.delete(node);
  5723. images.delete(node);
  5724. }
  5725. }
  5726. function createInstance(imageNode) {
  5727. const src = imageNode.getAttribute("src");
  5728. const srcset = imageNode.getAttribute("srcset");
  5729. const parent = imageNode.parentElement;
  5730. if (!parent) throw new Error("no parent");
  5731. const originalSrc = parent.getAttribute("href") || src;
  5732. const originalSrcSuffix = originalSrc.split(".").pop();
  5733. let originalImage;
  5734. let translatedImage = translatedMap.get(originalSrc);
  5735. const [translateMounted, setTranslateMounted] = createSignal(false);
  5736. let buttonDisabled = false;
  5737. const [processing, setProcessing] = createSignal(false);
  5738. const [translated, setTranslated] = createSignal(false);
  5739. const [transStatus, setTransStatus] = createSignal(() => void 0);
  5740. parent.style.position = "relative";
  5741. const container = document.createElement("div");
  5742. parent.appendChild(container);
  5743. onCleanup(() => {
  5744. container.remove();
  5745. });
  5746. const disposeButton = render(() => {
  5747. const status = createMemo(() => transStatus()());
  5748. const [advancedMenuOpen, setAdvancedMenuOpen] = createSignal(false);
  5749. const [advDetectRes, setAdvDetectRes] = createSignal(detectionResolution());
  5750. const [advRenderTextDir, setAdvRenderTextDir] = createSignal(renderTextOrientation());
  5751. const [advTextDetector, setAdvTextDetector] = createSignal(textDetector());
  5752. const [advTranslator, setAdvTranslator] = createSignal(translatorService());
  5753. const [forceRetry, setForceRetry] = createSignal(false);
  5754. const [mouseInside, setMouseInside] = createSignal(false);
  5755. let mouseInsideTimeout;
  5756. const fullOpacity = createMemo(() => mouseInside() || advancedMenuOpen() || processing());
  5757. return (() => {
  5758. const _el$ = _tmpl$4$2(),
  5759. _el$2 = _el$.firstChild,
  5760. _el$3 = _el$2.firstChild,
  5761. _el$4 = _el$3.firstChild,
  5762. _el$5 = _el$2.nextSibling;
  5763. _el$.addEventListener("mouseout", () => {
  5764. if (!mouseInsideTimeout) {
  5765. mouseInsideTimeout = window.setTimeout(() => {
  5766. setMouseInside(false);
  5767. mouseInsideTimeout = void 0;
  5768. }, 400);
  5769. }
  5770. });
  5771. _el$.addEventListener("mouseover", () => {
  5772. if (mouseInsideTimeout) {
  5773. window.clearTimeout(mouseInsideTimeout);
  5774. mouseInsideTimeout = void 0;
  5775. }
  5776. setMouseInside(true);
  5777. });
  5778. _el$.addEventListener("click", e => {
  5779. e.stopPropagation();
  5780. e.preventDefault();
  5781. });
  5782. insert(_el$3, createComponent(Dynamic, {
  5783. get component() {
  5784. return translated() ? IconCarbonReset : IconCarbonTranslate;
  5785. },
  5786. get ["class"]() {
  5787. return tw("w-6 h-6 p-2 align-middle cursor-pointer");
  5788. },
  5789. onClick: e => {
  5790. e.stopPropagation();
  5791. e.preventDefault();
  5792. if (advancedMenuOpen()) return;
  5793. toggle();
  5794. },
  5795. onContextMenu: e => {
  5796. e.stopPropagation();
  5797. e.preventDefault();
  5798. if (translateMounted()) setAdvancedMenuOpen(false);else setAdvancedMenuOpen(v => !v);
  5799. }
  5800. }), _el$4);
  5801. insert(_el$5, createComponent(Show, {
  5802. get when() {
  5803. return !translateMounted();
  5804. },
  5805. get children() {
  5806. const _el$6 = _tmpl$$6();
  5807. insert(_el$6, createComponent(Switch, {
  5808. get children() {
  5809. return [createComponent(Match, {
  5810. get when() {
  5811. return status();
  5812. },
  5813. get children() {
  5814. const _el$7 = _tmpl$$6();
  5815. insert(_el$7, status);
  5816. createRenderEffect(() => className(_el$7, tw("px-1")));
  5817. return _el$7;
  5818. }
  5819. }), createComponent(Match, {
  5820. get when() {
  5821. return advancedMenuOpen();
  5822. },
  5823. get children() {
  5824. return [(() => {
  5825. const _el$8 = _tmpl$2$2(),
  5826. _el$9 = _el$8.firstChild;
  5827. _el$8.addEventListener("click", e => {
  5828. e.stopPropagation();
  5829. e.preventDefault();
  5830. setAdvancedMenuOpen(false);
  5831. });
  5832. insert(_el$8, createComponent(IconCarbonChevronLeft, {
  5833. get ["class"]() {
  5834. return tw("align-middle cursor-pointer");
  5835. }
  5836. }), _el$9);
  5837. insert(_el$9, t$1("settings.inline-options-title"));
  5838. createRenderEffect(() => className(_el$8, tw("flex items-center py-1")));
  5839. return _el$8;
  5840. })(), (() => {
  5841. const _el$10 = _tmpl$3$2(),
  5842. _el$11 = _el$10.firstChild,
  5843. _el$12 = _el$11.firstChild;
  5844. insert(_el$10, createComponent(For, {
  5845. get each() {
  5846. return [[t$1("settings.detection-resolution"), advDetectRes, setAdvDetectRes, detectResOptions, detectResOptionsMap], [t$1("settings.text-detector"), advTextDetector, setAdvTextDetector, textDetectorOptions, textDetectorOptionsMap], [t$1("settings.translator"), advTranslator, setAdvTranslator, translatorOptions, translatorOptionsMap], [t$1("settings.render-text-orientation"), advRenderTextDir, setAdvRenderTextDir, renderTextDirOptions, renderTextDirOptionsMap]];
  5847. },
  5848. children: ([title, opt, setOpt, opts, optMap]) => (() => {
  5849. const _el$14 = _tmpl$5$2(),
  5850. _el$15 = _el$14.firstChild,
  5851. _el$16 = _el$15.nextSibling,
  5852. _el$17 = _el$16.firstChild;
  5853. insert(_el$15, title);
  5854. _el$17.addEventListener("change", e => {
  5855. setOpt(e.target.value);
  5856. });
  5857. insert(_el$17, createComponent(For, {
  5858. each: opts,
  5859. children: opt2 => (() => {
  5860. const _el$18 = _tmpl$6();
  5861. _el$18.value = opt2;
  5862. insert(_el$18, () =>
  5863. // @ts-expect-error optMap are incompatible with each other
  5864. optMap[opt2]());
  5865. return _el$18;
  5866. })()
  5867. }));
  5868. insert(_el$16, createComponent(IconCarbonChevronDown, {
  5869. get ["class"]() {
  5870. return tw("absolute top-1 right-1 pointer-events-none");
  5871. }
  5872. }), null);
  5873. createRenderEffect(_p$ => {
  5874. const _v$9 = tw("relative px-1"),
  5875. _v$10 = tw("w-full py-1 appearance-none text-black border-x-0 border-t-0 border-b border-solid border-gray-600 bg-transparent");
  5876. _v$9 !== _p$._v$9 && className(_el$16, _p$._v$9 = _v$9);
  5877. _v$10 !== _p$._v$10 && className(_el$17, _p$._v$10 = _v$10);
  5878. return _p$;
  5879. }, {
  5880. _v$9: undefined,
  5881. _v$10: undefined
  5882. });
  5883. createRenderEffect(() => _el$17.value = opt());
  5884. return _el$14;
  5885. })()
  5886. }), _el$11);
  5887. _el$11.addEventListener("click", e => {
  5888. e.stopImmediatePropagation();
  5889. });
  5890. _el$12.addEventListener("change", e => {
  5891. setForceRetry(e.target.checked);
  5892. });
  5893. _el$12.checked = forceRetry();
  5894. insert(_el$11, t$1("settings.force-retry"), null);
  5895. createRenderEffect(_p$ => {
  5896. const _v$ = tw("flex flex-col w-48 gap-2 mx-2"),
  5897. _v$2 = tw("flex items-center cursor-pointer");
  5898. _v$ !== _p$._v$ && className(_el$10, _p$._v$ = _v$);
  5899. _v$2 !== _p$._v$2 && className(_el$11, _p$._v$2 = _v$2);
  5900. return _p$;
  5901. }, {
  5902. _v$: undefined,
  5903. _v$2: undefined
  5904. });
  5905. return _el$10;
  5906. })(), (() => {
  5907. const _el$13 = _tmpl$$6();
  5908. _el$13.addEventListener("click", e => {
  5909. e.stopPropagation();
  5910. e.preventDefault();
  5911. if (buttonDisabled) return;
  5912. if (translateMounted()) return;
  5913. enable({
  5914. detectionResolution: advDetectRes(),
  5915. renderTextOrientation: advRenderTextDir(),
  5916. textDetector: advTextDetector(),
  5917. translator: advTranslator(),
  5918. forceRetry: forceRetry()
  5919. });
  5920. setAdvancedMenuOpen(false);
  5921. });
  5922. insert(_el$13, t$1("common.control.translate"));
  5923. createRenderEffect(() => className(_el$13, tw("w-full mt-2 mb-1 py-1 border border-solid border-gray-600 rounded-full text-center cursor-pointer")));
  5924. return _el$13;
  5925. })()];
  5926. }
  5927. }), createComponent(Match, {
  5928. when: true,
  5929. get children() {
  5930. return createComponent(IconCarbonChevronRight, {
  5931. get ["class"]() {
  5932. return tw("py-1 align-middle cursor-pointer");
  5933. },
  5934. onClick: e => {
  5935. e.stopPropagation();
  5936. e.preventDefault();
  5937. setAdvancedMenuOpen(true);
  5938. }
  5939. });
  5940. }
  5941. })];
  5942. }
  5943. }));
  5944. createRenderEffect(() => className(_el$6, tw("flex flex-col text-base px-1 border-1 border-solid border-gray-300 rounded-2xl bg-white cursor-default")));
  5945. return _el$6;
  5946. }
  5947. }));
  5948. createRenderEffect(_p$ => {
  5949. const _v$3 = tw("absolute z-1 flex top-1 left-2 transition-opacity duration-80"),
  5950. _v$4 = {
  5951. [tw("opacity-100")]: fullOpacity(),
  5952. [tw("opacity-30")]: !fullOpacity()
  5953. },
  5954. _v$5 = tw("relative rounded-full bg-white"),
  5955. _v$6 = tw("absolute inset-0 border-1 border-solid rounded-full pointer-events-none"),
  5956. _v$7 = {
  5957. [tw("border-x-gray-300 border-b-gray-300 border-t-gray-600 animate-spin")]: processing(),
  5958. [tw("border-gray-300")]: !processing()
  5959. },
  5960. _v$8 = tw("-ml-2 mt-1.5");
  5961. _v$3 !== _p$._v$3 && className(_el$, _p$._v$3 = _v$3);
  5962. _p$._v$4 = classList(_el$, _v$4, _p$._v$4);
  5963. _v$5 !== _p$._v$5 && className(_el$3, _p$._v$5 = _v$5);
  5964. _v$6 !== _p$._v$6 && className(_el$4, _p$._v$6 = _v$6);
  5965. _p$._v$7 = classList(_el$4, _v$7, _p$._v$7);
  5966. _v$8 !== _p$._v$8 && className(_el$5, _p$._v$8 = _v$8);
  5967. return _p$;
  5968. }, {
  5969. _v$3: undefined,
  5970. _v$4: undefined,
  5971. _v$5: undefined,
  5972. _v$6: undefined,
  5973. _v$7: undefined,
  5974. _v$8: undefined
  5975. });
  5976. return _el$;
  5977. })();
  5978. }, container);
  5979. onCleanup(disposeButton);
  5980. async function getTranslatedImage(optionsOverwrite) {
  5981. if (!optionsOverwrite && translatedImage) return translatedImage;
  5982. buttonDisabled = true;
  5983. const text = transStatus();
  5984. setProcessing(true);
  5985. const setStatus = t2 => setTransStatus(() => t2);
  5986. setStatus(t$1("common.source.download-image"));
  5987. if (!originalImage) {
  5988. const result = await GMP.xmlHttpRequest({
  5989. method: "GET",
  5990. responseType: "blob",
  5991. url: originalSrc,
  5992. headers: {
  5993. referer: "https://www.pixiv.net/"
  5994. },
  5995. overrideMimeType: "text/plain; charset=x-user-defined",
  5996. onprogress(e) {
  5997. if (e.lengthComputable) {
  5998. setStatus(t$1("common.source.download-image-progress", {
  5999. progress: formatProgress(e.loaded, e.total)
  6000. }));
  6001. }
  6002. }
  6003. }).catch(e => {
  6004. setStatus(t$1("common.source.download-image-error"));
  6005. throw e;
  6006. });
  6007. originalImage = result.response;
  6008. }
  6009. setStatus(t$1("common.client.resize"));
  6010. await new Promise(resolve => queueMicrotask(resolve));
  6011. const {
  6012. blob: resizedImage,
  6013. suffix: resizedSuffix
  6014. } = await resizeToSubmit(originalImage, originalSrcSuffix);
  6015. setStatus(t$1("common.client.submit"));
  6016. const task = await submitTranslate(resizedImage, resizedSuffix, {
  6017. onProgress(progress) {
  6018. setStatus(t$1("common.client.submit-progress", {
  6019. progress
  6020. }));
  6021. },
  6022. onFinal() {
  6023. setStatus(t$1("common.client.submit-final"));
  6024. }
  6025. }, optionsOverwrite).catch(e => {
  6026. setStatus(t$1("common.client.submit-error"));
  6027. throw e;
  6028. });
  6029. let maskUrl = task.result?.translation_mask;
  6030. if (!maskUrl) {
  6031. setStatus(t$1("common.status.pending"));
  6032. const res = await pullTranslationStatus(task.id, setStatus).catch(e => {
  6033. setStatus(e);
  6034. throw e;
  6035. });
  6036. maskUrl = res.translation_mask;
  6037. }
  6038. setStatus(t$1("common.client.download-image"));
  6039. const mask = await downloadBlob(maskUrl, {
  6040. onProgress(progress) {
  6041. setStatus(t$1("common.client.download-image-progress", {
  6042. progress
  6043. }));
  6044. }
  6045. }).catch(e => {
  6046. setStatus(t$1("common.client.download-image-error"));
  6047. throw e;
  6048. });
  6049. const maskUri = URL.createObjectURL(mask);
  6050. setStatus(t$1("common.client.merging"));
  6051. const canvas = document.createElement("canvas");
  6052. const canvasCtx = canvas.getContext("2d");
  6053. const img = new Image();
  6054. img.src = URL.createObjectURL(resizedImage);
  6055. await new Promise(resolve => {
  6056. img.onload = () => {
  6057. canvas.width = img.width;
  6058. canvas.height = img.height;
  6059. canvasCtx.drawImage(img, 0, 0);
  6060. resolve(null);
  6061. };
  6062. });
  6063. const img2 = new Image();
  6064. img2.src = maskUri;
  6065. img2.crossOrigin = "anonymous";
  6066. await new Promise(resolve => {
  6067. img2.onload = () => {
  6068. canvasCtx.drawImage(img2, 0, 0);
  6069. resolve(null);
  6070. };
  6071. });
  6072. const translated2 = await new Promise(resolve => {
  6073. canvas.toBlob(blob => {
  6074. resolve(blob);
  6075. }, "image/png");
  6076. });
  6077. const translatedUri = URL.createObjectURL(translated2);
  6078. translatedImage = translatedUri;
  6079. translatedMap.set(originalSrc, translatedUri);
  6080. setStatus(text);
  6081. setProcessing(false);
  6082. buttonDisabled = false;
  6083. return translatedUri;
  6084. }
  6085. async function enable(optionsOverwrite) {
  6086. try {
  6087. const translated2 = await getTranslatedImage(optionsOverwrite);
  6088. imageNode.setAttribute("data-trans", src);
  6089. imageNode.setAttribute("src", translated2);
  6090. imageNode.removeAttribute("srcset");
  6091. setTranslateMounted(true);
  6092. setTranslated(true);
  6093. } catch (e) {
  6094. buttonDisabled = false;
  6095. setTranslateMounted(false);
  6096. throw e;
  6097. }
  6098. }
  6099. function disable() {
  6100. imageNode.setAttribute("src", src);
  6101. if (srcset) imageNode.setAttribute("srcset", srcset);
  6102. imageNode.removeAttribute("data-trans");
  6103. setTranslateMounted(false);
  6104. setTranslated(false);
  6105. }
  6106. function toggle() {
  6107. if (buttonDisabled) return;
  6108. if (!translateMounted()) {
  6109. translateEnabledMap.set(originalSrc, true);
  6110. enable();
  6111. } else {
  6112. translateEnabledMap.delete(originalSrc);
  6113. disable();
  6114. }
  6115. }
  6116. if (translateEnabledMap.get(originalSrc)) enable();
  6117. onCleanup(() => {
  6118. if (translateMounted()) disable();
  6119. });
  6120. return {
  6121. imageNode,
  6122. async enable() {
  6123. translateEnabledMap.set(originalSrc, true);
  6124. return await enable();
  6125. },
  6126. disable() {
  6127. translateEnabledMap.delete(originalSrc);
  6128. return disable();
  6129. },
  6130. isEnabled: createMemo(() => processing() || translateMounted())
  6131. };
  6132. }
  6133. const TranslateAll = () => {
  6134. const [started, setStarted] = createSignal(false);
  6135. const [total, setTotal] = createSignal(0);
  6136. const [finished, setFinished] = createSignal(0);
  6137. const [erred, setErred] = createSignal(false);
  6138. return (() => {
  6139. const _el$19 = _tmpl$7();
  6140. _el$19.addEventListener("click", e => {
  6141. e.stopPropagation();
  6142. e.preventDefault();
  6143. if (started()) return;
  6144. setStarted(true);
  6145. setTotal(instances.size);
  6146. const inc = () => {
  6147. setFinished(finished() + 1);
  6148. };
  6149. const err = () => {
  6150. setErred(true);
  6151. inc();
  6152. };
  6153. for (const instance of instances.values()) {
  6154. if (instance.isEnabled()) inc();else instance.enable().then(inc).catch(err);
  6155. }
  6156. });
  6157. insert(_el$19, createComponent(Switch, {
  6158. get children() {
  6159. return [createComponent(Match, {
  6160. get when() {
  6161. return !started();
  6162. },
  6163. get children() {
  6164. return t$1("common.control.batch", {
  6165. count: instances.size
  6166. })();
  6167. }
  6168. }), createComponent(Match, {
  6169. get when() {
  6170. return finished() !== total();
  6171. },
  6172. get children() {
  6173. return t$1("common.batch.progress", {
  6174. count: finished(),
  6175. total: total()
  6176. })();
  6177. }
  6178. }), createComponent(Match, {
  6179. get when() {
  6180. return finished() === total();
  6181. },
  6182. get children() {
  6183. return createComponent(Show, {
  6184. get when() {
  6185. return !erred();
  6186. },
  6187. get fallback() {
  6188. return t$1("common.batch.error")();
  6189. },
  6190. get children() {
  6191. return t$1("common.batch.finish")();
  6192. }
  6193. });
  6194. }
  6195. })];
  6196. }
  6197. }));
  6198. createRenderEffect(() => className(_el$19, tw("inline-block mr-3 p-0 h-8 text-inherit leading-8 font-bold cursor-pointer")));
  6199. return _el$19;
  6200. })();
  6201. };
  6202. let disposeTransAll;
  6203. function refreshTransAll() {
  6204. if (document.querySelector(".sc-emr523-2")) return;
  6205. const section = document.querySelector(".sc-181ts2x-0");
  6206. if (section) {
  6207. if (section.querySelector("[data-transall]")) return;
  6208. const container = document.createElement("div");
  6209. section.appendChild(container);
  6210. const dispose = render(() => createComponent(TranslateAll, {}), container);
  6211. disposeTransAll = () => {
  6212. dispose();
  6213. container.remove();
  6214. };
  6215. } else {
  6216. if (disposeTransAll) {
  6217. disposeTransAll();
  6218. disposeTransAll = void 0;
  6219. }
  6220. }
  6221. }
  6222. onCleanup(() => {
  6223. disposeTransAll?.();
  6224. });
  6225. let disposeMangaViewerTransAll;
  6226. function refreshManagaViewerTransAll() {
  6227. const mangaViewer = document.querySelector(".gtm-manga-viewer-change-direction")?.parentElement?.parentElement;
  6228. if (mangaViewer) {
  6229. if (disposeMangaViewerTransAll) return;
  6230. const container = document.createElement("div");
  6231. mangaViewer.prepend(container);
  6232. const dispose = render(() => createComponent(TranslateAll, {}), container);
  6233. disposeMangaViewerTransAll = () => {
  6234. dispose();
  6235. container.remove();
  6236. };
  6237. } else {
  6238. if (disposeMangaViewerTransAll) {
  6239. disposeMangaViewerTransAll();
  6240. disposeMangaViewerTransAll = void 0;
  6241. }
  6242. }
  6243. }
  6244. onCleanup(() => {
  6245. disposeMangaViewerTransAll?.();
  6246. });
  6247. createMutationObserver(document.body, {
  6248. childList: true,
  6249. subtree: true
  6250. }, throttle(() => {
  6251. rescanImages();
  6252. refreshTransAll();
  6253. refreshManagaViewerTransAll();
  6254. }, 200));
  6255. rescanImages();
  6256. refreshTransAll();
  6257. onCleanup(() => {
  6258. images.clear();
  6259. instances.forEach(instance => instance.dispose());
  6260. instances.clear();
  6261. });
  6262. return {};
  6263. }
  6264. const translator$2 = {
  6265. match(url) {
  6266. return url.hostname.endsWith("pixiv.net") && url.pathname.match(/\/artworks\//);
  6267. },
  6268. mount: mount$4
  6269. };
  6270.  
  6271. const _tmpl$$5 = /*#__PURE__*/template(`<div><h2></h2><div>`);
  6272. function mount$3() {
  6273. const wrapper = document.getElementById("wrapper");
  6274. if (!wrapper) return {};
  6275. const adFooter = wrapper.querySelector(".ad-footer");
  6276. if (!adFooter) return {};
  6277. const settingsContainer = document.createElement("div");
  6278. onCleanup(() => {
  6279. settingsContainer.remove();
  6280. });
  6281. const disposeSettings = render(() => (() => {
  6282. const _el$ = _tmpl$$5(),
  6283. _el$2 = _el$.firstChild,
  6284. _el$3 = _el$2.nextSibling;
  6285. insert(_el$2, t$1("settings.title"));
  6286. insert(_el$3, createComponent(Settings, {
  6287. itemOrientation: "horizontal",
  6288. textStyle: {
  6289. "width": "185px",
  6290. "font-weight": "bold"
  6291. }
  6292. }));
  6293. createRenderEffect(_p$ => {
  6294. const _v$ = tw("mb-2.5 pt-2.5 px-5 pb-4 bg-white border border-solid border-[#d6dee5]"),
  6295. _v$2 = tw("text-lg font-bold"),
  6296. _v$3 = tw("w-[665px] my-2.5 mx-auto");
  6297. _v$ !== _p$._v$ && className(_el$, _p$._v$ = _v$);
  6298. _v$2 !== _p$._v$2 && className(_el$2, _p$._v$2 = _v$2);
  6299. _v$3 !== _p$._v$3 && className(_el$3, _p$._v$3 = _v$3);
  6300. return _p$;
  6301. }, {
  6302. _v$: undefined,
  6303. _v$2: undefined,
  6304. _v$3: undefined
  6305. });
  6306. return _el$;
  6307. })(), settingsContainer);
  6308. onCleanup(disposeSettings);
  6309. wrapper.insertBefore(settingsContainer, adFooter);
  6310. return {};
  6311. }
  6312. const settingsInjector$1 = {
  6313. match(url) {
  6314. return url.hostname.endsWith("pixiv.net") && url.pathname.match(/\/setting_user\.php/);
  6315. },
  6316. mount: mount$3
  6317. };
  6318.  
  6319. const $RAW = Symbol("store-raw"),
  6320. $NODE = Symbol("store-node");
  6321. function wrap$1(value) {
  6322. let p = value[$PROXY];
  6323. if (!p) {
  6324. Object.defineProperty(value, $PROXY, {
  6325. value: p = new Proxy(value, proxyTraps$1)
  6326. });
  6327. if (!Array.isArray(value)) {
  6328. const keys = Object.keys(value),
  6329. desc = Object.getOwnPropertyDescriptors(value);
  6330. for (let i = 0, l = keys.length; i < l; i++) {
  6331. const prop = keys[i];
  6332. if (desc[prop].get) {
  6333. Object.defineProperty(value, prop, {
  6334. enumerable: desc[prop].enumerable,
  6335. get: desc[prop].get.bind(p)
  6336. });
  6337. }
  6338. }
  6339. }
  6340. }
  6341. return p;
  6342. }
  6343. function isWrappable(obj) {
  6344. let proto;
  6345. return obj != null && typeof obj === "object" && (obj[$PROXY] || !(proto = Object.getPrototypeOf(obj)) || proto === Object.prototype || Array.isArray(obj));
  6346. }
  6347. function unwrap(item, set = new Set()) {
  6348. let result, unwrapped, v, prop;
  6349. if (result = item != null && item[$RAW]) return result;
  6350. if (!isWrappable(item) || set.has(item)) return item;
  6351. if (Array.isArray(item)) {
  6352. if (Object.isFrozen(item)) item = item.slice(0);else set.add(item);
  6353. for (let i = 0, l = item.length; i < l; i++) {
  6354. v = item[i];
  6355. if ((unwrapped = unwrap(v, set)) !== v) item[i] = unwrapped;
  6356. }
  6357. } else {
  6358. if (Object.isFrozen(item)) item = Object.assign({}, item);else set.add(item);
  6359. const keys = Object.keys(item),
  6360. desc = Object.getOwnPropertyDescriptors(item);
  6361. for (let i = 0, l = keys.length; i < l; i++) {
  6362. prop = keys[i];
  6363. if (desc[prop].get) continue;
  6364. v = item[prop];
  6365. if ((unwrapped = unwrap(v, set)) !== v) item[prop] = unwrapped;
  6366. }
  6367. }
  6368. return item;
  6369. }
  6370. function getDataNodes(target) {
  6371. let nodes = target[$NODE];
  6372. if (!nodes) Object.defineProperty(target, $NODE, {
  6373. value: nodes = Object.create(null)
  6374. });
  6375. return nodes;
  6376. }
  6377. function getDataNode(nodes, property, value) {
  6378. return nodes[property] || (nodes[property] = createDataNode(value));
  6379. }
  6380. function proxyDescriptor$1(target, property) {
  6381. const desc = Reflect.getOwnPropertyDescriptor(target, property);
  6382. if (!desc || desc.get || !desc.configurable || property === $PROXY || property === $NODE) return desc;
  6383. delete desc.value;
  6384. delete desc.writable;
  6385. desc.get = () => target[$PROXY][property];
  6386. return desc;
  6387. }
  6388. function trackSelf(target) {
  6389. if (getListener()) {
  6390. const nodes = getDataNodes(target);
  6391. (nodes._ || (nodes._ = createDataNode()))();
  6392. }
  6393. }
  6394. function ownKeys(target) {
  6395. trackSelf(target);
  6396. return Reflect.ownKeys(target);
  6397. }
  6398. function createDataNode(value) {
  6399. const [s, set] = createSignal(value, {
  6400. equals: false,
  6401. internal: true
  6402. });
  6403. s.$ = set;
  6404. return s;
  6405. }
  6406. const proxyTraps$1 = {
  6407. get(target, property, receiver) {
  6408. if (property === $RAW) return target;
  6409. if (property === $PROXY) return receiver;
  6410. if (property === $TRACK) {
  6411. trackSelf(target);
  6412. return receiver;
  6413. }
  6414. const nodes = getDataNodes(target);
  6415. const tracked = nodes[property];
  6416. let value = tracked ? tracked() : target[property];
  6417. if (property === $NODE || property === "__proto__") return value;
  6418. if (!tracked) {
  6419. const desc = Object.getOwnPropertyDescriptor(target, property);
  6420. if (getListener() && (typeof value !== "function" || target.hasOwnProperty(property)) && !(desc && desc.get)) value = getDataNode(nodes, property, value)();
  6421. }
  6422. return isWrappable(value) ? wrap$1(value) : value;
  6423. },
  6424. has(target, property) {
  6425. if (property === $RAW || property === $PROXY || property === $TRACK || property === $NODE || property === "__proto__") return true;
  6426. this.get(target, property, target);
  6427. return property in target;
  6428. },
  6429. set() {
  6430. return true;
  6431. },
  6432. deleteProperty() {
  6433. return true;
  6434. },
  6435. ownKeys: ownKeys,
  6436. getOwnPropertyDescriptor: proxyDescriptor$1
  6437. };
  6438. function setProperty(state, property, value, deleting = false) {
  6439. if (!deleting && state[property] === value) return;
  6440. const prev = state[property],
  6441. len = state.length;
  6442. if (value === undefined) delete state[property];else state[property] = value;
  6443. let nodes = getDataNodes(state),
  6444. node;
  6445. if (node = getDataNode(nodes, property, prev)) node.$(() => value);
  6446. if (Array.isArray(state) && state.length !== len) {
  6447. for (let i = state.length; i < len; i++) (node = nodes[i]) && node.$();
  6448. (node = getDataNode(nodes, "length", len)) && node.$(state.length);
  6449. }
  6450. (node = nodes._) && node.$();
  6451. }
  6452. function mergeStoreNode(state, value) {
  6453. const keys = Object.keys(value);
  6454. for (let i = 0; i < keys.length; i += 1) {
  6455. const key = keys[i];
  6456. setProperty(state, key, value[key]);
  6457. }
  6458. }
  6459. function updateArray(current, next) {
  6460. if (typeof next === "function") next = next(current);
  6461. next = unwrap(next);
  6462. if (Array.isArray(next)) {
  6463. if (current === next) return;
  6464. let i = 0,
  6465. len = next.length;
  6466. for (; i < len; i++) {
  6467. const value = next[i];
  6468. if (current[i] !== value) setProperty(current, i, value);
  6469. }
  6470. setProperty(current, "length", len);
  6471. } else mergeStoreNode(current, next);
  6472. }
  6473. function updatePath(current, path, traversed = []) {
  6474. let part,
  6475. prev = current;
  6476. if (path.length > 1) {
  6477. part = path.shift();
  6478. const partType = typeof part,
  6479. isArray = Array.isArray(current);
  6480. if (Array.isArray(part)) {
  6481. for (let i = 0; i < part.length; i++) {
  6482. updatePath(current, [part[i]].concat(path), traversed);
  6483. }
  6484. return;
  6485. } else if (isArray && partType === "function") {
  6486. for (let i = 0; i < current.length; i++) {
  6487. if (part(current[i], i)) updatePath(current, [i].concat(path), traversed);
  6488. }
  6489. return;
  6490. } else if (isArray && partType === "object") {
  6491. const {
  6492. from = 0,
  6493. to = current.length - 1,
  6494. by = 1
  6495. } = part;
  6496. for (let i = from; i <= to; i += by) {
  6497. updatePath(current, [i].concat(path), traversed);
  6498. }
  6499. return;
  6500. } else if (path.length > 1) {
  6501. updatePath(current[part], path, [part].concat(traversed));
  6502. return;
  6503. }
  6504. prev = current[part];
  6505. traversed = [part].concat(traversed);
  6506. }
  6507. let value = path[0];
  6508. if (typeof value === "function") {
  6509. value = value(prev, traversed);
  6510. if (value === prev) return;
  6511. }
  6512. if (part === undefined && value == undefined) return;
  6513. value = unwrap(value);
  6514. if (part === undefined || isWrappable(prev) && isWrappable(value) && !Array.isArray(value)) {
  6515. mergeStoreNode(prev, value);
  6516. } else setProperty(current, part, value);
  6517. }
  6518. function createStore(...[store, options]) {
  6519. const unwrappedStore = unwrap(store || {});
  6520. const isArray = Array.isArray(unwrappedStore);
  6521. const wrappedStore = wrap$1(unwrappedStore);
  6522. function setStore(...args) {
  6523. batch(() => {
  6524. isArray && args.length === 1 ? updateArray(unwrappedStore, args[0]) : updatePath(unwrappedStore, args);
  6525. });
  6526. }
  6527. return [wrappedStore, setStore];
  6528. }
  6529.  
  6530. const _tmpl$$4 = /*#__PURE__*/template(`<div>`),
  6531. _tmpl$2$1 = /*#__PURE__*/template(`<div><div>`),
  6532. _tmpl$3$1 = /*#__PURE__*/template(`<div><label><input type="checkbox">`),
  6533. _tmpl$4$1 = /*#__PURE__*/template(`<div><div></div><div><select>`),
  6534. _tmpl$5$1 = /*#__PURE__*/template(`<option>`);
  6535. function mount$2() {
  6536. const mountAuthorId = location.pathname.split("/", 2)[1];
  6537. const [statusId, setStatusId] = createSignal(location.pathname.match(/\/status\/(\d+)/)?.[1]);
  6538. const [translatedMap, setTranslatedMap] = createStore({});
  6539. const [translateStatusMap, setTranslateStatusMap] = createStore({});
  6540. const [translateEnabledMap, setTranslateEnabledMap] = createStore({});
  6541. const originalImageMap = {};
  6542. const [layers, setLayers] = createSignal(null);
  6543. let dialog;
  6544. const createDialog = () => {
  6545. const [active, setActive] = createSignal(0);
  6546. const buttonParent = dialog.querySelector('[aria-labelledby="modal-header"][role="dialog"]').firstElementChild.firstElementChild;
  6547. const getImages = () => {
  6548. try {
  6549. const cont = buttonParent.firstElementChild;
  6550. assert(cont.nodeName === "DIV");
  6551. const ul = cont.firstElementChild.firstElementChild.nextElementSibling.firstElementChild.firstElementChild;
  6552. assert(ul.nodeName === "UL");
  6553. const images2 = [];
  6554. let li = ul.firstElementChild;
  6555. do {
  6556. const img = li.firstElementChild.firstElementChild.firstElementChild.firstElementChild.lastElementChild;
  6557. assert(img.nodeName === "IMG");
  6558. images2.push(img);
  6559. } while (li = li.nextElementSibling);
  6560. return images2;
  6561. } catch (e) {
  6562. return [].slice.call(buttonParent.firstElementChild.querySelectorAll("img"));
  6563. }
  6564. };
  6565. const [images, setImages] = createSignal(getImages(), {
  6566. equals: (a, b) => a.length === b.length && a.every((img, i) => img === b[i])
  6567. });
  6568. const currentImg = createMemo(() => {
  6569. const img = images()[active()];
  6570. if (!img) return void 0;
  6571. return img.getAttribute("data-transurl") || img.src;
  6572. });
  6573. createEffect(() => {
  6574. for (const img of images()) {
  6575. const div = img.previousSibling;
  6576. if (img.hasAttribute("data-transurl")) {
  6577. const transurl = img.getAttribute("data-transurl");
  6578. if (!translateEnabledMap[transurl]) {
  6579. if (div) div.style.backgroundImage = `url("${transurl}")`;
  6580. img.src = transurl;
  6581. img.removeAttribute("data-transurl");
  6582. }
  6583. } else if (translateEnabledMap[img.src] && translatedMap[img.src]) {
  6584. const ori = img.src;
  6585. img.setAttribute("data-transurl", ori);
  6586. img.src = translatedMap[ori];
  6587. if (div) div.style.backgroundImage = `url("${translatedMap[ori]}")`;
  6588. }
  6589. }
  6590. });
  6591. const getTranslatedImage = async (url, optionsOverwrite) => {
  6592. if (!optionsOverwrite && translatedMap[url]) return translatedMap[url];
  6593. const setStatus = t2 => setTranslateStatusMap(url, () => t2);
  6594. setStatus(t$1("common.source.download-image"));
  6595. if (!originalImageMap[url]) {
  6596. const result = await GMP.xmlHttpRequest({
  6597. method: "GET",
  6598. responseType: "blob",
  6599. url,
  6600. headers: {
  6601. referer: "https://twitter.com/"
  6602. },
  6603. overrideMimeType: "text/plain; charset=x-user-defined",
  6604. onprogress(e) {
  6605. if (e.lengthComputable) {
  6606. setStatus(t$1("common.source.download-image-progress", {
  6607. progress: formatProgress(e.loaded, e.total)
  6608. }));
  6609. }
  6610. }
  6611. }).catch(e => {
  6612. setStatus(t$1("common.source.download-image-error"));
  6613. throw e;
  6614. });
  6615. originalImageMap[url] = result.response;
  6616. }
  6617. const originalImage = originalImageMap[url];
  6618. const originalSrcSuffix = new URL(url).searchParams.get("format") || url.split(".")[1] || "jpg";
  6619. setStatus(t$1("common.client.resize"));
  6620. await new Promise(resolve => queueMicrotask(resolve));
  6621. const {
  6622. blob: resizedImage,
  6623. suffix: resizedSuffix
  6624. } = await resizeToSubmit(originalImage, originalSrcSuffix);
  6625. setStatus(t$1("common.client.submit"));
  6626. const task = await submitTranslate(resizedImage, resizedSuffix, {
  6627. onProgress(progress) {
  6628. setStatus(t$1("common.client.submit-progress", {
  6629. progress
  6630. }));
  6631. },
  6632. onFinal() {
  6633. setStatus(t$1("common.client.submit-final"));
  6634. }
  6635. }, optionsOverwrite).catch(e => {
  6636. setStatus(t$1("common.client.submit-error"));
  6637. throw e;
  6638. });
  6639. let maskUrl = task.result?.translation_mask;
  6640. if (!maskUrl) {
  6641. setStatus(t$1("common.status.pending"));
  6642. const res = await pullTranslationStatusPolling(task.id, setStatus).catch(e => {
  6643. setStatus(e);
  6644. throw e;
  6645. });
  6646. maskUrl = res.translation_mask;
  6647. }
  6648. setStatus(t$1("common.client.download-image"));
  6649. const mask = await downloadBlob(maskUrl, {
  6650. onProgress(progress) {
  6651. t$1("common.client.download-image-progress", {
  6652. progress
  6653. });
  6654. }
  6655. }).catch(e => {
  6656. setStatus(t$1("common.client.download-image-error"));
  6657. throw e;
  6658. });
  6659. const maskUri = URL.createObjectURL(mask);
  6660. setStatus(t$1("common.client.merging"));
  6661. const canvas = document.createElement("canvas");
  6662. const canvasCtx = canvas.getContext("2d");
  6663. const img = new Image();
  6664. img.src = URL.createObjectURL(resizedImage);
  6665. await new Promise(resolve => {
  6666. img.onload = () => {
  6667. canvas.width = img.width;
  6668. canvas.height = img.height;
  6669. canvasCtx.drawImage(img, 0, 0);
  6670. resolve(null);
  6671. };
  6672. });
  6673. const img2 = new Image();
  6674. img2.src = maskUri;
  6675. img2.crossOrigin = "anonymous";
  6676. await new Promise(resolve => {
  6677. img2.onload = () => {
  6678. canvasCtx.drawImage(img2, 0, 0);
  6679. resolve(null);
  6680. };
  6681. });
  6682. const translated = await new Promise(resolve => {
  6683. canvas.toBlob(blob => {
  6684. resolve(blob);
  6685. }, "image/png");
  6686. });
  6687. const translatedUri = URL.createObjectURL(translated);
  6688. setTranslatedMap(url, translatedUri);
  6689. setStatus(() => "");
  6690. return translatedUri;
  6691. };
  6692. const enable = async (url, optionsOverwrite) => {
  6693. await getTranslatedImage(url, optionsOverwrite);
  6694. setTranslateEnabledMap(url, true);
  6695. };
  6696. const disable = url => {
  6697. setTranslateEnabledMap(url, false);
  6698. };
  6699. const isEnabled = createMemo(() => {
  6700. const img = currentImg();
  6701. return img ? !!translateEnabledMap[img] : false;
  6702. });
  6703. const transStatus = createMemo(() => {
  6704. const img = currentImg();
  6705. return img ? translateStatusMap[img]?.() : "";
  6706. });
  6707. const isProcessing = createMemo(() => !!transStatus());
  6708. const [advancedMenuOpen, setAdvancedMenuOpen] = createSignal(false);
  6709. const referenceEl = buttonParent.children[2];
  6710. const container = referenceEl.cloneNode(true);
  6711. container.style.top = "48px";
  6712. createEffect(() => {
  6713. container.style.display = currentImg() ? "flex" : "none";
  6714. container.style.alignItems = advancedMenuOpen() ? "start" : "center";
  6715. });
  6716. container.style.flexDirection = "row";
  6717. container.style.flexWrap = "nowrap";
  6718. const child = container.firstChild;
  6719. const referenceChild = referenceEl.firstChild;
  6720. const [backgroundColor, setBackgroundColor] = createSignal(referenceChild.style.backgroundColor);
  6721. buttonParent.appendChild(container);
  6722. const submitTranslateTest = () => {
  6723. const img = currentImg();
  6724. return img && !translateStatusMap[img]?.();
  6725. };
  6726. container.onclick = e => {
  6727. e.stopPropagation();
  6728. if (advancedMenuOpen()) return;
  6729. if (!submitTranslateTest()) return;
  6730. if (isEnabled()) disable(currentImg());else enable(currentImg());
  6731. };
  6732. container.oncontextmenu = e => {
  6733. e.preventDefault();
  6734. e.stopPropagation();
  6735. if (isEnabled()) setAdvancedMenuOpen(false);else setAdvancedMenuOpen(v => !v);
  6736. };
  6737. const spinnerContainer = container.firstChild;
  6738. const disposeProcessingSpinner = render(() => createComponent(Show, {
  6739. get when() {
  6740. return isProcessing();
  6741. },
  6742. get children() {
  6743. const _el$ = _tmpl$$4();
  6744. createRenderEffect(() => className(_el$, tw("absolute inset-0 border-1 border-solid border-x-transparent border-b-transparent border-t-gray-400 rounded-full animate-spin")));
  6745. return _el$;
  6746. }
  6747. }), spinnerContainer);
  6748. onCleanup(disposeProcessingSpinner);
  6749. const svg = container.querySelector("svg");
  6750. const svgParent = svg.parentElement;
  6751. const buttonIconContainer = document.createElement("div");
  6752. svgParent.insertBefore(buttonIconContainer, svg);
  6753. svg.remove();
  6754. const disposeButtonIcon = render(() => createComponent(Dynamic, {
  6755. get component() {
  6756. return isEnabled() ? IconCarbonReset : IconCarbonTranslate;
  6757. },
  6758. get ["class"]() {
  6759. return tw("w-5 h-5 mt-1");
  6760. }
  6761. }), buttonIconContainer);
  6762. onCleanup(disposeButtonIcon);
  6763. const buttonStatusContainer = document.createElement("div");
  6764. container.insertBefore(buttonStatusContainer, container.firstChild);
  6765. const disposeButtonStatus = render(() => {
  6766. const status = createMemo(() => transStatus());
  6767. const [advDetectRes, setAdvDetectRes] = createSignal(detectionResolution());
  6768. const [advRenderTextDir, setAdvRenderTextDir] = createSignal(renderTextOrientation());
  6769. const [advTextDetector, setAdvTextDetector] = createSignal(textDetector());
  6770. const [advTranslator, setAdvTranslator] = createSignal(translatorService());
  6771. const [forceRetry, setForceRetry] = createSignal(false);
  6772. createEffect(prev => {
  6773. const img = currentImg();
  6774. if (prev !== img) {
  6775. setAdvDetectRes(detectionResolution());
  6776. setAdvRenderTextDir(renderTextOrientation());
  6777. }
  6778. return img;
  6779. });
  6780. return (() => {
  6781. const _el$2 = _tmpl$$4();
  6782. insert(_el$2, createComponent(Switch, {
  6783. get children() {
  6784. return [createComponent(Match, {
  6785. get when() {
  6786. return status();
  6787. },
  6788. get children() {
  6789. const _el$3 = _tmpl$$4();
  6790. insert(_el$3, status);
  6791. createRenderEffect(() => className(_el$3, tw("px-2 py-1")));
  6792. return _el$3;
  6793. }
  6794. }), createComponent(Match, {
  6795. get when() {
  6796. return createMemo(() => !!currentImg())() && !translateEnabledMap[currentImg()];
  6797. },
  6798. get children() {
  6799. return createComponent(Show, {
  6800. get when() {
  6801. return advancedMenuOpen();
  6802. },
  6803. get fallback() {
  6804. return createComponent(IconCarbonChevronLeft, {
  6805. get ["class"]() {
  6806. return tw("py-1 align-middle cursor-pointer");
  6807. },
  6808. onClick: e => {
  6809. e.stopPropagation();
  6810. setAdvancedMenuOpen(true);
  6811. }
  6812. });
  6813. },
  6814. get children() {
  6815. return [(() => {
  6816. const _el$4 = _tmpl$2$1(),
  6817. _el$5 = _el$4.firstChild;
  6818. _el$4.addEventListener("click", e => {
  6819. e.stopPropagation();
  6820. setAdvancedMenuOpen(false);
  6821. });
  6822. insert(_el$5, t$1("settings.inline-options-title"));
  6823. insert(_el$4, createComponent(IconCarbonChevronRight, {
  6824. get ["class"]() {
  6825. return tw("align-middle cursor-pointer");
  6826. }
  6827. }), null);
  6828. createRenderEffect(_p$ => {
  6829. const _v$ = tw("flex justify-between items-center pl-2 py-1"),
  6830. _v$2 = tw("text-lg");
  6831. _v$ !== _p$._v$ && className(_el$4, _p$._v$ = _v$);
  6832. _v$2 !== _p$._v$2 && className(_el$5, _p$._v$2 = _v$2);
  6833. return _p$;
  6834. }, {
  6835. _v$: undefined,
  6836. _v$2: undefined
  6837. });
  6838. return _el$4;
  6839. })(), (() => {
  6840. const _el$6 = _tmpl$3$1(),
  6841. _el$7 = _el$6.firstChild,
  6842. _el$8 = _el$7.firstChild;
  6843. insert(_el$6, createComponent(For, {
  6844. get each() {
  6845. return [[t$1("settings.detection-resolution"), advDetectRes, setAdvDetectRes, detectResOptions, detectResOptionsMap], [t$1("settings.text-detector"), advTextDetector, setAdvTextDetector, textDetectorOptions, textDetectorOptionsMap], [t$1("settings.translator"), advTranslator, setAdvTranslator, translatorOptions, translatorOptionsMap], [t$1("settings.render-text-orientation"), advRenderTextDir, setAdvRenderTextDir, renderTextDirOptions, renderTextDirOptionsMap]];
  6846. },
  6847. children: ([title, opt, setOpt, opts, optMap]) => (() => {
  6848. const _el$10 = _tmpl$4$1(),
  6849. _el$11 = _el$10.firstChild,
  6850. _el$12 = _el$11.nextSibling,
  6851. _el$13 = _el$12.firstChild;
  6852. insert(_el$11, title);
  6853. _el$13.addEventListener("change", e => {
  6854. setOpt(e.target.value);
  6855. });
  6856. insert(_el$13, createComponent(For, {
  6857. each: opts,
  6858. children: opt2 => (() => {
  6859. const _el$14 = _tmpl$5$1();
  6860. _el$14.value = opt2;
  6861. insert(_el$14, () =>
  6862. // @ts-expect-error optMap are incompatible with each other
  6863. optMap[opt2]());
  6864. return _el$14;
  6865. })()
  6866. }));
  6867. insert(_el$12, createComponent(IconCarbonChevronDown, {
  6868. get ["class"]() {
  6869. return tw("absolute top-1 right-1 pointer-events-none");
  6870. }
  6871. }), null);
  6872. createRenderEffect(_p$ => {
  6873. const _v$7 = tw("relative px-1"),
  6874. _v$8 = tw("w-full py-1 appearance-none text-white border-x-0 border-t-0 border-b border-solid border-gray-300 bg-transparent");
  6875. _v$7 !== _p$._v$7 && className(_el$12, _p$._v$7 = _v$7);
  6876. _v$8 !== _p$._v$8 && className(_el$13, _p$._v$8 = _v$8);
  6877. return _p$;
  6878. }, {
  6879. _v$7: undefined,
  6880. _v$8: undefined
  6881. });
  6882. createRenderEffect(() => _el$13.value = opt());
  6883. return _el$10;
  6884. })()
  6885. }), _el$7);
  6886. _el$8.addEventListener("change", e => {
  6887. setForceRetry(e.target.checked);
  6888. });
  6889. _el$8.checked = forceRetry();
  6890. insert(_el$7, t$1("settings.force-retry"), null);
  6891. createRenderEffect(_p$ => {
  6892. const _v$3 = tw("flex flex-col w-48 gap-2 ml-2"),
  6893. _v$4 = tw("flex items-center cursor-pointer");
  6894. _v$3 !== _p$._v$3 && className(_el$6, _p$._v$3 = _v$3);
  6895. _v$4 !== _p$._v$4 && className(_el$7, _p$._v$4 = _v$4);
  6896. return _p$;
  6897. }, {
  6898. _v$3: undefined,
  6899. _v$4: undefined
  6900. });
  6901. return _el$6;
  6902. })(), (() => {
  6903. const _el$9 = _tmpl$$4();
  6904. _el$9.addEventListener("click", e => {
  6905. e.stopPropagation();
  6906. e.preventDefault();
  6907. if (!submitTranslateTest()) return;
  6908. if (translateEnabledMap[currentImg()]) return;
  6909. enable(currentImg(), {
  6910. detectionResolution: advDetectRes(),
  6911. renderTextOrientation: advRenderTextDir(),
  6912. textDetector: advTextDetector(),
  6913. translator: advTranslator(),
  6914. forceRetry: forceRetry()
  6915. });
  6916. setAdvancedMenuOpen(false);
  6917. });
  6918. insert(_el$9, t$1("common.control.translate"));
  6919. createRenderEffect(() => className(_el$9, tw("w-full mt-2 mb-1 py-1 border border-solid border-white rounded-full text-center cursor-pointer")));
  6920. return _el$9;
  6921. })()];
  6922. }
  6923. });
  6924. }
  6925. })];
  6926. }
  6927. }));
  6928. createRenderEffect(_p$ => {
  6929. const _v$5 = tw("flex flex-col -mr-3 pl-1 pr-2 text-white rounded-2xl cursor-default"),
  6930. _v$6 = backgroundColor();
  6931. _v$5 !== _p$._v$5 && className(_el$2, _p$._v$5 = _v$5);
  6932. _v$6 !== _p$._v$6 && ((_p$._v$6 = _v$6) != null ? _el$2.style.setProperty("background-color", _v$6) : _el$2.style.removeProperty("background-color"));
  6933. return _p$;
  6934. }, {
  6935. _v$5: undefined,
  6936. _v$6: undefined
  6937. });
  6938. return _el$2;
  6939. })();
  6940. }, buttonStatusContainer);
  6941. onCleanup(disposeButtonStatus);
  6942. onCleanup(() => {
  6943. container.remove();
  6944. for (const img of images()) {
  6945. if (img.hasAttribute("data-transurl")) {
  6946. const transurl = img.getAttribute("data-transurl");
  6947. img.src = transurl;
  6948. img.removeAttribute("data-transurl");
  6949. }
  6950. }
  6951. setImages([]);
  6952. });
  6953. return {
  6954. setActive,
  6955. update() {
  6956. if (referenceChild.style.backgroundColor) setBackgroundColor(child.style.backgroundColor = referenceChild.style.backgroundColor);
  6957. setImages(getImages());
  6958. }
  6959. };
  6960. };
  6961. let dialogInstance;
  6962. const rescanLayers = () => {
  6963. const [newDialog] = Array.from(layers().children).filter(el => el.querySelector('[aria-labelledby="modal-header"][role="dialog"]')?.firstChild?.firstChild?.childNodes[2]);
  6964. if (newDialog !== dialog || !newDialog) {
  6965. dialogInstance?.dispose();
  6966. dialogInstance = void 0;
  6967. dialog = newDialog;
  6968. if (!dialog) return;
  6969. dialogInstance = createRoot(dispose => {
  6970. const dialog2 = createDialog();
  6971. return {
  6972. ...dialog2,
  6973. dispose
  6974. };
  6975. });
  6976. }
  6977. const newIndex = Number(location.pathname.match(/\/status\/\d+\/photo\/(\d+)/)?.[1]) - 1;
  6978. dialogInstance.setActive(newIndex);
  6979. dialogInstance.update();
  6980. };
  6981. onCleanup(() => {
  6982. dialogInstance?.dispose();
  6983. });
  6984. let stopLayersObserver;
  6985. const onLayersUpdate = () => {
  6986. stopLayersObserver?.();
  6987. const [, {
  6988. stop
  6989. }] = createMutationObserver(() => layers(), {
  6990. childList: true,
  6991. subtree: true
  6992. }, throttle(() => rescanLayers(), 200));
  6993. stopLayersObserver = stop;
  6994. rescanLayers();
  6995. };
  6996. createEffect(prev => {
  6997. const id = statusId();
  6998. if (!id) stopLayersObserver?.();
  6999. if (id && id !== prev) {
  7000. const layers2 = document.getElementById("layers");
  7001. setLayers(layers2);
  7002. if (layers2) {
  7003. onLayersUpdate();
  7004. } else {
  7005. const [, {
  7006. stop
  7007. }] = createMutationObserver(document.body, {
  7008. childList: true,
  7009. subtree: true
  7010. }, throttle(() => {
  7011. const layers3 = document.getElementById("layers");
  7012. setLayers(layers3);
  7013. if (layers3) {
  7014. onLayersUpdate();
  7015. stop();
  7016. }
  7017. }, 200));
  7018. }
  7019. }
  7020. return id;
  7021. });
  7022. return {
  7023. canKeep(url) {
  7024. switch (keepInstances()) {
  7025. case "until-reload":
  7026. return url.startsWith("https://twitter.com/");
  7027. case "until-navigate":
  7028. return url.startsWith(`https://twitter.com/${mountAuthorId}`);
  7029. default:
  7030. return false;
  7031. }
  7032. },
  7033. onURLChange(url) {
  7034. setStatusId(url.match(/\/status\/(\d+)/)?.[1]);
  7035. }
  7036. };
  7037. }
  7038. const translator$1 = {
  7039. // https://twitter.com/<user>/status/<id>
  7040. match(url) {
  7041. return url.hostname.endsWith("twitter.com") && url.pathname.match(/\/status\//);
  7042. },
  7043. mount: mount$2
  7044. };
  7045.  
  7046. const _tmpl$$3 = /*#__PURE__*/template(`<div><div><h2>`);
  7047. function mount$1() {
  7048. let settingsTab;
  7049. let disposeText;
  7050. const checkTab = () => {
  7051. const tablist = document.querySelector('[role="tablist"]') || document.querySelector('[data-testid="loggedOutPrivacySection"]');
  7052. if (!tablist) {
  7053. if (disposeText) {
  7054. disposeText();
  7055. disposeText = void 0;
  7056. }
  7057. return;
  7058. }
  7059. if (tablist.querySelector(`div[data-imgtrans-settings-${EDITION}]`)) return;
  7060. const inactiveRefrenceEl = Array.from(tablist.children).find(el => el.children.length < 2 && el.querySelector("a"));
  7061. if (!inactiveRefrenceEl) return;
  7062. settingsTab = inactiveRefrenceEl.cloneNode(true);
  7063. settingsTab.setAttribute(`data-imgtrans-settings-${EDITION}`, "true");
  7064. const textEl = settingsTab.querySelector("span");
  7065. if (textEl) {
  7066. while (textEl.firstChild) textEl.removeChild(textEl.firstChild);
  7067. disposeText = render(() => t$1("settings.title")(), textEl);
  7068. onCleanup(disposeText);
  7069. }
  7070. const linkEl = settingsTab.querySelector("a");
  7071. if (linkEl) linkEl.href = `/settings/__imgtrans_${EDITION}`;
  7072. tablist.appendChild(settingsTab);
  7073. };
  7074. let disposeSettings;
  7075. const checkSettings = () => {
  7076. const section = document.querySelector('[data-testid="error-detail"]')?.parentElement?.parentElement;
  7077. if (!section?.querySelector(`[data-imgtrans-settings-${EDITION}-section]`)) {
  7078. if (disposeSettings) {
  7079. disposeSettings();
  7080. disposeSettings = void 0;
  7081. }
  7082. if (!section) return;
  7083. }
  7084. const title = `${t$1("settings.title")()} / Twitter`;
  7085. if (document.title !== title) document.title = title;
  7086. if (disposeSettings) return;
  7087. const errorPage = section.firstChild;
  7088. errorPage.style.display = "none";
  7089. const settingsContainer = document.createElement("div");
  7090. settingsContainer.setAttribute(`data-imgtrans-settings-${EDITION}-section`, "true");
  7091. section.appendChild(settingsContainer);
  7092. const disposeSettingsApp = render(() => {
  7093. onCleanup(() => {
  7094. errorPage.style.display = "";
  7095. });
  7096. return (// r-37j5jr: twitter font
  7097. (() => {
  7098. const _el$ = _tmpl$$3(),
  7099. _el$2 = _el$.firstChild,
  7100. _el$3 = _el$2.firstChild;
  7101. insert(_el$3, t$1("settings.title"));
  7102. insert(_el$, createComponent(Settings, {}), null);
  7103. createRenderEffect(_p$ => {
  7104. const _v$ = `${tw("px-4")} r-37j5jr`,
  7105. _v$2 = tw("flex items-center h-14"),
  7106. _v$3 = tw("text-xl leading-6");
  7107. _v$ !== _p$._v$ && className(_el$, _p$._v$ = _v$);
  7108. _v$2 !== _p$._v$2 && className(_el$2, _p$._v$2 = _v$2);
  7109. _v$3 !== _p$._v$3 && className(_el$3, _p$._v$3 = _v$3);
  7110. return _p$;
  7111. }, {
  7112. _v$: undefined,
  7113. _v$2: undefined,
  7114. _v$3: undefined
  7115. });
  7116. return _el$;
  7117. })()
  7118. );
  7119. }, settingsContainer);
  7120. disposeSettings = () => {
  7121. disposeSettingsApp();
  7122. settingsContainer.remove();
  7123. };
  7124. onCleanup(disposeSettings);
  7125. };
  7126. createMutationObserver(document.body, {
  7127. childList: true,
  7128. subtree: true
  7129. }, throttle(() => {
  7130. if (!location.pathname.startsWith("/settings")) return;
  7131. if (location.pathname === "/settings/profile") return;
  7132. checkTab();
  7133. if (location.pathname.match(`/settings/__imgtrans_${EDITION}`)) {
  7134. if (settingsTab && settingsTab.children.length < 2) {
  7135. settingsTab.style.backgroundColor = "#F7F9F9";
  7136. const activeIndicator = document.createElement("div");
  7137. activeIndicator.className = tw("absolute z-10 inset-0 border-y-0 border-l-0 border-r-2 border-solid border-[#1D9Bf0] pointer-events-none");
  7138. settingsTab.appendChild(activeIndicator);
  7139. }
  7140. checkSettings();
  7141. } else {
  7142. if (settingsTab && settingsTab.children.length > 1) {
  7143. settingsTab.style.backgroundColor = "";
  7144. settingsTab.removeChild(settingsTab.lastChild);
  7145. }
  7146. if (disposeSettings) {
  7147. disposeSettings();
  7148. disposeSettings = void 0;
  7149. }
  7150. }
  7151. }, 200));
  7152. return {
  7153. canKeep(url) {
  7154. return url.includes("twitter.com") && url.includes("/settings");
  7155. }
  7156. };
  7157. }
  7158. const settingsInjector = {
  7159. match(url) {
  7160. return url.hostname.endsWith("twitter.com") && (url.pathname === "/settings" || url.pathname.match(/^\/settings\//)) && url.pathname !== "/settings/profile";
  7161. },
  7162. mount: mount$1
  7163. };
  7164.  
  7165. // src/eventListener.ts
  7166. function makeEventListener(target, type, handler, options) {
  7167. target.addEventListener(type, handler, options);
  7168. return tryOnCleanup(target.removeEventListener.bind(target, type, handler, options));
  7169. }
  7170.  
  7171. const _tmpl$$2 = /*#__PURE__*/template(`<svg viewBox="0 0 24 24" width="1.2em" height="1.2em"><path fill="currentColor" d="M3.08 5.62a6.342 6.342 0 0 1 4.456-.33h.003c.638.188 1.153.484 1.547.881c.394.398.624.852.755 1.29c.202.678.18 1.422.168 1.838a5.73 5.73 0 0 0-.005.201v5.503a1 1 0 0 1-1.96.282a8.566 8.566 0 0 1-.08.039c-.964.462-2.397.92-3.877.507c-1.632-.457-2.453-1.81-2.572-3.136c-.114-1.28.41-2.736 1.682-3.448c1.529-.855 3.116-.839 4.262-.64a8.2 8.2 0 0 1 .555.116a2.45 2.45 0 0 0-.09-.689a1.046 1.046 0 0 0-.258-.454c-.121-.122-.325-.263-.69-.37a4.342 4.342 0 0 0-3.048.222a1 1 0 1 1-.848-1.811Zm4.037 4.957c-.884-.153-1.956-.137-2.943.416c-.424.237-.729.83-.667 1.523c.058.647.421 1.193 1.119 1.389c.79.22 1.681-.005 2.473-.385c.367-.176.68-.37.905-.523V10.8a6.321 6.321 0 0 0-.887-.222Zm9.186-3.53a1 1 0 0 1 .65 1.256a7.374 7.374 0 0 0-.155.584a17.546 17.546 0 0 0 1.964-.358a1 1 0 1 1 .476 1.942a20.18 20.18 0 0 1-2.842.473c-.064.338-.119.66-.166.964a5.988 5.988 0 0 1 1.796-.138A1 1 0 0 1 20 12c0 .11-.003.218-.006.326a4.752 4.752 0 0 1 2.103 2.164a4.436 4.436 0 0 1 .17 3.465c-.435 1.182-1.38 2.22-2.82 2.94a1 1 0 1 1-.895-1.79c1.06-.53 1.606-1.209 1.84-1.842a2.437 2.437 0 0 0-.1-1.91a2.723 2.723 0 0 0-.657-.864a8.405 8.405 0 0 1-2.735 4.06l.041.114a1 1 0 0 1-1.746.931a5.325 5.325 0 0 1-.988.32c-.795.17-1.824.148-2.5-.589c-.939-1.026-.863-2.6-.239-3.882c.495-1.017 1.374-1.984 2.638-2.7c.054-.523.133-1.086.239-1.698a19.88 19.88 0 0 1-1.417-.047a1 1 0 0 1 .143-1.995c.531.037 1.087.05 1.652.037c.088-.445.2-.954.324-1.343a1 1 0 0 1 1.256-.65Zm-2.278 8.233c-.344.34-.593.698-.758 1.038c-.424.87-.257 1.451-.095 1.645l.003.001c.027.012.186.085.615-.006c.203-.043.431-.118.674-.227a9.571 9.571 0 0 1-.341-1.478a10.843 10.843 0 0 1-.098-.973Zm2.172 1.205a6.363 6.363 0 0 0 1.568-2.73l-1.651.265a6.47 6.47 0 0 0-.1.036a10.39 10.39 0 0 0 .087 1.905c.028.187.06.361.096.524Z">`);
  7172. const IconFluentTranslate24Filled = ((props = {}) => (() => {
  7173. const _el$ = _tmpl$$2();
  7174. spread(_el$, props, true, true);
  7175. return _el$;
  7176. })());
  7177.  
  7178. const _tmpl$$1 = /*#__PURE__*/template(`<svg viewBox="0 0 24 24" width="1.2em" height="1.2em"><path fill="currentColor" d="M7.207 2.543a1 1 0 0 1 0 1.414L5.414 5.75h7.836a8 8 0 1 1-8 8a1 1 0 1 1 2 0a6 6 0 1 0 6-6H5.414l1.793 1.793a1 1 0 0 1-1.414 1.414l-3.5-3.5a1 1 0 0 1 0-1.414l3.5-3.5a1 1 0 0 1 1.414 0Z">`);
  7179. const IconFluentArrowReset24Filled = ((props = {}) => (() => {
  7180. const _el$ = _tmpl$$1();
  7181. spread(_el$, props, true, true);
  7182. return _el$;
  7183. })());
  7184.  
  7185. const _tmpl$ = /*#__PURE__*/template(`<div>`),
  7186. _tmpl$2 = /*#__PURE__*/template(`<div><div>`),
  7187. _tmpl$3 = /*#__PURE__*/template(`<div><label><input type="checkbox">`),
  7188. _tmpl$4 = /*#__PURE__*/template(`<div><div></div><div><select>`),
  7189. _tmpl$5 = /*#__PURE__*/template(`<option>`);
  7190. function mount() {
  7191. const appName = document.querySelector("meta[name~=application-name][content]")?.content;
  7192. const isCalckey = appName === "Calckey";
  7193. const origUrl = new URL(location.href);
  7194. const [translatedMap, setTranslatedMap] = createStore({});
  7195. const [translateStatusMap, setTranslateStatusMap] = createStore({});
  7196. const [translateEnabledMap, setTranslateEnabledMap] = createStore({});
  7197. const originalImageMap = {};
  7198. const [pswp, setPswp] = createSignal(null);
  7199. const updatePswp = () => setPswp(Array.from(document.body.children).find(el => el.classList.contains("pswp")));
  7200. updatePswp();
  7201. if (isCalckey) {
  7202. createMutationObserver(document.body, {
  7203. childList: true
  7204. }, updatePswp);
  7205. }
  7206. const createDialog = () => {
  7207. const [image, setImage] = createSignal(null);
  7208. const [currentImg, setCurrentImage] = createSignal();
  7209. const firstButton = createMemo(() => pswp().querySelector(".pswp__button"));
  7210. const getImage = () => {
  7211. return pswp().querySelector('[aria-hidden="false"] img.pswp__img');
  7212. };
  7213. const updateImage = () => {
  7214. const img = getImage();
  7215. setImage(img);
  7216. setCurrentImage(img ? img.getAttribute("data-transurl") || img.src : void 0);
  7217. };
  7218. updateImage();
  7219. const getActiveContainer = () => pswp().lastElementChild.firstElementChild.firstElementChild.nextElementSibling.firstElementChild;
  7220. const [activeContainer, setActiveContainer] = createSignal(getActiveContainer());
  7221. pswp()?.querySelectorAll(".pswp__button--arrow--prev, .pswp__button--arrow--next").forEach(el => makeEventListener(el, "click", () => {
  7222. setActiveContainer(getActiveContainer());
  7223. updateImage();
  7224. }));
  7225. try {
  7226. createMutationObserver(activeContainer, {
  7227. childList: true
  7228. }, updateImage);
  7229. } catch (e) {}
  7230. createEffect(() => {
  7231. const img = image();
  7232. if (!img) return;
  7233. if (img.hasAttribute("data-transurl")) {
  7234. const transurl = img.getAttribute("data-transurl");
  7235. if (!translateEnabledMap[transurl]) {
  7236. img.src = transurl;
  7237. img.removeAttribute("data-transurl");
  7238. }
  7239. } else if (translateEnabledMap[img.src] && translatedMap[img.src]) {
  7240. const ori = img.src;
  7241. img.setAttribute("data-transurl", ori);
  7242. img.src = translatedMap[ori];
  7243. }
  7244. });
  7245. const getTranslatedImage = async (url, optionsOverwrite) => {
  7246. if (!optionsOverwrite && translatedMap[url]) return translatedMap[url];
  7247. const setStatus = t2 => setTranslateStatusMap(url, () => t2);
  7248. setStatus(t$1("common.source.download-image"));
  7249. if (!originalImageMap[url]) {
  7250. const result = await GMP.xmlHttpRequest({
  7251. method: "GET",
  7252. responseType: "blob",
  7253. url,
  7254. headers: {
  7255. referer: `https://${origUrl.hostname}/`
  7256. },
  7257. overrideMimeType: "text/plain; charset=x-user-defined",
  7258. onprogress(e) {
  7259. if (e.lengthComputable) {
  7260. setStatus(t$1("common.source.download-image-progress", {
  7261. progress: formatProgress(e.loaded, e.total)
  7262. }));
  7263. }
  7264. }
  7265. }).catch(e => {
  7266. setStatus(t$1("common.source.download-image-error"));
  7267. throw e;
  7268. });
  7269. originalImageMap[url] = result.response;
  7270. }
  7271. const originalImage = originalImageMap[url];
  7272. const originalSrcSuffix = new URL(url).searchParams.get("format") || url.split(".")[1] || "jpg";
  7273. setStatus(t$1("common.client.resize"));
  7274. await new Promise(resolve => queueMicrotask(resolve));
  7275. const {
  7276. blob: resizedImage,
  7277. suffix: resizedSuffix
  7278. } = await resizeToSubmit(originalImage, originalSrcSuffix);
  7279. setStatus(t$1("common.client.submit"));
  7280. const task = await submitTranslate(resizedImage, resizedSuffix, {
  7281. onProgress(progress) {
  7282. setStatus(t$1("common.client.submit-progress", {
  7283. progress
  7284. }));
  7285. },
  7286. onFinal() {
  7287. setStatus(t$1("common.client.submit-final"));
  7288. }
  7289. }, optionsOverwrite).catch(e => {
  7290. setStatus(t$1("common.client.submit-error"));
  7291. throw e;
  7292. });
  7293. let maskUrl = task.result?.translation_mask;
  7294. if (!maskUrl) {
  7295. setStatus(t$1("common.status.pending"));
  7296. const res = await pullTranslationStatusPolling(task.id, setStatus).catch(e => {
  7297. setStatus(e);
  7298. throw e;
  7299. });
  7300. maskUrl = res.translation_mask;
  7301. }
  7302. setStatus(t$1("common.client.download-image"));
  7303. const mask = await downloadBlob(maskUrl, {
  7304. onProgress(progress) {
  7305. t$1("common.client.download-image-progress", {
  7306. progress
  7307. });
  7308. }
  7309. }).catch(e => {
  7310. setStatus(t$1("common.client.download-image-error"));
  7311. throw e;
  7312. });
  7313. const maskUri = URL.createObjectURL(mask);
  7314. setStatus(t$1("common.client.merging"));
  7315. const canvas = document.createElement("canvas");
  7316. const canvasCtx = canvas.getContext("2d");
  7317. const img = new Image();
  7318. img.src = URL.createObjectURL(resizedImage);
  7319. await new Promise(resolve => {
  7320. img.onload = () => {
  7321. canvas.width = img.width;
  7322. canvas.height = img.height;
  7323. canvasCtx.drawImage(img, 0, 0);
  7324. resolve(null);
  7325. };
  7326. });
  7327. const img2 = new Image();
  7328. img2.src = maskUri;
  7329. img2.crossOrigin = "anonymous";
  7330. await new Promise(resolve => {
  7331. img2.onload = () => {
  7332. canvasCtx.drawImage(img2, 0, 0);
  7333. resolve(null);
  7334. };
  7335. });
  7336. const translated = await new Promise(resolve => {
  7337. canvas.toBlob(blob => {
  7338. resolve(blob);
  7339. }, "image/png");
  7340. });
  7341. const translatedUri = URL.createObjectURL(translated);
  7342. setTranslatedMap(url, translatedUri);
  7343. setStatus(() => "");
  7344. return translatedUri;
  7345. };
  7346. const enable = async (url, optionsOverwrite) => {
  7347. await getTranslatedImage(url, optionsOverwrite);
  7348. setTranslateEnabledMap(url, true);
  7349. };
  7350. const disable = url => {
  7351. setTranslateEnabledMap(url, false);
  7352. };
  7353. const isEnabled = createMemo(() => {
  7354. const img = currentImg();
  7355. return img ? !!translateEnabledMap[img] : false;
  7356. });
  7357. const transStatus = createMemo(() => {
  7358. const img = currentImg();
  7359. return img ? translateStatusMap[img]?.() : "";
  7360. });
  7361. const isProcessing = createMemo(() => !!transStatus());
  7362. const [advancedMenuOpen, setAdvancedMenuOpen] = createSignal(false);
  7363. const container = firstButton().cloneNode(true);
  7364. container.style.display = "flex";
  7365. container.style.justifyContent = "center";
  7366. container.style.alignItems = "center";
  7367. container.style.flexDirection = "row";
  7368. container.style.flexWrap = "nowrap";
  7369. container.style.overflow = "visible";
  7370. container.removeAttribute("title");
  7371. container.removeAttribute("aria-label");
  7372. firstButton().parentElement.insertBefore(container, firstButton());
  7373. const submitTranslateTest = () => {
  7374. const img = currentImg();
  7375. return img && !translateStatusMap[img]?.();
  7376. };
  7377. container.onclick = e => {
  7378. e.stopPropagation();
  7379. if (advancedMenuOpen()) return;
  7380. if (!submitTranslateTest()) return;
  7381. if (isEnabled()) disable(currentImg());else enable(currentImg());
  7382. };
  7383. container.oncontextmenu = e => {
  7384. e.preventDefault();
  7385. e.stopPropagation();
  7386. if (isEnabled()) setAdvancedMenuOpen(false);else setAdvancedMenuOpen(v => !v);
  7387. };
  7388. container.onpointerdown = e => {
  7389. e.stopPropagation();
  7390. };
  7391. const spinnerContainer = container.appendChild(document.createElement("div"));
  7392. const disposeProcessingSpinner = render(() => createComponent(Show, {
  7393. get when() {
  7394. return isProcessing();
  7395. },
  7396. get children() {
  7397. const _el$ = _tmpl$();
  7398. createRenderEffect(() => className(_el$, tw("absolute top-1 -left-px w-7 h-7 m-4 border-1 border-solid border-x-transparent border-b-transparent border-t-white rounded-full animate-spin")));
  7399. return _el$;
  7400. }
  7401. }), spinnerContainer);
  7402. onCleanup(disposeProcessingSpinner);
  7403. const buttonIconContainer = document.createElement("div");
  7404. container.firstElementChild.remove();
  7405. container.appendChild(buttonIconContainer);
  7406. const disposeButtonIcon = render(() => createComponent(Dynamic, {
  7407. get component() {
  7408. return isEnabled() ? IconFluentArrowReset24Filled : IconFluentTranslate24Filled;
  7409. },
  7410. get ["class"]() {
  7411. return tw("text-white stroke-black w-6 h-6 mx-1 mb-1 mt-1.5");
  7412. },
  7413. style: {
  7414. "stroke-width": "0.5px"
  7415. }
  7416. }), buttonIconContainer);
  7417. onCleanup(disposeButtonIcon);
  7418. const buttonStatusContainer = document.createElement("div");
  7419. container.insertBefore(buttonStatusContainer, container.firstChild);
  7420. const disposeButtonStatus = render(() => {
  7421. const status = createMemo(() => transStatus());
  7422. const [advDetectRes, setAdvDetectRes] = createSignal(detectionResolution());
  7423. const [advRenderTextDir, setAdvRenderTextDir] = createSignal(renderTextOrientation());
  7424. const [advTextDetector, setAdvTextDetector] = createSignal(textDetector());
  7425. const [advTranslator, setAdvTranslator] = createSignal(translatorService());
  7426. const [forceRetry, setForceRetry] = createSignal(false);
  7427. createEffect(prev => {
  7428. const img = currentImg();
  7429. if (prev !== img) {
  7430. setAdvDetectRes(detectionResolution());
  7431. setAdvRenderTextDir(renderTextOrientation());
  7432. }
  7433. return img;
  7434. });
  7435. return (() => {
  7436. const _el$2 = _tmpl$();
  7437. insert(_el$2, createComponent(Switch, {
  7438. get children() {
  7439. return [createComponent(Match, {
  7440. get when() {
  7441. return status();
  7442. },
  7443. get children() {
  7444. const _el$3 = _tmpl$();
  7445. insert(_el$3, status);
  7446. createRenderEffect(() => className(_el$3, tw("mt-1.5 mr-2 px-2 py-1 rounded-2xl whitespace-nowrap bg-gray-500/70")));
  7447. return _el$3;
  7448. }
  7449. }), createComponent(Match, {
  7450. get when() {
  7451. return createMemo(() => !!currentImg())() && !translateEnabledMap[currentImg()];
  7452. },
  7453. get children() {
  7454. return createComponent(Show, {
  7455. get when() {
  7456. return advancedMenuOpen();
  7457. },
  7458. get fallback() {
  7459. return createComponent(IconCarbonChevronLeft, {
  7460. get ["class"]() {
  7461. return tw("mt-2 w-5 h-5 align-middle cursor-pointer");
  7462. },
  7463. onClick: e => {
  7464. e.stopPropagation();
  7465. setAdvancedMenuOpen(true);
  7466. }
  7467. });
  7468. },
  7469. get children() {
  7470. return [(() => {
  7471. const _el$4 = _tmpl$2(),
  7472. _el$5 = _el$4.firstChild;
  7473. _el$4.addEventListener("click", e => {
  7474. e.stopPropagation();
  7475. setAdvancedMenuOpen(false);
  7476. });
  7477. insert(_el$5, t$1("settings.inline-options-title"));
  7478. insert(_el$4, createComponent(IconCarbonChevronRight, {
  7479. get ["class"]() {
  7480. return tw("align-middle cursor-pointer");
  7481. }
  7482. }), null);
  7483. createRenderEffect(_p$ => {
  7484. const _v$ = tw("flex justify-between items-center pl-2 py-1"),
  7485. _v$2 = tw("text-lg");
  7486. _v$ !== _p$._v$ && className(_el$4, _p$._v$ = _v$);
  7487. _v$2 !== _p$._v$2 && className(_el$5, _p$._v$2 = _v$2);
  7488. return _p$;
  7489. }, {
  7490. _v$: undefined,
  7491. _v$2: undefined
  7492. });
  7493. return _el$4;
  7494. })(), (() => {
  7495. const _el$6 = _tmpl$3(),
  7496. _el$7 = _el$6.firstChild,
  7497. _el$8 = _el$7.firstChild;
  7498. insert(_el$6, createComponent(For, {
  7499. get each() {
  7500. return [[t$1("settings.detection-resolution"), advDetectRes, setAdvDetectRes, detectResOptions, detectResOptionsMap], [t$1("settings.text-detector"), advTextDetector, setAdvTextDetector, textDetectorOptions, textDetectorOptionsMap], [t$1("settings.translator"), advTranslator, setAdvTranslator, translatorOptions, translatorOptionsMap], [t$1("settings.render-text-orientation"), advRenderTextDir, setAdvRenderTextDir, renderTextDirOptions, renderTextDirOptionsMap]];
  7501. },
  7502. children: ([title, opt, setOpt, opts, optMap]) => (() => {
  7503. const _el$10 = _tmpl$4(),
  7504. _el$11 = _el$10.firstChild,
  7505. _el$12 = _el$11.nextSibling,
  7506. _el$13 = _el$12.firstChild;
  7507. insert(_el$11, title);
  7508. _el$13.addEventListener("change", e => {
  7509. setOpt(e.target.value);
  7510. });
  7511. insert(_el$13, createComponent(For, {
  7512. each: opts,
  7513. children: opt2 => (() => {
  7514. const _el$14 = _tmpl$5();
  7515. _el$14.value = opt2;
  7516. insert(_el$14, () =>
  7517. // @ts-expect-error optMap are incompatible with each other
  7518. optMap[opt2]());
  7519. return _el$14;
  7520. })()
  7521. }));
  7522. insert(_el$12, createComponent(IconCarbonChevronDown, {
  7523. get ["class"]() {
  7524. return tw("absolute top-1 right-1 pointer-events-none");
  7525. }
  7526. }), null);
  7527. createRenderEffect(_p$ => {
  7528. const _v$7 = tw("relative px-1"),
  7529. _v$8 = tw("w-full py-1 appearance-none text-white border-x-0 border-t-0 border-b border-solid border-gray-300 bg-transparent");
  7530. _v$7 !== _p$._v$7 && className(_el$12, _p$._v$7 = _v$7);
  7531. _v$8 !== _p$._v$8 && className(_el$13, _p$._v$8 = _v$8);
  7532. return _p$;
  7533. }, {
  7534. _v$7: undefined,
  7535. _v$8: undefined
  7536. });
  7537. createRenderEffect(() => _el$13.value = opt());
  7538. return _el$10;
  7539. })()
  7540. }), _el$7);
  7541. _el$8.addEventListener("change", e => {
  7542. setForceRetry(e.target.checked);
  7543. });
  7544. _el$8.checked = forceRetry();
  7545. insert(_el$7, t$1("settings.force-retry"), null);
  7546. createRenderEffect(_p$ => {
  7547. const _v$3 = tw("flex flex-col w-[14rem] gap-2 ml-2"),
  7548. _v$4 = tw("flex items-center cursor-pointer");
  7549. _v$3 !== _p$._v$3 && className(_el$6, _p$._v$3 = _v$3);
  7550. _v$4 !== _p$._v$4 && className(_el$7, _p$._v$4 = _v$4);
  7551. return _p$;
  7552. }, {
  7553. _v$3: undefined,
  7554. _v$4: undefined
  7555. });
  7556. return _el$6;
  7557. })(), (() => {
  7558. const _el$9 = _tmpl$();
  7559. _el$9.addEventListener("click", e => {
  7560. e.stopPropagation();
  7561. e.preventDefault();
  7562. if (!submitTranslateTest()) return;
  7563. if (translateEnabledMap[currentImg()]) return;
  7564. enable(currentImg(), {
  7565. detectionResolution: advDetectRes(),
  7566. renderTextOrientation: advRenderTextDir(),
  7567. textDetector: advTextDetector(),
  7568. translator: advTranslator(),
  7569. forceRetry: forceRetry()
  7570. });
  7571. setAdvancedMenuOpen(false);
  7572. });
  7573. insert(_el$9, t$1("common.control.translate"));
  7574. createRenderEffect(() => className(_el$9, tw("w-full mt-2 mb-1 py-1 border border-solid border-white rounded-full text-center cursor-pointer")));
  7575. return _el$9;
  7576. })()];
  7577. }
  7578. });
  7579. }
  7580. })];
  7581. }
  7582. }));
  7583. createRenderEffect(_p$ => {
  7584. const _v$5 = tw("absolute top-3.5 right-12 flex flex-col -mr-3 px-1 text-white rounded-2xl cursor-default pointer-events-initial"),
  7585. _v$6 = {
  7586. [tw("bg-gray-500/70")]: advancedMenuOpen()
  7587. };
  7588. _v$5 !== _p$._v$5 && className(_el$2, _p$._v$5 = _v$5);
  7589. _p$._v$6 = classList(_el$2, _v$6, _p$._v$6);
  7590. return _p$;
  7591. }, {
  7592. _v$5: undefined,
  7593. _v$6: undefined
  7594. });
  7595. return _el$2;
  7596. })();
  7597. }, buttonStatusContainer);
  7598. onCleanup(disposeButtonStatus);
  7599. onCleanup(() => {
  7600. container.remove();
  7601. const img = image();
  7602. if (img?.hasAttribute("data-transurl")) {
  7603. const transurl = img.getAttribute("data-transurl");
  7604. img.src = transurl;
  7605. img.removeAttribute("data-transurl");
  7606. }
  7607. setImage(null);
  7608. });
  7609. };
  7610. let disposeDialog;
  7611. createEffect(prev => {
  7612. if (pswp() !== prev || !pswp()) {
  7613. disposeDialog?.();
  7614. disposeDialog = void 0;
  7615. if (!pswp()) return null;
  7616. disposeDialog = createRoot(dispose => {
  7617. createDialog();
  7618. return dispose;
  7619. });
  7620. }
  7621. return pswp();
  7622. }, null);
  7623. onCleanup(() => {
  7624. disposeDialog?.();
  7625. });
  7626. return {
  7627. canKeep(url) {
  7628. const parsed = new URL(url);
  7629. switch (keepInstances()) {
  7630. case "until-reload":
  7631. return origUrl.hostname === parsed.hostname;
  7632. case "until-navigate":
  7633. return pswp();
  7634. default:
  7635. return false;
  7636. }
  7637. },
  7638. onURLChange(url) {
  7639. const parsed = new URL(url);
  7640. if (parsed.hash === "#pswp" || isCalckey) updatePswp();else setPswp(null);
  7641. }
  7642. };
  7643. }
  7644. const translator = {
  7645. // https://misskey.io/<slug>#pswp
  7646. match(url) {
  7647. const appName = document.querySelector("meta[name~=application-name][content]")?.content;
  7648. return appName === "Misskey" && new URL(url).hash === "#pswp" || appName === "Calckey";
  7649. },
  7650. mount
  7651. };
  7652.  
  7653. start([translator$2, translator$1, translator], [settingsInjector$1, settingsInjector]);
  7654.  
  7655. })();
  7656.  
  7657. /*
  7658. GNU GENERAL PUBLIC LICENSE
  7659. Version 3, 29 June 2007
  7660.  
  7661. Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
  7662. Everyone is permitted to copy and distribute verbatim copies
  7663. of this license document, but changing it is not allowed.
  7664.  
  7665. Preamble
  7666.  
  7667. The GNU General Public License is a free, copyleft license for
  7668. software and other kinds of works.
  7669.  
  7670. The licenses for most software and other practical works are designed
  7671. to take away your freedom to share and change the works. By contrast,
  7672. the GNU General Public License is intended to guarantee your freedom to
  7673. share and change all versions of a program--to make sure it remains free
  7674. software for all its users. We, the Free Software Foundation, use the
  7675. GNU General Public License for most of our software; it applies also to
  7676. any other work released this way by its authors. You can apply it to
  7677. your programs, too.
  7678.  
  7679. When we speak of free software, we are referring to freedom, not
  7680. price. Our General Public Licenses are designed to make sure that you
  7681. have the freedom to distribute copies of free software (and charge for
  7682. them if you wish), that you receive source code or can get it if you
  7683. want it, that you can change the software or use pieces of it in new
  7684. free programs, and that you know you can do these things.
  7685.  
  7686. To protect your rights, we need to prevent others from denying you
  7687. these rights or asking you to surrender the rights. Therefore, you have
  7688. certain responsibilities if you distribute copies of the software, or if
  7689. you modify it: responsibilities to respect the freedom of others.
  7690.  
  7691. For example, if you distribute copies of such a program, whether
  7692. gratis or for a fee, you must pass on to the recipients the same
  7693. freedoms that you received. You must make sure that they, too, receive
  7694. or can get the source code. And you must show them these terms so they
  7695. know their rights.
  7696.  
  7697. Developers that use the GNU GPL protect your rights with two steps:
  7698. (1) assert copyright on the software, and (2) offer you this License
  7699. giving you legal permission to copy, distribute and/or modify it.
  7700.  
  7701. For the developers' and authors' protection, the GPL clearly explains
  7702. that there is no warranty for this free software. For both users' and
  7703. authors' sake, the GPL requires that modified versions be marked as
  7704. changed, so that their problems will not be attributed erroneously to
  7705. authors of previous versions.
  7706.  
  7707. Some devices are designed to deny users access to install or run
  7708. modified versions of the software inside them, although the manufacturer
  7709. can do so. This is fundamentally incompatible with the aim of
  7710. protecting users' freedom to change the software. The systematic
  7711. pattern of such abuse occurs in the area of products for individuals to
  7712. use, which is precisely where it is most unacceptable. Therefore, we
  7713. have designed this version of the GPL to prohibit the practice for those
  7714. products. If such problems arise substantially in other domains, we
  7715. stand ready to extend this provision to those domains in future versions
  7716. of the GPL, as needed to protect the freedom of users.
  7717.  
  7718. Finally, every program is threatened constantly by software patents.
  7719. States should not allow patents to restrict development and use of
  7720. software on general-purpose computers, but in those that do, we wish to
  7721. avoid the special danger that patents applied to a free program could
  7722. make it effectively proprietary. To prevent this, the GPL assures that
  7723. patents cannot be used to render the program non-free.
  7724.  
  7725. The precise terms and conditions for copying, distribution and
  7726. modification follow.
  7727.  
  7728. TERMS AND CONDITIONS
  7729.  
  7730. 0. Definitions.
  7731.  
  7732. "This License" refers to version 3 of the GNU General Public License.
  7733.  
  7734. "Copyright" also means copyright-like laws that apply to other kinds of
  7735. works, such as semiconductor masks.
  7736.  
  7737. "The Program" refers to any copyrightable work licensed under this
  7738. License. Each licensee is addressed as "you". "Licensees" and
  7739. "recipients" may be individuals or organizations.
  7740.  
  7741. To "modify" a work means to copy from or adapt all or part of the work
  7742. in a fashion requiring copyright permission, other than the making of an
  7743. exact copy. The resulting work is called a "modified version" of the
  7744. earlier work or a work "based on" the earlier work.
  7745.  
  7746. A "covered work" means either the unmodified Program or a work based
  7747. on the Program.
  7748.  
  7749. To "propagate" a work means to do anything with it that, without
  7750. permission, would make you directly or secondarily liable for
  7751. infringement under applicable copyright law, except executing it on a
  7752. computer or modifying a private copy. Propagation includes copying,
  7753. distribution (with or without modification), making available to the
  7754. public, and in some countries other activities as well.
  7755.  
  7756. To "convey" a work means any kind of propagation that enables other
  7757. parties to make or receive copies. Mere interaction with a user through
  7758. a computer network, with no transfer of a copy, is not conveying.
  7759.  
  7760. An interactive user interface displays "Appropriate Legal Notices"
  7761. to the extent that it includes a convenient and prominently visible
  7762. feature that (1) displays an appropriate copyright notice, and (2)
  7763. tells the user that there is no warranty for the work (except to the
  7764. extent that warranties are provided), that licensees may convey the
  7765. work under this License, and how to view a copy of this License. If
  7766. the interface presents a list of user commands or options, such as a
  7767. menu, a prominent item in the list meets this criterion.
  7768.  
  7769. 1. Source Code.
  7770.  
  7771. The "source code" for a work means the preferred form of the work
  7772. for making modifications to it. "Object code" means any non-source
  7773. form of a work.
  7774.  
  7775. A "Standard Interface" means an interface that either is an official
  7776. standard defined by a recognized standards body, or, in the case of
  7777. interfaces specified for a particular programming language, one that
  7778. is widely used among developers working in that language.
  7779.  
  7780. The "System Libraries" of an executable work include anything, other
  7781. than the work as a whole, that (a) is included in the normal form of
  7782. packaging a Major Component, but which is not part of that Major
  7783. Component, and (b) serves only to enable use of the work with that
  7784. Major Component, or to implement a Standard Interface for which an
  7785. implementation is available to the public in source code form. A
  7786. "Major Component", in this context, means a major essential component
  7787. (kernel, window system, and so on) of the specific operating system
  7788. (if any) on which the executable work runs, or a compiler used to
  7789. produce the work, or an object code interpreter used to run it.
  7790.  
  7791. The "Corresponding Source" for a work in object code form means all
  7792. the source code needed to generate, install, and (for an executable
  7793. work) run the object code and to modify the work, including scripts to
  7794. control those activities. However, it does not include the work's
  7795. System Libraries, or general-purpose tools or generally available free
  7796. programs which are used unmodified in performing those activities but
  7797. which are not part of the work. For example, Corresponding Source
  7798. includes interface definition files associated with source files for
  7799. the work, and the source code for shared libraries and dynamically
  7800. linked subprograms that the work is specifically designed to require,
  7801. such as by intimate data communication or control flow between those
  7802. subprograms and other parts of the work.
  7803.  
  7804. The Corresponding Source need not include anything that users
  7805. can regenerate automatically from other parts of the Corresponding
  7806. Source.
  7807.  
  7808. The Corresponding Source for a work in source code form is that
  7809. same work.
  7810.  
  7811. 2. Basic Permissions.
  7812.  
  7813. All rights granted under this License are granted for the term of
  7814. copyright on the Program, and are irrevocable provided the stated
  7815. conditions are met. This License explicitly affirms your unlimited
  7816. permission to run the unmodified Program. The output from running a
  7817. covered work is covered by this License only if the output, given its
  7818. content, constitutes a covered work. This License acknowledges your
  7819. rights of fair use or other equivalent, as provided by copyright law.
  7820.  
  7821. You may make, run and propagate covered works that you do not
  7822. convey, without conditions so long as your license otherwise remains
  7823. in force. You may convey covered works to others for the sole purpose
  7824. of having them make modifications exclusively for you, or provide you
  7825. with facilities for running those works, provided that you comply with
  7826. the terms of this License in conveying all material for which you do
  7827. not control copyright. Those thus making or running the covered works
  7828. for you must do so exclusively on your behalf, under your direction
  7829. and control, on terms that prohibit them from making any copies of
  7830. your copyrighted material outside their relationship with you.
  7831.  
  7832. Conveying under any other circumstances is permitted solely under
  7833. the conditions stated below. Sublicensing is not allowed; section 10
  7834. makes it unnecessary.
  7835.  
  7836. 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
  7837.  
  7838. No covered work shall be deemed part of an effective technological
  7839. measure under any applicable law fulfilling obligations under article
  7840. 11 of the WIPO copyright treaty adopted on 20 December 1996, or
  7841. similar laws prohibiting or restricting circumvention of such
  7842. measures.
  7843.  
  7844. When you convey a covered work, you waive any legal power to forbid
  7845. circumvention of technological measures to the extent such circumvention
  7846. is effected by exercising rights under this License with respect to
  7847. the covered work, and you disclaim any intention to limit operation or
  7848. modification of the work as a means of enforcing, against the work's
  7849. users, your or third parties' legal rights to forbid circumvention of
  7850. technological measures.
  7851.  
  7852. 4. Conveying Verbatim Copies.
  7853.  
  7854. You may convey verbatim copies of the Program's source code as you
  7855. receive it, in any medium, provided that you conspicuously and
  7856. appropriately publish on each copy an appropriate copyright notice;
  7857. keep intact all notices stating that this License and any
  7858. non-permissive terms added in accord with section 7 apply to the code;
  7859. keep intact all notices of the absence of any warranty; and give all
  7860. recipients a copy of this License along with the Program.
  7861.  
  7862. You may charge any price or no price for each copy that you convey,
  7863. and you may offer support or warranty protection for a fee.
  7864.  
  7865. 5. Conveying Modified Source Versions.
  7866.  
  7867. You may convey a work based on the Program, or the modifications to
  7868. produce it from the Program, in the form of source code under the
  7869. terms of section 4, provided that you also meet all of these conditions:
  7870.  
  7871. a) The work must carry prominent notices stating that you modified
  7872. it, and giving a relevant date.
  7873.  
  7874. b) The work must carry prominent notices stating that it is
  7875. released under this License and any conditions added under section
  7876. 7. This requirement modifies the requirement in section 4 to
  7877. "keep intact all notices".
  7878.  
  7879. c) You must license the entire work, as a whole, under this
  7880. License to anyone who comes into possession of a copy. This
  7881. License will therefore apply, along with any applicable section 7
  7882. additional terms, to the whole of the work, and all its parts,
  7883. regardless of how they are packaged. This License gives no
  7884. permission to license the work in any other way, but it does not
  7885. invalidate such permission if you have separately received it.
  7886.  
  7887. d) If the work has interactive user interfaces, each must display
  7888. Appropriate Legal Notices; however, if the Program has interactive
  7889. interfaces that do not display Appropriate Legal Notices, your
  7890. work need not make them do so.
  7891.  
  7892. A compilation of a covered work with other separate and independent
  7893. works, which are not by their nature extensions of the covered work,
  7894. and which are not combined with it such as to form a larger program,
  7895. in or on a volume of a storage or distribution medium, is called an
  7896. "aggregate" if the compilation and its resulting copyright are not
  7897. used to limit the access or legal rights of the compilation's users
  7898. beyond what the individual works permit. Inclusion of a covered work
  7899. in an aggregate does not cause this License to apply to the other
  7900. parts of the aggregate.
  7901.  
  7902. 6. Conveying Non-Source Forms.
  7903.  
  7904. You may convey a covered work in object code form under the terms
  7905. of sections 4 and 5, provided that you also convey the
  7906. machine-readable Corresponding Source under the terms of this License,
  7907. in one of these ways:
  7908.  
  7909. a) Convey the object code in, or embodied in, a physical product
  7910. (including a physical distribution medium), accompanied by the
  7911. Corresponding Source fixed on a durable physical medium
  7912. customarily used for software interchange.
  7913.  
  7914. b) Convey the object code in, or embodied in, a physical product
  7915. (including a physical distribution medium), accompanied by a
  7916. written offer, valid for at least three years and valid for as
  7917. long as you offer spare parts or customer support for that product
  7918. model, to give anyone who possesses the object code either (1) a
  7919. copy of the Corresponding Source for all the software in the
  7920. product that is covered by this License, on a durable physical
  7921. medium customarily used for software interchange, for a price no
  7922. more than your reasonable cost of physically performing this
  7923. conveying of source, or (2) access to copy the
  7924. Corresponding Source from a network server at no charge.
  7925.  
  7926. c) Convey individual copies of the object code with a copy of the
  7927. written offer to provide the Corresponding Source. This
  7928. alternative is allowed only occasionally and noncommercially, and
  7929. only if you received the object code with such an offer, in accord
  7930. with subsection 6b.
  7931.  
  7932. d) Convey the object code by offering access from a designated
  7933. place (gratis or for a charge), and offer equivalent access to the
  7934. Corresponding Source in the same way through the same place at no
  7935. further charge. You need not require recipients to copy the
  7936. Corresponding Source along with the object code. If the place to
  7937. copy the object code is a network server, the Corresponding Source
  7938. may be on a different server (operated by you or a third party)
  7939. that supports equivalent copying facilities, provided you maintain
  7940. clear directions next to the object code saying where to find the
  7941. Corresponding Source. Regardless of what server hosts the
  7942. Corresponding Source, you remain obligated to ensure that it is
  7943. available for as long as needed to satisfy these requirements.
  7944.  
  7945. e) Convey the object code using peer-to-peer transmission, provided
  7946. you inform other peers where the object code and Corresponding
  7947. Source of the work are being offered to the general public at no
  7948. charge under subsection 6d.
  7949.  
  7950. A separable portion of the object code, whose source code is excluded
  7951. from the Corresponding Source as a System Library, need not be
  7952. included in conveying the object code work.
  7953.  
  7954. A "User Product" is either (1) a "consumer product", which means any
  7955. tangible personal property which is normally used for personal, family,
  7956. or household purposes, or (2) anything designed or sold for incorporation
  7957. into a dwelling. In determining whether a product is a consumer product,
  7958. doubtful cases shall be resolved in favor of coverage. For a particular
  7959. product received by a particular user, "normally used" refers to a
  7960. typical or common use of that class of product, regardless of the status
  7961. of the particular user or of the way in which the particular user
  7962. actually uses, or expects or is expected to use, the product. A product
  7963. is a consumer product regardless of whether the product has substantial
  7964. commercial, industrial or non-consumer uses, unless such uses represent
  7965. the only significant mode of use of the product.
  7966.  
  7967. "Installation Information" for a User Product means any methods,
  7968. procedures, authorization keys, or other information required to install
  7969. and execute modified versions of a covered work in that User Product from
  7970. a modified version of its Corresponding Source. The information must
  7971. suffice to ensure that the continued functioning of the modified object
  7972. code is in no case prevented or interfered with solely because
  7973. modification has been made.
  7974.  
  7975. If you convey an object code work under this section in, or with, or
  7976. specifically for use in, a User Product, and the conveying occurs as
  7977. part of a transaction in which the right of possession and use of the
  7978. User Product is transferred to the recipient in perpetuity or for a
  7979. fixed term (regardless of how the transaction is characterized), the
  7980. Corresponding Source conveyed under this section must be accompanied
  7981. by the Installation Information. But this requirement does not apply
  7982. if neither you nor any third party retains the ability to install
  7983. modified object code on the User Product (for example, the work has
  7984. been installed in ROM).
  7985.  
  7986. The requirement to provide Installation Information does not include a
  7987. requirement to continue to provide support service, warranty, or updates
  7988. for a work that has been modified or installed by the recipient, or for
  7989. the User Product in which it has been modified or installed. Access to a
  7990. network may be denied when the modification itself materially and
  7991. adversely affects the operation of the network or violates the rules and
  7992. protocols for communication across the network.
  7993.  
  7994. Corresponding Source conveyed, and Installation Information provided,
  7995. in accord with this section must be in a format that is publicly
  7996. documented (and with an implementation available to the public in
  7997. source code form), and must require no special password or key for
  7998. unpacking, reading or copying.
  7999.  
  8000. 7. Additional Terms.
  8001.  
  8002. "Additional permissions" are terms that supplement the terms of this
  8003. License by making exceptions from one or more of its conditions.
  8004. Additional permissions that are applicable to the entire Program shall
  8005. be treated as though they were included in this License, to the extent
  8006. that they are valid under applicable law. If additional permissions
  8007. apply only to part of the Program, that part may be used separately
  8008. under those permissions, but the entire Program remains governed by
  8009. this License without regard to the additional permissions.
  8010.  
  8011. When you convey a copy of a covered work, you may at your option
  8012. remove any additional permissions from that copy, or from any part of
  8013. it. (Additional permissions may be written to require their own
  8014. removal in certain cases when you modify the work.) You may place
  8015. additional permissions on material, added by you to a covered work,
  8016. for which you have or can give appropriate copyright permission.
  8017.  
  8018. Notwithstanding any other provision of this License, for material you
  8019. add to a covered work, you may (if authorized by the copyright holders of
  8020. that material) supplement the terms of this License with terms:
  8021.  
  8022. a) Disclaiming warranty or limiting liability differently from the
  8023. terms of sections 15 and 16 of this License; or
  8024.  
  8025. b) Requiring preservation of specified reasonable legal notices or
  8026. author attributions in that material or in the Appropriate Legal
  8027. Notices displayed by works containing it; or
  8028.  
  8029. c) Prohibiting misrepresentation of the origin of that material, or
  8030. requiring that modified versions of such material be marked in
  8031. reasonable ways as different from the original version; or
  8032.  
  8033. d) Limiting the use for publicity purposes of names of licensors or
  8034. authors of the material; or
  8035.  
  8036. e) Declining to grant rights under trademark law for use of some
  8037. trade names, trademarks, or service marks; or
  8038.  
  8039. f) Requiring indemnification of licensors and authors of that
  8040. material by anyone who conveys the material (or modified versions of
  8041. it) with contractual assumptions of liability to the recipient, for
  8042. any liability that these contractual assumptions directly impose on
  8043. those licensors and authors.
  8044.  
  8045. All other non-permissive additional terms are considered "further
  8046. restrictions" within the meaning of section 10. If the Program as you
  8047. received it, or any part of it, contains a notice stating that it is
  8048. governed by this License along with a term that is a further
  8049. restriction, you may remove that term. If a license document contains
  8050. a further restriction but permits relicensing or conveying under this
  8051. License, you may add to a covered work material governed by the terms
  8052. of that license document, provided that the further restriction does
  8053. not survive such relicensing or conveying.
  8054.  
  8055. If you add terms to a covered work in accord with this section, you
  8056. must place, in the relevant source files, a statement of the
  8057. additional terms that apply to those files, or a notice indicating
  8058. where to find the applicable terms.
  8059.  
  8060. Additional terms, permissive or non-permissive, may be stated in the
  8061. form of a separately written license, or stated as exceptions;
  8062. the above requirements apply either way.
  8063.  
  8064. 8. Termination.
  8065.  
  8066. You may not propagate or modify a covered work except as expressly
  8067. provided under this License. Any attempt otherwise to propagate or
  8068. modify it is void, and will automatically terminate your rights under
  8069. this License (including any patent licenses granted under the third
  8070. paragraph of section 11).
  8071.  
  8072. However, if you cease all violation of this License, then your
  8073. license from a particular copyright holder is reinstated (a)
  8074. provisionally, unless and until the copyright holder explicitly and
  8075. finally terminates your license, and (b) permanently, if the copyright
  8076. holder fails to notify you of the violation by some reasonable means
  8077. prior to 60 days after the cessation.
  8078.  
  8079. Moreover, your license from a particular copyright holder is
  8080. reinstated permanently if the copyright holder notifies you of the
  8081. violation by some reasonable means, this is the first time you have
  8082. received notice of violation of this License (for any work) from that
  8083. copyright holder, and you cure the violation prior to 30 days after
  8084. your receipt of the notice.
  8085.  
  8086. Termination of your rights under this section does not terminate the
  8087. licenses of parties who have received copies or rights from you under
  8088. this License. If your rights have been terminated and not permanently
  8089. reinstated, you do not qualify to receive new licenses for the same
  8090. material under section 10.
  8091.  
  8092. 9. Acceptance Not Required for Having Copies.
  8093.  
  8094. You are not required to accept this License in order to receive or
  8095. run a copy of the Program. Ancillary propagation of a covered work
  8096. occurring solely as a consequence of using peer-to-peer transmission
  8097. to receive a copy likewise does not require acceptance. However,
  8098. nothing other than this License grants you permission to propagate or
  8099. modify any covered work. These actions infringe copyright if you do
  8100. not accept this License. Therefore, by modifying or propagating a
  8101. covered work, you indicate your acceptance of this License to do so.
  8102.  
  8103. 10. Automatic Licensing of Downstream Recipients.
  8104.  
  8105. Each time you convey a covered work, the recipient automatically
  8106. receives a license from the original licensors, to run, modify and
  8107. propagate that work, subject to this License. You are not responsible
  8108. for enforcing compliance by third parties with this License.
  8109.  
  8110. An "entity transaction" is a transaction transferring control of an
  8111. organization, or substantially all assets of one, or subdividing an
  8112. organization, or merging organizations. If propagation of a covered
  8113. work results from an entity transaction, each party to that
  8114. transaction who receives a copy of the work also receives whatever
  8115. licenses to the work the party's predecessor in interest had or could
  8116. give under the previous paragraph, plus a right to possession of the
  8117. Corresponding Source of the work from the predecessor in interest, if
  8118. the predecessor has it or can get it with reasonable efforts.
  8119.  
  8120. You may not impose any further restrictions on the exercise of the
  8121. rights granted or affirmed under this License. For example, you may
  8122. not impose a license fee, royalty, or other charge for exercise of
  8123. rights granted under this License, and you may not initiate litigation
  8124. (including a cross-claim or counterclaim in a lawsuit) alleging that
  8125. any patent claim is infringed by making, using, selling, offering for
  8126. sale, or importing the Program or any portion of it.
  8127.  
  8128. 11. Patents.
  8129.  
  8130. A "contributor" is a copyright holder who authorizes use under this
  8131. License of the Program or a work on which the Program is based. The
  8132. work thus licensed is called the contributor's "contributor version".
  8133.  
  8134. A contributor's "essential patent claims" are all patent claims
  8135. owned or controlled by the contributor, whether already acquired or
  8136. hereafter acquired, that would be infringed by some manner, permitted
  8137. by this License, of making, using, or selling its contributor version,
  8138. but do not include claims that would be infringed only as a
  8139. consequence of further modification of the contributor version. For
  8140. purposes of this definition, "control" includes the right to grant
  8141. patent sublicenses in a manner consistent with the requirements of
  8142. this License.
  8143.  
  8144. Each contributor grants you a non-exclusive, worldwide, royalty-free
  8145. patent license under the contributor's essential patent claims, to
  8146. make, use, sell, offer for sale, import and otherwise run, modify and
  8147. propagate the contents of its contributor version.
  8148.  
  8149. In the following three paragraphs, a "patent license" is any express
  8150. agreement or commitment, however denominated, not to enforce a patent
  8151. (such as an express permission to practice a patent or covenant not to
  8152. sue for patent infringement). To "grant" such a patent license to a
  8153. party means to make such an agreement or commitment not to enforce a
  8154. patent against the party.
  8155.  
  8156. If you convey a covered work, knowingly relying on a patent license,
  8157. and the Corresponding Source of the work is not available for anyone
  8158. to copy, free of charge and under the terms of this License, through a
  8159. publicly available network server or other readily accessible means,
  8160. then you must either (1) cause the Corresponding Source to be so
  8161. available, or (2) arrange to deprive yourself of the benefit of the
  8162. patent license for this particular work, or (3) arrange, in a manner
  8163. consistent with the requirements of this License, to extend the patent
  8164. license to downstream recipients. "Knowingly relying" means you have
  8165. actual knowledge that, but for the patent license, your conveying the
  8166. covered work in a country, or your recipient's use of the covered work
  8167. in a country, would infringe one or more identifiable patents in that
  8168. country that you have reason to believe are valid.
  8169.  
  8170. If, pursuant to or in connection with a single transaction or
  8171. arrangement, you convey, or propagate by procuring conveyance of, a
  8172. covered work, and grant a patent license to some of the parties
  8173. receiving the covered work authorizing them to use, propagate, modify
  8174. or convey a specific copy of the covered work, then the patent license
  8175. you grant is automatically extended to all recipients of the covered
  8176. work and works based on it.
  8177.  
  8178. A patent license is "discriminatory" if it does not include within
  8179. the scope of its coverage, prohibits the exercise of, or is
  8180. conditioned on the non-exercise of one or more of the rights that are
  8181. specifically granted under this License. You may not convey a covered
  8182. work if you are a party to an arrangement with a third party that is
  8183. in the business of distributing software, under which you make payment
  8184. to the third party based on the extent of your activity of conveying
  8185. the work, and under which the third party grants, to any of the
  8186. parties who would receive the covered work from you, a discriminatory
  8187. patent license (a) in connection with copies of the covered work
  8188. conveyed by you (or copies made from those copies), or (b) primarily
  8189. for and in connection with specific products or compilations that
  8190. contain the covered work, unless you entered into that arrangement,
  8191. or that patent license was granted, prior to 28 March 2007.
  8192.  
  8193. Nothing in this License shall be construed as excluding or limiting
  8194. any implied license or other defenses to infringement that may
  8195. otherwise be available to you under applicable patent law.
  8196.  
  8197. 12. No Surrender of Others' Freedom.
  8198.  
  8199. If conditions are imposed on you (whether by court order, agreement or
  8200. otherwise) that contradict the conditions of this License, they do not
  8201. excuse you from the conditions of this License. If you cannot convey a
  8202. covered work so as to satisfy simultaneously your obligations under this
  8203. License and any other pertinent obligations, then as a consequence you may
  8204. not convey it at all. For example, if you agree to terms that obligate you
  8205. to collect a royalty for further conveying from those to whom you convey
  8206. the Program, the only way you could satisfy both those terms and this
  8207. License would be to refrain entirely from conveying the Program.
  8208.  
  8209. 13. Use with the GNU Affero General Public License.
  8210.  
  8211. Notwithstanding any other provision of this License, you have
  8212. permission to link or combine any covered work with a work licensed
  8213. under version 3 of the GNU Affero General Public License into a single
  8214. combined work, and to convey the resulting work. The terms of this
  8215. License will continue to apply to the part which is the covered work,
  8216. but the special requirements of the GNU Affero General Public License,
  8217. section 13, concerning interaction through a network will apply to the
  8218. combination as such.
  8219.  
  8220. 14. Revised Versions of this License.
  8221.  
  8222. The Free Software Foundation may publish revised and/or new versions of
  8223. the GNU General Public License from time to time. Such new versions will
  8224. be similar in spirit to the present version, but may differ in detail to
  8225. address new problems or concerns.
  8226.  
  8227. Each version is given a distinguishing version number. If the
  8228. Program specifies that a certain numbered version of the GNU General
  8229. Public License "or any later version" applies to it, you have the
  8230. option of following the terms and conditions either of that numbered
  8231. version or of any later version published by the Free Software
  8232. Foundation. If the Program does not specify a version number of the
  8233. GNU General Public License, you may choose any version ever published
  8234. by the Free Software Foundation.
  8235.  
  8236. If the Program specifies that a proxy can decide which future
  8237. versions of the GNU General Public License can be used, that proxy's
  8238. public statement of acceptance of a version permanently authorizes you
  8239. to choose that version for the Program.
  8240.  
  8241. Later license versions may give you additional or different
  8242. permissions. However, no additional obligations are imposed on any
  8243. author or copyright holder as a result of your choosing to follow a
  8244. later version.
  8245.  
  8246. 15. Disclaimer of Warranty.
  8247.  
  8248. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
  8249. APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  8250. HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
  8251. OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
  8252. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  8253. PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
  8254. IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
  8255. ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
  8256.  
  8257. 16. Limitation of Liability.
  8258.  
  8259. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  8260. WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
  8261. THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
  8262. GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  8263. USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
  8264. DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
  8265. PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
  8266. EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
  8267. SUCH DAMAGES.
  8268.  
  8269. 17. Interpretation of Sections 15 and 16.
  8270.  
  8271. If the disclaimer of warranty and limitation of liability provided
  8272. above cannot be given local legal effect according to their terms,
  8273. reviewing courts shall apply local law that most closely approximates
  8274. an absolute waiver of all civil liability in connection with the
  8275. Program, unless a warranty or assumption of liability accompanies a
  8276. copy of the Program in return for a fee.
  8277.  
  8278. END OF TERMS AND CONDITIONS
  8279.  
  8280. How to Apply These Terms to Your New Programs
  8281.  
  8282. If you develop a new program, and you want it to be of the greatest
  8283. possible use to the public, the best way to achieve this is to make it
  8284. free software which everyone can redistribute and change under these terms.
  8285.  
  8286. To do so, attach the following notices to the program. It is safest
  8287. to attach them to the start of each source file to most effectively
  8288. state the exclusion of warranty; and each file should have at least
  8289. the "copyright" line and a pointer to where the full notice is found.
  8290.  
  8291. <one line to give the program's name and a brief idea of what it does.>
  8292. Copyright (C) <year> <name of author>
  8293.  
  8294. This program is free software: you can redistribute it and/or modify
  8295. it under the terms of the GNU General Public License as published by
  8296. the Free Software Foundation, either version 3 of the License, or
  8297. (at your option) any later version.
  8298.  
  8299. This program is distributed in the hope that it will be useful,
  8300. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8301. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  8302. GNU General Public License for more details.
  8303.  
  8304. You should have received a copy of the GNU General Public License
  8305. along with this program. If not, see <https://www.gnu.org/licenses/>.
  8306.  
  8307. Also add information on how to contact you by electronic and paper mail.
  8308.  
  8309. If the program does terminal interaction, make it output a short
  8310. notice like this when it starts in an interactive mode:
  8311.  
  8312. <program> Copyright (C) <year> <name of author>
  8313. This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
  8314. This is free software, and you are welcome to redistribute it
  8315. under certain conditions; type `show c' for details.
  8316.  
  8317. The hypothetical commands `show w' and `show c' should show the appropriate
  8318. parts of the General Public License. Of course, your program's commands
  8319. might be different; for a GUI interface, you would use an "about box".
  8320.  
  8321. You should also get your employer (if you work as a programmer) or school,
  8322. if any, to sign a "copyright disclaimer" for the program, if necessary.
  8323. For more information on this, and how to apply and follow the GNU GPL, see
  8324. <https://www.gnu.org/licenses/>.
  8325.  
  8326. The GNU General Public License does not permit incorporating your program
  8327. into proprietary programs. If your program is a subroutine library, you
  8328. may consider it more useful to permit linking proprietary applications with
  8329. the library. If this is what you want to do, use the GNU Lesser General
  8330. Public License instead of this License. But first, please read
  8331. <https://www.gnu.org/licenses/why-not-lgpl.html>.
  8332. */
  8333.  
  8334. /*
  8335. MIT License
  8336.  
  8337. Copyright (c) 2021 Solid Primitives Working Group
  8338.  
  8339. Permission is hereby granted, free of charge, to any person obtaining a copy
  8340. of this software and associated documentation files (the "Software"), to deal
  8341. in the Software without restriction, including without limitation the rights
  8342. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8343. copies of the Software, and to permit persons to whom the Software is
  8344. furnished to do so, subject to the following conditions:
  8345.  
  8346. The above copyright notice and this permission notice shall be included in all
  8347. copies or substantial portions of the Software.
  8348.  
  8349. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  8350. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  8351. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  8352. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  8353. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  8354. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  8355. SOFTWARE.
  8356. */
  8357.  
  8358. /*
  8359. MIT License
  8360.  
  8361. Copyright (c) 2022 [these people](https://github.com/tw-in-js/twind/graphs/contributors)
  8362.  
  8363. Permission is hereby granted, free of charge, to any person obtaining a copy
  8364. of this software and associated documentation files (the "Software"), to deal
  8365. in the Software without restriction, including without limitation the rights
  8366. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8367. copies of the Software, and to permit persons to whom the Software is
  8368. furnished to do so, subject to the following conditions:
  8369.  
  8370. The above copyright notice and this permission notice shall be included in all
  8371. copies or substantial portions of the Software.
  8372.  
  8373. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  8374. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  8375. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  8376. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  8377. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  8378. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  8379. SOFTWARE.
  8380. */
  8381.  
  8382. /*
  8383. MIT License
  8384.  
  8385. Copyright (c) 2016-2023 Ryan Carniato
  8386.  
  8387. Permission is hereby granted, free of charge, to any person obtaining a copy
  8388. of this software and associated documentation files (the "Software"), to deal
  8389. in the Software without restriction, including without limitation the rights
  8390. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8391. copies of the Software, and to permit persons to whom the Software is
  8392. furnished to do so, subject to the following conditions:
  8393.  
  8394. The above copyright notice and this permission notice shall be included in all
  8395. copies or substantial portions of the Software.
  8396.  
  8397. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  8398. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  8399. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  8400. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  8401. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  8402. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  8403. SOFTWARE.
  8404. */
  8405.  
  8406. /*
  8407. Copyright (c) 2017-2018 Fredrik Nicol
  8408.  
  8409. Permission is hereby granted, free of charge, to any person obtaining a copy
  8410. of this software and associated documentation files (the "Software"), to deal
  8411. in the Software without restriction, including without limitation the rights
  8412. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8413. copies of the Software, and to permit persons to whom the Software is
  8414. furnished to do so, subject to the following conditions:
  8415.  
  8416. The above copyright notice and this permission notice shall be included in all
  8417. copies or substantial portions of the Software.
  8418.  
  8419. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  8420. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  8421. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  8422. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  8423. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  8424. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  8425. SOFTWARE.
  8426. */
  8427.  
  8428. /*
  8429. The MIT License (MIT)
  8430.  
  8431. Copyright (c) 2020-2022 Kristóf Poduszló
  8432.  
  8433. Permission is hereby granted, free of charge, to any person obtaining a copy
  8434. of this software and associated documentation files (the "Software"), to deal
  8435. in the Software without restriction, including without limitation the rights
  8436. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8437. copies of the Software, and to permit persons to whom the Software is
  8438. furnished to do so, subject to the following conditions:
  8439.  
  8440. The above copyright notice and this permission notice shall be included in all
  8441. copies or substantial portions of the Software.
  8442.  
  8443. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  8444. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  8445. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  8446. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  8447. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  8448. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  8449. SOFTWARE.
  8450. */
  8451.  
  8452. /*
  8453. MIT License Copyright (c) 2023 Alexis Munsayac <alexis.munsayac@gmail.com>
  8454.  
  8455. 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:
  8456.  
  8457. The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
  8458.  
  8459. 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.
  8460. */