lib:all functions

none

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

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

QingJ © 2025

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