all functions lib

none

当前为 2024-04-04 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name all functions lib
  3. // @version 1.0
  4. // @description none
  5. // @license GPLv3
  6. // @run-at document-start
  7. // @author You
  8. // @match *://*/*
  9. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABICAMAAABiM0N1AAAAAXNSR0IB2cksfwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAHJQTFRFAAAAEIijAo2yAI60BYyuF4WaFIifAY6zBI2wB4usGIaZEYigIoiZCIyrE4igG4iYD4mjEomhFoedCoqpDIqnDomlBYyvE4efEYmiDYqlA42xBoytD4mkCYqqGYSUFYidC4qoC4upAo6yCoupDYqmCYur4zowOQAAACZ0Uk5TAO////9vr////1+/D/+/L+/Pf/////+f3///////H4////////+5G91rAAACgUlEQVR4nM2Y22KjIBCGidg1264liZqDadK03X3/V2wNKHMC7MpF/xthHD5mgERAqZhWhfYqH6K+Qf2qNNf625hCoFj9/gblMUi5q5jLkXLCKudgyiRm0FMK82cWJp1fLbV5VmvJbCIc0GCYaFqqlDJgADdBjncqAXYobm1xh72aFMflbysteFfdy2Yi1XGOm5HGBzQ1dq7TzEoxjeNTjQZb7VA3e1c7+ImgasAgQ9+xusNVNZIo5xmOMgihIS2PbCQIiHEUdTvhxCcS/kPomfFI2zHy2PkWmA6aNatIJpKFJyekyy02xh5Y3DI9T4aOT6VhIUrsNTFp1pf79Z4SIIVDegl6IJO6cHiL/GimIZDhgTu/BlYWCQzHMl0zBWT/T3KAhtxOuUB9FtBrpsz0RV4xsjHmW+UCaffcSy/5viMGer0/6HdFNMZBq/vjJL38H9Dqx4Fuy0Em12DbZy+9pGtiDijbglwAehyj11n0tRD3WUBm+lwulE/8h4BuA+iWAQQnteg2Xm63WQLTpnMnpjdge0Mgu/GRPsV4xdjQ94Lfi624fabhDkfUqIKNrM64Q837v8yL0prasepCgrtvw1sJpoqanGEX7b5mQboNW8eawXaWXTMfMGxub472hzWzHSn6Sg2G9+6TAyRruE71s+zAzjWaknoyJCQzwxrghH2k5FDT4eqWunuNxyN9QCGcxVod5oADbYnIUkDTGZEf1xDJnSFteQ3KdsT8zYDMQXcHxsevcLH1TrsABzkNPyA/L7b0jg704viMMlpQI96WsHknCt/3YH0kOEo9zcGkwrFK39ck72rmoehmKqo2RKlilzSy/nJKEV45CT38myJp456fezktHjN5aeMAAAAASUVORK5CYII=
  10. // @grant none
  11. // @namespace https://gf.qytechs.cn/users/1184528
  12. // ==/UserScript==
  13. ;(async function () {
  14. const { savelib } = loadlib("libloader", "allfuncs.js")
  15. const proxy_set = new WeakSet()
  16. const oldproxy = Proxy
  17. window.Proxy = new Proxy(oldproxy, {
  18. construct(_target, args) {
  19. const proxy = new oldproxy(...args)
  20. proxy_set.add(proxy)
  21. return proxy
  22. },
  23. })
  24. const isproxy = function (proxy) {
  25. return proxy_set.has(proxy)
  26. }
  27. Object.keys(console).forEach((e) => {
  28. window[e] = function (...args) {
  29. var z = []
  30. let pi = 0
  31. args.forEach((y) => {
  32. let rand = `{${pi}}${a().randstr().val}`
  33. while (true) {
  34. if (isa(y)) {
  35. z.push("function_chain >")
  36. y = y.val
  37. continue
  38. } else if (a(y).gettype("promise").val) {
  39. pi++
  40. y.then((...args) => window[e]("RESOLVED - " + rand, ...args)).catch(
  41. (...args) => window[e]("REJECTED - " + rand, ...args)
  42. )
  43. y = "PROMISE - " + rand
  44. continue
  45. }
  46. z.push(y)
  47. break
  48. }
  49. })
  50. console[e](...z)
  51. return z
  52. }
  53. })
  54.  
  55. const warn = console.warn.bind(window)
  56. const log = console.log.bind(window)
  57. const error = console.error.bind(window)
  58. const time = console.time.bind(window)
  59. const timeEnd = console.timeEnd.bind(window)
  60. // Object.assign(window, console)
  61. // if (window.a) error("allfuncs allready exists")
  62. var getvm = function () {
  63. const oldBind = Function.prototype.bind
  64. Function.prototype.bind = function (...args) {
  65. if (
  66. args[0] &&
  67. args[0]?.hasOwnProperty?.("editingTarget") &&
  68. args[0].hasOwnProperty("runtime")
  69. ) {
  70. Function.prototype.bind = oldBind
  71. savelib("scratch", { vm: args[0] })
  72. }
  73. return oldBind.apply(this, args)
  74. }
  75. }
  76. getvm()
  77.  
  78. function isa(inp1) {
  79. return (
  80. inp1?.[Math.random()]?.name === "function_chain" ||
  81. inp1?.name === "function_chain"
  82. )
  83. }
  84.  
  85. function noa(inp1) {
  86. return isa(inp1) ? inp1.val : inp1
  87. }
  88. const blank = {}
  89. const isstrict = {}
  90. const ischaining = {}
  91.  
  92. function a(inp1, ic, temparr) {
  93. if (ic !== ischaining) {
  94. temparr = []
  95. }
  96. inp1 = noa(inp1)
  97. return new Proxy(
  98. {},
  99. {
  100. set(_obj, _prop, _val) {},
  101. get(_obj, prop) {
  102. if (prop == Symbol.toStringTag) {
  103. warn(Symbol.toStringTag)
  104. return "testing"
  105. }
  106. if (prop == Symbol.iterator) {
  107. switch (a(inp1).gettype().val) {
  108. case "string":
  109. return function* () {
  110. for (var i in inp1.split("")) yield inp1[i]
  111. }
  112. case "number":
  113. return function* () {
  114. for (var i in String(inp1).split("")) yield inp1[i]
  115. }
  116. case "array":
  117. return function* () {
  118. for (var i in inp1) yield inp1[i]
  119. }
  120. case "object":
  121. return function* () {
  122. for (var i in Object.entries(inp1)) yield inp1[i]
  123. }
  124. default:
  125. return function* () {
  126. yield inp1
  127. }
  128. }
  129. }
  130. if (prop == Symbol.toPrimitive) {
  131. return function (hint) {
  132. switch (hint) {
  133. case "number":
  134. if (Number(inp1) != inp1)
  135. error(`"${inp1}" is not a number or is nan`, inp1)
  136. return Number(inp1)
  137. case "string":
  138. if (a(inp1).gettype(["array", "object"]).val)
  139. return JSON.stringify(inp1)
  140. return String(inp1)
  141. case "default":
  142. if (a(inp1).gettype("string").val)
  143. if (String(Number(inp1)) == inp1) return Number(inp1)
  144. else return String(inp1)
  145. if (a(inp1).gettype(["array", "object"]).val)
  146. return JSON.stringify(inp1)
  147. if (a(inp1).gettype(["undefined", "null", "nan"]))
  148. return String(inp1)
  149. }
  150. error(prop, hint)
  151. return hint
  152. }
  153. }
  154. if (typeof prop == "symbol") log(prop)
  155. if (["end", "out", "ret", "done", "value", "val"].includes(prop)) {
  156. if (temparr.length) {
  157. var x = [...temparr]
  158. temparr = []
  159. return x
  160. }
  161. return inp1
  162. }
  163.  
  164. if (prop == "allfuncs")
  165. return new Proxy(allfuncs, {
  166. set(_a, s) {
  167. throw new Error(
  168. `you can't overwrite property "${s}" on "allfuncs".
  169. if you are trying to add a new function
  170. use allfuncs.new(function_name, function, folders)`
  171. )
  172. },
  173. deleteProperty(_a, s) {
  174. throw new Error(
  175. `you can't delete property "${s}" on "allfuncs".`
  176. )
  177. },
  178. })
  179. if (prop == "push")
  180. return new Proxy(
  181. {},
  182. {
  183. get(_a, s) {
  184. temparr.push(inp1[s])
  185. return a(inp1, ischaining, temparr)
  186. },
  187. }
  188. )
  189. if (prop == "get")
  190. return new Proxy(
  191. {},
  192. {
  193. get(_a, s) {
  194. return a(inp1[s], ischaining, temparr)
  195. },
  196. }
  197. )
  198. if (prop == "set")
  199. return new Proxy(
  200. {},
  201. {
  202. get(_a, s) {
  203. return function (val) {
  204. inp1[s] = val
  205. return a(inp1, ischaining, temparr)
  206. }
  207. },
  208. }
  209. )
  210. if (prop == "run")
  211. return new Proxy(
  212. {},
  213. {
  214. get(_a, s) {
  215. if (s == "same") {
  216. return new Proxy(
  217. {},
  218. {
  219. get(_a, s) {
  220. return function (...args) {
  221. var inp = inp1
  222. inp1[s](...args)
  223. return a(inp, ischaining, temparr)
  224. }
  225. },
  226. }
  227. )
  228. } else
  229. return function (...args) {
  230. return a(inp1[s](...args), ischaining, temparr)
  231. }
  232. },
  233. }
  234. )
  235. const { gettype } = allfuncs
  236. const function_chain = function (...rest) {
  237. if (gettype(allfuncs[prop]) !== "function")
  238. if (!gettype(inp1, ["undefined", "null", "nan"]))
  239. if (gettype(Object.getPrototypeOf(inp1)[prop], "function"))
  240. return a(
  241. Object.getPrototypeOf(inp1)[prop].call(inp1, ...rest)
  242. )
  243. else throw new Error(`"${prop}" is not a function`)
  244. var inps = inp1 === blank ? rest : [inp1, ...rest]
  245. var ret = allfuncs[prop](...inps)
  246. if (
  247. gettype(ret, "array") &&
  248. inp1?.strictargs?.[0] === isstrict &&
  249. ret?.strictargs?.[0] !== isstrict
  250. )
  251. switch (inp1.strictargs[1]) {
  252. case "object":
  253. ret = strictobj(
  254. inp1.strictargs[2],
  255. inp1.strictargs[3],
  256. ret,
  257. inp1.strictargs[5]
  258. )
  259. break
  260. case "array":
  261. ret = strictarr(
  262. inp1.strictargs[2],
  263. inp1.strictargs[3],
  264. ret,
  265. inp1.strictargs[5]
  266. )
  267. break
  268. }
  269. return a(ret)
  270. }
  271. var temp = {}
  272. Object.assign(temp, allfuncs[prop]?.function ?? {})
  273. Object.assign(temp, allfuncs[prop])
  274. Object.keys(temp).forEach((e) => {
  275. let func = temp[e]
  276. function_chain[e] = function (...args) {
  277. return a(func(...args))
  278. }
  279. })
  280.  
  281. if (gettype(allfuncs[prop], "function"))
  282. function_chain.inputs = getprops(allfuncs[prop])
  283. function_chain.same = function (...args) {
  284. var inp = inp1
  285. a(inp1, ischaining, temparr)[prop](...args)
  286. return a(inp, ischaining, temparr)
  287. }
  288. function_chain.run = function (obj) {
  289. var m = [...function_chain.inputs]
  290. m = m.vars.map((e, i) =>
  291. i == 0
  292. ? e.var in obj
  293. ? obj[e.var]
  294. : inp1 == blank
  295. ? undefined
  296. : inp1
  297. : obj[e.var]
  298. )
  299. var ret = allfuncs[prop](...m)
  300. if (inp1?.strictargs[0] === isstrict)
  301. switch (inp1.strictargs[1]) {
  302. case "object":
  303. ret = strictobj(
  304. inp1.strictargs[2],
  305. inp1.strictargs[3],
  306. ret,
  307. inp1.strictargs[5]
  308. )
  309. break
  310. case "array":
  311. ret = strictarr(
  312. inp1.strictargs[2],
  313. inp1.strictargs[3],
  314. ret,
  315. inp1.strictargs[5]
  316. )
  317. break
  318. }
  319. var shouldret = getprops(allfuncs[prop]).return
  320. if (
  321. shouldret
  322. .split("|")
  323. .find((type) => type == "any" || type == gettype(ret))
  324. )
  325. return a(ret)
  326. throw new Error(
  327. `the function "${prop}" returned a type of "${gettype(
  328. ret
  329. )}",\nwhich doesn't match type of "${shouldret}"`
  330. )
  331. }
  332. return function_chain
  333. },
  334. }
  335. )
  336. }
  337.  
  338. function expandederror( //error
  339. obj //object
  340. ) {
  341. error(obj)
  342. return Error(obj.message)
  343. }
  344. const strictfunction = function (
  345. //any
  346. func, //function|class
  347. name, //string|none
  348. notrequired //boolean|none
  349. ) {
  350. if (notrequired) {
  351. if (getprops(func).broken) {
  352. warn("the function is missing type data")
  353. return func
  354. }
  355. } else {
  356. if (getprops(func).broken) {
  357. error(getprops(func))
  358. throw new Error(`the function doesn't have the required type data`)
  359. }
  360. }
  361. var temp = function (...args) {
  362. var vars = getprops(func).vars
  363. if (
  364. vars.filter(
  365. (e) =>
  366. !(
  367. e.type.includes("?") ||
  368. e.type.split("|").includes("none") ||
  369. e.type.split("|").includes("undefined")
  370. )
  371. ).length > args.length
  372. ) {
  373. error(
  374. `function [${
  375. Object.getPrototypeOf(func).name || name || "unknown"
  376. }] - requires ${
  377. vars.filter((e) => !e.type.includes("?")).length
  378. } arguments but only found ${args.length}`
  379. )
  380. }
  381. vars.length = args.length
  382. vars.map(function (thing, index) {
  383. if (thing.type) {
  384. if (index > args.length - 1) {
  385. if (thing.type.includes("?") || thing.type.includes("none"))
  386. return true
  387. throw expandederror({
  388. message: `function [${
  389. Object.getPrototypeOf(func).name || name || "unknown"
  390. }] - input "${thing.var}" is not optional`,
  391. function_name:
  392. Object.getPrototypeOf(func).name || name || "unknown",
  393. function: func,
  394. values: args,
  395. function_string: String(func),
  396. })
  397. }
  398. if (
  399. thing.type.split("|").includes("array") &&
  400. a(args[index]).gettype("htmlcollection").val
  401. ) {
  402. args[index] = [...args[index]]
  403. }
  404. if (
  405. thing.type
  406. .split("|")
  407. .find(
  408. (type) =>
  409. (!!args[index] === true && type == "true") ||
  410. (!!args[index] === false && type == "false") ||
  411. (a(args[index]).gettype(["null", "undefined", "nan"]).val &&
  412. type == "none") ||
  413. type == "any" ||
  414. a(args[index]).gettype(type).val
  415. )
  416. )
  417. return true
  418. else if (
  419. thing.type.split("|").includes("elements") &&
  420. a(args[index]).toelem().gettype("array").val
  421. ) {
  422. args[index] = a(args[index]).toelem().val
  423. if (
  424. thing.type.split("|").includes("element") &&
  425. args[index].length === 1
  426. )
  427. args[index] = args[index][0]
  428. return true
  429. } else if (
  430. thing.type.split("|").includes("element") &&
  431. a(args[index]).toelem(true).gettype("element").val
  432. )
  433. args[index] = a(args[index]).toelem(true).val
  434. if (
  435. thing.type.split("|").includes("element") &&
  436. a(args[index]).toelem(true).gettype("element").val
  437. ) {
  438. args[index] = a(args[index]).toelem(true).val
  439. return true
  440. } else {
  441. throw expandederror({
  442. message: `function [${
  443. Object.getPrototypeOf(func).name || name || "unknown"
  444. }] - in "${thing.var}", the input of "${
  445. args[index]
  446. }" is a type of "${
  447. a(args[index]).gettype().val
  448. }", which doesn't match required type of "${thing.type}"`,
  449. function_name:
  450. Object.getPrototypeOf(func).name || name || "unknown",
  451. function: func,
  452. function_string: String(func),
  453. })
  454. }
  455. } else return true
  456. })
  457. var shouldret = getprops(func).return
  458. if (a(func).gettype("function").val) {
  459. var ret = func(
  460. ...args //...getprops(func).vars.map((_e, index) => args[index])
  461. )
  462. } else {
  463. var ret = new func(...args)
  464. }
  465. // if (args[0]?.strictargs?.[0] === isstrict)
  466. // switch (args[0].strictargs[1]) {
  467. // case "object":
  468. // ret = strictobj(
  469. // args[0].strictargs[2],
  470. // args[0].strictargs[3],
  471. // ret,
  472. // args[0].strictargs[5]
  473. // )
  474. // break
  475. // case "array":
  476. // ret = strictarr(
  477. // args[0].strictargs[2],
  478. // args[0].strictargs[3],
  479. // ret,
  480. // args[0].strictargs[5]
  481. // )
  482. // break
  483. // }
  484. if (
  485. shouldret
  486. .split("|")
  487. .find(
  488. (type) =>
  489. (!!ret === true && type == "true") ||
  490. (!!ret === false && type == "false") ||
  491. (["null", "undefined", "nan"].includes(a(ret).gettype().val) &&
  492. type == "none") ||
  493. type == "any" ||
  494. a(ret).gettype(type).val
  495. )
  496. )
  497. return ret
  498. throw expandederror({
  499. message: `the function [${
  500. Object.getPrototypeOf(func).name || name || "unknown"
  501. }] returned a type of "${
  502. a(ret).gettype().val
  503. }", which doesn't match type of "${shouldret}"`,
  504. function_name: Object.getPrototypeOf(func).name || name || "unknown",
  505. function: func,
  506. function_string: String(func),
  507. })
  508. }
  509. temp.function = func
  510. return temp
  511. }
  512. const getprops = (function () {
  513. var cache = {}
  514. return function (
  515. //array
  516. func //function
  517. ) {
  518. var test = String(func).match(/\(([^]*)/)[1]
  519. if (cache[test]) return cache[test]
  520.  
  521. var arr = []
  522. var x
  523. test = test
  524. .replaceAll(/\\./g, "")
  525. .replaceAll(/`[^]*?(?<!\\)`/g, "")
  526. .replaceAll(/'.*?(?<!\\)'/g, "")
  527. .replaceAll(/".*?(?<!\\)"/g, "")
  528. .replaceAll(/(\/\/).*|\/\*[^]*?\*(?<!\\)\//g, function (e, a) {
  529. arr.push(
  530. a
  531. ? e.replace("//", "")
  532. : e.replace(/^\/\*/, "").replace(/\*\/$/, "")
  533. )
  534. return `\u1111${arr.length - 1}\u1111`
  535. })
  536. .replaceAll(/\/.*?(?<!\\)\//g)
  537. var prevtest = test
  538. while (prevtest.match(/(?<![\]})])[{\[(]/)) {
  539. test = prevtest
  540. x = prevtest.match(/(?<![\]})].*?)[{\[(]/)
  541. if (!x) break
  542. var count = 0
  543. var i = 0
  544. var start = x.index
  545. var end = x.index
  546. while (i++ < 40) {
  547. if (/[\[{(]/.test(x[0])) count++
  548. else count--
  549. if (count == 0) break
  550. test = test.slice(x.index + 1)
  551. x = test.match(/[{\[(\])}]/)
  552. end += x.index + 1
  553. }
  554. prevtest = prevtest.slice(0, start) + "<><><>" + prevtest.slice(end + 1)
  555. }
  556. var fualtyreturn = false
  557. var temp = {
  558. return: arr[0],
  559. vars: [
  560. ...[
  561. ...prevtest
  562. .match(/[^]*?(?=\))/)[0]
  563. .matchAll(
  564. /(?<=(?:,|^)[^=]*)([a-zA-Z_$][\da-zA-Z_$]*)(?:(?:[^](?![a-zA-Z_$][\da-zA-Z_$].*,|,.*[a-zA-Z_$][\da-zA-Z_$]))*?(?:\s*=\s*)?[^\u1111]*\u1111(\d+)\u1111)?/g
  565. ),
  566. ].map((e, _i) => {
  567. if (e[2] == 0) fualtyreturn = true
  568. return {
  569. var: e[1],
  570. type: arr[e[2]],
  571. }
  572. }),
  573. ],
  574. }
  575. if (fualtyreturn) temp.return = undefined
  576. temp.broken = false
  577. if (temp.return == undefined) temp.broken = true
  578. temp.vars.forEach((e) => {
  579. if (e.type === undefined) temp.broken = true
  580. })
  581. // temp.return||='any'
  582. // temp.broken
  583. // temp.vars = temp.vars.map(e=>{return{...e, type:e.type||'any'}})
  584. cache[String(func).match(/\(([^]*)/)[1]] = temp
  585. return temp
  586. }
  587. })()
  588. const allfuncs = {
  589. new(name, func, folder) {
  590. if (this[name]) {
  591. name += Math.random()
  592. error(name)
  593. }
  594. this[name] =
  595. name == "gettype" || name == "toelem"
  596. ? func
  597. : strictfunction(func, name, true)
  598. var arr = getprops(func)
  599. arr = [
  600. ...arr.vars,
  601. {
  602. return: arr.return,
  603. },
  604. ]
  605. if (
  606. arr.map((e) => e.type || e?.return).filter((e) => typeof e !== "string")
  607. .length
  608. )
  609. warn(name)
  610. this[name].help = arr
  611. this[name].function = func
  612. this[name].table = function () {
  613. var x = getprops(this?.function || allfuncs[name].function)
  614. var arr = {}
  615. x.vars.forEach((e) => {
  616. arr = {
  617. ...arr,
  618. ...{
  619. [e.var]: e.type,
  620. },
  621. }
  622. })
  623. table({
  624. ...arr,
  625. broken: x.broken,
  626. return: x.return,
  627. })
  628. }
  629. if (!folder) folder = "unknown"
  630. if (folder.includes("/")) folder = folder.split("/")
  631. else if (typeof folder == "string") folder = [folder]
  632. folder.forEach((folder) => {
  633. if (!this.folders) this.folders = {}
  634. if (!this.folders[folder]) this.folders[folder] = {}
  635. this.folders[folder][name] = func
  636. this.folders[folder][name].help = arr
  637. })
  638. this[name].folders = folder
  639. Object.defineProperty(a, "length", {
  640. //new
  641. //folders
  642. value: Object.keys(allfuncs).length - 2,
  643. })
  644. return this[name]
  645. },
  646. }
  647. class tween {
  648. #from
  649. #to
  650. #time
  651. #delay
  652. #loopondone
  653. #reverseondone
  654. #updatefunc = []
  655. #donefunc = []
  656. #active = 0
  657. #firstfrom
  658. #firstto
  659. constructor(
  660. //object
  661. from, //number
  662. to, //number
  663. time, //number
  664. delay, //number
  665. loopondone, //boolean|none
  666. reverseondone, //boolean|none
  667. ignorefocusloss //boolean|none
  668. ) {
  669. if (typeof from == "number") {
  670. this.#from = from
  671. this.#to = to
  672. this.#time = time
  673. this.#delay = delay
  674. this.#loopondone = loopondone
  675. this.#reverseondone = reverseondone
  676. } else if (typeof from == "object") {
  677. a(from).foreach(function (key, value) {
  678. this["#" + key] = value
  679. })
  680. }
  681. this.restart = this.restart
  682. this.onchange = this.onchange
  683. this.ondone = this.ondone
  684. this.#firstfrom = this.#from
  685. this.#firstto = this.#to
  686. const top = this
  687. if (!ignorefocusloss) {
  688. a(window).listen("blur", function () {
  689. if (!top.paused) top.paused = 1
  690. })
  691. a(window).listen("focus", function () {
  692. if (top.paused === 1) top.paused = false
  693. })
  694. }
  695. if (this.#loopondone) this.#reverseondone = false
  696. this.#updatefunc = []
  697. this.#donefunc = []
  698. this.#go()
  699. }
  700. restart() {
  701. this.#from = this.#firstfrom
  702. this.#to = this.#firstto
  703. this.#go()
  704. }
  705. async #go() {
  706. this.#active++
  707. var lastactive = this.#active
  708. var from = this.#from
  709. var to = this.#to
  710. var time = this.#time
  711. var delay = this.#delay || 30
  712. this.out = this.#from
  713. var i = 0
  714. var last = Date.now()
  715. var dt = 0
  716. while (i < time) {
  717. if (lastactive !== this.#active) return
  718. await a(() => !this.paused).waituntil().val
  719. a(() => this.#updatefunc.forEach((e) => e(this.out))).ignore()
  720. last = Date.now()
  721. var lastwait = delay - dt
  722. var dt = await a(lastwait).wait().val
  723. dt = Date.now() - last
  724. i += dt
  725. dt -= lastwait
  726. if (lastactive !== this.#active) return
  727. this.out = a(i).rerange(0, time, from, to).val
  728. }
  729. if (lastactive !== this.#active) return
  730. this.out = to
  731. a(() => this.#updatefunc.forEach((e) => e(this.out))).ignore()
  732. a(() => this.#donefunc.forEach((e) => e())).ignore()
  733. if (lastactive !== this.#active) return
  734. if (this.#reverseondone) {
  735. this.#flip()
  736. this.#go()
  737. }
  738. if (this.#loopondone) this.#go()
  739. }
  740. #flip() {
  741. var x = this.#from
  742. this.#from = this.#to
  743. this.#to = x
  744. }
  745. onchange(func) {
  746. this.#updatefunc.push(func)
  747. }
  748. ondone(func) {
  749. this.#donefunc.push(func)
  750. }
  751. destroy() {
  752. this.#active = null
  753. this.paused = false
  754. this.#updatefunc = undefined
  755. this.#donefunc = undefined
  756. var top = this
  757. a(this).foreach(function (a) {
  758. delete top[a]
  759. })
  760. }
  761. }
  762.  
  763. allfuncs.new("tween", tween, "time", false)
  764. allfuncs.new(
  765. "foreach",
  766. function (
  767. //none
  768. arr, //array|object|any
  769. func //function
  770. ) {
  771. var type = a(arr).gettype().val
  772. if (type == "array") arr.forEach(func)
  773. else if (type == "object") {
  774. Reflect.ownKeys(arr).forEach((e, i) => {
  775. func(e, arr[e], i)
  776. })
  777. } else {
  778. ;[arr].forEach(func)
  779. }
  780. },
  781. "array",
  782. true
  783. )
  784. allfuncs.new(
  785. "sendevent",
  786. function (
  787. //element
  788. element, //element
  789. eventName //string
  790. ) {
  791. function extend(destination, source) {
  792. for (var property in source) destination[property] = source[property]
  793. return destination
  794. }
  795.  
  796. var eventMatchers = {
  797. HTMLEvents:
  798. /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
  799. MouseEvents: /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/,
  800. }
  801. var defaultOptions = {
  802. pointerX: 0,
  803. pointerY: 0,
  804. button: 0,
  805. ctrlKey: false,
  806. altKey: false,
  807. shiftKey: false,
  808. metaKey: false,
  809. bubbles: true,
  810. cancelable: true,
  811. }
  812. var options = extend(defaultOptions, arguments[2] || {})
  813. var oEvent,
  814. eventType = null
  815.  
  816. for (var name in eventMatchers) {
  817. if (eventMatchers[name].test(eventName)) {
  818. eventType = name
  819. break
  820. }
  821. }
  822.  
  823. if (!eventType)
  824. throw new SyntaxError(
  825. "Only HTMLEvents and MouseEvents interfaces are supported"
  826. )
  827.  
  828. if (document.createEvent) {
  829. oEvent = document.createEvent(eventType)
  830. if (eventType == "HTMLEvents") {
  831. oEvent.initEvent(eventName, options.bubbles, options.cancelable)
  832. } else {
  833. oEvent.initMouseEvent(
  834. eventName,
  835. options.bubbles,
  836. options.cancelable,
  837. document.defaultView,
  838. options.button,
  839. options.pointerX,
  840. options.pointerY,
  841. options.pointerX,
  842. options.pointerY,
  843. options.ctrlKey,
  844. options.altKey,
  845. options.shiftKey,
  846. options.metaKey,
  847. options.button,
  848. element
  849. )
  850. }
  851. element.dispatchEvent(oEvent)
  852. } else {
  853. options.clientX = options.pointerX
  854. options.clientY = options.pointerY
  855. var evt = document.createEventObject()
  856. oEvent = extend(evt, options)
  857. element.fireEvent("on" + eventName, oEvent)
  858. }
  859. return element
  860. },
  861. "element/event/automation"
  862. )
  863. allfuncs.new(
  864. "ignore",
  865. function (
  866. //any
  867. func, //function
  868. senderr, //boolean|none
  869. ...args //any|none
  870. ) {
  871. try {
  872. return func(...args)
  873. } catch (e) {
  874. return senderr ? e.message : undefined
  875. }
  876. },
  877. "error",
  878. true
  879. )
  880. allfuncs.new(
  881. "wait",
  882. function (
  883. //promise
  884. ms //number
  885. ) {
  886. return new Promise(function (a) {
  887. var last = Date.now()
  888. setTimeout(() => a(Date.now() - last - ms), ms)
  889. })
  890. },
  891. "time",
  892. true
  893. )
  894. allfuncs.new(
  895. "waituntil",
  896. function (
  897. //promise
  898. q, //function
  899. cb //function|none
  900. ) {
  901. return new Promise((resolve) => {
  902. var last = Date.now()
  903. // if (!!q()) {
  904. // ignore(() => cb(Date.now() - last))
  905. // return resolve(Date.now() - last)
  906. // }
  907. var int = setInterval(
  908. function (q, cb) {
  909. if (!!q()) {
  910. clearInterval(int)
  911. a(() => cb(Date.now() - last)).ignore()
  912. resolve(Date.now() - last)
  913. }
  914. },
  915. 0,
  916. q,
  917. cb
  918. )
  919. })
  920. },
  921. "time",
  922. true
  923. )
  924. allfuncs.new(
  925. "keeponlyone",
  926. function (
  927. //array
  928. arr //array
  929. ) {
  930. return [...new Set(arr)]
  931. },
  932. "array",
  933. true
  934. )
  935. allfuncs.new(
  936. "inin",
  937. function (
  938. //any
  939. x, //any
  940. y, //array
  941. z //array
  942. ) {
  943. return z[y.indexOf(x)]
  944. },
  945. "array",
  946. true
  947. )
  948. allfuncs.new(
  949. "matchall",
  950. function (
  951. //array|string
  952. x, //string
  953. y //regex
  954. ) {
  955. return [...x.matchAll(y)].map((e) => (e[1] !== undefined ? [...e] : e[0]))
  956. },
  957. "regex",
  958. true
  959. )
  960. allfuncs.new(
  961. "matchany",
  962. function (
  963. //boolean
  964. x, //any
  965. ...y //any
  966. ) {
  967. return y.includes(x)
  968. },
  969. "string",
  970. true
  971. )
  972. allfuncs.new(
  973. "randfrom",
  974. function (
  975. //any
  976. min, //array|number
  977. max //undefined|number
  978. ) {
  979. if (max === undefined)
  980. return min.length ? min[a(0).randfrom(min.length - 1).val] : ""
  981. if (min == max) return min
  982. if (max) return Math.round(Math.random() * (max - min)) + min
  983. return min[Math.round(Math.random() * (min.length - 1))]
  984. },
  985. "number/array",
  986. true
  987. )
  988. allfuncs.new(
  989. "unlisten",
  990. function (
  991. //array
  992. data //array
  993. ) {
  994. data.forEach((data) => data[0].removeEventListener(data[1], data[2]))
  995. return data
  996. },
  997. "event/elem",
  998. true
  999. )
  1000. allfuncs.new(
  1001. "listen",
  1002. function (
  1003. //array
  1004. elem, //element
  1005. type, //string|object|array
  1006. cb //function|array|undefined
  1007. ) {
  1008. var all = []
  1009. if (a(type).gettype("array").val) {
  1010. var temp = {}
  1011. a(type).foreach((e) => (temp[e] = cb))
  1012. type = temp
  1013. }
  1014. if (a(type).gettype("object").val)
  1015. a(type).foreach(function (type, cb) {
  1016. if (a(type).gettype("string").val)
  1017. type = a(type).matchall(/[a-z]+/g).val
  1018. type.forEach((type) => {
  1019. const newcb = function (...e) {
  1020. cb(...e)
  1021. }
  1022. elem.addEventListener(type, newcb)
  1023. all.push([elem, type, newcb])
  1024. })
  1025. })
  1026. else if (a(type).gettype("string").val) {
  1027. type = a(type).matchall(/[a-z]+/g).val
  1028. type.forEach((type) => {
  1029. const newcb = function (e) {
  1030. cb(e, type)
  1031. }
  1032. elem.addEventListener(type, newcb)
  1033. all.push([elem, type, newcb])
  1034. })
  1035. }
  1036. return all
  1037. },
  1038. "event/elem",
  1039. true
  1040. )
  1041. allfuncs.new(
  1042. "toelem",
  1043. function (
  1044. //element|undefined|array
  1045. elem, //any
  1046. single //boolean|none
  1047. ) {
  1048. if (a(elem).gettype("element").val) return elem
  1049. switch (a(elem).gettype().val) {
  1050. case "string":
  1051. return single ? a(elem).qs().val : a(elem).qsa().val
  1052. case "array":
  1053. return elem.map((elem) => {
  1054. return a(elem).toelem(single).val
  1055. })
  1056. case "object":
  1057. var newobj = {
  1058. ...elem,
  1059. }
  1060. if (single)
  1061. return {
  1062. [Object.keys(newobj)[0]]: a(
  1063. newobj[Object.keys(newobj)[0]]
  1064. ).toelem(single).val,
  1065. }
  1066. a(newobj).foreach(function (a, s) {
  1067. newobj[a] = a(s).toelem().val
  1068. })
  1069. return newobj
  1070. default:
  1071. error(elem, "inside [toelem] - not an element?")
  1072. return undefined
  1073. }
  1074. },
  1075. "elem",
  1076. true
  1077. )
  1078. allfuncs.new(
  1079. "geturlperams",
  1080. function (
  1081. //object
  1082. e = location.href //undefined|string
  1083. ) {
  1084. var arr = {}
  1085. ;[...e.matchAll(/[?&]([^&\s]+?)(?:=([^&\s]*?))?(?=&|$|\s)/g)].forEach(
  1086. (e) => {
  1087. if (e[1].includes("#")) arr["#"] = e[1].match(/#(.*$)/)[1]
  1088. if (e[2].includes("#")) arr["#"] = e[2].match(/#(.*$)/)[1]
  1089. e[1] = e[1].replace(/#.*$/, "")
  1090. e[2] = e[2].replace(/#.*$/, "")
  1091. arr[decodeURIComponent(e[1]).replaceAll("+", " ")] =
  1092. e[2] === undefined
  1093. ? undefined
  1094. : decodeURIComponent(e[2]).replaceAll("+", " ")
  1095. }
  1096. )
  1097. return arr
  1098. },
  1099. "url",
  1100. false
  1101. )
  1102. allfuncs.new(
  1103. "updateurlperam",
  1104. function (
  1105. //string
  1106. key, //string
  1107. value, //string|undefined
  1108. cangoback //undefined|boolean
  1109. ) {
  1110. var g = {
  1111. ...a().geturlperams().val,
  1112. [key]: value,
  1113. }
  1114. var k = ""
  1115. var hash = ""
  1116. a(g).foreach(function (key, value) {
  1117. if (key == "#") return (hash = key + value)
  1118. key = encodeURIComponent(key)
  1119. value = encodeURIComponent(value)
  1120. k += "&" + (value === undefined ? key : key + "=" + value)
  1121. })
  1122. k = k.replace("&", "?")
  1123. k += hash
  1124. cangoback
  1125. ? history.pushState(null, null, k)
  1126. : history.replaceState(null, null, k)
  1127. return key
  1128. },
  1129. "url",
  1130. true
  1131. )
  1132. allfuncs.new(
  1133. "newvarfunc",
  1134. function (
  1135. //undefined
  1136. name, //string
  1137. func, //function
  1138. obj = window //undefined|object
  1139. ) {
  1140. Object.defineProperty(obj, name, {
  1141. configurable: false,
  1142. get() {
  1143. return func.call({})
  1144. },
  1145. set(a) {
  1146. return func.call(a, a, true)
  1147. },
  1148. })
  1149. },
  1150. "var",
  1151. true
  1152. )
  1153. allfuncs.new(
  1154. "rerange",
  1155. function (
  1156. //number
  1157. val, //number
  1158. low1, //number
  1159. high1, //number
  1160. low2, //number
  1161. high2 //number
  1162. ) {
  1163. return ((val - low1) / (high1 - low1)) * (high2 - low2) + low2
  1164. },
  1165. "number",
  1166. false
  1167. )
  1168. allfuncs.new(
  1169. "destring",
  1170. function (
  1171. //any
  1172. inp //string
  1173. ) {
  1174. var out = inp
  1175. if (/^[\-0-9]+$/.test(inp)) return Number(inp)
  1176. if (a((out = JSON.parse(inp))).gettype("array").val) return out
  1177. if (
  1178. a(
  1179. (out = JSON.parse(inp.replaceAll("'", '"').replaceAll("`", '"')))
  1180. ).gettype("object").val
  1181. )
  1182. return out
  1183. if (inp == "true") return true
  1184. if (inp == "false") return false
  1185. if (inp == "undefined") return undefined
  1186. if (inp == "NaN") return NaN
  1187. return inp
  1188. },
  1189. "string/parse",
  1190. true
  1191. )
  1192. allfuncs.new(
  1193. "eachelem",
  1194. function (
  1195. //array
  1196. arr1, //array
  1197. cb //function
  1198. ) {
  1199. var arr = []
  1200. var elem = []
  1201. if (a(arr1).gettype("array").val) {
  1202. arr1.foreach((e) => {
  1203. elem = [
  1204. ...elem,
  1205. ...(a(e).gettype("string").val ? a(e).qsa().val : [e]),
  1206. ]
  1207. })
  1208. } else {
  1209. elem = a(arr1).gettype("string").val ? a(ar1).qsa().val : [arr1]
  1210. }
  1211. elem = elem.filter((e) => {
  1212. return e instanceof Element
  1213. })
  1214. elem.foreach(function (...a) {
  1215. arr.push(cb(...a))
  1216. })
  1217. if (arr.length == 1) arr = arr[0]
  1218. return arr
  1219. },
  1220. "elem",
  1221. true
  1222. )
  1223. allfuncs.new(
  1224. "remove",
  1225. function (
  1226. //array
  1227. arr, //array
  1228. idx, //number|any
  1229. isidx //boolean|undefined
  1230. ) {
  1231. arr = [...arr]
  1232. idx = isidx ? idx : arr.indexOf(idx)
  1233. if (idx < 0 || typeof idx !== "number") return arr
  1234. arr.splice(idx, 1)
  1235. return arr
  1236. },
  1237. "array",
  1238. true
  1239. )
  1240. allfuncs.new(
  1241. "download",
  1242. function (
  1243. //string|file|blob
  1244. data, //string|file|blob
  1245. filename = "temp.txt", //string|undefined
  1246. type, //string|undefined
  1247. isurl //boolean|undefined
  1248. ) {
  1249. var url
  1250. if (isurl) {
  1251. url = data
  1252. } else {
  1253. var file = a(data).gettype("string").val
  1254. ? new Blob([data], {
  1255. type,
  1256. })
  1257. : (data.name ? (filename = data.name) : "", data)
  1258. url = URL.createObjectURL(file)
  1259. }
  1260. a()
  1261. .bodyload()
  1262. .then(() => {
  1263. var link = a(document.body).createelem("a", {
  1264. href: url,
  1265. download: filename,
  1266. }).val
  1267. link.click()
  1268. link.remove()
  1269. if (!isurl) window.URL.revokeObjectURL(url)
  1270. })
  1271. return data
  1272. },
  1273. "file",
  1274. true
  1275. )
  1276. allfuncs.new(
  1277. "idx",
  1278. function (
  1279. //array
  1280. arr, //array|string
  1281. idx //number
  1282. ) {
  1283. return idx >= 0 ? arr[idx] : arr[arr.length + idx]
  1284. },
  1285. "array",
  1286. true
  1287. )
  1288. allfuncs.new(
  1289. "compare",
  1290. function (
  1291. //boolean
  1292. x, //string|any
  1293. y //string|any
  1294. ) {
  1295. return x && y
  1296. ? (typeof x == "string" ? x.toLowerCase() : x) ==
  1297. (typeof y == "string" ? y.toLowerCase() : y)
  1298. : true
  1299. },
  1300. "check",
  1301. true
  1302. )
  1303. allfuncs.new(
  1304. "createelem",
  1305. function (
  1306. //element
  1307. parent, //element|none
  1308. elem, //string
  1309. data //object
  1310. ) {
  1311. //if (!parent) warn("no parent set", elem, data)
  1312. var type = elem
  1313. var issvg = elem == "svg" || parent?.tagName?.toLowerCase?.() == "svg"
  1314. // warn(issvg, 'issvg', elem, parent, parent?.tagName)
  1315. elem = issvg
  1316. ? document.createElementNS("http://www.w3.org/2000/svg", elem)
  1317. : document.createElement(elem)
  1318. if (data.class)
  1319. data.class.split(" ").forEach((e) => {
  1320. elem.classList.add(e)
  1321. })
  1322. if (data.options && type == "select")
  1323. data.options = data.options.map(
  1324. (e) =>
  1325. a(elem).createelem("option", {
  1326. innerHTML: e,
  1327. value: e,
  1328. }).val
  1329. )
  1330. Object.assign(elem.style, data)
  1331. if (type == "select") {
  1332. a(data).foreach(function (a, s) {
  1333. elem[a] = s
  1334. })
  1335. } else if (issvg) {
  1336. Object.keys(data).forEach((e) => (elem[e] = data[e]))
  1337. } else {
  1338. Object.assign(elem, data)
  1339. }
  1340. if (typeof parent == "string") parent = a(parent).qs().val
  1341. a(() => parent.appendChild(elem)).ignore()
  1342. return elem
  1343. },
  1344. "elem",
  1345. true
  1346. )
  1347. allfuncs.new(
  1348. "gettype",
  1349. function (
  1350. //string
  1351. thing, //any
  1352. match //undefined|string|array
  1353. ) {
  1354. if (
  1355. !match ||
  1356. (Object.prototype.toString
  1357. .call(match)
  1358. .toLowerCase()
  1359. .match(/^\[[a-z]+ (\w+)\]$/)[1] == "string" &&
  1360. !match.includes("|"))
  1361. ) {
  1362. var type = Object.prototype.toString
  1363. .call(thing)
  1364. .toLowerCase()
  1365. .match(/^\[[a-z]+ (\w+)\]$/)[1]
  1366. if (type !== "function") if (type == match) return true
  1367. if (match == "normalfunction") return type == "function"
  1368. if (type == "htmldocument" && match == "document") return true
  1369. if (match == "body" && type == "htmlbodyelement") return true
  1370. if (match && new RegExp(`^html${match}element$`).test(type)) return true
  1371. if (/^html\w+element$/.test(type)) type = "element"
  1372. if (type == "htmldocument") type = "element"
  1373. if (type == "asyncfunction") type = "function"
  1374. if (type == "generatorfunction") type = "function"
  1375. if (type == "regexp") type = "regex"
  1376. if (match == "regexp") match = "regex"
  1377. if (match == "element" && type == "window") return true
  1378. if (match == "element" && type == "shadowroot") return true
  1379. if (/^(html|svg).*element$/.test(type)) type = "element"
  1380. if (type == "function") {
  1381. type = /^\s*class\s/.test(Function.prototype.toString.call(thing))
  1382. ? "class"
  1383. : "function"
  1384. }
  1385. if (match == "none")
  1386. return type == "nan" || type == "undefined" || type == "null"
  1387. try {
  1388. if (type === "number" && isNaN(thing) && match == "nan") return true
  1389. } catch (e) {
  1390. error(thing)
  1391. }
  1392. return match ? match === type : type
  1393. } else {
  1394. if (match.includes("|")) match = match.split("|")
  1395. match = [...new Set(match)]
  1396. return match.filter((e) => a(thing).gettype(e).val).length > 0
  1397. }
  1398. },
  1399. "check",
  1400. true
  1401. )
  1402. allfuncs.new(
  1403. "waitforelem",
  1404. async function (
  1405. //promise
  1406. selector //string|array
  1407. ) {
  1408. if (a(selector).gettype("string").val) {
  1409. selector = [selector]
  1410. }
  1411. await a().bodyload()
  1412. var g = false
  1413. return new Promise((resolve) => {
  1414. var observer = new MutationObserver(check)
  1415. observer.observe(document.body, {
  1416. childList: true,
  1417. subtree: true,
  1418. attributes: true,
  1419. characterData: false,
  1420. })
  1421. check()
  1422. function check() {
  1423. if (g) return
  1424. if (selector.find((selector) => !a(selector).qs().val)) return
  1425. observer.disconnect()
  1426. resolve(
  1427. selector.length == 1
  1428. ? a(selector[0]).qs().val
  1429. : selector.map((e) => a(e).qs().val)
  1430. )
  1431. }
  1432. })
  1433. },
  1434. "time/elem"
  1435. )
  1436. allfuncs.new(
  1437. "findvar",
  1438. function (
  1439. //any
  1440. obj, //object|element
  1441. findkey, //any
  1442. objectname = "obj", //string
  1443. exact, //boolean
  1444. all //boolean
  1445. ) {
  1446. var vvv = []
  1447. var allarr = []
  1448. var chain = objectname
  1449. var arr = []
  1450. var arr2 = [
  1451. {
  1452. chain,
  1453. value: obj,
  1454. },
  1455. ]
  1456. var visited = []
  1457. var i = 0
  1458. while (arr2.length && i++ < 800) {
  1459. if (
  1460. arr2
  1461. .map((e) => e.chain)
  1462. .join("/")
  1463. .includes("." + findkey + (exact ? "/" : ""))
  1464. ) {
  1465. if (all)
  1466. vvv.push(
  1467. arr2.filter((e) =>
  1468. exact
  1469. ? e.chain.endsWith("." + findkey)
  1470. : e.chain.includes("." + findkey)
  1471. )
  1472. )
  1473. else
  1474. return arr2.filter((e) =>
  1475. exact
  1476. ? e.chain.endsWith("." + findkey)
  1477. : e.chain.includes("." + findkey)
  1478. )[0]
  1479. }
  1480. var oldarr2 = [...arr2]
  1481. allarr.push(arr2)
  1482. arr2 = []
  1483. oldarr2.forEach((e) => {
  1484. if (
  1485. a(e.value).gettype("object").val ||
  1486. a(e.value).gettype("element").val
  1487. )
  1488. a(e.value).foreach(function (key, value) {
  1489. if (a(key).gettype().val !== "string")
  1490. return warn(key, a(key).gettype().val)
  1491. var newchain = /^[a-z_][_a-z0-9]*$/i.test(key)
  1492. ? "." + key
  1493. : `["${key.replaceAll('"', '\\"')}"]`
  1494. arr.push(e.chain + newchain)
  1495. if (visited.includes(e.value)) return
  1496. arr2.push({
  1497. chain: e.chain + newchain,
  1498. value,
  1499. })
  1500. })
  1501. visited.push(e.value)
  1502. })
  1503. }
  1504. return vvv.length > 0 ? vvv : allarr
  1505. },
  1506. "debug",
  1507. false
  1508. )
  1509. allfuncs.new(
  1510. "getallvars",
  1511. function () {
  1512. //object
  1513. var obj = {}
  1514. var variables = []
  1515. for (var name in this)
  1516. if (
  1517. !`window self document name location customElements history locationbar menubar personalbar scrollbars statusbar toolbar status closed frames length top opener parent frameElement navigator origin external screen innerWidth innerHeight scrollX pageXOffset scrollY pageYOffset visualViewport screenX screenY outerWidth outerHeight devicePixelRatio clientInformation screenLeft screenTop styleMedia onsearch isSecureContext trustedTypes performance onappinstalled onbeforeinstallprompt crypto indexedDB sessionStorage localStorage onbeforexrselect onabort onbeforeinput onblur oncancel oncanplay oncanplaythrough onchange onclick onclose oncontextlost oncontextmenu oncontextrestored oncuechange ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended onerror onfocus onformdata oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart onmousedown onmouseenter onmouseleave onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange onreset onresize onscroll onsecuritypolicyviolation onseeked onseeking onselect onslotchange onstalled onsubmit onsuspend ontimeupdate ontoggle onvolumechange onwaiting onwebkitanimationend onwebkitanimationiteration onwebkitanimationstart onwebkittransitionend onwheel onauxclick ongotpointercapture onlostpointercapture onpointerdown onpointermove onpointerrawupdate onpointerup onpointercancel onpointerover onpointerout onpointerenter onpointerleave onselectstart onselectionchange onanimationend onanimationiteration onanimationstart ontransitionrun ontransitionstart ontransitionend ontransitioncancel onafterprint onbeforeprint onbeforeunload onhashchange onlanguagechange onmessage onmessageerror onoffline ononline onpagehide onpageshow onpopstate onrejectionhandled onstorage onunhandledrejection onunload crossOriginIsolated scheduler alert atob blur btoa cancelAnimationFrame cancelIdleCallback captureEvents clearInterval clearTimeout close confirm createImageBitmap fetch find focus getComputedStyle getSelection matchMedia moveBy moveTo open postMessage print prompt queueMicrotask releaseEvents reportError requestAnimationFrame requestIdleCallback resizeBy resizeTo scroll scrollBy scrollTo setInterval setTimeout stop structuredClone webkitCancelAnimationFrame webkitRequestAnimationFrame originAgentCluster navigation webkitStorageInfo speechSynthesis oncontentvisibilityautostatechange openDatabase webkitRequestFileSystem webkitResolveLocalFileSystemURL chrome caches cookieStore ondevicemotion ondeviceorientation ondeviceorientationabsolute launchQueue onbeforematch getDigitalGoodsService getScreenDetails queryLocalFonts showDirectoryPicker showOpenFilePicker showSaveFilePicker TEMPORARY PERSISTENT addEventListener dispatchEvent removeEventListener`
  1518. .split(" ")
  1519. .includes(name)
  1520. )
  1521. variables.push(name)
  1522. variables.forEach((e) => {
  1523. var c = String(a(this[e]).gettype().val)
  1524. if (c === "object") c = "variable"
  1525. if (!obj[c]) obj[c] = []
  1526. obj[c].push(e)
  1527. })
  1528. return obj
  1529. },
  1530. "debug",
  1531. false
  1532. )
  1533. allfuncs.new(
  1534. "scratch_getallkeys",
  1535. function () {
  1536. //object
  1537. var m = vm.runtime
  1538. var f = {
  1539. bools: m.targets
  1540. .map((e) => {
  1541. return {
  1542. name: e.sprite.name,
  1543. blocks: Object.values(e.blocks._blocks)
  1544. .filter((e) => e.opcode === "sensing_keypressed")
  1545. .map((e) => e.inputs.KEY_OPTION.block),
  1546. otherblocks: e.blocks._blocks,
  1547. }
  1548. })
  1549. .filter((e) => e.blocks.length)
  1550. .map((e) => {
  1551. return {
  1552. name: e.name,
  1553. value: [
  1554. ...new Set(
  1555. e.blocks
  1556. .map((y) => e.otherblocks[y])
  1557. .map(
  1558. (e) =>
  1559. e.fields?.KEY_OPTION?.value ||
  1560. e.fields?.VALUE?.value ||
  1561. error(e)
  1562. )
  1563. ),
  1564. ],
  1565. }
  1566. }),
  1567. hats: m.targets
  1568. .map((e) => {
  1569. return {
  1570. name: e.name,
  1571. blocks: Object.values(e.blocks)
  1572. .filter((e) => e.opcode === "event_whenkeypressed")
  1573. .map((e) => e.fields.KEY_OPTION.value),
  1574. }
  1575. })
  1576. .filter((e) => e.blocks.length),
  1577. }
  1578. f.all = [
  1579. ...f.hats.map((e) => e.blocks).flat(),
  1580. ...f.bools.map((e) => e.value).flat(),
  1581. ]
  1582. f.all = [...new Set(f.all)]
  1583. return f
  1584. },
  1585. "scratch",
  1586. false
  1587. )
  1588. allfuncs.new(
  1589. "newfunc",
  1590. function (
  1591. //undefined
  1592. func1, //string
  1593. func2 //function
  1594. ) {
  1595. eval(`var a = ${func1}
  1596. var s = ${func2}
  1597. ${func1} = function (...args) {
  1598. a.call(this, ...args)
  1599. s(arguments)
  1600. }`)
  1601. },
  1602. "function/jank",
  1603. true
  1604. )
  1605. allfuncs.new(
  1606. "findall",
  1607. function (
  1608. //array
  1609. obj, //object
  1610. objectname = "obj" //string
  1611. ) {
  1612. var chain = objectname
  1613. var arr = []
  1614. var arr2 = [
  1615. {
  1616. chain,
  1617. value: obj,
  1618. },
  1619. ]
  1620. var visited = []
  1621. var i = 0
  1622. while (arr2.length && i++ < 800) {
  1623. var oldarr2 = [...arr2]
  1624. arr2 = []
  1625. oldarr2.forEach((e) => {
  1626. if (a(e.value).gettype("object").val)
  1627. a(e.value).foreach(function (key, value) {
  1628. var newchain = /^[_a-z][_a-z0-9]*$/i.test(key)
  1629. ? "." + key
  1630. : `["${key.replaceAll('"', '\\"')}"]`
  1631. arr.push(e.chain + newchain)
  1632. if (visited.includes(e.value)) return
  1633. log({
  1634. key,
  1635. value,
  1636. chain: e.chain + newchain,
  1637. })
  1638. arr2.push({
  1639. chain: e.chain + newchain,
  1640. value,
  1641. })
  1642. })
  1643. visited.push(e.value)
  1644. })
  1645. }
  1646. return visited
  1647. },
  1648. "debug",
  1649. true
  1650. )
  1651. allfuncs.new(
  1652. "sha",
  1653. function (
  1654. //string
  1655. s = "", //string
  1656. includesymbols //boolean|string
  1657. ) {
  1658. var tab
  1659. if (typeof includesymbols == "string") {
  1660. tab = includesymbols
  1661. } else if (includesymbols) {
  1662. tab =
  1663. "`~\\|[];',./{}:<>?\"!@#$%^&*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  1664. } else {
  1665. tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  1666. }
  1667. return binb2b64(core_sha1(str2binb(s), s.length * 8))
  1668.  
  1669. function core_sha1(x, len) {
  1670. x[len >> 5] |= 0x80 << (24 - len)
  1671. x[(((len + 64) >> 9) << 4) + 15] = len
  1672. var w = Array(80)
  1673. var a = 1732584193
  1674. var b = -271733879
  1675. var c = -1732584194
  1676. var d = 271733878
  1677. var e = -1009589776
  1678. for (var i = 0; i < x.length; i += 16) {
  1679. var olda = a
  1680. var oldb = b
  1681. var oldc = c
  1682. var oldd = d
  1683. var olde = e
  1684. for (var j = 0; j < 80; j++) {
  1685. if (j < 16) w[j] = x[i + j]
  1686. else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)
  1687. var t = safe_add(
  1688. safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
  1689. safe_add(safe_add(e, w[j]), sha1_kt(j))
  1690. )
  1691. e = d
  1692. d = c
  1693. c = rol(b, 30)
  1694. b = a
  1695. a = t
  1696. }
  1697. a = safe_add(a, olda)
  1698. b = safe_add(b, oldb)
  1699. c = safe_add(c, oldc)
  1700. d = safe_add(d, oldd)
  1701. e = safe_add(e, olde)
  1702. }
  1703. return Array(a, b, c, d, e)
  1704. }
  1705.  
  1706. function sha1_ft(t, b, c, d) {
  1707. if (t < 20) return (b & c) | (~b & d)
  1708. if (t < 40) return b ^ c ^ d
  1709. if (t < 60) return (b & c) | (b & d) | (c & d)
  1710. return b ^ c ^ d
  1711. }
  1712.  
  1713. function sha1_kt(t) {
  1714. return t < 20
  1715. ? 1518500249
  1716. : t < 40
  1717. ? 1859775393
  1718. : t < 60
  1719. ? -1894007588
  1720. : -899497514
  1721. }
  1722.  
  1723. function safe_add(x, y) {
  1724. var lsw = (x & 0xffff) + (y & 0xffff)
  1725. var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
  1726. return (msw << 16) | (lsw & 0xffff)
  1727. }
  1728.  
  1729. function rol(num, cnt) {
  1730. return (num << cnt) | (num >>> (32 - cnt))
  1731. }
  1732.  
  1733. function str2binb(str) {
  1734. var bin = Array()
  1735. var mask = (1 << 8) - 1
  1736. for (var i = 0; i < str.length * 8; i += 8)
  1737. bin[i >> 5] |= (str.charCodeAt(i / 8) & mask) << (24 - i)
  1738. return bin
  1739. }
  1740.  
  1741. function binb2b64(binarray) {
  1742. var str = ""
  1743. for (var i = 0; i < binarray.length * 4; i += 3) {
  1744. var triplet =
  1745. (((binarray[i >> 2] >> (8 * (3 - (i % 4)))) & 0xff) << 16) |
  1746. (((binarray[(i + 1) >> 2] >> (8 * (3 - ((i + 1) % 4)))) & 0xff) <<
  1747. 8) |
  1748. ((binarray[(i + 2) >> 2] >> (8 * (3 - ((i + 2) % 4)))) & 0xff)
  1749. for (var j = 0; j < 4; j++) {
  1750. if (i * 8 + j * 6 > binarray.length * 32) str += ""
  1751. else str += tab.charAt((triplet >> (6 * (3 - j))) & 0x3f)
  1752. }
  1753. }
  1754. return str
  1755. }
  1756. },
  1757. "code",
  1758. true
  1759. )
  1760. allfuncs.new(
  1761. "qs",
  1762. function (
  1763. //element|none
  1764. text, //string
  1765. parent = document //element|none
  1766. ) {
  1767. return parent.querySelector(text)
  1768. },
  1769. "elem",
  1770. true
  1771. )
  1772. allfuncs.new(
  1773. "qsa",
  1774. function (
  1775. //array
  1776. text, //string
  1777. parent = document //element|none
  1778. ) {
  1779. return Array.from(parent.querySelectorAll(text))
  1780. },
  1781. "elem",
  1782. true
  1783. )
  1784. allfuncs.new(
  1785. "csspath",
  1786. function (
  1787. //string|array
  1788. el //elements|element
  1789. ) {
  1790. if (a(el).gettype("array").val)
  1791. return a(el).map((e) => a(e).csspath().val)
  1792. if (!(el instanceof Element)) return
  1793. var path = []
  1794. while (el.nodeType === Node.ELEMENT_NODE) {
  1795. var selector = el.nodeName.toLowerCase()
  1796. if (el.id) {
  1797. selector += "#" + el.id
  1798. path.unshift(selector)
  1799. break
  1800. } else {
  1801. var sib = el,
  1802. nth = 1
  1803. while ((sib = sib.previousElementSibling)) {
  1804. if (sib.nodeName.toLowerCase() == selector) nth++
  1805. }
  1806. if (nth != 1) selector += ":nth-of-type(" + nth + ")"
  1807. }
  1808. path.unshift(selector)
  1809. el = el.parentNode
  1810. }
  1811. return path.join(" > ")
  1812. },
  1813. "elem",
  1814. true
  1815. )
  1816. allfuncs.new(
  1817. "fromms",
  1818. function (
  1819. //object
  1820. ms //number
  1821. ) {
  1822. //returns a unix timestamp as an object where "ms" is the unixtimestamp
  1823. ms = Number(ms)
  1824. return {
  1825. years: Math.floor(ms / 1000 / 60 / 60 / 24 / 365),
  1826. days: Math.floor(ms / 1000 / 60 / 60 / 24) % 365,
  1827. hours: Math.floor(ms / 1000 / 60 / 60) % 24,
  1828. mins: Math.floor(ms / 1000 / 60) % 60,
  1829. secs: Math.floor(ms / 1000) % 60,
  1830. ms: Math.floor(ms) % 1000,
  1831. }
  1832. },
  1833. "time",
  1834. true
  1835. )
  1836. allfuncs.new(
  1837. "toms",
  1838. function (
  1839. //number
  1840. { ms = 0, secs = 0, mins = 0, hours = 0, days = 0, years = 0 } //object
  1841. ) {
  1842. return (
  1843. ms +
  1844. secs * 1000 +
  1845. mins * 60000 +
  1846. hours * 3600000 +
  1847. days * 86400000 +
  1848. years * 31560000000
  1849. )
  1850. },
  1851. "time",
  1852. true
  1853. )
  1854. allfuncs.new(
  1855. "rect",
  1856. function (
  1857. //object
  1858. e //element
  1859. ) {
  1860. if (a(e).gettype("string").val) e = a(e).qs().val
  1861. var { x, y, width, height } = e.getBoundingClientRect().toJSON()
  1862. return {
  1863. x,
  1864. y,
  1865. w: width,
  1866. h: height,
  1867. }
  1868. },
  1869. "elem",
  1870. true
  1871. )
  1872. allfuncs.new(
  1873. "setelem",
  1874. function (
  1875. //element|array
  1876. elem, //elements|element
  1877. data //object
  1878. ) {
  1879. if (data.class)
  1880. data.class.split(" ").forEach((e) => {
  1881. elem.classList.add(e)
  1882. })
  1883. if (data.options && elem.tagName.toLowerCase() == "select")
  1884. data.options = data.options.map(
  1885. (e) =>
  1886. a(elem).createelem("option", {
  1887. innerHTML: e,
  1888. value: e,
  1889. }).val
  1890. )
  1891. Object.assign(elem.style, data)
  1892. if (elem.tagName.toLowerCase() == "select") {
  1893. a(data).foreach(function (a, s) {
  1894. elem[a] = s
  1895. })
  1896. } else if (issvg) {
  1897. Object.keys(data).forEach((e) => (elem[e] = data[e]))
  1898. } else {
  1899. Object.assign(elem, data)
  1900. }
  1901. if (typeof parent == "string") parent = a(parent).qs().val
  1902. a(() => parent.appendChild(elem)).ignore()
  1903. return elem
  1904. },
  1905. "elem",
  1906. true
  1907. )
  1908. allfuncs.new(
  1909. "watchvar",
  1910. function (
  1911. //undefined
  1912. varname, //string
  1913. onset, //function
  1914. onget, //function|none
  1915. obj = window //object|window
  1916. ) {
  1917. //creates a new var and runs "onset" on the change of "varname", and "onget" when "varname" is read
  1918. obj = obj || window
  1919. obj[`_${varname}`] = undefined
  1920. obj[`${varname}`] = undefined
  1921. Object.defineProperty(obj, varname, {
  1922. configurable: false,
  1923. get() {
  1924. if (onget) return onget(obj[`_${varname}`])
  1925. return obj[`_${varname}`]
  1926. },
  1927. set(value) {
  1928. if (value === obj[`_${value}`]) {
  1929. return
  1930. }
  1931. var s = onset(value, obj[`_${varname}`])
  1932. if (s) obj[`_${varname}`] = value
  1933. },
  1934. })
  1935. },
  1936. "var/debug",
  1937. true
  1938. )
  1939. allfuncs.new(
  1940. "randomizeorder",
  1941. function (
  1942. //array
  1943. arr //array
  1944. ) {
  1945. arr = [...arr]
  1946. var arr2 = []
  1947. var count = arr.length
  1948. for (var i = 0; i < count; i++) {
  1949. var idx = randfrom(0, arr.length - 1)
  1950. arr2.push(arr[idx])
  1951. arr.splice(idx, 1)
  1952. }
  1953. return arr2
  1954. },
  1955. "array",
  1956. true
  1957. )
  1958. allfuncs.new(
  1959. "constrainvar",
  1960. function (
  1961. //undefined
  1962. varname, //string
  1963. min, //number
  1964. max //number
  1965. ) {
  1966. //creates a new var that can't go beyond the bounds of "min" and "max"
  1967. window[`_${varname}`] = undefined
  1968. window[`${varname}`] = undefined
  1969. Object.defineProperty(window, varname, {
  1970. configurable: false,
  1971. get() {
  1972. return window[`_${varname}`]
  1973. },
  1974. set(value) {
  1975. if (value === window[`_${varname}`]) {
  1976. return
  1977. }
  1978. if (value > max) value = max
  1979. if (value < min) value = min
  1980. window[`_${varname}`] = value
  1981. },
  1982. })
  1983. },
  1984. "var",
  1985. true
  1986. )
  1987. allfuncs.new(
  1988. "isbetween",
  1989. function (
  1990. //boolean
  1991. z, //number
  1992. x, //number
  1993. c //number
  1994. ) {
  1995. //returns true if "z" is between "x" and "c"
  1996. if (x == c) return false
  1997. var big, small
  1998. if (x > c) {
  1999. big = x
  2000. small = c
  2001. } else {
  2002. big = c
  2003. small = x
  2004. return z > big && z < small
  2005. }
  2006. },
  2007. "check",
  2008. true
  2009. )
  2010. allfuncs.new(
  2011. "indexsof",
  2012. function (
  2013. //array
  2014. y, //string
  2015. x //string
  2016. ) {
  2017. var i = 0
  2018. var arr = []
  2019. y.split(x).forEach((e, k) => {
  2020. i += e.length
  2021. arr.push(i + k)
  2022. })
  2023. arr.pop()
  2024. return arr
  2025. },
  2026. "array",
  2027. true
  2028. )
  2029. allfuncs.new(
  2030. "export",
  2031. function () {
  2032. //string
  2033. //saves the data of text inputs and checkboxes
  2034. var s = []
  2035. a("input, textarea")
  2036. .qsa()
  2037. .foreach((e) => {
  2038. s.push({
  2039. path: a(e).csspath().val,
  2040. value: escape(e.value),
  2041. checked: e.checked,
  2042. })
  2043. })
  2044. return JSON.stringify(s)
  2045. },
  2046. "data",
  2047. false
  2048. )
  2049. allfuncs.new(
  2050. "import",
  2051. function (
  2052. //string
  2053. data //string
  2054. ) {
  2055. //loads the data of text inputs and checkboxes
  2056. data.forEach((e) => {
  2057. var s = a(e.path).qs().val
  2058. s.checked = e.checked
  2059. s.value = unescape(e.value)
  2060. })
  2061. return data
  2062. },
  2063. "data",
  2064. true
  2065. )
  2066. allfuncs.new(
  2067. "popup",
  2068. function (
  2069. //window
  2070. data, //string
  2071. x, //number|none
  2072. y, //number|none
  2073. w, //number|none
  2074. h //number|none
  2075. ) {
  2076. //creates a popup window
  2077. if (x || x === 0) {
  2078. x = (screen.width / 100) * x
  2079. y = (screen.height / 100) * y
  2080. w = (screen.width / 100) * w
  2081. h = (screen.height / 100) * h
  2082. var win = open("", "", `left=${x}, top=${y} width=${w},height=${h}`)
  2083. win.document.write(data)
  2084. return win
  2085. } else {
  2086. var win = open("")
  2087. win.document.write(data)
  2088. return win
  2089. }
  2090. },
  2091. "window",
  2092. true
  2093. )
  2094. allfuncs.new(
  2095. "same",
  2096. function (
  2097. //boolean
  2098. ...a //any
  2099. ) {
  2100. if (a.length == 1) a = a[0]
  2101. return [...new Set(a.map((e) => JSON.stringify(e)))].length === 1
  2102. },
  2103. "check",
  2104. true
  2105. )
  2106. allfuncs.new(
  2107. "containsany",
  2108. function (
  2109. //boolean
  2110. arr1, //array|string
  2111. arr2 //array
  2112. ) {
  2113. return !!arr2.find((e) => arr1.includes(e))
  2114. },
  2115. "array"
  2116. )
  2117. allfuncs.new(
  2118. "run",
  2119. function (
  2120. //any
  2121. func, //function
  2122. obj //object
  2123. ) {
  2124. return func(...getprops(func).vars.map((e) => obj[e.var]))
  2125. },
  2126. "function",
  2127. true
  2128. )
  2129. allfuncs.new(
  2130. "getprops",
  2131. function (
  2132. //array|object
  2133. func, //function
  2134. peramsonly /*?|boolean*/
  2135. ) {
  2136. return peramsonly
  2137. ? getprops(func)
  2138. .vars.map((e) => e.var)
  2139. .filter((e) => e)
  2140. : getprops(func)
  2141. },
  2142. "function/parse",
  2143. true
  2144. )
  2145. allfuncs.new(
  2146. "bodyload",
  2147. function () {
  2148. //promise
  2149. return new Promise((resolve) => {
  2150. if (document.body) resolve()
  2151. const int = setInterval(() => {
  2152. if (document.body) resolve(clearInterval(int))
  2153. })
  2154. })
  2155. },
  2156. "elem/time",
  2157. false
  2158. )
  2159. ;(async function () {
  2160. const { bodyload } = allfuncs
  2161. await bodyload()
  2162. // var optionselem = loadlib("addnewoption", "optionselem")
  2163. // delete localStorage.buttonsheight
  2164. // delete localStorage.buttonswidth
  2165. // delete localStorage.buttonsx
  2166. // delete localStorage.buttonsy
  2167. if (!localStorage.buttonsheight) localStorage.buttonsheight = "100px"
  2168. if (!localStorage.buttonswidth) localStorage.buttonswidth = "120px"
  2169. var c = document.body
  2170. if (!window.optionselem) {
  2171. c = a(c)
  2172. .createelem("div", {
  2173. position: "fixed",
  2174. top: (Number(localStorage.buttonsy) || 10) + "px",
  2175. left:
  2176. (Number(localStorage.buttonsx) ||
  2177. Number(localStorage.buttonswidth.match(/[0-9]+/)[0]) / 2) + "px",
  2178. width: 0,
  2179. height: 0,
  2180. zIndex: 999999999999999,
  2181. pointerEvents: "all",
  2182. backgroundColor: "#0000",
  2183. })
  2184. .val.attachShadow({
  2185. mode: "closed",
  2186. })
  2187. window.optionselem = a(c).createelem("div", {
  2188. overflow: "hidden",
  2189. position: "fixed",
  2190. top:
  2191. constrain(
  2192. (Number(localStorage.buttonsy) || 10, 0 + 50 / 2),
  2193. innerHeight - this.clientHeight / 2
  2194. ) + "px",
  2195. left:
  2196. constrain(
  2197. localStorage.buttonswidth,
  2198. 0 + this.clientWidth / 2,
  2199. innerWidth - this.clientWidth / 2
  2200. ) + "px",
  2201. zIndex: 999999999999999,
  2202. height: "20px",
  2203. pointerEvents: "all",
  2204. backgroundColor: "#0f09",
  2205. test(e) {
  2206. if (!this.moving && e) return
  2207. if (!e) {
  2208. this.style.translate = "0 0"
  2209. e = {
  2210. clientX: this.getBoundingClientRect().toJSON().x,
  2211. clientY: this.getBoundingClientRect().toJSON().y,
  2212. }
  2213. }
  2214. // this.style.translate = "-50% -50%"
  2215. this.style.top =
  2216. constrain(e.clientY - 10, 0, innerHeight - this.clientHeight) + "px"
  2217. this.style.left =
  2218. constrain(
  2219. e.clientX - this.clientWidth / 2,
  2220. 0,
  2221. innerWidth - this.clientWidth
  2222. ) + "px"
  2223. localStorage.buttonsx = e.clientX
  2224. localStorage.buttonsy = e.clientY
  2225. },
  2226. onmouseup() {
  2227. this.moving = false
  2228. },
  2229. }).val
  2230. optionselem.style.left =
  2231. constrain(
  2232. Number(localStorage.buttonswidth) || 0,
  2233. 0 + optionselem.clientWidth / 2,
  2234. innerWidth - optionselem.clientWidth / 2
  2235. ) + "px"
  2236. optionselem.style.top =
  2237. constrain(
  2238. Number(localStorage.buttonsy) || 10,
  2239. 0 + 50 / 2,
  2240. innerHeight - optionselem.clientHeight / 2
  2241. ) + "px"
  2242. var ismain
  2243. try {
  2244. ismain = window?.parent?.location?.href === location.href
  2245. } catch (e) {
  2246. ismain = false
  2247. }
  2248. a(window.optionselem).createelem("div", {
  2249. backgroundColor: ismain ? "#00f" : "#f00",
  2250. width: "100%",
  2251. height: "20px",
  2252. oncontextmenu(e) {
  2253. e.preventDefault()
  2254. log(window.optionselem)
  2255. if (window.optionselem.style.height === "20px")
  2256. window.optionselem.style.height = "auto"
  2257. else window.optionselem.style.height = "20px"
  2258. },
  2259. onmousedown(e) {
  2260. e.preventDefault()
  2261. if (e.which == 3 || e.button == 2) return
  2262. window.optionselem.moving = true
  2263. },
  2264. onmouseup() {
  2265. window.optionselem.moving = false
  2266. },
  2267. })
  2268. }
  2269.  
  2270. function constrain(inp, max, min) {
  2271. if (min > max) {
  2272. var c = min
  2273. min = max
  2274. max = c
  2275. }
  2276. return Math.min(max, Math.max(min, inp))
  2277. }
  2278. a(window).listen({
  2279. resize() {
  2280. window.optionselem.moving = false
  2281. optionselem.test.call(optionselem)
  2282. },
  2283. blur() {
  2284. window.optionselem.moving = false
  2285. },
  2286. focus() {
  2287. window.optionselem.moving = false
  2288. },
  2289. mousemove(e) {
  2290. optionselem.test.call(optionselem, e)
  2291. },
  2292. })
  2293.  
  2294. function addnewoption( //undefined
  2295. ...z //object|undefined
  2296. ) {
  2297. var zz = z[0]
  2298. // trymatch(zz.host, location.host)
  2299. // trymatch(zz.href, location.n)
  2300. // trymatch(zz.hostname, location.n)
  2301. // trymatch(zz.origin, location.n)
  2302. // trymatch(zz.pathname, location.n)
  2303. var s = a(optionselem).createelem("div", {
  2304. textAlign: "center",
  2305. width: localStorage.buttonswidth,
  2306. minHeight: localStorage.buttonsheight,
  2307. backgroundColor: zz.backgroundColor || "#0000",
  2308. }).val
  2309. a(s).createelem("p", {
  2310. innerHTML: zz.title || " ",
  2311. textAlign: "center",
  2312. color: zz.titlecolor,
  2313. })
  2314. ;[...z].forEach((z, i) => {
  2315. if (i === 0) return
  2316. var elem
  2317. switch (z.type) {
  2318. case "button":
  2319. elem = a(s).createelem("button", {
  2320. id: z.id,
  2321. itemnumber: i,
  2322. index: i,
  2323. innerHTML: z.text,
  2324. onclick: z.onclick,
  2325. textAlign: "center",
  2326. }).val
  2327. break
  2328. case "toggle":
  2329. elem = a(s).createelem("input", {
  2330. id: z.id,
  2331. itemnumber: i,
  2332. index: i,
  2333. type: "checkbox",
  2334. onclick(e) {
  2335. if (this.checked) z.onon?.call?.(this, e)
  2336. else z.onoff?.call?.(this, e)
  2337. z.onclick?.call?.(this, e)
  2338. },
  2339. }).val
  2340. break
  2341. case "select":
  2342. var x = a(s).createelem("select", {
  2343. id: z.id,
  2344. options: z.options,
  2345. index: i,
  2346. itemnumber: i,
  2347. value: z.value,
  2348. onchange: z.onchange,
  2349. }).val
  2350. elem = x
  2351. break
  2352. case "input":
  2353. elem = a(s).createelem("input", {
  2354. id: z.id,
  2355. itemnumber: i,
  2356. index: i,
  2357. width: "90%",
  2358. value: z.value,
  2359. placeholder: z.placeholder,
  2360. onchange(e) {
  2361. z.onchange.call(this, e)
  2362. },
  2363. }).val
  2364. break
  2365. case "p":
  2366. elem = a(s).createelem("p", {
  2367. id: z.id,
  2368. innerHTML: z.text,
  2369. }).val
  2370. break
  2371. case "br":
  2372. elem = a(s).createelem("br", {}).val
  2373. break
  2374. default:
  2375. error(`type not found: "${z.type}"`)
  2376. }
  2377. if (z.id) window[z.id] = elem
  2378. })
  2379. }
  2380. // addnewoption({ title: "asddssa" }, { type: "button" })
  2381. allfuncs.new("addnewoption", addnewoption, "elem", true)
  2382. })()
  2383. allfuncs.new(
  2384. "scratch_gettarget",
  2385. function (
  2386. //object
  2387. sprite //string|none
  2388. ) {
  2389. if (sprite) var x = vm.runtime.getSpriteTargetByName(sprite)
  2390. else var x = vm.runtime.getTargetForStage()
  2391. x.getvar = x.lookupVariableByNameAndType
  2392. return x
  2393. },
  2394. "scratch",
  2395. true
  2396. )
  2397. allfuncs.new(
  2398. "scratch_sendbroadcast",
  2399. function (
  2400. //string
  2401. data //string
  2402. ) {
  2403. vm.runtime.startHats("event_whenbroadcastreceived", {
  2404. BROADCAST_OPTION: data,
  2405. })
  2406. return data
  2407. },
  2408. "scratch",
  2409. true
  2410. )
  2411. allfuncs.new(
  2412. "scratch_canvas",
  2413. function () {
  2414. //element
  2415. return (
  2416. window?.vm?.runtime?.renderer?.canvas ||
  2417. a(
  2418. "#app > div > div.gui_body-wrapper_-N0sA.box_box_2jjDp > div > div.gui_stage-and-target-wrapper_69KBf.box_box_2jjDp > div.stage-wrapper_stage-wrapper_2bejr.box_box_2jjDp > div.stage-wrapper_stage-canvas-wrapper_3ewmd.box_box_2jjDp > div > div.stage_stage_1fD7k.box_box_2jjDp > div:nth-child(1) > canvas"
  2419. ).qs().val ||
  2420. a(
  2421. "#view > div > div.inner > div:nth-child(2) > div.guiPlayer > div.stage-wrapper_stage-wrapper_2bejr.box_box_2jjDp > div.stage-wrapper_stage-canvas-wrapper_3ewmd.box_box_2jjDp > div > div.stage_stage_1fD7k.box_box_2jjDp > div:nth-child(1) > canvas"
  2422. ).qs().val ||
  2423. a(
  2424. "#app > div > div > div > div.gui_body-wrapper_-N0sA.box_box_2jjDp > div > div.gui_stage-and-target-wrapper_69KBf.box_box_2jjDp > div.stage-wrapper_stage-wrapper_2bejr.box_box_2jjDp > div.stage-wrapper_stage-canvas-wrapper_3ewmd.box_box_2jjDp > div > div.stage_stage_1fD7k.box_box_2jjDp > div:nth-child(1) > canvas"
  2425. ).qs().val
  2426. )
  2427. },
  2428. "scratch",
  2429. false
  2430. )
  2431. allfuncs.new(
  2432. "replacealltext",
  2433. function (
  2434. //string|regex
  2435. pattern, //string|regex
  2436. string, //string
  2437. element = document.body //element|none
  2438. ) {
  2439. ;[
  2440. element,
  2441. ...element.querySelectorAll("*:not(script):not(noscript):not(style)"),
  2442. ].forEach(({ childNodes: [...nodes] }) =>
  2443. nodes
  2444. .filter(({ nodeType }) => nodeType === Node.TEXT_NODE)
  2445. .forEach(
  2446. (textNode) =>
  2447. (textNode.textContent = textNode.textContent.replaceAll(
  2448. pattern,
  2449. string
  2450. ))
  2451. )
  2452. )
  2453. return pattern
  2454. },
  2455. "string",
  2456. true
  2457. )
  2458. allfuncs.new(
  2459. "repeat",
  2460. function (
  2461. //promise|undefined
  2462. func, //function
  2463. count, //number
  2464. delay, //number|none
  2465. instantstart, //boolean|none
  2466. waituntildone //boolean|none
  2467. ) {
  2468. if (delay || waituntildone)
  2469. return new Promise(async (resolve) => {
  2470. if (delay) {
  2471. var extra = 0
  2472. for (var i = 0; i < count; i++) {
  2473. if (instantstart) waituntildone ? await func(i) : func(i)
  2474. extra = await a(delay - extra).wait().val
  2475. if (!instantstart) waituntildone ? await func(i) : func(i)
  2476. }
  2477. resolve()
  2478. } else
  2479. for (var i = 0; i < count; i++)
  2480. waituntildone ? await func(i) : func(i)
  2481. resolve()
  2482. })
  2483. for (var i = 0; i < count; i++) func(i)
  2484. return
  2485. },
  2486. "repeat",
  2487. true
  2488. )
  2489. allfuncs.new(
  2490. "repeatuntil",
  2491. function (
  2492. //promise
  2493. func, //function
  2494. donecheck, //function
  2495. delay, //number|none
  2496. instantstart, //boolean|none
  2497. waituntildone //boolean|none
  2498. ) {
  2499. return new Promise(async (resolve) => {
  2500. if (delay) {
  2501. var extra = 0
  2502. var i = 0
  2503. while (!donecheck()) {
  2504. i++
  2505. if (instantstart) {
  2506. waituntildone ? await func(i) : func(i)
  2507. }
  2508. extra = await a(delay - extra).wait().val
  2509. if (!instantstart) {
  2510. waituntildone ? await func(i) : func(i)
  2511. }
  2512. }
  2513. resolve()
  2514. } else {
  2515. var i = 0
  2516. while (!donecheck()) {
  2517. i++
  2518. waituntildone ? await func(i) : func(i)
  2519. }
  2520. resolve()
  2521. }
  2522. })
  2523. },
  2524. "repeat",
  2525. true
  2526. )
  2527. // ;(async function () {
  2528. // const { bodyload } = allfuncs
  2529. // await bodyload()
  2530. // const listeners = []
  2531. // a(document).listen({
  2532. // dragover(e) {
  2533. // e.stopPropagation()
  2534. // e.preventDefault()
  2535. // },
  2536. // drop(e) {
  2537. // e.stopPropagation()
  2538. // e.preventDefault()
  2539. // var files = [...e.dataTransfer.files]
  2540. // listeners.forEach((y) => y[0](y[1] ? files[0] : files))
  2541. // },
  2542. // })
  2543. // allfuncs.new(
  2544. // "newdrop",
  2545. // function (
  2546. // //undefined
  2547. // func, //function
  2548. // onlyone //boolean
  2549. // ) {
  2550. // listeners.push([func, onlyone])
  2551. // },
  2552. // "file"
  2553. // )
  2554. // })()
  2555. ;(async () => {
  2556. const drops = []
  2557. await a().bodyload()
  2558. a(document.body).listen({
  2559. dragover(e) {
  2560. e.preventDefault()
  2561. },
  2562. async drop(e) {
  2563. e.preventDefault()
  2564. drops.forEach(async ({ types, multi, func, elem }) => {
  2565. if (elem) if (e.target !== elem) return
  2566. if (multi) var ret = []
  2567. for (const item of e.dataTransfer.items) {
  2568. if (item.kind == "file") {
  2569. if (types.includes("file") || types.includes("directory")) {
  2570. const entry = await item.getAsFileSystemHandle()
  2571. if (entry.kind === "file" && types.includes("file")) {
  2572. if (!multi) return func(entry, e)
  2573. ret.push(entry)
  2574. } else if (
  2575. entry.kind === "directory" &&
  2576. types.includes("directory")
  2577. ) {
  2578. if (!multi) return func(entry, e)
  2579. ret.push(entry)
  2580. }
  2581. }
  2582. }
  2583. }
  2584. if (multi && ret.length) return func(ret, e)
  2585. })
  2586. },
  2587. })
  2588. allfuncs.new(
  2589. "ondrop",
  2590. function (
  2591. //object
  2592. obj //object
  2593. ) {
  2594. if (!obj.types) obj.types = "all"
  2595. obj.types = a(obj.types).toarray().val
  2596. if (!obj.func) throw new Error('object is missing "func"')
  2597. var oldelem = obj.elem
  2598. if (obj.elem) obj.elem = a(obj.elem).toelem(true).val
  2599. if (obj.elem && !a(obj.elem).gettype("element").val)
  2600. throw new Error(`elem is not an elem, ${oldelem} -> ${obj.elem}`)
  2601. drops.push(obj)
  2602. return obj
  2603. },
  2604. "file"
  2605. )
  2606. })()
  2607.  
  2608. allfuncs.new(
  2609. "getfolderpath",
  2610. async function (
  2611. //promise
  2612. folder //filesystemdirectoryhandle
  2613. ) {
  2614. async function parsedir(dir, x) {
  2615. if (!x) {
  2616. return [
  2617. {
  2618. name: dir.name,
  2619. inside: await parsedir(dir, true),
  2620. type: "folder",
  2621. handle: dir,
  2622. },
  2623. ]
  2624. } else var arr = []
  2625. for await (const [name, handle] of dir.entries()) {
  2626. arr.push(
  2627. a(handle).gettype("filesystemdirectoryhandle").val
  2628. ? {
  2629. type: "folder",
  2630. inside: await parsedir(handle, true),
  2631. name,
  2632. handle,
  2633. }
  2634. : { type: "file", handle, name }
  2635. )
  2636. }
  2637. return arr
  2638. }
  2639. return parsedir(folder)
  2640. },
  2641. "file",
  2642. false
  2643. )
  2644. allfuncs.new(
  2645. "getfiles",
  2646. async function (
  2647. //promise
  2648. oldway, //boolean|none
  2649. multiple, //boolean|none
  2650. accept = [], //array|string|none
  2651. options = {} //object|undefined
  2652. ) {
  2653. const supportsFileSystemAccess =
  2654. "showOpenFilePicker" in window &&
  2655. (() => {
  2656. try {
  2657. return window.self === window.top
  2658. } catch {
  2659. return false
  2660. }
  2661. })()
  2662. if (!oldway) {
  2663. if (!supportsFileSystemAccess) throw new Error("no access")
  2664. let fileOrFiles = undefined
  2665. try {
  2666. const handles = await showOpenFilePicker({
  2667. types: [
  2668. {
  2669. accept: {
  2670. "*/*": accept,
  2671. },
  2672. },
  2673. ],
  2674. multiple,
  2675. ...options,
  2676. })
  2677. if (!multiple) {
  2678. fileOrFiles = handles[0]
  2679. } else {
  2680. fileOrFiles = await Promise.all(handles)
  2681. }
  2682. } catch (err) {
  2683. if (err.name !== "AbortError") {
  2684. error(err.name, err.message)
  2685. }
  2686. }
  2687. return fileOrFiles
  2688. }
  2689. return new Promise(async (resolve) => {
  2690. await a().bodyload().val
  2691. const input = document.createElement("input")
  2692. input.style.display = "none"
  2693. input.type = "file"
  2694. if (accept) input.accept = accept
  2695. document.body.append(input)
  2696. if (multiple) {
  2697. input.multiple = true
  2698. }
  2699. input.addEventListener("change", () => {
  2700. input.remove()
  2701. // if (!input.files) {
  2702. // return
  2703. // }
  2704. resolve(multiple ? Array.from(input.files) : input.files[0])
  2705. })
  2706. if ("showPicker" in HTMLInputElement.prototype) {
  2707. input.showPicker()
  2708. } else {
  2709. input.click()
  2710. }
  2711. })
  2712. },
  2713. "file",
  2714. true
  2715. )
  2716. allfuncs.new(
  2717. "map",
  2718. function (
  2719. //array|object
  2720. arr, //array|object|any
  2721. func //function
  2722. ) {
  2723. var type = a(arr).gettype().val
  2724. if (type == "array") return arr.map(func)
  2725. else if (type == "object") {
  2726. var temparr = {}
  2727. Reflect.ownKeys(arr).forEach((e, i) => {
  2728. temparr = {
  2729. ...temparr,
  2730. ...func(e, arr[e], i),
  2731. }
  2732. })
  2733. return temparr
  2734. } else {
  2735. return [arr].map(func)
  2736. }
  2737. },
  2738. "array",
  2739. true
  2740. )
  2741. allfuncs.new(
  2742. "find",
  2743. function (
  2744. //any
  2745. arr, //array|object|any
  2746. func //function
  2747. ) {
  2748. var type = a(arr).gettype().val
  2749. if (type == "array") return arr.find(func)
  2750. else if (type == "object") {
  2751. return Reflect.ownKeys(arr).find((e, i) => {
  2752. return func(e, arr[e], i)
  2753. })
  2754. } else {
  2755. return [arr].find(func)
  2756. }
  2757. },
  2758. "array",
  2759. true
  2760. )
  2761. allfuncs.new(
  2762. "filteridx",
  2763. function (
  2764. //array
  2765. arr, //array|any
  2766. func //function
  2767. ) {
  2768. if (a(arr).gettype("object").val) arr = [arr]
  2769. return a(arr)
  2770. .map((e, i) => (func(e, i) ? i : undefined))
  2771. .filter((e) => e !== undefined)
  2772. },
  2773. "array"
  2774. )
  2775. allfuncs.new(
  2776. "filter",
  2777. function (
  2778. //array|object
  2779. arr, //array|object|any
  2780. func //function
  2781. ) {
  2782. var type = a(arr).gettype().val
  2783. if (type == "array") return arr.filter(func)
  2784. else if (type == "object") {
  2785. var temparr = {}
  2786. Reflect.ownKeys(arr).forEach((e, i) => {
  2787. if (func(e, arr[e], i))
  2788. temparr = {
  2789. ...temparr,
  2790. [e]: arr[e],
  2791. }
  2792. })
  2793. return temparr
  2794. } else {
  2795. return [arr].filter(func)
  2796. }
  2797. },
  2798. "array",
  2799. true
  2800. )
  2801. ;(function () {
  2802. var last
  2803. var different = allfuncs.new(
  2804. "unique",
  2805. function () /*object*/ {
  2806. return last || (last = different.new())
  2807. },
  2808. "check",
  2809. false
  2810. )
  2811. different.new = function (name) {
  2812. var $ = new Proxy(
  2813. {},
  2814. {
  2815. get(_a, s) {
  2816. return s == "name" ? name || "different" : $
  2817. },
  2818. set() {
  2819. return $
  2820. },
  2821. }
  2822. )
  2823. return (last = $)
  2824. }
  2825. })()
  2826. allfuncs.new(
  2827. "elif",
  2828. function (
  2829. //any
  2830. cond, //any
  2831. iftrue, //any
  2832. iffalse //any
  2833. ) {
  2834. return cond ? iftrue : iffalse
  2835. },
  2836. "check",
  2837. true
  2838. )
  2839. allfuncs.new(
  2840. "tonumber",
  2841. function (
  2842. //number
  2843. e //any
  2844. ) {
  2845. return Number(e)
  2846. },
  2847. "number/format",
  2848. true
  2849. )
  2850. allfuncs.new(
  2851. "toarray",
  2852. function (
  2853. //array
  2854. e, //any
  2855. split //string|none|undefined
  2856. ) {
  2857. if (a(e).gettype("string").val) {
  2858. if (split) e = e.split(split)
  2859. else return [e]
  2860. }
  2861. return [...e]
  2862. },
  2863. "number/format",
  2864. true
  2865. )
  2866. allfuncs.new(
  2867. "tostring",
  2868. function (
  2869. //string
  2870. e //any
  2871. ) {
  2872. if (["object", "array"].includes(a(e).gettype().val))
  2873. return JSON.stringify(e)
  2874. if (a(e).gettype("element").val) return a(e).csspath().val
  2875. return String(e)
  2876. },
  2877. "string/format",
  2878. true
  2879. )
  2880. allfuncs.new(
  2881. "eval",
  2882. function (
  2883. //any
  2884. a //any
  2885. ) {
  2886. return eval(a)
  2887. },
  2888. "js/eval",
  2889. true
  2890. )
  2891. allfuncs.new(
  2892. "toregex",
  2893. function (
  2894. //regex
  2895. d, //string|array|regex
  2896. s //undefined|string
  2897. ) {
  2898. if (a(d).gettype("array").val) var temp = d
  2899. if (s) var temp = [d, s]
  2900. else if (String(d).match(/^\/(.*)\/(\w*)$/)) {
  2901. var m = String(d).match(/^\/(.*)\/(\w*)$/)
  2902. var temp = [m[1], m[2]]
  2903. } else var temp = [String(d), ""]
  2904. temp[1] = temp[1].toLowerCase()
  2905. if (temp[1].includes("w")) {
  2906. temp[1] = temp[1].replace("w", "")
  2907. temp[0] = `(?<=[^a-z0-9]|^)${temp[0]}(?=[^a-z0-9]|$)`
  2908. }
  2909. return new RegExp(temp[0], temp[1].replaceAll(/(.)(?=.*\1)/g, ""))
  2910. },
  2911. "regex",
  2912. true
  2913. )
  2914. allfuncs.new(
  2915. "isregex",
  2916. function (
  2917. //boolean
  2918. s //string|regex
  2919. ) {
  2920. if (a(s).gettype("regex").val) return true
  2921. return /^\/.*(?<!\\)\/[gimusy]*$/.test(s) && !/^\/\*.*\*\/$/.test(s)
  2922. },
  2923. "check",
  2924. true
  2925. )
  2926. allfuncs.new(
  2927. "ispressed",
  2928. function (
  2929. //boolean
  2930. e /*event*/,
  2931. code //string
  2932. ) {
  2933. code = code.toLowerCase()
  2934. var temp =
  2935. e.shiftKey == code.includes("shift") &&
  2936. e.altKey == code.includes("alt") &&
  2937. e.ctrlKey == code.includes("ctrl") &&
  2938. e.metaKey == code.includes("meta") &&
  2939. e.key.toLowerCase() ==
  2940. code.replaceAll(/alt|ctrl|shift|meta/g, "").trim()
  2941. if (temp && !a) e.preventDefault()
  2942. return temp
  2943. },
  2944. "check/input/event",
  2945. true
  2946. )
  2947. allfuncs.new(
  2948. "controller_vibrate",
  2949. function (
  2950. //number
  2951. pad, //number
  2952. duration = 1000, //number|none
  2953. strongMagnitude = 0, //number|none
  2954. weakMagnitude = 0 //number|none
  2955. ) {
  2956. getpad(pad).vibrationActuator.playEffect("dual-rumble", {
  2957. duration,
  2958. strongMagnitude,
  2959. weakMagnitude,
  2960. })
  2961. return pad
  2962. },
  2963. "controller/haptic",
  2964. true
  2965. )
  2966. allfuncs.new(
  2967. "controller_getbutton",
  2968. function (
  2969. //number
  2970. pad, //number
  2971. button //number|none
  2972. ) {
  2973. return button
  2974. ? getpad(pad).buttons[button].value
  2975. : getpad(pad).buttons.map((e) => e.value)
  2976. },
  2977. "controller/input",
  2978. true
  2979. )
  2980. allfuncs.new(
  2981. "controller_getaxes",
  2982. function (
  2983. //array|number
  2984. pad, //number
  2985. axes //number|none
  2986. ) {
  2987. return axes ? getpad(pad).axes[axes] : getpad(pad).axes
  2988. },
  2989. "controller/input",
  2990. true
  2991. )
  2992. allfuncs.new(
  2993. "controller_exists",
  2994. function (
  2995. //boolean|number
  2996. pad //number|none
  2997. ) {
  2998. return pad === undefined
  2999. ? getpad().filter((e) => e).length
  3000. : !!getpad(pad)
  3001. },
  3002. "controller/check",
  3003. true
  3004. )
  3005. allfuncs.new(
  3006. "runall",
  3007. function (
  3008. //array|function
  3009. funcs, //array|function
  3010. args //array|any
  3011. ) {
  3012. if (!a(args).gettype("array").val) args = [args]
  3013. if (!a(funcs).gettype("array").val) funcs = [funcs]
  3014. funcs.map((func) => func(...args))
  3015. return funcs
  3016. },
  3017. "function"
  3018. )
  3019. allfuncs.new(
  3020. "readfile",
  3021. async function (
  3022. //promise
  3023. file, //file
  3024. type = "Text" //string|none
  3025. ) {
  3026. return new Promise(function (done, error) {
  3027. var f = new FileReader()
  3028. f.onerror = error
  3029. f.onload = () => done(type == "json" ? JSON.parse(f.result) : f.result)
  3030. f["readAs" + (type == "json" ? "Text" : type)](file)
  3031. })
  3032. },
  3033. "file"
  3034. )
  3035. allfuncs.new(
  3036. "writefile",
  3037. async function writefile(
  3038. //promise
  3039. file, //filesystemfilehandle
  3040. text //string
  3041. ) {
  3042. var f = await await file.createWritable()
  3043. await f.write(text)
  3044. await f.close()
  3045. return file
  3046. },
  3047. "file"
  3048. )
  3049. allfuncs.new(
  3050. "getfileperms",
  3051. async function (
  3052. //promise
  3053. fileHandle, //filesystemfilehandle
  3054. readWrite //boolean|none
  3055. ) {
  3056. const options = {}
  3057. if (readWrite) {
  3058. options.mode = "readwrite"
  3059. }
  3060. return (
  3061. (await fileHandle.queryPermission(options)) === "granted" ||
  3062. (await fileHandle.requestPermission(options)) === "granted"
  3063. )
  3064. },
  3065. "file/permission",
  3066. true
  3067. )
  3068. allfuncs.new(
  3069. "indexeddb_set",
  3070. async function (
  3071. //promise
  3072. place, //object
  3073. obj //object
  3074. ) {
  3075. return new Promise((done, error) =>
  3076. place.put(
  3077. obj,
  3078. (e) => done(e),
  3079. (e) => error(e)
  3080. )
  3081. )
  3082. },
  3083. "indexeddb",
  3084. true
  3085. )
  3086. allfuncs.new(
  3087. "indexeddb_get",
  3088. async function (
  3089. //promise
  3090. place, //object
  3091. obj //string
  3092. ) {
  3093. return new Promise((done, error) =>
  3094. place.get(
  3095. obj,
  3096. (e) => done(e),
  3097. (e) => error(e)
  3098. )
  3099. )
  3100. },
  3101. "indexeddb",
  3102. true
  3103. )
  3104. allfuncs.new(
  3105. "indexeddb_getall",
  3106. async function (
  3107. //promise
  3108. place //object
  3109. ) {
  3110. return new Promise((done, error) =>
  3111. place.getAll(
  3112. (e) => done(e),
  3113. (e) => error(e)
  3114. )
  3115. )
  3116. },
  3117. "indexeddb",
  3118. true
  3119. )
  3120. allfuncs.new(
  3121. "indexeddb_clearall",
  3122. async function (
  3123. //promise
  3124. place //object
  3125. ) {
  3126. return new Promise((done, error) =>
  3127. place.clear(
  3128. (e) => done(e),
  3129. (e) => error(e)
  3130. )
  3131. )
  3132. },
  3133. "indexeddb",
  3134. true
  3135. )
  3136. allfuncs.new(
  3137. "indexeddb_remove",
  3138. async function (
  3139. //promise
  3140. place, //object
  3141. obj //string|number
  3142. ) {
  3143. return new Promise((done, error) =>
  3144. place.remove(
  3145. obj,
  3146. (e) => done(e),
  3147. (e) => error(e)
  3148. )
  3149. )
  3150. },
  3151. "indexeddb",
  3152. true
  3153. )
  3154. allfuncs.new(
  3155. "indexeddb_setup",
  3156. async function (
  3157. //promise
  3158. obj //object|none
  3159. ) {
  3160. return new Promise((e) => {
  3161. var x
  3162. obj = {
  3163. ...{
  3164. dbVersion: 1,
  3165. storeName: "tempstorename",
  3166. keyPath: "id",
  3167. autoIncrement: true,
  3168. },
  3169. ...obj,
  3170. onStoreReady() {
  3171. e(x)
  3172. },
  3173. }
  3174. if (!window.IDBStore) {
  3175. //IDBStore start
  3176. ;(function (p, h, k) {
  3177. "function" === typeof define
  3178. ? define(h)
  3179. : "undefined" !== typeof module && module.exports
  3180. ? (module.exports = h())
  3181. : (k[p] = h())
  3182. })(
  3183. "IDBStore",
  3184. function () {
  3185. function p(a, b) {
  3186. var c, d
  3187. for (c in b) (d = b[c]), d !== u[c] && d !== a[c] && (a[c] = d)
  3188. return a
  3189. }
  3190. var h = function (a) {
  3191. throw a
  3192. },
  3193. k = function () {},
  3194. r = {
  3195. storeName: "Store",
  3196. storePrefix: "IDBWrapper-",
  3197. dbVersion: 1,
  3198. keyPath: "id",
  3199. autoIncrement: !0,
  3200. onStoreReady: function () {},
  3201. onError: h,
  3202. indexes: [],
  3203. implementationPreference: [
  3204. "indexedDB",
  3205. "webkitIndexedDB",
  3206. "mozIndexedDB",
  3207. "shimIndexedDB",
  3208. ],
  3209. },
  3210. q = function (a, b) {
  3211. "undefined" == typeof b && "function" == typeof a && (b = a)
  3212. "[object Object]" != Object.prototype.toString.call(a) &&
  3213. (a = {})
  3214. for (var c in r)
  3215. this[c] = "undefined" != typeof a[c] ? a[c] : r[c]
  3216. this.dbName = this.storePrefix + this.storeName
  3217. this.dbVersion = parseInt(this.dbVersion, 10) || 1
  3218. b && (this.onStoreReady = b)
  3219. var d = "object" == typeof window ? window : self
  3220. this.implementation = this.implementationPreference.filter(
  3221. function (a) {
  3222. return a in d
  3223. }
  3224. )[0]
  3225. this.idb = d[this.implementation]
  3226. this.keyRange =
  3227. d.IDBKeyRange || d.webkitIDBKeyRange || d.mozIDBKeyRange
  3228. this.consts = {
  3229. READ_ONLY: "readonly",
  3230. READ_WRITE: "readwrite",
  3231. VERSION_CHANGE: "versionchange",
  3232. NEXT: "next",
  3233. NEXT_NO_DUPLICATE: "nextunique",
  3234. PREV: "prev",
  3235. PREV_NO_DUPLICATE: "prevunique",
  3236. }
  3237. this.openDB()
  3238. },
  3239. t = {
  3240. constructor: q,
  3241. version: "1.7.2",
  3242. db: null,
  3243. dbName: null,
  3244. dbVersion: null,
  3245. store: null,
  3246. storeName: null,
  3247. storePrefix: null,
  3248. keyPath: null,
  3249. autoIncrement: null,
  3250. indexes: null,
  3251. implementationPreference: null,
  3252. implementation: "",
  3253. onStoreReady: null,
  3254. onError: null,
  3255. _insertIdCount: 0,
  3256. openDB: function () {
  3257. var a = this.idb.open(this.dbName, this.dbVersion),
  3258. b = !1
  3259. a.onerror = function (a) {
  3260. var b
  3261. b =
  3262. "error" in a.target
  3263. ? "VersionError" == a.target.error.name
  3264. : "errorCode" in a.target
  3265. ? 12 == a.target.errorCode
  3266. : !1
  3267. if (b)
  3268. this.onError(
  3269. Error(
  3270. "The version number provided is lower than the existing one."
  3271. )
  3272. )
  3273. else
  3274. a.target.error
  3275. ? (a = a.target.error)
  3276. : ((b =
  3277. "IndexedDB unknown error occurred when opening DB " +
  3278. this.dbName +
  3279. " version " +
  3280. this.dbVersion),
  3281. "errorCode" in a.target &&
  3282. (b += " with error code " + a.target.errorCode),
  3283. (a = Error(b))),
  3284. this.onError(a)
  3285. }.bind(this)
  3286. a.onsuccess = function (a) {
  3287. if (!b)
  3288. if (this.db) this.onStoreReady()
  3289. else if (
  3290. ((this.db = a.target.result),
  3291. "string" == typeof this.db.version)
  3292. )
  3293. this.onError(
  3294. Error(
  3295. "The IndexedDB implementation in this browser is outdated. Please upgrade your browser."
  3296. )
  3297. )
  3298. else if (
  3299. this.db.objectStoreNames.contains(this.storeName)
  3300. ) {
  3301. this.store = this.db
  3302. .transaction(
  3303. [this.storeName],
  3304. this.consts.READ_ONLY
  3305. )
  3306. .objectStore(this.storeName)
  3307. var d = Array.prototype.slice.call(
  3308. this.getIndexList()
  3309. )
  3310. this.indexes.forEach(function (a) {
  3311. var c = a.name
  3312. if (c)
  3313. if (
  3314. (this.normalizeIndexData(a), this.hasIndex(c))
  3315. ) {
  3316. var g = this.store.index(c)
  3317. this.indexComplies(g, a) ||
  3318. ((b = !0),
  3319. this.onError(
  3320. Error(
  3321. 'Cannot modify index "' +
  3322. c +
  3323. '" for current version. Please bump version number to ' +
  3324. (this.dbVersion + 1) +
  3325. "."
  3326. )
  3327. ))
  3328. d.splice(d.indexOf(c), 1)
  3329. } else
  3330. (b = !0),
  3331. this.onError(
  3332. Error(
  3333. 'Cannot create new index "' +
  3334. c +
  3335. '" for current version. Please bump version number to ' +
  3336. (this.dbVersion + 1) +
  3337. "."
  3338. )
  3339. )
  3340. else
  3341. (b = !0),
  3342. this.onError(
  3343. Error(
  3344. "Cannot create index: No index name given."
  3345. )
  3346. )
  3347. }, this)
  3348. d.length &&
  3349. ((b = !0),
  3350. this.onError(
  3351. Error(
  3352. 'Cannot delete index(es) "' +
  3353. d.toString() +
  3354. '" for current version. Please bump version number to ' +
  3355. (this.dbVersion + 1) +
  3356. "."
  3357. )
  3358. ))
  3359. b || this.onStoreReady()
  3360. } else
  3361. this.onError(
  3362. Error("Object store couldn't be created.")
  3363. )
  3364. }.bind(this)
  3365. a.onupgradeneeded = function (a) {
  3366. this.db = a.target.result
  3367. this.db.objectStoreNames.contains(this.storeName)
  3368. ? (this.store = a.target.transaction.objectStore(
  3369. this.storeName
  3370. ))
  3371. : ((a = { autoIncrement: this.autoIncrement }),
  3372. null !== this.keyPath && (a.keyPath = this.keyPath),
  3373. (this.store = this.db.createObjectStore(
  3374. this.storeName,
  3375. a
  3376. )))
  3377. var d = Array.prototype.slice.call(this.getIndexList())
  3378. this.indexes.forEach(function (a) {
  3379. var c = a.name
  3380. c ||
  3381. ((b = !0),
  3382. this.onError(
  3383. Error("Cannot create index: No index name given.")
  3384. ))
  3385. this.normalizeIndexData(a)
  3386. if (this.hasIndex(c)) {
  3387. var g = this.store.index(c)
  3388. this.indexComplies(g, a) ||
  3389. (this.store.deleteIndex(c),
  3390. this.store.createIndex(c, a.keyPath, {
  3391. unique: a.unique,
  3392. multiEntry: a.multiEntry,
  3393. }))
  3394. d.splice(d.indexOf(c), 1)
  3395. } else
  3396. this.store.createIndex(c, a.keyPath, {
  3397. unique: a.unique,
  3398. multiEntry: a.multiEntry,
  3399. })
  3400. }, this)
  3401. d.length &&
  3402. d.forEach(function (a) {
  3403. this.store.deleteIndex(a)
  3404. }, this)
  3405. }.bind(this)
  3406. },
  3407. deleteDatabase: function (a, b) {
  3408. if (this.idb.deleteDatabase) {
  3409. this.db.close()
  3410. var c = this.idb.deleteDatabase(this.dbName)
  3411. c.onsuccess = a
  3412. c.onerror = b
  3413. } else
  3414. b(
  3415. Error(
  3416. "Browser does not support IndexedDB deleteDatabase!"
  3417. )
  3418. )
  3419. },
  3420. put: function (a, b, c, d) {
  3421. null !== this.keyPath && ((d = c), (c = b), (b = a))
  3422. d || (d = h)
  3423. c || (c = k)
  3424. var f = !1,
  3425. e = null,
  3426. g = this.db.transaction(
  3427. [this.storeName],
  3428. this.consts.READ_WRITE
  3429. )
  3430. g.oncomplete = function () {
  3431. ;(f ? c : d)(e)
  3432. }
  3433. g.onabort = d
  3434. g.onerror = d
  3435. null !== this.keyPath
  3436. ? (this._addIdPropertyIfNeeded(b),
  3437. (a = g
  3438. .objectStore(this.storeName)
  3439. .put(isproxy(b) ? JSON.parse(JSON.stringify(b)) : b)))
  3440. : (a = g.objectStore(this.storeName).put(b, a))
  3441. a.onsuccess = function (a) {
  3442. f = !0
  3443. e = a.target.result
  3444. }
  3445. a.onerror = d
  3446. return g
  3447. },
  3448. get: function (a, b, c) {
  3449. c || (c = h)
  3450. b || (b = k)
  3451. var d = !1,
  3452. f = null,
  3453. e = this.db.transaction(
  3454. [this.storeName],
  3455. this.consts.READ_ONLY
  3456. )
  3457. e.oncomplete = function () {
  3458. ;(d ? b : c)(f)
  3459. }
  3460. e.onabort = c
  3461. e.onerror = c
  3462. a = e.objectStore(this.storeName).get(a)
  3463. a.onsuccess = function (a) {
  3464. d = !0
  3465. f = a.target.result
  3466. }
  3467. a.onerror = c
  3468. return e
  3469. },
  3470. remove: function (a, b, c) {
  3471. c || (c = h)
  3472. b || (b = k)
  3473. var d = !1,
  3474. f = null,
  3475. e = this.db.transaction(
  3476. [this.storeName],
  3477. this.consts.READ_WRITE
  3478. )
  3479. e.oncomplete = function () {
  3480. ;(d ? b : c)(f)
  3481. }
  3482. e.onabort = c
  3483. e.onerror = c
  3484. a = e.objectStore(this.storeName)["delete"](a)
  3485. a.onsuccess = function (a) {
  3486. d = !0
  3487. f = a.target.result
  3488. }
  3489. a.onerror = c
  3490. return e
  3491. },
  3492. batch: function (a, b, c) {
  3493. c || (c = h)
  3494. b || (b = k)
  3495. if ("[object Array]" != Object.prototype.toString.call(a))
  3496. c(Error("dataArray argument must be of type Array."))
  3497. else if (0 === a.length) return b(!0)
  3498. var d = a.length,
  3499. f = !1,
  3500. e = !1,
  3501. g = this.db.transaction(
  3502. [this.storeName],
  3503. this.consts.READ_WRITE
  3504. )
  3505. g.oncomplete = function () {
  3506. ;(e ? b : c)(e)
  3507. }
  3508. g.onabort = c
  3509. g.onerror = c
  3510. var l = function () {
  3511. d--
  3512. 0 !== d || f || (e = f = !0)
  3513. }
  3514. a.forEach(function (a) {
  3515. var b = a.type,
  3516. d = a.key,
  3517. e = a.value
  3518. a = function (a) {
  3519. g.abort()
  3520. f || ((f = !0), c(a, b, d))
  3521. }
  3522. "remove" == b
  3523. ? ((e = g.objectStore(this.storeName)["delete"](d)),
  3524. (e.onsuccess = l),
  3525. (e.onerror = a))
  3526. : "put" == b &&
  3527. (null !== this.keyPath
  3528. ? (this._addIdPropertyIfNeeded(e),
  3529. (e = g.objectStore(this.storeName).put(e)))
  3530. : (e = g.objectStore(this.storeName).put(e, d)),
  3531. (e.onsuccess = l),
  3532. (e.onerror = a))
  3533. }, this)
  3534. return g
  3535. },
  3536. putBatch: function (a, b, c) {
  3537. a = a.map(function (a) {
  3538. return { type: "put", value: a }
  3539. })
  3540. return this.batch(a, b, c)
  3541. },
  3542. upsertBatch: function (a, b, c, d) {
  3543. "function" == typeof b && ((d = c = b), (b = {}))
  3544. d || (d = h)
  3545. c || (c = k)
  3546. b || (b = {})
  3547. "[object Array]" != Object.prototype.toString.call(a) &&
  3548. d(Error("dataArray argument must be of type Array."))
  3549. var f = b.keyField || this.keyPath,
  3550. e = a.length,
  3551. g = !1,
  3552. l = !1,
  3553. n = 0,
  3554. m = this.db.transaction(
  3555. [this.storeName],
  3556. this.consts.READ_WRITE
  3557. )
  3558. m.oncomplete = function () {
  3559. l ? c(a) : d(!1)
  3560. }
  3561. m.onabort = d
  3562. m.onerror = d
  3563. var v = function (b) {
  3564. a[n++][f] = b.target.result
  3565. e--
  3566. 0 !== e || g || (l = g = !0)
  3567. }
  3568. a.forEach(function (a) {
  3569. var b = a.key
  3570. null !== this.keyPath
  3571. ? (this._addIdPropertyIfNeeded(a),
  3572. (a = m.objectStore(this.storeName).put(a)))
  3573. : (a = m.objectStore(this.storeName).put(a, b))
  3574. a.onsuccess = v
  3575. a.onerror = function (a) {
  3576. m.abort()
  3577. g || ((g = !0), d(a))
  3578. }
  3579. }, this)
  3580. return m
  3581. },
  3582. removeBatch: function (a, b, c) {
  3583. a = a.map(function (a) {
  3584. return { type: "remove", key: a }
  3585. })
  3586. return this.batch(a, b, c)
  3587. },
  3588. getBatch: function (a, b, c, d) {
  3589. c || (c = h)
  3590. b || (b = k)
  3591. d || (d = "sparse")
  3592. if ("[object Array]" != Object.prototype.toString.call(a))
  3593. c(Error("keyArray argument must be of type Array."))
  3594. else if (0 === a.length) return b([])
  3595. var f = [],
  3596. e = a.length,
  3597. g = !1,
  3598. l = null,
  3599. n = this.db.transaction(
  3600. [this.storeName],
  3601. this.consts.READ_ONLY
  3602. )
  3603. n.oncomplete = function () {
  3604. ;(g ? b : c)(l)
  3605. }
  3606. n.onabort = c
  3607. n.onerror = c
  3608. var m = function (a) {
  3609. a.target.result || "dense" == d
  3610. ? f.push(a.target.result)
  3611. : "sparse" == d && f.length++
  3612. e--
  3613. 0 === e && ((g = !0), (l = f))
  3614. }
  3615. a.forEach(function (a) {
  3616. a = n.objectStore(this.storeName).get(a)
  3617. a.onsuccess = m
  3618. a.onerror = function (a) {
  3619. l = a
  3620. c(a)
  3621. n.abort()
  3622. }
  3623. }, this)
  3624. return n
  3625. },
  3626. getAll: function (a, b) {
  3627. b || (b = h)
  3628. a || (a = k)
  3629. var c = this.db.transaction(
  3630. [this.storeName],
  3631. this.consts.READ_ONLY
  3632. ),
  3633. d = c.objectStore(this.storeName)
  3634. d.getAll
  3635. ? this._getAllNative(c, d, a, b)
  3636. : this._getAllCursor(c, d, a, b)
  3637. return c
  3638. },
  3639. _getAllNative: function (a, b, c, d) {
  3640. var f = !1,
  3641. e = null
  3642. a.oncomplete = function () {
  3643. ;(f ? c : d)(e)
  3644. }
  3645. a.onabort = d
  3646. a.onerror = d
  3647. a = b.getAll()
  3648. a.onsuccess = function (a) {
  3649. f = !0
  3650. e = a.target.result
  3651. }
  3652. a.onerror = d
  3653. },
  3654. _getAllCursor: function (a, b, c, d) {
  3655. var f = [],
  3656. e = !1,
  3657. g = null
  3658. a.oncomplete = function () {
  3659. ;(e ? c : d)(g)
  3660. }
  3661. a.onabort = d
  3662. a.onerror = d
  3663. a = b.openCursor()
  3664. a.onsuccess = function (a) {
  3665. ;(a = a.target.result)
  3666. ? (f.push(a.value), a["continue"]())
  3667. : ((e = !0), (g = f))
  3668. }
  3669. a.onError = d
  3670. },
  3671. clear: function (a, b) {
  3672. b || (b = h)
  3673. a || (a = k)
  3674. var c = !1,
  3675. d = null,
  3676. f = this.db.transaction(
  3677. [this.storeName],
  3678. this.consts.READ_WRITE
  3679. )
  3680. f.oncomplete = function () {
  3681. ;(c ? a : b)(d)
  3682. }
  3683. f.onabort = b
  3684. f.onerror = b
  3685. var e = f.objectStore(this.storeName).clear()
  3686. e.onsuccess = function (a) {
  3687. c = !0
  3688. d = a.target.result
  3689. }
  3690. e.onerror = b
  3691. return f
  3692. },
  3693. _addIdPropertyIfNeeded: function (a) {
  3694. "undefined" == typeof a[this.keyPath] &&
  3695. (a[this.keyPath] = this._insertIdCount++ + Date.now())
  3696. },
  3697. getIndexList: function () {
  3698. return this.store.indexNames
  3699. },
  3700. hasIndex: function (a) {
  3701. return this.store.indexNames.contains(a)
  3702. },
  3703. normalizeIndexData: function (a) {
  3704. a.keyPath = a.keyPath || a.name
  3705. a.unique = !!a.unique
  3706. a.multiEntry = !!a.multiEntry
  3707. },
  3708. indexComplies: function (a, b) {
  3709. return ["keyPath", "unique", "multiEntry"].every(function (
  3710. c
  3711. ) {
  3712. if ("multiEntry" == c && void 0 === a[c] && !1 === b[c])
  3713. return !0
  3714. if (
  3715. "keyPath" == c &&
  3716. "[object Array]" == Object.prototype.toString.call(b[c])
  3717. ) {
  3718. c = b.keyPath
  3719. var d = a.keyPath
  3720. if ("string" == typeof d) return c.toString() == d
  3721. if (
  3722. ("function" != typeof d.contains &&
  3723. "function" != typeof d.indexOf) ||
  3724. d.length !== c.length
  3725. )
  3726. return !1
  3727. for (var f = 0, e = c.length; f < e; f++)
  3728. if (
  3729. !(
  3730. (d.contains && d.contains(c[f])) ||
  3731. d.indexOf(-1 !== c[f])
  3732. )
  3733. )
  3734. return !1
  3735. return !0
  3736. }
  3737. return b[c] == a[c]
  3738. })
  3739. },
  3740. iterate: function (a, b) {
  3741. b = p(
  3742. {
  3743. index: null,
  3744. order: "ASC",
  3745. autoContinue: !0,
  3746. filterDuplicates: !1,
  3747. keyRange: null,
  3748. writeAccess: !1,
  3749. onEnd: null,
  3750. onError: h,
  3751. limit: Infinity,
  3752. offset: 0,
  3753. allowItemRejection: !1,
  3754. },
  3755. b || {}
  3756. )
  3757. var c = "desc" == b.order.toLowerCase() ? "PREV" : "NEXT"
  3758. b.filterDuplicates && (c += "_NO_DUPLICATE")
  3759. var d = !1,
  3760. f = this.db.transaction(
  3761. [this.storeName],
  3762. this.consts[b.writeAccess ? "READ_WRITE" : "READ_ONLY"]
  3763. ),
  3764. e = f.objectStore(this.storeName)
  3765. b.index && (e = e.index(b.index))
  3766. var g = 0
  3767. f.oncomplete = function () {
  3768. if (d)
  3769. if (b.onEnd) b.onEnd()
  3770. else a(null)
  3771. else b.onError(null)
  3772. }
  3773. f.onabort = b.onError
  3774. f.onerror = b.onError
  3775. c = e.openCursor(b.keyRange, this.consts[c])
  3776. c.onerror = b.onError
  3777. c.onsuccess = function (c) {
  3778. if ((c = c.target.result))
  3779. if (b.offset) c.advance(b.offset), (b.offset = 0)
  3780. else {
  3781. var e = a(c.value, c, f)
  3782. ;(b.allowItemRejection && !1 === e) || g++
  3783. if (b.autoContinue)
  3784. if (g + b.offset < b.limit) c["continue"]()
  3785. else d = !0
  3786. }
  3787. else d = !0
  3788. }
  3789. return f
  3790. },
  3791. query: function (a, b) {
  3792. var c = [],
  3793. d = 0
  3794. b = b || {}
  3795. b.autoContinue = !0
  3796. b.writeAccess = !1
  3797. b.allowItemRejection = !!b.filter
  3798. b.onEnd = function () {
  3799. a(c, d)
  3800. }
  3801. return this.iterate(function (a) {
  3802. d++
  3803. var e = b.filter ? b.filter(a) : !0
  3804. !1 !== e && c.push(a)
  3805. return e
  3806. }, b)
  3807. },
  3808. count: function (a, b) {
  3809. b = p({ index: null, keyRange: null }, b || {})
  3810. var c = b.onError || h,
  3811. d = !1,
  3812. f = null,
  3813. e = this.db.transaction(
  3814. [this.storeName],
  3815. this.consts.READ_ONLY
  3816. )
  3817. e.oncomplete = function () {
  3818. ;(d ? a : c)(f)
  3819. }
  3820. e.onabort = c
  3821. e.onerror = c
  3822. var g = e.objectStore(this.storeName)
  3823. b.index && (g = g.index(b.index))
  3824. g = g.count(b.keyRange)
  3825. g.onsuccess = function (a) {
  3826. d = !0
  3827. f = a.target.result
  3828. }
  3829. g.onError = c
  3830. return e
  3831. },
  3832. makeKeyRange: function (a) {
  3833. var b = "undefined" != typeof a.lower,
  3834. c = "undefined" != typeof a.upper,
  3835. d = "undefined" != typeof a.only
  3836. switch (!0) {
  3837. case d:
  3838. a = this.keyRange.only(a.only)
  3839. break
  3840. case b && c:
  3841. a = this.keyRange.bound(
  3842. a.lower,
  3843. a.upper,
  3844. a.excludeLower,
  3845. a.excludeUpper
  3846. )
  3847. break
  3848. case b:
  3849. a = this.keyRange.lowerBound(a.lower, a.excludeLower)
  3850. break
  3851. case c:
  3852. a = this.keyRange.upperBound(a.upper, a.excludeUpper)
  3853. break
  3854. default:
  3855. throw Error(
  3856. 'Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.'
  3857. )
  3858. }
  3859. return a
  3860. },
  3861. },
  3862. u = {}
  3863. q.prototype = t
  3864. q.version = t.version
  3865. return q
  3866. },
  3867. this
  3868. )
  3869. //IDBStore end
  3870. }
  3871. x = new IDBStore(obj)
  3872. })
  3873. },
  3874. "indexeddb",
  3875. true
  3876. )
  3877. allfuncs.new(
  3878. "keepsame",
  3879. function (
  3880. //object|any
  3881. thing //object|element
  3882. ) {
  3883. var all = []
  3884. var x = new Proxy(thing, {
  3885. get(_obj, prop) {
  3886. if (prop == "val") return _obj
  3887. if (prop == "all") return all
  3888. if (prop == "func")
  3889. return function (e) {
  3890. all.push(e(thing))
  3891. return x
  3892. }
  3893. return function (...args) {
  3894. try {
  3895. all.push(thing[prop](thing, ...args))
  3896. } catch (e) {
  3897. all.push(thing[prop])
  3898. }
  3899. return x
  3900. }
  3901. },
  3902. })
  3903. return x
  3904. },
  3905. "function",
  3906. true
  3907. )
  3908. allfuncs.new(
  3909. "scratch_press",
  3910. function (
  3911. //string
  3912. key //string
  3913. ) {
  3914. if (key == " ") key = "space"
  3915. if (/^[a-z]$/.test(key)) key = key.toUpperCase()
  3916. var index = vm.runtime.ioDevices.keyboard._keysPressed.indexOf(key)
  3917. if (index !== -1) {
  3918. vm.runtime.ioDevices.keyboard._keysPressed.splice(index, 1)
  3919. }
  3920. vm.runtime.ioDevices.keyboard._keysPressed.push(key)
  3921. vm.runtime.startHats("event_whenkeypressed", {
  3922. KEY_OPTION: key,
  3923. })
  3924. vm.runtime.startHats("event_whenkeypressed", {
  3925. KEY_OPTION: "any",
  3926. })
  3927. return key
  3928. },
  3929. "scratch"
  3930. )
  3931. allfuncs.new(
  3932. "scratch_unpress",
  3933. function (
  3934. //undefined
  3935. key //string
  3936. ) {
  3937. if (key == " ") key = "space"
  3938. if (/^[a-z]$/.test(key)) key = key.toUpperCase()
  3939. var index = vm.runtime.ioDevices.keyboard._keysPressed.indexOf(key)
  3940. if (index !== -1) {
  3941. vm.runtime.ioDevices.keyboard._keysPressed.splice(index, 1)
  3942. }
  3943. },
  3944. "scratch"
  3945. )
  3946. allfuncs.new("strictfunction", strictfunction, "function/typescript", true)
  3947. allfuncs.new(
  3948. "readfileslow",
  3949. function (
  3950. //undefined
  3951. file, //file
  3952. type = "Text", //string|undefined
  3953. cb1 = (e) => e, //function|undefined
  3954. cb2 = (e) => e //function|undefined
  3955. ) {
  3956. var fileSize = file.size
  3957. var chunkSize = 64 * 1024 * 50 // bytes
  3958. var offset = 0
  3959. var chunkReaderBlock = null
  3960. var arr = []
  3961. var lastidx
  3962. var readEventHandler = function (evt, idx) {
  3963. if (evt.target.error == null) {
  3964. arr.push([idx, evt.target.result])
  3965. cb1(a(arr.length).rerange(0, lastidx, 0, 100).val)
  3966. if (arr.length === lastidx)
  3967. cb2(arr.sort((e) => e[0]).map((e) => e[1]))
  3968. } else {
  3969. return error("Read error: " + evt.target.error)
  3970. }
  3971. }
  3972. chunkReaderBlock = function (_offset, length, _file, idx) {
  3973. var r = new FileReader()
  3974. var blob = _file.slice(_offset, length + _offset)
  3975. const zzz = idx + 1
  3976. r.onload = function (e) {
  3977. readEventHandler(e, zzz - 1)
  3978. }
  3979. r["readAs" + type](blob)
  3980. }
  3981. let idx = 0
  3982. while (offset < fileSize) {
  3983. idx++
  3984. chunkReaderBlock(offset, chunkSize, file, idx)
  3985. offset += chunkSize
  3986. }
  3987. lastidx = idx
  3988. },
  3989. "file"
  3990. )
  3991. allfuncs.new(
  3992. "cbtoasync",
  3993. function (
  3994. //promise
  3995. func, //function
  3996. ...args //any
  3997. ) {
  3998. return new Promise(function (resolve) {
  3999. func(...args, resolve)
  4000. })
  4001. },
  4002. "function"
  4003. )
  4004. allfuncs.new(
  4005. "asynctocb",
  4006. function (
  4007. //undefined
  4008. func, //function
  4009. ...args //any
  4010. ) {
  4011. var cb = args.pop()
  4012. return func(...args).then(cb)
  4013. },
  4014. "function"
  4015. )
  4016. // ;(function () {
  4017. // const samerand = function () //string
  4018. // {
  4019. // return (
  4020. // lastrand ||
  4021. // (lastrand = samerand.new(20, {
  4022. // lower: true,
  4023. // upper: true,
  4024. // }))
  4025. // )
  4026. // }
  4027. // allfuncs.new("samerand", samerand, "function/random", false)
  4028. // var lastrand = ""
  4029. // samerand.new = (
  4030. // e = 20,
  4031. // { lower = true, upper = false, number = false, symbol = false } = {
  4032. // lower: true,
  4033. // upper: false,
  4034. // number: false,
  4035. // symbol: false,
  4036. // }
  4037. // ) => (
  4038. // (lastrand = ""),
  4039. // a(
  4040. // () =>
  4041. // (lastrand += a(
  4042. // `${lower ? "asdfghjklzxcvbnmqwertyuiop" : ""}${
  4043. // upper ? "ASDFGHJKLQWERTYUIOPZXCVBNM" : ""
  4044. // }${number ? "0123456789" : ""}${
  4045. // symbol ? ",./;'[]-=\\`~!@#$%^&*()_+|{}:\"<>?" : ""
  4046. // }`.split("")
  4047. // ).randfrom().val)
  4048. // ).repeat(e),
  4049. // lastrand
  4050. // )
  4051. // })()
  4052. allfuncs.new(
  4053. "randstr",
  4054. function (
  4055. /*string|input of object:
  4056. {
  4057. lower = true, //boolean|undefined
  4058. upper = false, //boolean|undefined
  4059. number = false, //boolean|undefined
  4060. symbol = false, //boolean|undefined
  4061. length = 20, //number|undefined
  4062. }
  4063. */
  4064. {
  4065. lower = true,
  4066. upper = false,
  4067. number = false,
  4068. symbol = false,
  4069. length = 20,
  4070. } = {
  4071. lower: true,
  4072. upper: false,
  4073. number: false,
  4074. symbol: false,
  4075. length: 20,
  4076. }
  4077. ) {
  4078. var rand = ""
  4079. a(() => {
  4080. rand += a(
  4081. `${lower ? "asdfghjklzxcvbnmqwertyuiop" : ""}${
  4082. upper ? "ASDFGHJKLQWERTYUIOPZXCVBNM" : ""
  4083. }${number ? "0123456789" : ""}${
  4084. symbol ? ",./;'[]-=\\`~!@#$%^&*()_+|{}:\"<>?" : ""
  4085. }`.split("")
  4086. ).randfrom().val
  4087. }).repeat(length)
  4088. return rand
  4089. },
  4090. "random/string"
  4091. )
  4092. allfuncs.new(
  4093. "toplaces",
  4094. function (
  4095. //string
  4096. num, //number|string
  4097. pre, //number|none
  4098. post = 0, //number|undefined
  4099. func = Math.round //function
  4100. ) {
  4101. num = String(num).split(".")
  4102. if (num.length == 1) num.push("")
  4103. if (pre !== undefined) {
  4104. num[0] = num[0].substring(num[0].length - pre, num[0].length)
  4105. while (num[0].length < pre) num[0] = "0" + num[0]
  4106. }
  4107. var temp = num[1].substring(post, post + 1) ?? 0
  4108. num[1] = num[1].substring(0, post)
  4109. while (num[1].length < post) num[1] += "0"
  4110. if (post > 0) {
  4111. temp = func(num[1].at(-1) + "." + temp)
  4112. num[1] = num[1].split("")
  4113. num[1].pop()
  4114. num[1].push(temp)
  4115. num[1] = num[1].join("")
  4116. num = num.join(".")
  4117. } else num = num[0]
  4118. return num
  4119. },
  4120. "number/format",
  4121. true
  4122. )
  4123. allfuncs.new(
  4124. "forcenumlength",
  4125. function (
  4126. //string
  4127. string, //string
  4128. lengths //array|number|object
  4129. ) {
  4130. var i = -1
  4131. if (a(lengths).gettype("object").val) {
  4132. lengths = lengths[[...string.matchAll(/\d+(?:\.\d+)?/g)].length]
  4133. }
  4134. if (!lengths) {
  4135. log(string)
  4136. debugger
  4137. }
  4138. return string.replaceAll(/\d+(?:\.\d+)?/g, function (v) {
  4139. i++
  4140. try {
  4141. return a(lengths[i]).gettype("array").val
  4142. ? a(Number(v)).toplaces(lengths[i][0], lengths[i][1]).val
  4143. : a(Number(v)).toplaces(lengths[i], 0).val
  4144. } catch (e) {
  4145. log(string, lengths, i)
  4146. debugger
  4147. }
  4148. })
  4149. },
  4150. "number/format",
  4151. true
  4152. )
  4153. ;(function () {
  4154. var lasttime = Date.now()
  4155. allfuncs.new(
  4156. "tick",
  4157. function () {
  4158. //number
  4159. var time = Date.now() - lasttime
  4160. lasttime = Date.now()
  4161. return time
  4162. },
  4163. "time"
  4164. )
  4165. })()
  4166.  
  4167. allfuncs.new("expandederror", expandederror, "error", true)
  4168. allfuncs.new(
  4169. "fetch",
  4170. async function (
  4171. //promise
  4172. url, //string
  4173. type = "text", //string|none
  4174. ...args //any|undefined
  4175. ) {
  4176. return await (await fetch(url, ...args))[type]()
  4177. },
  4178. "url/web"
  4179. )
  4180. allfuncs.new(
  4181. "copy",
  4182. function (
  4183. //string
  4184. text //string
  4185. ) {
  4186. navigator.clipboard.writeText(text)
  4187. return ""
  4188. try {
  4189. var temp = a(document.body)
  4190. .createelem("textarea", {
  4191. value: text,
  4192. width: 0,
  4193. height: 0,
  4194. position: "fixed",
  4195. top: 0,
  4196. left: 0,
  4197. })
  4198. .run.same.focus()
  4199. .run.same.select()
  4200. document.execCommand("copy")
  4201. temp.run.remove()
  4202. } catch (e) {
  4203. navigator.clipboard.writeText(text)
  4204. }
  4205. return text
  4206. },
  4207. "clipboard"
  4208. )
  4209. // allfuncs.new(
  4210. // "cache",
  4211. // (function () {
  4212. // var cac = {}
  4213. // function cache( //any
  4214. // args, //arguments|any
  4215. // data, //function
  4216. // notfoundincache //function|undefined
  4217. // ) {
  4218. // // if (a(args).gettype(["array", "arguments"]).val)
  4219. // // args = [...args].join("\u1111")
  4220. // args = JSON.stringify(args)
  4221. // var c = String(arguments.callee.caller).replaceAll(/\s\s+/g, " ").trim()
  4222. // // log(structuredClone(cac))
  4223. // if (!cac[c]) cac[c] = {}
  4224. // if (args in cac[c]) return cac[c][args]
  4225. // cac[c][args] = data()
  4226. // if (notfoundincache) notfoundincache(cac[c][args])
  4227. // return cac[c][args]
  4228. // }
  4229. // cache.getall = function () {
  4230. // return cac
  4231. // }
  4232. // cache.setall = function (e) {
  4233. // return (cac = e)
  4234. // }
  4235. // cache.add = function (e) {
  4236. // return (cac = { ...cac, ...e })
  4237. // }
  4238. // cache.clear = function () {
  4239. // cac = {}
  4240. // }
  4241. // return cache
  4242. // })(),
  4243. // "data/storage"
  4244. // )
  4245.  
  4246. Object.keys(console).forEach((e) =>
  4247. allfuncs.new(
  4248. e,
  4249. (/*undefined*/ ...z /*any*/) => console[e](...z),
  4250. "console/debug"
  4251. )
  4252. )
  4253. allfuncs.new(
  4254. "replaceall",
  4255. function (
  4256. //string
  4257. text, //string
  4258. regex, //regex|string|array
  4259. replacewith //string|function
  4260. ) {
  4261. return text.replaceAll(
  4262. a(String(a(regex).toregex().val) + "g").toregex().val,
  4263. replacewith
  4264. )
  4265. },
  4266. ""
  4267. )
  4268. allfuncs.new(
  4269. "setrange",
  4270. function (
  4271. //number
  4272. num, //number
  4273. min, //number
  4274. max //number
  4275. ) {
  4276. return num < min ? min : num > max ? max : num
  4277. },
  4278. "number"
  4279. )
  4280. allfuncs.new(
  4281. "isstrict",
  4282. function (
  4283. //boolean
  4284. thing //array|object
  4285. ) {
  4286. return thing?.strictargs?.[0] === isstrict
  4287. },
  4288. "typescript"
  4289. )
  4290. allfuncs.new(
  4291. "runonalltext",
  4292. function (
  4293. //undefined
  4294. func, //function
  4295. ignoretags = ["STYLE", "SCRIPT", "NOSCRIPT"] //array|undefined
  4296. ) {
  4297. // log(String(func))
  4298. a("*").qsa().foreach(repl)
  4299. watch(document.documentElement)
  4300. function watch(elem) {
  4301. new MutationObserver((e) => {
  4302. if (location.href.includes("scratch.mit.edu/projects")) return
  4303. ;[...e].forEach((e) => [...e.addedNodes].forEach(repl))
  4304. }).observe(elem, {
  4305. childList: true,
  4306. subtree: true,
  4307. attributes: true,
  4308. characterData: false,
  4309. })
  4310. }
  4311.  
  4312. function repl(node) {
  4313. if (node.shadowRoot) {
  4314. log(1, node, node.textContent)
  4315. a("*").qsa(node.shadowRoot).foreach(repl)
  4316. watch(node.shadowRoot)
  4317. return repl(node.shadowRoot)
  4318. }
  4319. if (ignoretags.includes(node.tagName)) return
  4320. var nodes = node?.childNodes
  4321. if (!nodes) return
  4322. for (var i = 0, m = nodes.length; i < m; i++) {
  4323. var n = nodes[i]
  4324. // if (n.textContent.includes("Jul 17, 2021‮‭")) log(n, n.textContent)
  4325. if (n.nodeType == n.TEXT_NODE) {
  4326. func(n)
  4327. } else {
  4328. repl(n)
  4329. }
  4330. }
  4331. }
  4332. },
  4333. "text/elem"
  4334. )
  4335. allfuncs.new(
  4336. "runonallelems",
  4337. function (
  4338. //undefined
  4339. func, //function
  4340. selector = "*", //string|undefined
  4341. ignoretags = [] //array|undefined
  4342. ) {
  4343. a("*").qsa().foreach(repl)
  4344.  
  4345. watch(document.documentElement)
  4346. function watch(elem) {
  4347. new MutationObserver((e) => {
  4348. if (location.href.includes("scratch.mit.edu/projects")) return
  4349. ;[...e].forEach((e) => [...e.addedNodes].forEach(repl))
  4350. }).observe(elem, {
  4351. childList: true,
  4352. subtree: true,
  4353. attributes: true,
  4354. characterData: true,
  4355. })
  4356. }
  4357. function repl(elem) {
  4358. if (elem.shadowRoot) {
  4359. repl(elem.shadowRoot)
  4360. a("*").qsa(elem.shadowRoot).foreach(repl)
  4361. watch(elem.shadowRoot)
  4362. }
  4363. if (elem.children) [...elem.children].forEach(repl)
  4364. if (!elem.matches) return
  4365. if (ignoretags.includes(elem.tagName)) return
  4366. if (elem.matches(selector)) func(elem)
  4367. }
  4368. },
  4369. "elem"
  4370. )
  4371. savelib("allfuncs", a)
  4372.  
  4373. function extras() {
  4374. ;(() => {
  4375. if (!window.showDirectoryPicker) return
  4376. if (!window.showOpenFilePicker) return
  4377. if (!window.showSaveFilePicker) return
  4378. const old = {
  4379. showDirectoryPicker: showDirectoryPicker.bind(window),
  4380. showOpenFilePicker: showOpenFilePicker.bind(window),
  4381. showSaveFilePicker: showSaveFilePicker.bind(window),
  4382. }
  4383. showDirectoryPicker = a(function (
  4384. //promise
  4385. obj = false //object|boolean|undefined
  4386. ) {
  4387. if (obj === true) {
  4388. obj = { mode: "readwrite" }
  4389. } else if (obj === false) {
  4390. obj = { mode: "read" }
  4391. }
  4392. return old.showDirectoryPicker(obj)
  4393. }).strictfunction("showDirectoryPicker").val
  4394. showOpenFilePicker = a(async function (
  4395. //promise
  4396. obj = {}, //object|undefined
  4397. write, //boolean|undefined
  4398. multiple, //boolean|undefined
  4399. types, //array|undefined
  4400. exts, //array|string|undefined
  4401. excludeAcceptAllOption = false //boolean|undefined
  4402. ) {
  4403. if (obj.types && !types) {
  4404. types = obj.types
  4405. delete obj.types
  4406. }
  4407. if (obj.exts && !exts) {
  4408. exts = obj.exts
  4409. delete obj.exts
  4410. }
  4411. if (excludeAcceptAllOption) obj.excludeAcceptAllOption = true
  4412. if (obj.name) obj.suggestedName = obj.name
  4413. if (multiple !== undefined) {
  4414. obj.multiple = multiple
  4415. delete obj.name
  4416. }
  4417. if (exts) {
  4418. obj.types = {
  4419. accept: {
  4420. "*/*": exts,
  4421. },
  4422. }
  4423. }
  4424. if (types) {
  4425. if (!obj.type) obj.type = { accept: {} }
  4426. types.forEach((type) => (obj.type.accept[type] = ["*"]))
  4427. }
  4428. if (obj.multiple) return await old.showOpenFilePicker(obj)
  4429. var x = await old.showOpenFilePicker(obj)
  4430. x = x[0] ?? x
  4431. if (obj.mode == "readwrite" || write)
  4432. if ((await x.requestPermission({ mode: "readwrite" })) !== "granted")
  4433. throw new Error("user didn't grant write permission")
  4434. return x
  4435. }).strictfunction("showOpenFilePicker").val
  4436. showSaveFilePicker = a(function (
  4437. //promise
  4438. obj = {}, //object|none|string
  4439. multiple = false, //boolean|none
  4440. types, //array|none
  4441. exts, //array|string|none
  4442. excludeAcceptAllOption = false //boolean|undefined
  4443. ) {
  4444. if (typeof obj == "string") obj = { suggestedName: obj }
  4445. if (obj.types && !types) {
  4446. types = obj.types
  4447. delete obj.types
  4448. }
  4449. if (obj.exts && !exts) {
  4450. exts = obj.exts
  4451. delete obj.exts
  4452. }
  4453. if (excludeAcceptAllOption) obj.excludeAcceptAllOption = true
  4454. if (obj.name) obj.suggestedName = obj.name
  4455. if (multiple !== undefined) {
  4456. obj.multiple = multiple
  4457. delete obj.name
  4458. }
  4459. if (exts) {
  4460. obj.types = {
  4461. accept: {
  4462. "*/*": exts,
  4463. },
  4464. }
  4465. }
  4466. if (types) {
  4467. if (!obj.type) obj.type = { accept: {} }
  4468. types.forEach((type) => (obj.type.accept[type] = ["*"]))
  4469. }
  4470. return old.showSaveFilePicker(obj)
  4471. }).strictfunction("showSaveFilePicker").val
  4472. })()
  4473. }
  4474. extras()
  4475. //log(...Object.keys( allfuncs).map(e=>[e, allfuncs[e].help, allfuncs[e]]||warn(e)))
  4476. })()

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址