lib:all functions

none

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

  1. // ==UserScript==
  2. // @name lib:all functions
  3. // @version 8
  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. // @exclude /livereload.net\/files\/ffopen\/index.html$/
  12. // @namespace https://greasyfork.org/users/1184528
  13. // ==/UserScript==
  14. ;(async function () {
  15. const { savelib } = loadlib("libloader", "allfuncs.js")
  16. const proxy_set = new WeakSet()
  17. const oldproxy = Proxy
  18. window.Proxy = new Proxy(oldproxy, {
  19. construct(_target, args) {
  20. const proxy = new oldproxy(...args)
  21. proxy_set.add(proxy)
  22. return proxy
  23. },
  24. })
  25. const isproxy = function (proxy) {
  26. return proxy_set.has(proxy)
  27. }
  28. Object.keys(console).forEach((e) => {
  29. window[e] = function (...args) {
  30. var z = []
  31. let pi = 0
  32. args.forEach((y) => {
  33. let rand = `{${pi}}${a().randstr().val}`
  34. while (true) {
  35. if (isa(y)) {
  36. z.push("function_chain >")
  37. y = y.val
  38. continue
  39. } else if (a(y).gettype("promise").val) {
  40. pi++
  41. y.then((...args) => window[e]("RESOLVED - " + rand, ...args)).catch(
  42. (...args) => window[e]("REJECTED - " + rand, ...args)
  43. )
  44. y = "PROMISE - " + rand
  45. continue
  46. }
  47. z.push(y)
  48. break
  49. }
  50. })
  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|boolean|undefined
  1008. istrue = false //boolean|undefined
  1009. ) {
  1010. var all = []
  1011. if (a(type).gettype("array").val) {
  1012. var temp = {}
  1013. a(type).foreach((e) => (temp[e] = cb))
  1014. type = temp
  1015. }
  1016. if (a(type).gettype("object").val) {
  1017. istrue = cb
  1018. a(type).foreach(function (type, cb) {
  1019. if (a(type).gettype("string").val)
  1020. type = a(type).matchall(/[a-z]+/g).val
  1021. type.forEach((type) => {
  1022. const newcb = function (...e) {
  1023. cb(...e)
  1024. }
  1025. elem.addEventListener(type, newcb, istrue)
  1026. all.push([elem, type, newcb])
  1027. })
  1028. })
  1029. } else if (a(type).gettype("string").val) {
  1030. type = a(type).matchall(/[a-z]+/g).val
  1031. type.forEach((type) => {
  1032. const newcb = function (e) {
  1033. cb(e, type)
  1034. }
  1035. elem.addEventListener(type, newcb, istrue)
  1036. all.push([elem, type, newcb])
  1037. })
  1038. }
  1039. return all
  1040. },
  1041. "event/elem",
  1042. true
  1043. )
  1044. allfuncs.new(
  1045. "toelem",
  1046. function (
  1047. //element|undefined|array
  1048. elem, //any
  1049. single //boolean|none
  1050. ) {
  1051. if (a(elem).gettype("element").val) return elem
  1052. switch (a(elem).gettype().val) {
  1053. case "string":
  1054. return single ? a(elem).qs().val : a(elem).qsa().val
  1055. case "array":
  1056. return elem.map((elem) => {
  1057. return a(elem).toelem(single).val
  1058. })
  1059. case "object":
  1060. var newobj = {
  1061. ...elem,
  1062. }
  1063. if (single)
  1064. return {
  1065. [Object.keys(newobj)[0]]: a(
  1066. newobj[Object.keys(newobj)[0]]
  1067. ).toelem(single).val,
  1068. }
  1069. a(newobj).foreach(function (a, s) {
  1070. newobj[a] = a(s).toelem().val
  1071. })
  1072. return newobj
  1073. default:
  1074. error(elem, "inside [toelem] - not an element?")
  1075. return undefined
  1076. }
  1077. },
  1078. "elem",
  1079. true
  1080. )
  1081. allfuncs.new(
  1082. "geturlperams",
  1083. function (
  1084. //object
  1085. e = location.href //undefined|string
  1086. ) {
  1087. var arr = {}
  1088. ;[...e.matchAll(/[?&]([^&\s]+?)(?:=([^&\s]*?))?(?=&|$|\s)/g)].forEach(
  1089. (e) => {
  1090. if (e[1].includes("#")) arr["#"] = e[1].match(/#(.*$)/)[1]
  1091. if (e[2].includes("#")) arr["#"] = e[2].match(/#(.*$)/)[1]
  1092. e[1] = e[1].replace(/#.*$/, "")
  1093. e[2] = e[2].replace(/#.*$/, "")
  1094. arr[decodeURIComponent(e[1]).replaceAll("+", " ")] =
  1095. e[2] === undefined
  1096. ? undefined
  1097. : decodeURIComponent(e[2]).replaceAll("+", " ")
  1098. }
  1099. )
  1100. return arr
  1101. },
  1102. "url",
  1103. false
  1104. )
  1105. allfuncs.new(
  1106. "updateurlperam",
  1107. function (
  1108. //string
  1109. key, //string
  1110. value, //string|undefined
  1111. cangoback //undefined|boolean
  1112. ) {
  1113. var g = {
  1114. ...a().geturlperams().val,
  1115. [key]: value,
  1116. }
  1117. var k = ""
  1118. var hash = ""
  1119. a(g).foreach(function (key, value) {
  1120. if (key == "#") return (hash = key + value)
  1121. key = encodeURIComponent(key)
  1122. value = encodeURIComponent(value)
  1123. k += "&" + (value === undefined ? key : key + "=" + value)
  1124. })
  1125. k = k.replace("&", "?")
  1126. k += hash
  1127. cangoback
  1128. ? history.pushState(null, null, k)
  1129. : history.replaceState(null, null, k)
  1130. return key
  1131. },
  1132. "url",
  1133. true
  1134. )
  1135. allfuncs.new(
  1136. "newvarfunc",
  1137. function (
  1138. //undefined
  1139. name, //string
  1140. func, //function
  1141. obj = window //undefined|object
  1142. ) {
  1143. Object.defineProperty(obj, name, {
  1144. configurable: false,
  1145. get() {
  1146. return func.call({})
  1147. },
  1148. set(a) {
  1149. return func.call(a, a, true)
  1150. },
  1151. })
  1152. },
  1153. "var",
  1154. true
  1155. )
  1156. allfuncs.new(
  1157. "rerange",
  1158. function (
  1159. //number
  1160. val, //number
  1161. low1, //number
  1162. high1, //number
  1163. low2, //number
  1164. high2 //number
  1165. ) {
  1166. return ((val - low1) / (high1 - low1)) * (high2 - low2) + low2
  1167. },
  1168. "number",
  1169. false
  1170. )
  1171. allfuncs.new(
  1172. "destring",
  1173. function (
  1174. //any
  1175. inp //string
  1176. ) {
  1177. var out = inp
  1178. if (/^[\-0-9]+$/.test(inp)) return Number(inp)
  1179. if (a((out = JSON.parse(inp))).gettype("array").val) return out
  1180. if (
  1181. a(
  1182. (out = JSON.parse(inp.replaceAll("'", '"').replaceAll("`", '"')))
  1183. ).gettype("object").val
  1184. )
  1185. return out
  1186. if (inp == "true") return true
  1187. if (inp == "false") return false
  1188. if (inp == "undefined") return undefined
  1189. if (inp == "NaN") return NaN
  1190. return inp
  1191. },
  1192. "string/parse",
  1193. true
  1194. )
  1195. allfuncs.new(
  1196. "eachelem",
  1197. function (
  1198. //array
  1199. arr1, //array
  1200. cb //function
  1201. ) {
  1202. var arr = []
  1203. var elem = []
  1204. if (a(arr1).gettype("array").val) {
  1205. arr1.foreach((e) => {
  1206. elem = [
  1207. ...elem,
  1208. ...(a(e).gettype("string").val ? a(e).qsa().val : [e]),
  1209. ]
  1210. })
  1211. } else {
  1212. elem = a(arr1).gettype("string").val ? a(ar1).qsa().val : [arr1]
  1213. }
  1214. elem = elem.filter((e) => {
  1215. return e instanceof Element
  1216. })
  1217. elem.foreach(function (...a) {
  1218. arr.push(cb(...a))
  1219. })
  1220. if (arr.length == 1) arr = arr[0]
  1221. return arr
  1222. },
  1223. "elem",
  1224. true
  1225. )
  1226. allfuncs.new(
  1227. "remove",
  1228. function (
  1229. //array
  1230. arr, //array
  1231. idx, //number|any
  1232. isidx //boolean|undefined
  1233. ) {
  1234. arr = [...arr]
  1235. idx = isidx ? idx : arr.indexOf(idx)
  1236. if (idx < 0 || typeof idx !== "number") return arr
  1237. arr.splice(idx, 1)
  1238. return arr
  1239. },
  1240. "array",
  1241. true
  1242. )
  1243. allfuncs.new(
  1244. "download",
  1245. function (
  1246. //string|file|blob
  1247. data, //string|file|blob
  1248. filename = "temp.txt", //string|undefined
  1249. type, //string|undefined
  1250. isurl //boolean|undefined
  1251. ) {
  1252. var url
  1253. if (isurl) {
  1254. url = data
  1255. } else {
  1256. var file = a(data).gettype("string").val
  1257. ? new Blob([data], {
  1258. type,
  1259. })
  1260. : (data.name ? (filename = data.name) : "", data)
  1261. url = URL.createObjectURL(file)
  1262. }
  1263. a()
  1264. .bodyload()
  1265. .then(() => {
  1266. var link = a(document.body).createelem("a", {
  1267. href: url,
  1268. download: filename,
  1269. }).val
  1270. link.click()
  1271. link.remove()
  1272. if (!isurl) window.URL.revokeObjectURL(url)
  1273. })
  1274. return data
  1275. },
  1276. "file",
  1277. true
  1278. )
  1279. allfuncs.new(
  1280. "idx",
  1281. function (
  1282. //array
  1283. arr, //array|string
  1284. idx //number
  1285. ) {
  1286. return idx >= 0 ? arr[idx] : arr[arr.length + idx]
  1287. },
  1288. "array",
  1289. true
  1290. )
  1291. allfuncs.new(
  1292. "compare",
  1293. function (
  1294. //boolean
  1295. x, //string|any
  1296. y //string|any
  1297. ) {
  1298. return x && y
  1299. ? (typeof x == "string" ? x.toLowerCase() : x) ==
  1300. (typeof y == "string" ? y.toLowerCase() : y)
  1301. : true
  1302. },
  1303. "check",
  1304. true
  1305. )
  1306. allfuncs.new(
  1307. "createelem",
  1308. function (
  1309. //element
  1310. parent, //element|none
  1311. elem, //string
  1312. data //object
  1313. ) {
  1314. //if (!parent) warn("no parent set", elem, data)
  1315. var type = elem
  1316. var issvg = elem == "svg" || parent?.tagName?.toLowerCase?.() == "svg"
  1317. // warn(issvg, 'issvg', elem, parent, parent?.tagName)
  1318. elem = issvg
  1319. ? document.createElementNS("http://www.w3.org/2000/svg", elem)
  1320. : document.createElement(elem)
  1321. if (data.class)
  1322. data.class.split(" ").forEach((e) => {
  1323. elem.classList.add(e)
  1324. })
  1325. if (data.options && type == "select")
  1326. data.options = data.options.map((e) =>
  1327. a(e).gettype("array").val
  1328. ? a(elem).createelem("option", {
  1329. innerHTML: e[0],
  1330. value: e[1],
  1331. }).val
  1332. : a(elem).createelem("option", {
  1333. innerHTML: e,
  1334. value: e,
  1335. }).val
  1336. )
  1337. if (type == "label" && "for" in data) {
  1338. data.htmlFor = data.for
  1339. }
  1340. Object.assign(elem.style, data)
  1341. if (type == "select") {
  1342. a(data).foreach(function (a, s) {
  1343. elem[a] = s
  1344. })
  1345. } else if (issvg) {
  1346. Object.keys(data).forEach((e) => (elem[e] = data[e]))
  1347. } else {
  1348. Object.assign(elem, data)
  1349. }
  1350. if (typeof parent == "string") parent = a(parent).qs().val
  1351. a(() => parent.appendChild(elem)).ignore()
  1352. return elem
  1353. },
  1354. "elem",
  1355. true
  1356. )
  1357. allfuncs.new(
  1358. "gettype",
  1359. function (
  1360. //string
  1361. thing, //any
  1362. match //undefined|string|array
  1363. ) {
  1364. if (
  1365. !match ||
  1366. (Object.prototype.toString
  1367. .call(match)
  1368. .toLowerCase()
  1369. .match(/^\[[a-z]+ (.+)\]$/)[1] == "string" &&
  1370. !match.includes("|"))
  1371. ) {
  1372. var type = Object.prototype.toString
  1373. .call(thing)
  1374. .toLowerCase()
  1375. .match(/^\[[a-z]+ (.+)\]$/)[1]
  1376. if (type !== "function") if (type == match) return true
  1377. if (match == "normalfunction") return type == "function"
  1378. if (type == "htmldocument" && match == "document") return true
  1379. if (match == "body" && type == "htmlbodyelement") return true
  1380. if (match && new RegExp(`^html${match}element$`).test(type)) return true
  1381. if (/^html\w+element$/.test(type)) type = "element"
  1382. if (type == "htmldocument") type = "element"
  1383. if (type == "asyncfunction") type = "function"
  1384. if (type == "generatorfunction") type = "function"
  1385. if (type == "regexp") type = "regex"
  1386. if (match == "regexp") match = "regex"
  1387. if (match == "element" && type == "window") return true
  1388. if (match == "element" && type == "shadowroot") return true
  1389. if (match == "event" && /\w+event$/.test(type)) return true
  1390. if (/^(html|svg).*element$/.test(type)) type = "element"
  1391. if (type == "function") {
  1392. type = /^\s*class\s/.test(Function.prototype.toString.call(thing))
  1393. ? "class"
  1394. : "function"
  1395. }
  1396. if (match == "none")
  1397. return type == "nan" || type == "undefined" || type == "null"
  1398. try {
  1399. if (type === "number" && isNaN(thing) && match == "nan") return true
  1400. } catch (e) {
  1401. error(thing)
  1402. }
  1403. return match ? match === type : type
  1404. } else {
  1405. if (match.includes("|")) match = match.split("|")
  1406. match = [...new Set(match)]
  1407. return match.filter((e) => a(thing).gettype(e).val).length > 0
  1408. }
  1409. },
  1410. "check",
  1411. true
  1412. )
  1413. allfuncs.new(
  1414. "waitforelem",
  1415. async function (
  1416. //promise
  1417. selector //string|array
  1418. ) {
  1419. if (a(selector).gettype("string").val) {
  1420. selector = [selector]
  1421. }
  1422. await a().bodyload()
  1423. var g = false
  1424. return new Promise((resolve) => {
  1425. var observer = new MutationObserver(check)
  1426. observer.observe(document.body, {
  1427. childList: true,
  1428. subtree: true,
  1429. attributes: true,
  1430. characterData: false,
  1431. })
  1432. check()
  1433. function check() {
  1434. if (g) return
  1435. if (selector.find((selector) => !a(selector).qs().val)) return
  1436. observer.disconnect()
  1437. resolve(
  1438. selector.length == 1
  1439. ? a(selector[0]).qs().val
  1440. : selector.map((e) => a(e).qs().val)
  1441. )
  1442. }
  1443. })
  1444. },
  1445. "time/elem"
  1446. )
  1447. allfuncs.new(
  1448. "findvar",
  1449. function (
  1450. //any
  1451. obj, //object|element
  1452. findkey, //any
  1453. objectname = "obj", //string
  1454. exact, //boolean
  1455. all //boolean
  1456. ) {
  1457. var vvv = []
  1458. var allarr = []
  1459. var chain = objectname
  1460. var arr = []
  1461. var arr2 = [
  1462. {
  1463. chain,
  1464. value: obj,
  1465. },
  1466. ]
  1467. var visited = []
  1468. var i = 0
  1469. while (arr2.length && i++ < 800) {
  1470. if (
  1471. arr2
  1472. .map((e) => e.chain)
  1473. .join("/")
  1474. .includes("." + findkey + (exact ? "/" : ""))
  1475. ) {
  1476. if (all)
  1477. vvv.push(
  1478. arr2.filter((e) =>
  1479. exact
  1480. ? e.chain.endsWith("." + findkey)
  1481. : e.chain.includes("." + findkey)
  1482. )
  1483. )
  1484. else
  1485. return arr2.filter((e) =>
  1486. exact
  1487. ? e.chain.endsWith("." + findkey)
  1488. : e.chain.includes("." + findkey)
  1489. )[0]
  1490. }
  1491. var oldarr2 = [...arr2]
  1492. allarr.push(arr2)
  1493. arr2 = []
  1494. oldarr2.forEach((e) => {
  1495. if (
  1496. a(e.value).gettype("object").val ||
  1497. a(e.value).gettype("element").val
  1498. )
  1499. a(e.value).foreach(function (key, value) {
  1500. if (a(key).gettype().val !== "string")
  1501. return warn(key, a(key).gettype().val)
  1502. var newchain = /^[a-z_][_a-z0-9]*$/i.test(key)
  1503. ? "." + key
  1504. : `["${key.replaceAll('"', '\\"')}"]`
  1505. arr.push(e.chain + newchain)
  1506. if (visited.includes(e.value)) return
  1507. arr2.push({
  1508. chain: e.chain + newchain,
  1509. value,
  1510. })
  1511. })
  1512. visited.push(e.value)
  1513. })
  1514. }
  1515. return vvv.length > 0 ? vvv : allarr
  1516. },
  1517. "debug",
  1518. false
  1519. )
  1520. allfuncs.new(
  1521. "getallvars",
  1522. function () {
  1523. //object
  1524. var obj = {}
  1525. var variables = []
  1526. for (var name in this)
  1527. if (
  1528. !`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`
  1529. .split(" ")
  1530. .includes(name)
  1531. )
  1532. variables.push(name)
  1533. variables.forEach((e) => {
  1534. var c = String(a(this[e]).gettype().val)
  1535. if (c === "object") c = "variable"
  1536. if (!obj[c]) obj[c] = []
  1537. obj[c].push(e)
  1538. })
  1539. return obj
  1540. },
  1541. "debug",
  1542. false
  1543. )
  1544. allfuncs.new(
  1545. "scratch_getallkeys",
  1546. function () {
  1547. //object
  1548. var m = vm.runtime
  1549. var f = {
  1550. bools: m.targets
  1551. .map((e) => {
  1552. return {
  1553. name: e.sprite.name,
  1554. blocks: Object.values(e.blocks._blocks)
  1555. .filter((e) => e.opcode === "sensing_keypressed")
  1556. .map((e) => e.inputs.KEY_OPTION.block),
  1557. otherblocks: e.blocks._blocks,
  1558. }
  1559. })
  1560. .filter((e) => e.blocks.length)
  1561. .map((e) => {
  1562. return {
  1563. name: e.name,
  1564. value: [
  1565. ...new Set(
  1566. e.blocks
  1567. .map((y) => e.otherblocks[y])
  1568. .map(
  1569. (e) =>
  1570. e.fields?.KEY_OPTION?.value ||
  1571. e.fields?.VALUE?.value ||
  1572. error(e)
  1573. )
  1574. ),
  1575. ],
  1576. }
  1577. }),
  1578. hats: m.targets
  1579. .map((e) => {
  1580. return {
  1581. name: e.name,
  1582. blocks: Object.values(e.blocks)
  1583. .filter((e) => e.opcode === "event_whenkeypressed")
  1584. .map((e) => e.fields.KEY_OPTION.value),
  1585. }
  1586. })
  1587. .filter((e) => e.blocks.length),
  1588. }
  1589. f.all = [
  1590. ...f.hats.map((e) => e.blocks).flat(),
  1591. ...f.bools.map((e) => e.value).flat(),
  1592. ]
  1593. f.all = [...new Set(f.all)]
  1594. return f
  1595. },
  1596. "scratch",
  1597. false
  1598. )
  1599. allfuncs.new(
  1600. "newfunc",
  1601. function (
  1602. //undefined
  1603. func1, //string
  1604. func2 //function
  1605. ) {
  1606. eval(`var a = ${func1}
  1607. var s = ${func2}
  1608. ${func1} = function (...args) {
  1609. a.call(this, ...args)
  1610. s(arguments)
  1611. }`)
  1612. },
  1613. "function/jank",
  1614. true
  1615. )
  1616. allfuncs.new(
  1617. "findall",
  1618. function (
  1619. //array
  1620. obj, //object
  1621. objectname = "obj" //string
  1622. ) {
  1623. var chain = objectname
  1624. var arr = []
  1625. var arr2 = [
  1626. {
  1627. chain,
  1628. value: obj,
  1629. },
  1630. ]
  1631. var visited = []
  1632. var i = 0
  1633. while (arr2.length && i++ < 800) {
  1634. var oldarr2 = [...arr2]
  1635. arr2 = []
  1636. oldarr2.forEach((e) => {
  1637. if (a(e.value).gettype("object").val)
  1638. a(e.value).foreach(function (key, value) {
  1639. var newchain = /^[_a-z][_a-z0-9]*$/i.test(key)
  1640. ? "." + key
  1641. : `["${key.replaceAll('"', '\\"')}"]`
  1642. arr.push(e.chain + newchain)
  1643. if (visited.includes(e.value)) return
  1644. log({
  1645. key,
  1646. value,
  1647. chain: e.chain + newchain,
  1648. })
  1649. arr2.push({
  1650. chain: e.chain + newchain,
  1651. value,
  1652. })
  1653. })
  1654. visited.push(e.value)
  1655. })
  1656. }
  1657. return visited
  1658. },
  1659. "debug",
  1660. true
  1661. )
  1662. allfuncs.new(
  1663. "sha",
  1664. function (
  1665. //string
  1666. s = "", //string
  1667. includesymbols //boolean|string
  1668. ) {
  1669. var tab
  1670. if (typeof includesymbols == "string") {
  1671. tab = includesymbols
  1672. } else if (includesymbols) {
  1673. tab =
  1674. "`~\\|[];',./{}:<>?\"!@#$%^&*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  1675. } else {
  1676. tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  1677. }
  1678. return binb2b64(core_sha1(str2binb(s), s.length * 8))
  1679.  
  1680. function core_sha1(x, len) {
  1681. x[len >> 5] |= 0x80 << (24 - len)
  1682. x[(((len + 64) >> 9) << 4) + 15] = len
  1683. var w = Array(80)
  1684. var a = 1732584193
  1685. var b = -271733879
  1686. var c = -1732584194
  1687. var d = 271733878
  1688. var e = -1009589776
  1689. for (var i = 0; i < x.length; i += 16) {
  1690. var olda = a
  1691. var oldb = b
  1692. var oldc = c
  1693. var oldd = d
  1694. var olde = e
  1695. for (var j = 0; j < 80; j++) {
  1696. if (j < 16) w[j] = x[i + j]
  1697. else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)
  1698. var t = safe_add(
  1699. safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
  1700. safe_add(safe_add(e, w[j]), sha1_kt(j))
  1701. )
  1702. e = d
  1703. d = c
  1704. c = rol(b, 30)
  1705. b = a
  1706. a = t
  1707. }
  1708. a = safe_add(a, olda)
  1709. b = safe_add(b, oldb)
  1710. c = safe_add(c, oldc)
  1711. d = safe_add(d, oldd)
  1712. e = safe_add(e, olde)
  1713. }
  1714. return Array(a, b, c, d, e)
  1715. }
  1716.  
  1717. function sha1_ft(t, b, c, d) {
  1718. if (t < 20) return (b & c) | (~b & d)
  1719. if (t < 40) return b ^ c ^ d
  1720. if (t < 60) return (b & c) | (b & d) | (c & d)
  1721. return b ^ c ^ d
  1722. }
  1723.  
  1724. function sha1_kt(t) {
  1725. return t < 20
  1726. ? 1518500249
  1727. : t < 40
  1728. ? 1859775393
  1729. : t < 60
  1730. ? -1894007588
  1731. : -899497514
  1732. }
  1733.  
  1734. function safe_add(x, y) {
  1735. var lsw = (x & 0xffff) + (y & 0xffff)
  1736. var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
  1737. return (msw << 16) | (lsw & 0xffff)
  1738. }
  1739.  
  1740. function rol(num, cnt) {
  1741. return (num << cnt) | (num >>> (32 - cnt))
  1742. }
  1743.  
  1744. function str2binb(str) {
  1745. var bin = Array()
  1746. var mask = (1 << 8) - 1
  1747. for (var i = 0; i < str.length * 8; i += 8)
  1748. bin[i >> 5] |= (str.charCodeAt(i / 8) & mask) << (24 - i)
  1749. return bin
  1750. }
  1751.  
  1752. function binb2b64(binarray) {
  1753. var str = ""
  1754. for (var i = 0; i < binarray.length * 4; i += 3) {
  1755. var triplet =
  1756. (((binarray[i >> 2] >> (8 * (3 - (i % 4)))) & 0xff) << 16) |
  1757. (((binarray[(i + 1) >> 2] >> (8 * (3 - ((i + 1) % 4)))) & 0xff) <<
  1758. 8) |
  1759. ((binarray[(i + 2) >> 2] >> (8 * (3 - ((i + 2) % 4)))) & 0xff)
  1760. for (var j = 0; j < 4; j++) {
  1761. if (i * 8 + j * 6 > binarray.length * 32) str += ""
  1762. else str += tab.charAt((triplet >> (6 * (3 - j))) & 0x3f)
  1763. }
  1764. }
  1765. return str
  1766. }
  1767. },
  1768. "code",
  1769. true
  1770. )
  1771. allfuncs.new(
  1772. "qs",
  1773. function (
  1774. //element|none
  1775. text, //string
  1776. parent = document //element|none
  1777. ) {
  1778. return parent.querySelector(text)
  1779. },
  1780. "elem",
  1781. true
  1782. )
  1783. allfuncs.new(
  1784. "qsa",
  1785. function (
  1786. //array
  1787. text, //string
  1788. parent = document //element|none
  1789. ) {
  1790. return Array.from(parent.querySelectorAll(text))
  1791. },
  1792. "elem",
  1793. true
  1794. )
  1795. allfuncs.new(
  1796. "csspath",
  1797. function (
  1798. //string|array
  1799. el //elements|element
  1800. ) {
  1801. if (a(el).gettype("array").val)
  1802. return a(el).map((e) => a(e).csspath().val)
  1803. if (!(el instanceof Element)) return
  1804. var path = []
  1805. while (el.nodeType === Node.ELEMENT_NODE) {
  1806. var selector = el.nodeName.toLowerCase()
  1807. if (el.id) {
  1808. selector += "#" + el.id
  1809. path.unshift(selector)
  1810. break
  1811. } else {
  1812. var sib = el,
  1813. nth = 1
  1814. while ((sib = sib.previousElementSibling)) {
  1815. if (sib.nodeName.toLowerCase() == selector) nth++
  1816. }
  1817. if (nth != 1) selector += ":nth-of-type(" + nth + ")"
  1818. }
  1819. path.unshift(selector)
  1820. el = el.parentNode
  1821. }
  1822. return path.join(" > ")
  1823. },
  1824. "elem",
  1825. true
  1826. )
  1827. allfuncs.new(
  1828. "fromms",
  1829. function (
  1830. //object
  1831. ms //number
  1832. ) {
  1833. //returns a unix timestamp as an object where "ms" is the unixtimestamp
  1834. ms = Number(ms)
  1835. return {
  1836. years: Math.floor(ms / 1000 / 60 / 60 / 24 / 365),
  1837. days: Math.floor(ms / 1000 / 60 / 60 / 24) % 365,
  1838. hours: Math.floor(ms / 1000 / 60 / 60) % 24,
  1839. mins: Math.floor(ms / 1000 / 60) % 60,
  1840. secs: Math.floor(ms / 1000) % 60,
  1841. ms: Math.floor(ms) % 1000,
  1842. }
  1843. },
  1844. "time",
  1845. true
  1846. )
  1847. allfuncs.new(
  1848. "toms",
  1849. function (
  1850. //number
  1851. { ms = 0, secs = 0, mins = 0, hours = 0, days = 0, years = 0 } //object
  1852. ) {
  1853. return (
  1854. ms +
  1855. secs * 1000 +
  1856. mins * 60000 +
  1857. hours * 3600000 +
  1858. days * 86400000 +
  1859. years * 31560000000
  1860. )
  1861. },
  1862. "time",
  1863. true
  1864. )
  1865. allfuncs.new(
  1866. "rect",
  1867. function (
  1868. //object
  1869. e //element
  1870. ) {
  1871. if (a(e).gettype("string").val) e = a(e).qs().val
  1872. var { x, y, width, height } = e.getBoundingClientRect().toJSON()
  1873. return {
  1874. x,
  1875. y,
  1876. w: width,
  1877. h: height,
  1878. }
  1879. },
  1880. "elem",
  1881. true
  1882. )
  1883. allfuncs.new(
  1884. "setelem",
  1885. function (
  1886. //element
  1887. elem, //element
  1888. data //object
  1889. ) {
  1890. var issvg = elem == "svg" || parent?.tagName?.toLowerCase?.() == "svg"
  1891. // warn(issvg, 'issvg', elem, parent, parent?.tagName)
  1892. if (data.class)
  1893. data.class.split(" ").forEach((e) => {
  1894. elem.classList.add(e)
  1895. })
  1896. if (data.options && elem.tagName.toLowerCase() == "select")
  1897. data.options = data.options.map((e) =>
  1898. a(e).gettype("array").val
  1899. ? a(elem).createelem("option", {
  1900. innerHTML: e[0],
  1901. value: e[1],
  1902. }).val
  1903. : a(elem).createelem("option", {
  1904. innerHTML: e,
  1905. value: e,
  1906. }).val
  1907. )
  1908. if (type == "label" && "for" in data) {
  1909. data.htmlFor = data.for
  1910. }
  1911. Object.assign(elem.style, data)
  1912. if (elem.tagName.toLowerCase() == "select") {
  1913. a(data).foreach(function (a, s) {
  1914. elem[a] = s
  1915. })
  1916. } else if (issvg) {
  1917. Object.keys(data).forEach((e) => (elem[e] = data[e]))
  1918. } else {
  1919. Object.assign(elem, data)
  1920. }
  1921. return elem
  1922. },
  1923. "elem",
  1924. true
  1925. )
  1926. allfuncs.new(
  1927. "watchvar",
  1928. function (
  1929. //undefined
  1930. varname, //string
  1931. onset, //function
  1932. onget, //function|none
  1933. obj = window //object|window
  1934. ) {
  1935. //creates a new var and runs "onset" on the change of "varname", and "onget" when "varname" is read
  1936. obj = obj || window
  1937. obj[`_${varname}`] = undefined
  1938. obj[`${varname}`] = undefined
  1939. Object.defineProperty(obj, varname, {
  1940. configurable: false,
  1941. get() {
  1942. if (onget) return onget(obj[`_${varname}`])
  1943. return obj[`_${varname}`]
  1944. },
  1945. set(value) {
  1946. if (value === obj[`_${value}`]) {
  1947. return
  1948. }
  1949. var s = onset(value, obj[`_${varname}`])
  1950. if (s) obj[`_${varname}`] = value
  1951. },
  1952. })
  1953. },
  1954. "var/debug",
  1955. true
  1956. )
  1957. allfuncs.new(
  1958. "randomizeorder",
  1959. function (
  1960. //array
  1961. arr //array
  1962. ) {
  1963. arr = [...arr]
  1964. var arr2 = []
  1965. var count = arr.length
  1966. for (var i = 0; i < count; i++) {
  1967. var idx = randfrom(0, arr.length - 1)
  1968. arr2.push(arr[idx])
  1969. arr.splice(idx, 1)
  1970. }
  1971. return arr2
  1972. },
  1973. "array",
  1974. true
  1975. )
  1976. allfuncs.new(
  1977. "constrainvar",
  1978. function (
  1979. //undefined
  1980. varname, //string
  1981. min, //number
  1982. max //number
  1983. ) {
  1984. //creates a new var that can't go beyond the bounds of "min" and "max"
  1985. window[`_${varname}`] = undefined
  1986. window[`${varname}`] = undefined
  1987. Object.defineProperty(window, varname, {
  1988. configurable: false,
  1989. get() {
  1990. return window[`_${varname}`]
  1991. },
  1992. set(value) {
  1993. if (value === window[`_${varname}`]) {
  1994. return
  1995. }
  1996. if (value > max) value = max
  1997. if (value < min) value = min
  1998. window[`_${varname}`] = value
  1999. },
  2000. })
  2001. },
  2002. "var",
  2003. true
  2004. )
  2005. allfuncs.new(
  2006. "isbetween",
  2007. function (
  2008. //boolean
  2009. z, //number
  2010. x, //number
  2011. c //number
  2012. ) {
  2013. //returns true if "z" is between "x" and "c"
  2014. if (x == c) return false
  2015. var big, small
  2016. if (x > c) {
  2017. big = x
  2018. small = c
  2019. } else {
  2020. big = c
  2021. small = x
  2022. return z > big && z < small
  2023. }
  2024. },
  2025. "check",
  2026. true
  2027. )
  2028. allfuncs.new(
  2029. "indexsof",
  2030. function (
  2031. //array
  2032. y, //string
  2033. x //string
  2034. ) {
  2035. var i = 0
  2036. var arr = []
  2037. y.split(x).forEach((e, k) => {
  2038. i += e.length
  2039. arr.push(i + k)
  2040. })
  2041. arr.pop()
  2042. return arr
  2043. },
  2044. "array",
  2045. true
  2046. )
  2047. allfuncs.new(
  2048. "export",
  2049. function () {
  2050. //string
  2051. //saves the data of text inputs and checkboxes
  2052. var s = []
  2053. a("input, textarea")
  2054. .qsa()
  2055. .foreach((e) => {
  2056. s.push({
  2057. path: a(e).csspath().val,
  2058. value: escape(e.value),
  2059. checked: e.checked,
  2060. })
  2061. })
  2062. return JSON.stringify(s)
  2063. },
  2064. "data",
  2065. false
  2066. )
  2067. allfuncs.new(
  2068. "import",
  2069. function (
  2070. //string
  2071. data //string
  2072. ) {
  2073. //loads the data of text inputs and checkboxes
  2074. data.forEach((e) => {
  2075. var s = a(e.path).qs().val
  2076. s.checked = e.checked
  2077. s.value = unescape(e.value)
  2078. })
  2079. return data
  2080. },
  2081. "data",
  2082. true
  2083. )
  2084. allfuncs.new(
  2085. "popup",
  2086. function (
  2087. //window
  2088. data, //string
  2089. x, //number|none
  2090. y, //number|none
  2091. w, //number|none
  2092. h //number|none
  2093. ) {
  2094. //creates a popup window
  2095. if (x || x === 0) {
  2096. x = (screen.width / 100) * x
  2097. y = (screen.height / 100) * y
  2098. w = (screen.width / 100) * w
  2099. h = (screen.height / 100) * h
  2100. var win = open("", "", `left=${x}, top=${y} width=${w},height=${h}`)
  2101. win.document.write(data)
  2102. return win
  2103. } else {
  2104. var win = open("")
  2105. win.document.write(data)
  2106. return win
  2107. }
  2108. },
  2109. "window",
  2110. true
  2111. )
  2112. allfuncs.new(
  2113. "same",
  2114. function (
  2115. //boolean
  2116. ...a //any
  2117. ) {
  2118. if (a.length == 1) a = a[0]
  2119. return [...new Set(a.map((e) => JSON.stringify(e)))].length === 1
  2120. },
  2121. "check",
  2122. true
  2123. )
  2124. allfuncs.new(
  2125. "containsany",
  2126. function (
  2127. //boolean
  2128. arr1, //array|string
  2129. arr2 //array
  2130. ) {
  2131. return !!arr2.find((e) => arr1.includes(e))
  2132. },
  2133. "array"
  2134. )
  2135. allfuncs.new(
  2136. "run",
  2137. function (
  2138. //any
  2139. func, //function
  2140. obj //object
  2141. ) {
  2142. return func(...getprops(func).vars.map((e) => obj[e.var]))
  2143. },
  2144. "function",
  2145. true
  2146. )
  2147. allfuncs.new(
  2148. "getprops",
  2149. function (
  2150. //array|object
  2151. func, //function
  2152. peramsonly /*?|boolean*/
  2153. ) {
  2154. return peramsonly
  2155. ? getprops(func)
  2156. .vars.map((e) => e.var)
  2157. .filter((e) => e)
  2158. : getprops(func)
  2159. },
  2160. "function/parse",
  2161. true
  2162. )
  2163. allfuncs.new(
  2164. "bodyload",
  2165. function () {
  2166. //promise
  2167. return new Promise((resolve) => {
  2168. if (document.body) resolve()
  2169. const int = setInterval(() => {
  2170. if (document.body) resolve(clearInterval(int))
  2171. })
  2172. })
  2173. },
  2174. "elem/time",
  2175. false
  2176. )
  2177. ;(async function () {
  2178. const { bodyload } = allfuncs
  2179. await bodyload()
  2180. // var optionselem = loadlib("addnewoption", "optionselem")
  2181. // delete localStorage.buttonsheight
  2182. // delete localStorage.buttonswidth
  2183. // delete localStorage.buttonsx
  2184. // delete localStorage.buttonsy
  2185. if (!localStorage.buttonsheight) localStorage.buttonsheight = "100px"
  2186. if (!localStorage.buttonswidth) localStorage.buttonswidth = "120px"
  2187. var c = document.body
  2188. if (!window.optionselem) {
  2189. c = a(c)
  2190. .createelem("div", {
  2191. position: "fixed",
  2192. top: (Number(localStorage.buttonsy) || 10) + "px",
  2193. left:
  2194. (Number(localStorage.buttonsx) ||
  2195. Number(localStorage.buttonswidth.match(/[0-9]+/)[0]) / 2) + "px",
  2196. width: 0,
  2197. height: 0,
  2198. zIndex: 999999999999999,
  2199. pointerEvents: "all",
  2200. backgroundColor: "#0000",
  2201. })
  2202. .val.attachShadow({
  2203. mode: "closed",
  2204. })
  2205. window.optionselem = a(c).createelem("div", {
  2206. overflow: "hidden",
  2207. position: "fixed",
  2208. top:
  2209. constrain(
  2210. (Number(localStorage.buttonsy) || 10, 0 + 50 / 2),
  2211. innerHeight - this.clientHeight / 2
  2212. ) + "px",
  2213. left:
  2214. constrain(
  2215. localStorage.buttonswidth,
  2216. 0 + this.clientWidth / 2,
  2217. innerWidth - this.clientWidth / 2
  2218. ) + "px",
  2219. zIndex: 999999999999999,
  2220. height: "20px",
  2221. pointerEvents: "all",
  2222. backgroundColor: "#0f09",
  2223. test(e) {
  2224. if (!this.moving && e) return
  2225. if (!e) {
  2226. this.style.translate = "0 0"
  2227. e = {
  2228. clientX: this.getBoundingClientRect().toJSON().x,
  2229. clientY: this.getBoundingClientRect().toJSON().y,
  2230. }
  2231. }
  2232. // this.style.translate = "-50% -50%"
  2233. this.style.top =
  2234. constrain(e.clientY - 10, 0, innerHeight - this.clientHeight) + "px"
  2235. this.style.left =
  2236. constrain(
  2237. e.clientX - this.clientWidth / 2,
  2238. 0,
  2239. innerWidth - this.clientWidth
  2240. ) + "px"
  2241. localStorage.buttonsx = e.clientX
  2242. localStorage.buttonsy = e.clientY
  2243. },
  2244. onmouseup() {
  2245. this.moving = false
  2246. },
  2247. }).val
  2248. optionselem.style.left =
  2249. constrain(
  2250. Number(localStorage.buttonswidth) || 0,
  2251. 0 + optionselem.clientWidth / 2,
  2252. innerWidth - optionselem.clientWidth / 2
  2253. ) + "px"
  2254. optionselem.style.top =
  2255. constrain(
  2256. Number(localStorage.buttonsy) || 10,
  2257. 0 + 50 / 2,
  2258. innerHeight - optionselem.clientHeight / 2
  2259. ) + "px"
  2260. var ismain
  2261. try {
  2262. ismain = window?.parent?.location?.href === location.href
  2263. } catch (e) {
  2264. ismain = false
  2265. }
  2266. a(window.optionselem).createelem("div", {
  2267. backgroundColor: ismain ? "#00f" : "#f00",
  2268. width: "100%",
  2269. height: "20px",
  2270. oncontextmenu(e) {
  2271. e.preventDefault()
  2272. log(window.optionselem)
  2273. if (window.optionselem.style.height === "20px")
  2274. window.optionselem.style.height = "auto"
  2275. else window.optionselem.style.height = "20px"
  2276. },
  2277. onmousedown(e) {
  2278. e.preventDefault()
  2279. if (e.which == 3 || e.button == 2) return
  2280. window.optionselem.moving = true
  2281. },
  2282. onmouseup() {
  2283. window.optionselem.moving = false
  2284. },
  2285. })
  2286. }
  2287.  
  2288. function constrain(inp, max, min) {
  2289. if (min > max) {
  2290. var c = min
  2291. min = max
  2292. max = c
  2293. }
  2294. return Math.min(max, Math.max(min, inp))
  2295. }
  2296. a(window).listen({
  2297. resize() {
  2298. window.optionselem.moving = false
  2299. optionselem.test.call(optionselem)
  2300. },
  2301. blur() {
  2302. window.optionselem.moving = false
  2303. },
  2304. focus() {
  2305. window.optionselem.moving = false
  2306. },
  2307. mousemove(e) {
  2308. optionselem.test.call(optionselem, e)
  2309. },
  2310. })
  2311.  
  2312. function addnewoption( //undefined
  2313. ...z //object|undefined
  2314. ) {
  2315. var zz = z[0]
  2316. // trymatch(zz.host, location.host)
  2317. // trymatch(zz.href, location.n)
  2318. // trymatch(zz.hostname, location.n)
  2319. // trymatch(zz.origin, location.n)
  2320. // trymatch(zz.pathname, location.n)
  2321. var s = a(optionselem).createelem("div", {
  2322. textAlign: "center",
  2323. width: localStorage.buttonswidth,
  2324. minHeight: localStorage.buttonsheight,
  2325. backgroundColor: zz.backgroundColor || "#0000",
  2326. }).val
  2327. a(s).createelem("p", {
  2328. innerHTML: zz.title || " ",
  2329. textAlign: "center",
  2330. color: zz.titlecolor,
  2331. })
  2332. ;[...z].forEach((z, i) => {
  2333. if (i === 0) return
  2334. var elem
  2335. switch (z.type) {
  2336. case "button":
  2337. elem = a(s).createelem("button", {
  2338. id: z.id,
  2339. itemnumber: i,
  2340. index: i,
  2341. innerHTML: z.text,
  2342. onclick: z.onclick,
  2343. textAlign: "center",
  2344. }).val
  2345. break
  2346. case "toggle":
  2347. elem = a(s).createelem("input", {
  2348. id: z.id,
  2349. itemnumber: i,
  2350. index: i,
  2351. type: "checkbox",
  2352. onclick(e) {
  2353. if (this.checked) z.onon?.call?.(this, e)
  2354. else z.onoff?.call?.(this, e)
  2355. z.onclick?.call?.(this, e)
  2356. },
  2357. }).val
  2358. break
  2359. case "select":
  2360. var x = a(s).createelem("select", {
  2361. id: z.id,
  2362. options: z.options,
  2363. index: i,
  2364. itemnumber: i,
  2365. value: z.value,
  2366. onchange: z.onchange,
  2367. }).val
  2368. elem = x
  2369. break
  2370. case "input":
  2371. elem = a(s).createelem("input", {
  2372. id: z.id,
  2373. itemnumber: i,
  2374. index: i,
  2375. width: "90%",
  2376. value: z.value,
  2377. placeholder: z.placeholder,
  2378. onchange(e) {
  2379. z.onchange.call(this, e)
  2380. },
  2381. }).val
  2382. break
  2383. case "p":
  2384. elem = a(s).createelem("p", {
  2385. id: z.id,
  2386. innerHTML: z.text,
  2387. }).val
  2388. break
  2389. case "br":
  2390. elem = a(s).createelem("br", {}).val
  2391. break
  2392. default:
  2393. error(`type not found: "${z.type}"`)
  2394. }
  2395. if (z.id) window[z.id] = elem
  2396. })
  2397. }
  2398. // addnewoption({ title: "asddssa" }, { type: "button" })
  2399. allfuncs.new("addnewoption", addnewoption, "elem", true)
  2400. })()
  2401. allfuncs.new(
  2402. "scratch_gettarget",
  2403. function (
  2404. //object
  2405. sprite //string|none
  2406. ) {
  2407. if (sprite) var x = vm.runtime.getSpriteTargetByName(sprite)
  2408. else var x = vm.runtime.getTargetForStage()
  2409. x.getvar = x.lookupVariableByNameAndType
  2410. return x
  2411. },
  2412. "scratch",
  2413. true
  2414. )
  2415. allfuncs.new(
  2416. "scratch_sendbroadcast",
  2417. function (
  2418. //string
  2419. data //string
  2420. ) {
  2421. vm.runtime.startHats("event_whenbroadcastreceived", {
  2422. BROADCAST_OPTION: data,
  2423. })
  2424. return data
  2425. },
  2426. "scratch",
  2427. true
  2428. )
  2429. allfuncs.new(
  2430. "scratch_canvas",
  2431. function () {
  2432. //element
  2433. return (
  2434. window?.vm?.runtime?.renderer?.canvas ||
  2435. a(
  2436. "#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"
  2437. ).qs().val ||
  2438. a(
  2439. "#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"
  2440. ).qs().val ||
  2441. a(
  2442. "#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"
  2443. ).qs().val
  2444. )
  2445. },
  2446. "scratch",
  2447. false
  2448. )
  2449. allfuncs.new(
  2450. "replacealltext",
  2451. function (
  2452. //string|regex
  2453. pattern, //string|regex
  2454. string, //string
  2455. element = document.body //element|none
  2456. ) {
  2457. ;[
  2458. element,
  2459. ...element.querySelectorAll("*:not(script):not(noscript):not(style)"),
  2460. ].forEach(({ childNodes: [...nodes] }) =>
  2461. nodes
  2462. .filter(({ nodeType }) => nodeType === Node.TEXT_NODE)
  2463. .forEach(
  2464. (textNode) =>
  2465. (textNode.textContent = textNode.textContent.replaceAll(
  2466. pattern,
  2467. string
  2468. ))
  2469. )
  2470. )
  2471. return pattern
  2472. },
  2473. "string",
  2474. true
  2475. )
  2476. allfuncs.new(
  2477. "repeat",
  2478. function (
  2479. //promise|undefined
  2480. func, //function
  2481. count, //number
  2482. delay, //number|none
  2483. instantstart, //boolean|none
  2484. waituntildone //boolean|none
  2485. ) {
  2486. if (delay || waituntildone)
  2487. return new Promise(async (resolve) => {
  2488. if (delay) {
  2489. var extra = 0
  2490. for (var i = 0; i < count; i++) {
  2491. if (instantstart) waituntildone ? await func(i) : func(i)
  2492. extra = await a(delay - extra).wait().val
  2493. if (!instantstart) waituntildone ? await func(i) : func(i)
  2494. }
  2495. resolve()
  2496. } else
  2497. for (var i = 0; i < count; i++)
  2498. waituntildone ? await func(i) : func(i)
  2499. resolve()
  2500. })
  2501. for (var i = 0; i < count; i++) func(i)
  2502. return
  2503. },
  2504. "repeat",
  2505. true
  2506. )
  2507. allfuncs.new(
  2508. "repeatuntil",
  2509. function (
  2510. //promise
  2511. func, //function
  2512. donecheck, //function
  2513. delay, //number|none
  2514. instantstart, //boolean|none
  2515. waituntildone //boolean|none
  2516. ) {
  2517. return new Promise(async (resolve) => {
  2518. if (delay) {
  2519. var extra = 0
  2520. var i = 0
  2521. while (!donecheck()) {
  2522. i++
  2523. if (instantstart) {
  2524. waituntildone ? await func(i) : func(i)
  2525. }
  2526. extra = await a(delay - extra).wait().val
  2527. if (!instantstart) {
  2528. waituntildone ? await func(i) : func(i)
  2529. }
  2530. }
  2531. resolve()
  2532. } else {
  2533. var i = 0
  2534. while (!donecheck()) {
  2535. i++
  2536. waituntildone ? await func(i) : func(i)
  2537. }
  2538. resolve()
  2539. }
  2540. })
  2541. },
  2542. "repeat",
  2543. true
  2544. )
  2545. // ;(async function () {
  2546. // const { bodyload } = allfuncs
  2547. // await bodyload()
  2548. // const listeners = []
  2549. // a(document).listen({
  2550. // dragover(e) {
  2551. // e.stopPropagation()
  2552. // e.preventDefault()
  2553. // },
  2554. // drop(e) {
  2555. // e.stopPropagation()
  2556. // e.preventDefault()
  2557. // var files = [...e.dataTransfer.files]
  2558. // listeners.forEach((y) => y[0](y[1] ? files[0] : files))
  2559. // },
  2560. // })
  2561. // allfuncs.new(
  2562. // "newdrop",
  2563. // function (
  2564. // //undefined
  2565. // func, //function
  2566. // onlyone //boolean
  2567. // ) {
  2568. // listeners.push([func, onlyone])
  2569. // },
  2570. // "file"
  2571. // )
  2572. // })()
  2573. ;(async () => {
  2574. const drops = []
  2575. await a().bodyload()
  2576. a(document.body).listen({
  2577. dragover(e) {
  2578. e.preventDefault()
  2579. },
  2580. async drop(e) {
  2581. e.preventDefault()
  2582. drops.forEach(async ({ types, multi, func, elem }) => {
  2583. if (elem) if (e.target !== elem) return
  2584. if (multi) var ret = []
  2585. for (const item of e.dataTransfer.items) {
  2586. if (item.kind == "file") {
  2587. if (types.includes("file") || types.includes("directory")) {
  2588. const entry = await item.getAsFileSystemHandle()
  2589. if (entry.kind === "file" && types.includes("file")) {
  2590. if (!multi) return func(entry, e)
  2591. ret.push(entry)
  2592. } else if (
  2593. entry.kind === "directory" &&
  2594. types.includes("directory")
  2595. ) {
  2596. if (!multi) return func(entry, e)
  2597. ret.push(entry)
  2598. }
  2599. }
  2600. }
  2601. }
  2602. if (multi && ret.length) return func(ret, e)
  2603. })
  2604. },
  2605. })
  2606. allfuncs.new(
  2607. "ondrop",
  2608. function (
  2609. //object
  2610. obj //object
  2611. ) {
  2612. if (!obj.types) obj.types = "all"
  2613. obj.types = a(obj.types).toarray().val
  2614. if (!obj.func) throw new Error('object is missing "func"')
  2615. var oldelem = obj.elem
  2616. if (obj.elem) obj.elem = a(obj.elem).toelem(true).val
  2617. if (obj.elem && !a(obj.elem).gettype("element").val)
  2618. throw new Error(`elem is not an elem, ${oldelem} -> ${obj.elem}`)
  2619. drops.push(obj)
  2620. return obj
  2621. },
  2622. "file"
  2623. )
  2624. })()
  2625.  
  2626. allfuncs.new(
  2627. "getfolderpath",
  2628. async function (
  2629. //promise
  2630. folder //filesystemdirectoryhandle
  2631. ) {
  2632. async function parsedir(dir, x) {
  2633. if (!x) {
  2634. return [
  2635. {
  2636. name: dir.name,
  2637. inside: await parsedir(dir, true),
  2638. type: "folder",
  2639. handle: dir,
  2640. },
  2641. ]
  2642. } else var arr = []
  2643. for await (const [name, handle] of dir.entries()) {
  2644. arr.push(
  2645. a(handle).gettype("filesystemdirectoryhandle").val
  2646. ? {
  2647. type: "folder",
  2648. inside: await parsedir(handle, true),
  2649. name,
  2650. handle,
  2651. }
  2652. : { type: "file", handle, name }
  2653. )
  2654. }
  2655. return arr
  2656. }
  2657. return parsedir(folder)
  2658. },
  2659. "file",
  2660. false
  2661. )
  2662. allfuncs.new(
  2663. "getfiles",
  2664. async function (
  2665. //promise
  2666. oldway, //boolean|none
  2667. multiple, //boolean|none
  2668. accept = [], //array|string|none
  2669. options = {} //object|undefined
  2670. ) {
  2671. const supportsFileSystemAccess =
  2672. "showOpenFilePicker" in window &&
  2673. (() => {
  2674. try {
  2675. return window.self === window.top
  2676. } catch {
  2677. return false
  2678. }
  2679. })()
  2680. if (!oldway) {
  2681. if (!supportsFileSystemAccess) throw new Error("no access")
  2682. let fileOrFiles = undefined
  2683. try {
  2684. const handles = await showOpenFilePicker({
  2685. types: [
  2686. {
  2687. accept: {
  2688. "*/*": accept,
  2689. },
  2690. },
  2691. ],
  2692. multiple,
  2693. ...options,
  2694. })
  2695. if (!multiple) {
  2696. fileOrFiles = handles[0]
  2697. } else {
  2698. fileOrFiles = await Promise.all(handles)
  2699. }
  2700. } catch (err) {
  2701. if (err.name !== "AbortError") {
  2702. error(err.name, err.message)
  2703. }
  2704. }
  2705. return fileOrFiles
  2706. }
  2707. return new Promise(async (resolve) => {
  2708. await a().bodyload().val
  2709. const input = document.createElement("input")
  2710. input.style.display = "none"
  2711. input.type = "file"
  2712. if (accept) input.accept = accept
  2713. document.body.append(input)
  2714. if (multiple) {
  2715. input.multiple = true
  2716. }
  2717. input.addEventListener("change", () => {
  2718. input.remove()
  2719. // if (!input.files) {
  2720. // return
  2721. // }
  2722. resolve(multiple ? Array.from(input.files) : input.files[0])
  2723. })
  2724. if ("showPicker" in HTMLInputElement.prototype) {
  2725. input.showPicker()
  2726. } else {
  2727. input.click()
  2728. }
  2729. })
  2730. },
  2731. "file",
  2732. true
  2733. )
  2734. allfuncs.new(
  2735. "map",
  2736. function (
  2737. //array|object
  2738. arr, //array|object|any
  2739. func //function
  2740. ) {
  2741. var type = a(arr).gettype().val
  2742. if (type == "array") return arr.map(func)
  2743. else if (type == "object") {
  2744. var temparr = {}
  2745. Reflect.ownKeys(arr).forEach((e, i) => {
  2746. temparr = {
  2747. ...temparr,
  2748. ...func(e, arr[e], i),
  2749. }
  2750. })
  2751. return temparr
  2752. } else {
  2753. return [arr].map(func)
  2754. }
  2755. },
  2756. "array",
  2757. true
  2758. )
  2759. allfuncs.new(
  2760. "find",
  2761. function (
  2762. //any
  2763. arr, //array|object|any
  2764. func //function
  2765. ) {
  2766. var type = a(arr).gettype().val
  2767. if (type == "array") return arr.find(func)
  2768. else if (type == "object") {
  2769. return Reflect.ownKeys(arr).find((e, i) => {
  2770. return func(e, arr[e], i)
  2771. })
  2772. } else {
  2773. return [arr].find(func)
  2774. }
  2775. },
  2776. "array",
  2777. true
  2778. )
  2779. allfuncs.new(
  2780. "filteridx",
  2781. function (
  2782. //array
  2783. arr, //array|any
  2784. func //function
  2785. ) {
  2786. if (a(arr).gettype("object").val) arr = [arr]
  2787. return a(arr)
  2788. .map((e, i) => (func(e, i) ? i : undefined))
  2789. .filter((e) => e !== undefined)
  2790. },
  2791. "array"
  2792. )
  2793. allfuncs.new(
  2794. "filter",
  2795. function (
  2796. //array|object
  2797. arr, //array|object|any
  2798. func //function
  2799. ) {
  2800. var type = a(arr).gettype().val
  2801. if (type == "array") return arr.filter(func)
  2802. else if (type == "object") {
  2803. var temparr = {}
  2804. Reflect.ownKeys(arr).forEach((e, i) => {
  2805. if (func(e, arr[e], i))
  2806. temparr = {
  2807. ...temparr,
  2808. [e]: arr[e],
  2809. }
  2810. })
  2811. return temparr
  2812. } else {
  2813. return [arr].filter(func)
  2814. }
  2815. },
  2816. "array",
  2817. true
  2818. )
  2819. ;(function () {
  2820. var last
  2821. var different = allfuncs.new(
  2822. "unique",
  2823. function () /*object*/ {
  2824. return last || (last = different.new())
  2825. },
  2826. "check",
  2827. false
  2828. )
  2829. different.new = function (name) {
  2830. var $ = new Proxy(
  2831. {},
  2832. {
  2833. get(_a, s) {
  2834. return s == "name" ? name || "different" : $
  2835. },
  2836. set() {
  2837. return $
  2838. },
  2839. }
  2840. )
  2841. return (last = $)
  2842. }
  2843. })()
  2844. allfuncs.new(
  2845. "elif",
  2846. function (
  2847. //any
  2848. cond, //any
  2849. iftrue, //any
  2850. iffalse //any
  2851. ) {
  2852. return cond ? iftrue : iffalse
  2853. },
  2854. "check",
  2855. true
  2856. )
  2857. allfuncs.new(
  2858. "tonumber",
  2859. function (
  2860. //number
  2861. e //any
  2862. ) {
  2863. return Number(e)
  2864. },
  2865. "number/format",
  2866. true
  2867. )
  2868. allfuncs.new(
  2869. "toarray",
  2870. function (
  2871. //array
  2872. e, //any
  2873. split //string|none|undefined
  2874. ) {
  2875. if (a(e).gettype("string").val) {
  2876. if (split) e = e.split(split)
  2877. else return [e]
  2878. }
  2879. return [...e]
  2880. },
  2881. "number/format",
  2882. true
  2883. )
  2884. allfuncs.new(
  2885. "tostring",
  2886. function (
  2887. //string
  2888. e //any
  2889. ) {
  2890. if (["object", "array"].includes(a(e).gettype().val))
  2891. return JSON.stringify(e)
  2892. if (a(e).gettype("element").val) return a(e).csspath().val
  2893. return String(e)
  2894. },
  2895. "string/format",
  2896. true
  2897. )
  2898. allfuncs.new(
  2899. "eval",
  2900. function (
  2901. //any
  2902. a //any
  2903. ) {
  2904. return eval(a)
  2905. },
  2906. "js/eval",
  2907. true
  2908. )
  2909. allfuncs.new(
  2910. "toregex",
  2911. function (
  2912. //regex
  2913. d, //string|array|regex
  2914. s //undefined|string
  2915. ) {
  2916. if (a(d).gettype("array").val) var temp = d
  2917. if (s) var temp = [d, s]
  2918. else if (String(d).match(/^\/(.*)\/(\w*)$/)) {
  2919. var m = String(d).match(/^\/(.*)\/(\w*)$/)
  2920. var temp = [m[1], m[2]]
  2921. } else var temp = [String(d), ""]
  2922. temp[1] = temp[1].toLowerCase()
  2923. if (temp[1].includes("w")) {
  2924. temp[1] = temp[1].replace("w", "")
  2925. temp[0] = `(?<=[^a-z0-9]|^)${temp[0]}(?=[^a-z0-9]|$)`
  2926. }
  2927. return new RegExp(temp[0], temp[1].replaceAll(/(.)(?=.*\1)/g, ""))
  2928. },
  2929. "regex",
  2930. true
  2931. )
  2932. allfuncs.new(
  2933. "isregex",
  2934. function (
  2935. //boolean
  2936. s //string|regex
  2937. ) {
  2938. if (a(s).gettype("regex").val) return true
  2939. return /^\/.*(?<!\\)\/[gimusy]*$/.test(s) && !/^\/\*.*\*\/$/.test(s)
  2940. },
  2941. "check",
  2942. true
  2943. )
  2944. allfuncs.new(
  2945. "ispressed",
  2946. function (
  2947. //boolean
  2948. e /*event*/,
  2949. code //string
  2950. ) {
  2951. code = code.toLowerCase()
  2952. var temp =
  2953. e.shiftKey == code.includes("shift") &&
  2954. e.altKey == code.includes("alt") &&
  2955. e.ctrlKey == code.includes("ctrl") &&
  2956. e.metaKey == code.includes("meta") &&
  2957. e.key.toLowerCase() ==
  2958. code.replaceAll(/alt|ctrl|shift|meta/g, "").trim()
  2959. if (temp && !a) e.preventDefault()
  2960. return temp
  2961. },
  2962. "check/input/event",
  2963. true
  2964. )
  2965. allfuncs.new(
  2966. "controller_vibrate",
  2967. function (
  2968. //number
  2969. pad, //number
  2970. duration = 1000, //number|none
  2971. strongMagnitude = 0, //number|none
  2972. weakMagnitude = 0 //number|none
  2973. ) {
  2974. getpad(pad).vibrationActuator.playEffect("dual-rumble", {
  2975. duration,
  2976. strongMagnitude,
  2977. weakMagnitude,
  2978. })
  2979. return pad
  2980. },
  2981. "controller/haptic",
  2982. true
  2983. )
  2984. allfuncs.new(
  2985. "controller_getbutton",
  2986. function (
  2987. //number
  2988. pad, //number
  2989. button //number|none
  2990. ) {
  2991. return button
  2992. ? getpad(pad).buttons[button].value
  2993. : getpad(pad).buttons.map((e) => e.value)
  2994. },
  2995. "controller/input",
  2996. true
  2997. )
  2998. allfuncs.new(
  2999. "controller_getaxes",
  3000. function (
  3001. //array|number
  3002. pad, //number
  3003. axes //number|none
  3004. ) {
  3005. return axes ? getpad(pad).axes[axes] : getpad(pad).axes
  3006. },
  3007. "controller/input",
  3008. true
  3009. )
  3010. allfuncs.new(
  3011. "controller_exists",
  3012. function (
  3013. //boolean|number
  3014. pad //number|none
  3015. ) {
  3016. return pad === undefined
  3017. ? getpad().filter((e) => e).length
  3018. : !!getpad(pad)
  3019. },
  3020. "controller/check",
  3021. true
  3022. )
  3023. allfuncs.new(
  3024. "runall",
  3025. function (
  3026. //array|function
  3027. funcs, //array|function
  3028. args //array|any
  3029. ) {
  3030. if (!a(args).gettype("array").val) args = [args]
  3031. if (!a(funcs).gettype("array").val) funcs = [funcs]
  3032. funcs.map((func) => func(...args))
  3033. return funcs
  3034. },
  3035. "function"
  3036. )
  3037. allfuncs.new(
  3038. "readfile",
  3039. async function (
  3040. //promise
  3041. file, //file
  3042. type = "Text" //string|none
  3043. ) {
  3044. return new Promise(function (done, error) {
  3045. var f = new FileReader()
  3046. f.onerror = error
  3047. f.onload = () => done(type == "json" ? JSON.parse(f.result) : f.result)
  3048. f["readAs" + (type == "json" ? "Text" : type)](file)
  3049. })
  3050. },
  3051. "file"
  3052. )
  3053. allfuncs.new(
  3054. "writefile",
  3055. async function writefile(
  3056. //promise
  3057. file, //filesystemfilehandle
  3058. text //string
  3059. ) {
  3060. var f = await await file.createWritable()
  3061. await f.write(text)
  3062. await f.close()
  3063. return file
  3064. },
  3065. "file"
  3066. )
  3067. allfuncs.new(
  3068. "getfileperms",
  3069. async function (
  3070. //promise
  3071. fileHandle, //filesystemfilehandle
  3072. readWrite //boolean|none
  3073. ) {
  3074. const options = {}
  3075. if (readWrite) {
  3076. options.mode = "readwrite"
  3077. }
  3078. return (
  3079. (await fileHandle.queryPermission(options)) === "granted" ||
  3080. (await fileHandle.requestPermission(options)) === "granted"
  3081. )
  3082. },
  3083. "file/permission",
  3084. true
  3085. )
  3086. allfuncs.new(
  3087. "indexeddb_set",
  3088. async function (
  3089. //promise
  3090. place, //object
  3091. obj //object
  3092. ) {
  3093. return new Promise((done, error) =>
  3094. place.put(
  3095. obj,
  3096. (e) => done(e),
  3097. (e) => error(e)
  3098. )
  3099. )
  3100. },
  3101. "indexeddb",
  3102. true
  3103. )
  3104. allfuncs.new(
  3105. "indexeddb_get",
  3106. async function (
  3107. //promise
  3108. place, //object
  3109. obj //string
  3110. ) {
  3111. return new Promise((done, error) =>
  3112. place.get(
  3113. obj,
  3114. (e) => done(e),
  3115. (e) => error(e)
  3116. )
  3117. )
  3118. },
  3119. "indexeddb",
  3120. true
  3121. )
  3122. allfuncs.new(
  3123. "indexeddb_getall",
  3124. async function (
  3125. //promise
  3126. place //object
  3127. ) {
  3128. return new Promise((done, error) =>
  3129. place.getAll(
  3130. (e) => done(e),
  3131. (e) => error(e)
  3132. )
  3133. )
  3134. },
  3135. "indexeddb",
  3136. true
  3137. )
  3138. allfuncs.new(
  3139. "indexeddb_clearall",
  3140. async function (
  3141. //promise
  3142. place //object
  3143. ) {
  3144. return new Promise((done, error) =>
  3145. place.clear(
  3146. (e) => done(e),
  3147. (e) => error(e)
  3148. )
  3149. )
  3150. },
  3151. "indexeddb",
  3152. true
  3153. )
  3154. allfuncs.new(
  3155. "indexeddb_remove",
  3156. async function (
  3157. //promise
  3158. place, //object
  3159. obj //string|number
  3160. ) {
  3161. return new Promise((done, error) =>
  3162. place.remove(
  3163. obj,
  3164. (e) => done(e),
  3165. (e) => error(e)
  3166. )
  3167. )
  3168. },
  3169. "indexeddb",
  3170. true
  3171. )
  3172. allfuncs.new(
  3173. "indexeddb_setup",
  3174. async function (
  3175. //promise
  3176. obj //object|none
  3177. ) {
  3178. return new Promise((e) => {
  3179. var x
  3180. obj = {
  3181. ...{
  3182. dbVersion: 1,
  3183. storeName: "tempstorename",
  3184. keyPath: "id",
  3185. autoIncrement: true,
  3186. },
  3187. ...obj,
  3188. onStoreReady() {
  3189. e(x)
  3190. },
  3191. }
  3192. if (!window.IDBStore) {
  3193. //IDBStore start
  3194. ;(function (p, h, k) {
  3195. "function" === typeof define
  3196. ? define(h)
  3197. : "undefined" !== typeof module && module.exports
  3198. ? (module.exports = h())
  3199. : (k[p] = h())
  3200. })(
  3201. "IDBStore",
  3202. function () {
  3203. function p(a, b) {
  3204. var c, d
  3205. for (c in b) (d = b[c]), d !== u[c] && d !== a[c] && (a[c] = d)
  3206. return a
  3207. }
  3208. var h = function (a) {
  3209. throw a
  3210. },
  3211. k = function () {},
  3212. r = {
  3213. storeName: "Store",
  3214. storePrefix: "IDBWrapper-",
  3215. dbVersion: 1,
  3216. keyPath: "id",
  3217. autoIncrement: !0,
  3218. onStoreReady: function () {},
  3219. onError: h,
  3220. indexes: [],
  3221. implementationPreference: [
  3222. "indexedDB",
  3223. "webkitIndexedDB",
  3224. "mozIndexedDB",
  3225. "shimIndexedDB",
  3226. ],
  3227. },
  3228. q = function (a, b) {
  3229. "undefined" == typeof b && "function" == typeof a && (b = a)
  3230. "[object Object]" != Object.prototype.toString.call(a) &&
  3231. (a = {})
  3232. for (var c in r)
  3233. this[c] = "undefined" != typeof a[c] ? a[c] : r[c]
  3234. this.dbName = this.storePrefix + this.storeName
  3235. this.dbVersion = parseInt(this.dbVersion, 10) || 1
  3236. b && (this.onStoreReady = b)
  3237. var d = "object" == typeof window ? window : self
  3238. this.implementation = this.implementationPreference.filter(
  3239. function (a) {
  3240. return a in d
  3241. }
  3242. )[0]
  3243. this.idb = d[this.implementation]
  3244. this.keyRange =
  3245. d.IDBKeyRange || d.webkitIDBKeyRange || d.mozIDBKeyRange
  3246. this.consts = {
  3247. READ_ONLY: "readonly",
  3248. READ_WRITE: "readwrite",
  3249. VERSION_CHANGE: "versionchange",
  3250. NEXT: "next",
  3251. NEXT_NO_DUPLICATE: "nextunique",
  3252. PREV: "prev",
  3253. PREV_NO_DUPLICATE: "prevunique",
  3254. }
  3255. this.openDB()
  3256. },
  3257. t = {
  3258. constructor: q,
  3259. version: "1.7.2",
  3260. db: null,
  3261. dbName: null,
  3262. dbVersion: null,
  3263. store: null,
  3264. storeName: null,
  3265. storePrefix: null,
  3266. keyPath: null,
  3267. autoIncrement: null,
  3268. indexes: null,
  3269. implementationPreference: null,
  3270. implementation: "",
  3271. onStoreReady: null,
  3272. onError: null,
  3273. _insertIdCount: 0,
  3274. openDB: function () {
  3275. var a = this.idb.open(this.dbName, this.dbVersion),
  3276. b = !1
  3277. a.onerror = function (a) {
  3278. var b
  3279. b =
  3280. "error" in a.target
  3281. ? "VersionError" == a.target.error.name
  3282. : "errorCode" in a.target
  3283. ? 12 == a.target.errorCode
  3284. : !1
  3285. if (b)
  3286. this.onError(
  3287. Error(
  3288. "The version number provided is lower than the existing one."
  3289. )
  3290. )
  3291. else
  3292. a.target.error
  3293. ? (a = a.target.error)
  3294. : ((b =
  3295. "IndexedDB unknown error occurred when opening DB " +
  3296. this.dbName +
  3297. " version " +
  3298. this.dbVersion),
  3299. "errorCode" in a.target &&
  3300. (b += " with error code " + a.target.errorCode),
  3301. (a = Error(b))),
  3302. this.onError(a)
  3303. }.bind(this)
  3304. a.onsuccess = function (a) {
  3305. if (!b)
  3306. if (this.db) this.onStoreReady()
  3307. else if (
  3308. ((this.db = a.target.result),
  3309. "string" == typeof this.db.version)
  3310. )
  3311. this.onError(
  3312. Error(
  3313. "The IndexedDB implementation in this browser is outdated. Please upgrade your browser."
  3314. )
  3315. )
  3316. else if (
  3317. this.db.objectStoreNames.contains(this.storeName)
  3318. ) {
  3319. this.store = this.db
  3320. .transaction(
  3321. [this.storeName],
  3322. this.consts.READ_ONLY
  3323. )
  3324. .objectStore(this.storeName)
  3325. var d = Array.prototype.slice.call(
  3326. this.getIndexList()
  3327. )
  3328. this.indexes.forEach(function (a) {
  3329. var c = a.name
  3330. if (c)
  3331. if (
  3332. (this.normalizeIndexData(a), this.hasIndex(c))
  3333. ) {
  3334. var g = this.store.index(c)
  3335. this.indexComplies(g, a) ||
  3336. ((b = !0),
  3337. this.onError(
  3338. Error(
  3339. 'Cannot modify index "' +
  3340. c +
  3341. '" for current version. Please bump version number to ' +
  3342. (this.dbVersion + 1) +
  3343. "."
  3344. )
  3345. ))
  3346. d.splice(d.indexOf(c), 1)
  3347. } else
  3348. (b = !0),
  3349. this.onError(
  3350. Error(
  3351. 'Cannot create new index "' +
  3352. c +
  3353. '" for current version. Please bump version number to ' +
  3354. (this.dbVersion + 1) +
  3355. "."
  3356. )
  3357. )
  3358. else
  3359. (b = !0),
  3360. this.onError(
  3361. Error(
  3362. "Cannot create index: No index name given."
  3363. )
  3364. )
  3365. }, this)
  3366. d.length &&
  3367. ((b = !0),
  3368. this.onError(
  3369. Error(
  3370. 'Cannot delete index(es) "' +
  3371. d.toString() +
  3372. '" for current version. Please bump version number to ' +
  3373. (this.dbVersion + 1) +
  3374. "."
  3375. )
  3376. ))
  3377. b || this.onStoreReady()
  3378. } else
  3379. this.onError(
  3380. Error("Object store couldn't be created.")
  3381. )
  3382. }.bind(this)
  3383. a.onupgradeneeded = function (a) {
  3384. this.db = a.target.result
  3385. this.db.objectStoreNames.contains(this.storeName)
  3386. ? (this.store = a.target.transaction.objectStore(
  3387. this.storeName
  3388. ))
  3389. : ((a = { autoIncrement: this.autoIncrement }),
  3390. null !== this.keyPath && (a.keyPath = this.keyPath),
  3391. (this.store = this.db.createObjectStore(
  3392. this.storeName,
  3393. a
  3394. )))
  3395. var d = Array.prototype.slice.call(this.getIndexList())
  3396. this.indexes.forEach(function (a) {
  3397. var c = a.name
  3398. c ||
  3399. ((b = !0),
  3400. this.onError(
  3401. Error("Cannot create index: No index name given.")
  3402. ))
  3403. this.normalizeIndexData(a)
  3404. if (this.hasIndex(c)) {
  3405. var g = this.store.index(c)
  3406. this.indexComplies(g, a) ||
  3407. (this.store.deleteIndex(c),
  3408. this.store.createIndex(c, a.keyPath, {
  3409. unique: a.unique,
  3410. multiEntry: a.multiEntry,
  3411. }))
  3412. d.splice(d.indexOf(c), 1)
  3413. } else
  3414. this.store.createIndex(c, a.keyPath, {
  3415. unique: a.unique,
  3416. multiEntry: a.multiEntry,
  3417. })
  3418. }, this)
  3419. d.length &&
  3420. d.forEach(function (a) {
  3421. this.store.deleteIndex(a)
  3422. }, this)
  3423. }.bind(this)
  3424. },
  3425. deleteDatabase: function (a, b) {
  3426. if (this.idb.deleteDatabase) {
  3427. this.db.close()
  3428. var c = this.idb.deleteDatabase(this.dbName)
  3429. c.onsuccess = a
  3430. c.onerror = b
  3431. } else
  3432. b(
  3433. Error(
  3434. "Browser does not support IndexedDB deleteDatabase!"
  3435. )
  3436. )
  3437. },
  3438. put: function (a, b, c, d) {
  3439. null !== this.keyPath && ((d = c), (c = b), (b = a))
  3440. d || (d = h)
  3441. c || (c = k)
  3442. var f = !1,
  3443. e = null,
  3444. g = this.db.transaction(
  3445. [this.storeName],
  3446. this.consts.READ_WRITE
  3447. )
  3448. g.oncomplete = function () {
  3449. ;(f ? c : d)(e)
  3450. }
  3451. g.onabort = d
  3452. g.onerror = d
  3453. null !== this.keyPath
  3454. ? (this._addIdPropertyIfNeeded(b),
  3455. (a = g.objectStore(this.storeName).put(
  3456. (() => {
  3457. function isFilesystemHandle(obj) {
  3458. // Check if the object is a FilesystemFileHandle or FilesystemDirectoryHandle
  3459. return (
  3460. obj &&
  3461. (obj instanceof FileSystemFileHandle ||
  3462. obj instanceof FileSystemDirectoryHandle)
  3463. )
  3464. }
  3465.  
  3466. function replaceProxies(obj) {
  3467. if (isFilesystemHandle(obj)) {
  3468. return obj // Skip replacing FilesystemFileHandle and FilesystemDirectoryHandle
  3469. }
  3470.  
  3471. if (typeof obj !== "object" || obj === null) {
  3472. return obj
  3473. }
  3474.  
  3475. if (Array.isArray(obj)) {
  3476. return obj.map((item) => replaceProxies(item))
  3477. }
  3478.  
  3479. const result = {}
  3480. for (const key in obj) {
  3481. if (obj.hasOwnProperty(key)) {
  3482. result[key] = replaceProxies(obj[key])
  3483. }
  3484. }
  3485.  
  3486. return result
  3487. }
  3488. // warn("ghadsgjasdjh", b, replaceProxies(b))
  3489. // throw ""
  3490. return replaceProxies(b)
  3491. })()
  3492. )))
  3493. : (a = g.objectStore(this.storeName).put(b, a))
  3494. a.onsuccess = function (a) {
  3495. f = !0
  3496. e = a.target.result
  3497. }
  3498. a.onerror = d
  3499. return g
  3500. },
  3501. get: function (a, b, c) {
  3502. c || (c = h)
  3503. b || (b = k)
  3504. var d = !1,
  3505. f = null,
  3506. e = this.db.transaction(
  3507. [this.storeName],
  3508. this.consts.READ_ONLY
  3509. )
  3510. e.oncomplete = function () {
  3511. ;(d ? b : c)(f)
  3512. }
  3513. e.onabort = c
  3514. e.onerror = c
  3515. a = e.objectStore(this.storeName).get(a)
  3516. a.onsuccess = function (a) {
  3517. d = !0
  3518. f = a.target.result
  3519. }
  3520. a.onerror = c
  3521. return e
  3522. },
  3523. remove: function (a, b, c) {
  3524. c || (c = h)
  3525. b || (b = k)
  3526. var d = !1,
  3527. f = null,
  3528. e = this.db.transaction(
  3529. [this.storeName],
  3530. this.consts.READ_WRITE
  3531. )
  3532. e.oncomplete = function () {
  3533. ;(d ? b : c)(f)
  3534. }
  3535. e.onabort = c
  3536. e.onerror = c
  3537. a = e.objectStore(this.storeName)["delete"](a)
  3538. a.onsuccess = function (a) {
  3539. d = !0
  3540. f = a.target.result
  3541. }
  3542. a.onerror = c
  3543. return e
  3544. },
  3545. batch: function (a, b, c) {
  3546. c || (c = h)
  3547. b || (b = k)
  3548. if ("[object Array]" != Object.prototype.toString.call(a))
  3549. c(Error("dataArray argument must be of type Array."))
  3550. else if (0 === a.length) return b(!0)
  3551. var d = a.length,
  3552. f = !1,
  3553. e = !1,
  3554. g = this.db.transaction(
  3555. [this.storeName],
  3556. this.consts.READ_WRITE
  3557. )
  3558. g.oncomplete = function () {
  3559. ;(e ? b : c)(e)
  3560. }
  3561. g.onabort = c
  3562. g.onerror = c
  3563. var l = function () {
  3564. d--
  3565. 0 !== d || f || (e = f = !0)
  3566. }
  3567. a.forEach(function (a) {
  3568. var b = a.type,
  3569. d = a.key,
  3570. e = a.value
  3571. a = function (a) {
  3572. g.abort()
  3573. f || ((f = !0), c(a, b, d))
  3574. }
  3575. "remove" == b
  3576. ? ((e = g.objectStore(this.storeName)["delete"](d)),
  3577. (e.onsuccess = l),
  3578. (e.onerror = a))
  3579. : "put" == b &&
  3580. (null !== this.keyPath
  3581. ? (this._addIdPropertyIfNeeded(e),
  3582. (e = g.objectStore(this.storeName).put(e)))
  3583. : (e = g.objectStore(this.storeName).put(e, d)),
  3584. (e.onsuccess = l),
  3585. (e.onerror = a))
  3586. }, this)
  3587. return g
  3588. },
  3589. putBatch: function (a, b, c) {
  3590. a = a.map(function (a) {
  3591. return { type: "put", value: a }
  3592. })
  3593. return this.batch(a, b, c)
  3594. },
  3595. upsertBatch: function (a, b, c, d) {
  3596. "function" == typeof b && ((d = c = b), (b = {}))
  3597. d || (d = h)
  3598. c || (c = k)
  3599. b || (b = {})
  3600. "[object Array]" != Object.prototype.toString.call(a) &&
  3601. d(Error("dataArray argument must be of type Array."))
  3602. var f = b.keyField || this.keyPath,
  3603. e = a.length,
  3604. g = !1,
  3605. l = !1,
  3606. n = 0,
  3607. m = this.db.transaction(
  3608. [this.storeName],
  3609. this.consts.READ_WRITE
  3610. )
  3611. m.oncomplete = function () {
  3612. l ? c(a) : d(!1)
  3613. }
  3614. m.onabort = d
  3615. m.onerror = d
  3616. var v = function (b) {
  3617. a[n++][f] = b.target.result
  3618. e--
  3619. 0 !== e || g || (l = g = !0)
  3620. }
  3621. a.forEach(function (a) {
  3622. var b = a.key
  3623. null !== this.keyPath
  3624. ? (this._addIdPropertyIfNeeded(a),
  3625. (a = m.objectStore(this.storeName).put(a)))
  3626. : (a = m.objectStore(this.storeName).put(a, b))
  3627. a.onsuccess = v
  3628. a.onerror = function (a) {
  3629. m.abort()
  3630. g || ((g = !0), d(a))
  3631. }
  3632. }, this)
  3633. return m
  3634. },
  3635. removeBatch: function (a, b, c) {
  3636. a = a.map(function (a) {
  3637. return { type: "remove", key: a }
  3638. })
  3639. return this.batch(a, b, c)
  3640. },
  3641. getBatch: function (a, b, c, d) {
  3642. c || (c = h)
  3643. b || (b = k)
  3644. d || (d = "sparse")
  3645. if ("[object Array]" != Object.prototype.toString.call(a))
  3646. c(Error("keyArray argument must be of type Array."))
  3647. else if (0 === a.length) return b([])
  3648. var f = [],
  3649. e = a.length,
  3650. g = !1,
  3651. l = null,
  3652. n = this.db.transaction(
  3653. [this.storeName],
  3654. this.consts.READ_ONLY
  3655. )
  3656. n.oncomplete = function () {
  3657. ;(g ? b : c)(l)
  3658. }
  3659. n.onabort = c
  3660. n.onerror = c
  3661. var m = function (a) {
  3662. a.target.result || "dense" == d
  3663. ? f.push(a.target.result)
  3664. : "sparse" == d && f.length++
  3665. e--
  3666. 0 === e && ((g = !0), (l = f))
  3667. }
  3668. a.forEach(function (a) {
  3669. a = n.objectStore(this.storeName).get(a)
  3670. a.onsuccess = m
  3671. a.onerror = function (a) {
  3672. l = a
  3673. c(a)
  3674. n.abort()
  3675. }
  3676. }, this)
  3677. return n
  3678. },
  3679. getAll: function (a, b) {
  3680. b || (b = h)
  3681. a || (a = k)
  3682. var c = this.db.transaction(
  3683. [this.storeName],
  3684. this.consts.READ_ONLY
  3685. ),
  3686. d = c.objectStore(this.storeName)
  3687. d.getAll
  3688. ? this._getAllNative(c, d, a, b)
  3689. : this._getAllCursor(c, d, a, b)
  3690. return c
  3691. },
  3692. _getAllNative: function (a, b, c, d) {
  3693. var f = !1,
  3694. e = null
  3695. a.oncomplete = function () {
  3696. ;(f ? c : d)(e)
  3697. }
  3698. a.onabort = d
  3699. a.onerror = d
  3700. a = b.getAll()
  3701. a.onsuccess = function (a) {
  3702. f = !0
  3703. e = a.target.result
  3704. }
  3705. a.onerror = d
  3706. },
  3707. _getAllCursor: function (a, b, c, d) {
  3708. var f = [],
  3709. e = !1,
  3710. g = null
  3711. a.oncomplete = function () {
  3712. ;(e ? c : d)(g)
  3713. }
  3714. a.onabort = d
  3715. a.onerror = d
  3716. a = b.openCursor()
  3717. a.onsuccess = function (a) {
  3718. ;(a = a.target.result)
  3719. ? (f.push(a.value), a["continue"]())
  3720. : ((e = !0), (g = f))
  3721. }
  3722. a.onError = d
  3723. },
  3724. clear: function (a, b) {
  3725. b || (b = h)
  3726. a || (a = k)
  3727. var c = !1,
  3728. d = null,
  3729. f = this.db.transaction(
  3730. [this.storeName],
  3731. this.consts.READ_WRITE
  3732. )
  3733. f.oncomplete = function () {
  3734. ;(c ? a : b)(d)
  3735. }
  3736. f.onabort = b
  3737. f.onerror = b
  3738. var e = f.objectStore(this.storeName).clear()
  3739. e.onsuccess = function (a) {
  3740. c = !0
  3741. d = a.target.result
  3742. }
  3743. e.onerror = b
  3744. return f
  3745. },
  3746. _addIdPropertyIfNeeded: function (a) {
  3747. "undefined" == typeof a[this.keyPath] &&
  3748. (a[this.keyPath] = this._insertIdCount++ + Date.now())
  3749. },
  3750. getIndexList: function () {
  3751. return this.store.indexNames
  3752. },
  3753. hasIndex: function (a) {
  3754. return this.store.indexNames.contains(a)
  3755. },
  3756. normalizeIndexData: function (a) {
  3757. a.keyPath = a.keyPath || a.name
  3758. a.unique = !!a.unique
  3759. a.multiEntry = !!a.multiEntry
  3760. },
  3761. indexComplies: function (a, b) {
  3762. return ["keyPath", "unique", "multiEntry"].every(function (
  3763. c
  3764. ) {
  3765. if ("multiEntry" == c && void 0 === a[c] && !1 === b[c])
  3766. return !0
  3767. if (
  3768. "keyPath" == c &&
  3769. "[object Array]" == Object.prototype.toString.call(b[c])
  3770. ) {
  3771. c = b.keyPath
  3772. var d = a.keyPath
  3773. if ("string" == typeof d) return c.toString() == d
  3774. if (
  3775. ("function" != typeof d.contains &&
  3776. "function" != typeof d.indexOf) ||
  3777. d.length !== c.length
  3778. )
  3779. return !1
  3780. for (var f = 0, e = c.length; f < e; f++)
  3781. if (
  3782. !(
  3783. (d.contains && d.contains(c[f])) ||
  3784. d.indexOf(-1 !== c[f])
  3785. )
  3786. )
  3787. return !1
  3788. return !0
  3789. }
  3790. return b[c] == a[c]
  3791. })
  3792. },
  3793. iterate: function (a, b) {
  3794. b = p(
  3795. {
  3796. index: null,
  3797. order: "ASC",
  3798. autoContinue: !0,
  3799. filterDuplicates: !1,
  3800. keyRange: null,
  3801. writeAccess: !1,
  3802. onEnd: null,
  3803. onError: h,
  3804. limit: Infinity,
  3805. offset: 0,
  3806. allowItemRejection: !1,
  3807. },
  3808. b || {}
  3809. )
  3810. var c = "desc" == b.order.toLowerCase() ? "PREV" : "NEXT"
  3811. b.filterDuplicates && (c += "_NO_DUPLICATE")
  3812. var d = !1,
  3813. f = this.db.transaction(
  3814. [this.storeName],
  3815. this.consts[b.writeAccess ? "READ_WRITE" : "READ_ONLY"]
  3816. ),
  3817. e = f.objectStore(this.storeName)
  3818. b.index && (e = e.index(b.index))
  3819. var g = 0
  3820. f.oncomplete = function () {
  3821. if (d)
  3822. if (b.onEnd) b.onEnd()
  3823. else a(null)
  3824. else b.onError(null)
  3825. }
  3826. f.onabort = b.onError
  3827. f.onerror = b.onError
  3828. c = e.openCursor(b.keyRange, this.consts[c])
  3829. c.onerror = b.onError
  3830. c.onsuccess = function (c) {
  3831. if ((c = c.target.result))
  3832. if (b.offset) c.advance(b.offset), (b.offset = 0)
  3833. else {
  3834. var e = a(c.value, c, f)
  3835. ;(b.allowItemRejection && !1 === e) || g++
  3836. if (b.autoContinue)
  3837. if (g + b.offset < b.limit) c["continue"]()
  3838. else d = !0
  3839. }
  3840. else d = !0
  3841. }
  3842. return f
  3843. },
  3844. query: function (a, b) {
  3845. var c = [],
  3846. d = 0
  3847. b = b || {}
  3848. b.autoContinue = !0
  3849. b.writeAccess = !1
  3850. b.allowItemRejection = !!b.filter
  3851. b.onEnd = function () {
  3852. a(c, d)
  3853. }
  3854. return this.iterate(function (a) {
  3855. d++
  3856. var e = b.filter ? b.filter(a) : !0
  3857. !1 !== e && c.push(a)
  3858. return e
  3859. }, b)
  3860. },
  3861. count: function (a, b) {
  3862. b = p({ index: null, keyRange: null }, b || {})
  3863. var c = b.onError || h,
  3864. d = !1,
  3865. f = null,
  3866. e = this.db.transaction(
  3867. [this.storeName],
  3868. this.consts.READ_ONLY
  3869. )
  3870. e.oncomplete = function () {
  3871. ;(d ? a : c)(f)
  3872. }
  3873. e.onabort = c
  3874. e.onerror = c
  3875. var g = e.objectStore(this.storeName)
  3876. b.index && (g = g.index(b.index))
  3877. g = g.count(b.keyRange)
  3878. g.onsuccess = function (a) {
  3879. d = !0
  3880. f = a.target.result
  3881. }
  3882. g.onError = c
  3883. return e
  3884. },
  3885. makeKeyRange: function (a) {
  3886. var b = "undefined" != typeof a.lower,
  3887. c = "undefined" != typeof a.upper,
  3888. d = "undefined" != typeof a.only
  3889. switch (!0) {
  3890. case d:
  3891. a = this.keyRange.only(a.only)
  3892. break
  3893. case b && c:
  3894. a = this.keyRange.bound(
  3895. a.lower,
  3896. a.upper,
  3897. a.excludeLower,
  3898. a.excludeUpper
  3899. )
  3900. break
  3901. case b:
  3902. a = this.keyRange.lowerBound(a.lower, a.excludeLower)
  3903. break
  3904. case c:
  3905. a = this.keyRange.upperBound(a.upper, a.excludeUpper)
  3906. break
  3907. default:
  3908. throw Error(
  3909. 'Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.'
  3910. )
  3911. }
  3912. return a
  3913. },
  3914. },
  3915. u = {}
  3916. q.prototype = t
  3917. q.version = t.version
  3918. return q
  3919. },
  3920. this
  3921. )
  3922. //IDBStore end
  3923. }
  3924. x = new IDBStore(obj)
  3925. })
  3926. },
  3927. "indexeddb",
  3928. true
  3929. )
  3930. allfuncs.new(
  3931. "keepsame",
  3932. function (
  3933. //object|any
  3934. thing //object|element
  3935. ) {
  3936. var all = []
  3937. var x = new Proxy(thing, {
  3938. get(_obj, prop) {
  3939. if (prop == "val") return _obj
  3940. if (prop == "all") return all
  3941. if (prop == "func")
  3942. return function (e) {
  3943. all.push(e(thing))
  3944. return x
  3945. }
  3946. return function (...args) {
  3947. try {
  3948. all.push(thing[prop](thing, ...args))
  3949. } catch (e) {
  3950. all.push(thing[prop])
  3951. }
  3952. return x
  3953. }
  3954. },
  3955. })
  3956. return x
  3957. },
  3958. "function",
  3959. true
  3960. )
  3961. allfuncs.new(
  3962. "scratch_press",
  3963. function (
  3964. //string
  3965. key //string
  3966. ) {
  3967. if (key == " ") key = "space"
  3968. if (/^[a-z]$/.test(key)) key = key.toUpperCase()
  3969. var index = vm.runtime.ioDevices.keyboard._keysPressed.indexOf(key)
  3970. if (index !== -1) {
  3971. vm.runtime.ioDevices.keyboard._keysPressed.splice(index, 1)
  3972. }
  3973. vm.runtime.ioDevices.keyboard._keysPressed.push(key)
  3974. vm.runtime.startHats("event_whenkeypressed", {
  3975. KEY_OPTION: key,
  3976. })
  3977. vm.runtime.startHats("event_whenkeypressed", {
  3978. KEY_OPTION: "any",
  3979. })
  3980. return key
  3981. },
  3982. "scratch"
  3983. )
  3984. allfuncs.new(
  3985. "scratch_unpress",
  3986. function (
  3987. //undefined
  3988. key //string
  3989. ) {
  3990. if (key == " ") key = "space"
  3991. if (/^[a-z]$/.test(key)) key = key.toUpperCase()
  3992. var index = vm.runtime.ioDevices.keyboard._keysPressed.indexOf(key)
  3993. if (index !== -1) {
  3994. vm.runtime.ioDevices.keyboard._keysPressed.splice(index, 1)
  3995. }
  3996. },
  3997. "scratch"
  3998. )
  3999. allfuncs.new("strictfunction", strictfunction, "function/typescript", true)
  4000. allfuncs.new(
  4001. "readfileslow",
  4002. function (
  4003. //undefined
  4004. file, //file
  4005. type = "Text", //string|undefined
  4006. cb1 = (e) => e, //function|undefined
  4007. cb2 = (e) => e //function|undefined
  4008. ) {
  4009. var fileSize = file.size
  4010. var chunkSize = 64 * 1024 * 50 // bytes
  4011. var offset = 0
  4012. var chunkReaderBlock = null
  4013. var arr = []
  4014. var lastidx
  4015. var readEventHandler = function (evt, idx) {
  4016. if (evt.target.error == null) {
  4017. arr.push([idx, evt.target.result])
  4018. cb1(a(arr.length).rerange(0, lastidx, 0, 100).val)
  4019. if (arr.length === lastidx)
  4020. cb2(arr.sort((e) => e[0]).map((e) => e[1]))
  4021. } else {
  4022. return error("Read error: " + evt.target.error)
  4023. }
  4024. }
  4025. chunkReaderBlock = function (_offset, length, _file, idx) {
  4026. var r = new FileReader()
  4027. var blob = _file.slice(_offset, length + _offset)
  4028. const zzz = idx + 1
  4029. r.onload = function (e) {
  4030. readEventHandler(e, zzz - 1)
  4031. }
  4032. r["readAs" + type](blob)
  4033. }
  4034. let idx = 0
  4035. while (offset < fileSize) {
  4036. idx++
  4037. chunkReaderBlock(offset, chunkSize, file, idx)
  4038. offset += chunkSize
  4039. }
  4040. lastidx = idx
  4041. },
  4042. "file"
  4043. )
  4044. allfuncs.new(
  4045. "cbtoasync",
  4046. function (
  4047. //promise
  4048. func, //function
  4049. ...args //any
  4050. ) {
  4051. return new Promise(function (resolve) {
  4052. func(...args, resolve)
  4053. })
  4054. },
  4055. "function"
  4056. )
  4057. allfuncs.new(
  4058. "asynctocb",
  4059. function (
  4060. //undefined
  4061. func, //function
  4062. ...args //any
  4063. ) {
  4064. var cb = args.pop()
  4065. return func(...args).then(cb)
  4066. },
  4067. "function"
  4068. )
  4069. // ;(function () {
  4070. // const samerand = function () //string
  4071. // {
  4072. // return (
  4073. // lastrand ||
  4074. // (lastrand = samerand.new(20, {
  4075. // lower: true,
  4076. // upper: true,
  4077. // }))
  4078. // )
  4079. // }
  4080. // allfuncs.new("samerand", samerand, "function/random", false)
  4081. // var lastrand = ""
  4082. // samerand.new = (
  4083. // e = 20,
  4084. // { lower = true, upper = false, number = false, symbol = false } = {
  4085. // lower: true,
  4086. // upper: false,
  4087. // number: false,
  4088. // symbol: false,
  4089. // }
  4090. // ) => (
  4091. // (lastrand = ""),
  4092. // a(
  4093. // () =>
  4094. // (lastrand += a(
  4095. // `${lower ? "asdfghjklzxcvbnmqwertyuiop" : ""}${
  4096. // upper ? "ASDFGHJKLQWERTYUIOPZXCVBNM" : ""
  4097. // }${number ? "0123456789" : ""}${
  4098. // symbol ? ",./;'[]-=\\`~!@#$%^&*()_+|{}:\"<>?" : ""
  4099. // }`.split("")
  4100. // ).randfrom().val)
  4101. // ).repeat(e),
  4102. // lastrand
  4103. // )
  4104. // })()
  4105. allfuncs.new(
  4106. "randstr",
  4107. function (
  4108. /*string|input of object:
  4109. {
  4110. lower = true, //boolean|undefined
  4111. upper = false, //boolean|undefined
  4112. number = false, //boolean|undefined
  4113. symbol = false, //boolean|undefined
  4114. length = 20, //number|undefined
  4115. }
  4116. */
  4117. {
  4118. lower = true,
  4119. upper = false,
  4120. number = false,
  4121. symbol = false,
  4122. length = 20,
  4123. } = {
  4124. lower: true,
  4125. upper: false,
  4126. number: false,
  4127. symbol: false,
  4128. length: 20,
  4129. }
  4130. ) {
  4131. var rand = ""
  4132. a(() => {
  4133. rand += a(
  4134. `${lower ? "asdfghjklzxcvbnmqwertyuiop" : ""}${
  4135. upper ? "ASDFGHJKLQWERTYUIOPZXCVBNM" : ""
  4136. }${number ? "0123456789" : ""}${
  4137. symbol ? ",./;'[]-=\\`~!@#$%^&*()_+|{}:\"<>?" : ""
  4138. }`.split("")
  4139. ).randfrom().val
  4140. }).repeat(length)
  4141. return rand
  4142. },
  4143. "random/string"
  4144. )
  4145. allfuncs.new(
  4146. "toplaces",
  4147. function (
  4148. //string
  4149. num, //number|string
  4150. pre, //number|none
  4151. post = 0, //number|undefined
  4152. func = Math.round //function
  4153. ) {
  4154. num = String(num).split(".")
  4155. if (num.length == 1) num.push("")
  4156. if (pre !== undefined) {
  4157. num[0] = num[0].substring(num[0].length - pre, num[0].length)
  4158. while (num[0].length < pre) num[0] = "0" + num[0]
  4159. }
  4160. var temp = num[1].substring(post, post + 1) ?? 0
  4161. num[1] = num[1].substring(0, post)
  4162. while (num[1].length < post) num[1] += "0"
  4163. if (post > 0) {
  4164. temp = func(num[1].at(-1) + "." + temp)
  4165. num[1] = num[1].split("")
  4166. num[1].pop()
  4167. num[1].push(temp)
  4168. num[1] = num[1].join("")
  4169. num = num.join(".")
  4170. } else num = num[0]
  4171. return num
  4172. },
  4173. "number/format",
  4174. true
  4175. )
  4176. allfuncs.new(
  4177. "forcenumlength",
  4178. function (
  4179. //string
  4180. string, //string
  4181. lengths //array|number|object
  4182. ) {
  4183. var i = -1
  4184. if (a(lengths).gettype("object").val) {
  4185. lengths = lengths[[...string.matchAll(/\d+(?:\.\d+)?/g)].length]
  4186. }
  4187. if (!lengths) {
  4188. log(string)
  4189. debugger
  4190. }
  4191. return string.replaceAll(/\d+(?:\.\d+)?/g, function (v) {
  4192. i++
  4193. try {
  4194. return a(lengths[i]).gettype("array").val
  4195. ? a(Number(v)).toplaces(lengths[i][0], lengths[i][1]).val
  4196. : a(Number(v)).toplaces(lengths[i], 0).val
  4197. } catch (e) {
  4198. log(string, lengths, i)
  4199. debugger
  4200. }
  4201. })
  4202. },
  4203. "number/format",
  4204. true
  4205. )
  4206. ;(function () {
  4207. var lasttime = Date.now()
  4208. allfuncs.new(
  4209. "tick",
  4210. function () {
  4211. //number
  4212. var time = Date.now() - lasttime
  4213. lasttime = Date.now()
  4214. return time
  4215. },
  4216. "time"
  4217. )
  4218. })()
  4219.  
  4220. allfuncs.new("expandederror", expandederror, "error", true)
  4221. allfuncs.new(
  4222. "fetch",
  4223. async function (
  4224. //promise
  4225. url, //string
  4226. type = "text", //string|none
  4227. ...args //any|undefined
  4228. ) {
  4229. return await (await fetch(url, ...args))[type]()
  4230. },
  4231. "url/web"
  4232. )
  4233. allfuncs.new(
  4234. "copy",
  4235. function (
  4236. //string
  4237. text //string
  4238. ) {
  4239. navigator.clipboard.writeText(text)
  4240. return ""
  4241. try {
  4242. var temp = a(document.body)
  4243. .createelem("textarea", {
  4244. value: text,
  4245. width: 0,
  4246. height: 0,
  4247. position: "fixed",
  4248. top: 0,
  4249. left: 0,
  4250. })
  4251. .run.same.focus()
  4252. .run.same.select()
  4253. document.execCommand("copy")
  4254. temp.run.remove()
  4255. } catch (e) {
  4256. navigator.clipboard.writeText(text)
  4257. }
  4258. return text
  4259. },
  4260. "clipboard"
  4261. )
  4262. // allfuncs.new(
  4263. // "cache",
  4264. // (function () {
  4265. // var cac = {}
  4266. // function cache( //any
  4267. // args, //arguments|any
  4268. // data, //function
  4269. // notfoundincache //function|undefined
  4270. // ) {
  4271. // // if (a(args).gettype(["array", "arguments"]).val)
  4272. // // args = [...args].join("\u1111")
  4273. // args = JSON.stringify(args)
  4274. // var c = String(arguments.callee.caller).replaceAll(/\s\s+/g, " ").trim()
  4275. // // log(structuredClone(cac))
  4276. // if (!cac[c]) cac[c] = {}
  4277. // if (args in cac[c]) return cac[c][args]
  4278. // cac[c][args] = data()
  4279. // if (notfoundincache) notfoundincache(cac[c][args])
  4280. // return cac[c][args]
  4281. // }
  4282. // cache.getall = function () {
  4283. // return cac
  4284. // }
  4285. // cache.setall = function (e) {
  4286. // return (cac = e)
  4287. // }
  4288. // cache.add = function (e) {
  4289. // return (cac = { ...cac, ...e })
  4290. // }
  4291. // cache.clear = function () {
  4292. // cac = {}
  4293. // }
  4294. // return cache
  4295. // })(),
  4296. // "data/storage"
  4297. // )
  4298.  
  4299. Object.keys(console).forEach((e) =>
  4300. allfuncs.new(
  4301. e,
  4302. (/*undefined*/ ...z /*any*/) => console[e](...z),
  4303. "console/debug"
  4304. )
  4305. )
  4306. allfuncs.new(
  4307. "replaceall",
  4308. function (
  4309. //string
  4310. text, //string
  4311. regex, //regex|string|array
  4312. replacewith //string|function
  4313. ) {
  4314. return text.replaceAll(
  4315. a(String(a(regex).toregex().val) + "g").toregex().val,
  4316. replacewith
  4317. )
  4318. },
  4319. ""
  4320. )
  4321. allfuncs.new(
  4322. "setrange",
  4323. function (
  4324. //number
  4325. num, //number
  4326. min, //number
  4327. max //number
  4328. ) {
  4329. return num < min ? min : num > max ? max : num
  4330. },
  4331. "number"
  4332. )
  4333. allfuncs.new(
  4334. "isstrict",
  4335. function (
  4336. //boolean
  4337. thing //array|object
  4338. ) {
  4339. return thing?.strictargs?.[0] === isstrict
  4340. },
  4341. "typescript"
  4342. )
  4343. allfuncs.new(
  4344. "runonalltext",
  4345. function (
  4346. //undefined
  4347. func, //function
  4348. ignoretags = ["STYLE", "SCRIPT", "NOSCRIPT"] //array|undefined
  4349. ) {
  4350. // log(String(func))
  4351. a("*").qsa().foreach(repl)
  4352. watch(document.documentElement)
  4353. function watch(elem) {
  4354. new MutationObserver((e) => {
  4355. if (location.href.includes("scratch.mit.edu/projects")) return
  4356. ;[...e].forEach((e) => repl(e.target))
  4357. // ;[...e].forEach((e) => [...e.addedNodes].forEach(repl))
  4358. }).observe(elem, {
  4359. childList: true,
  4360. subtree: true,
  4361. attributes: true,
  4362. characterData: false,
  4363. })
  4364. }
  4365.  
  4366. function repl(node) {
  4367. if (node.shadowRoot) {
  4368. a("*").qsa(node.shadowRoot).foreach(repl)
  4369. watch(node.shadowRoot)
  4370. return repl(node.shadowRoot)
  4371. }
  4372. if (ignoretags.includes(node.tagName)) return
  4373. var nodes = node?.childNodes
  4374. if (!nodes) return
  4375. for (var i = 0, m = nodes.length; i < m; i++) {
  4376. var n = nodes[i]
  4377. // if (n.textContent.includes("Jul 17, 2021")) log(n, n.textContent)
  4378. if (n.nodeType == n.TEXT_NODE) {
  4379. func(n)
  4380. } else {
  4381. repl(n)
  4382. }
  4383. }
  4384. }
  4385. },
  4386. "text/elem"
  4387. )
  4388. allfuncs.new(
  4389. "runonallelems",
  4390. function runonallelems(
  4391. //undefined
  4392. func, //function
  4393. selector = "*", //string|undefined
  4394. ignoretags = [] //array|undefined
  4395. ) {
  4396. let timeout
  4397. const observer = new MutationObserver((mutations) => {
  4398. clearTimeout(timeout)
  4399. timeout = setTimeout(() => {
  4400. for (const mutation of mutations) {
  4401. repl(mutation.target)
  4402. }
  4403. }, 100) // debounce mutations for 100ms
  4404. })
  4405.  
  4406. observer.observe(document.documentElement, {
  4407. childList: true,
  4408. subtree: true,
  4409. attributes: true,
  4410. characterData: true,
  4411. })
  4412.  
  4413. function repl(elem) {
  4414. if (elem.nodeType === 1) {
  4415. // Check if elem is an element node
  4416. if (elem.shadowRoot) {
  4417. repl(elem.shadowRoot)
  4418. const shadowRootElems = elem.shadowRoot.querySelectorAll(selector)
  4419. for (const elem of shadowRootElems) {
  4420. if (!ignoretags.includes(elem.tagName.toLowerCase())) {
  4421. func(elem)
  4422. }
  4423. }
  4424. }
  4425.  
  4426. const elems = elem.querySelectorAll(selector)
  4427. for (const elem of elems) {
  4428. if (!ignoretags.includes(elem.tagName.toLowerCase())) {
  4429. func(elem)
  4430. }
  4431. }
  4432. }
  4433. }
  4434. },
  4435. "elem"
  4436. )
  4437. savelib("allfuncs", a)
  4438.  
  4439. function extras() {
  4440. ;(() => {
  4441. if (!window.showDirectoryPicker) return
  4442. if (!window.showOpenFilePicker) return
  4443. if (!window.showSaveFilePicker) return
  4444. const old = {
  4445. showDirectoryPicker: showDirectoryPicker.bind(window),
  4446. showOpenFilePicker: showOpenFilePicker.bind(window),
  4447. showSaveFilePicker: showSaveFilePicker.bind(window),
  4448. }
  4449. showDirectoryPicker = a(function (
  4450. //promise
  4451. obj = false //object|boolean|undefined
  4452. ) {
  4453. if (obj === true) {
  4454. obj = { mode: "readwrite" }
  4455. } else if (obj === false) {
  4456. obj = { mode: "read" }
  4457. }
  4458. return old.showDirectoryPicker(obj)
  4459. }).strictfunction("showDirectoryPicker").val
  4460. showOpenFilePicker = a(async function (
  4461. //promise
  4462. obj = {}, //object|undefined
  4463. write, //boolean|undefined
  4464. multiple, //boolean|undefined
  4465. types, //array|undefined
  4466. exts, //array|string|undefined
  4467. excludeAcceptAllOption = false //boolean|undefined
  4468. ) {
  4469. if (obj.types && !types) {
  4470. types = obj.types
  4471. delete obj.types
  4472. }
  4473. if (obj.exts && !exts) {
  4474. exts = obj.exts
  4475. delete obj.exts
  4476. }
  4477. if (excludeAcceptAllOption) obj.excludeAcceptAllOption = true
  4478. if (obj.name) obj.suggestedName = obj.name
  4479. if (multiple !== undefined) {
  4480. obj.multiple = multiple
  4481. delete obj.name
  4482. }
  4483. if (exts) {
  4484. obj.types = {
  4485. accept: {
  4486. "*/*": exts,
  4487. },
  4488. }
  4489. }
  4490. if (types) {
  4491. if (!obj.type) obj.type = { accept: {} }
  4492. types.forEach((type) => (obj.type.accept[type] = ["*"]))
  4493. }
  4494. if (obj.multiple) return await old.showOpenFilePicker(obj)
  4495. var x = await old.showOpenFilePicker(obj)
  4496. x = x[0] ?? x
  4497. if (obj.mode == "readwrite" || write)
  4498. if ((await x.requestPermission({ mode: "readwrite" })) !== "granted")
  4499. throw new Error("user didn't grant write permission")
  4500. return x
  4501. }).strictfunction("showOpenFilePicker").val
  4502. showSaveFilePicker = a(function (
  4503. //promise
  4504. obj = {}, //object|none|string
  4505. multiple = false, //boolean|none
  4506. types, //array|none
  4507. exts, //array|string|none
  4508. excludeAcceptAllOption = false //boolean|undefined
  4509. ) {
  4510. if (typeof obj == "string") obj = { suggestedName: obj }
  4511. if (obj.types && !types) {
  4512. types = obj.types
  4513. delete obj.types
  4514. }
  4515. if (obj.exts && !exts) {
  4516. exts = obj.exts
  4517. delete obj.exts
  4518. }
  4519. if (excludeAcceptAllOption) obj.excludeAcceptAllOption = true
  4520. if (obj.name) obj.suggestedName = obj.name
  4521. if (multiple !== undefined) {
  4522. obj.multiple = multiple
  4523. delete obj.name
  4524. }
  4525. if (exts) {
  4526. obj.types = {
  4527. accept: {
  4528. "*/*": exts,
  4529. },
  4530. }
  4531. }
  4532. if (types) {
  4533. if (!obj.type) obj.type = { accept: {} }
  4534. types.forEach((type) => (obj.type.accept[type] = ["*"]))
  4535. }
  4536. return old.showSaveFilePicker(obj)
  4537. }).strictfunction("showSaveFilePicker").val
  4538. })()
  4539. }
  4540. extras()
  4541. //log(...Object.keys( allfuncs).map(e=>[e, allfuncs[e].help, allfuncs[e]]||warn(e)))
  4542. })()