lib:all functions

none

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

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

QingJ © 2025

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