all functions

alot of functions i've made. to add more do allfuncs.new. to run either use a(input1).functionname(...other_inputs), and use .val to get value - allows chaining functions together suchas a('string').toarray().push('string').warn('2 strings').keeponlyone().log('1 string').val //returns ['string'].

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

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

QingJ © 2025

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