lib:file opener

none

目前為 2025-01-25 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name lib:file opener
  3. // @version 5
  4. // @description none
  5. // @license GPLv3
  6. // @run-at document-start
  7. // @author rssaromeo
  8. // @match *://*/*
  9. // @tag lib
  10. // @exclude /livereload.net\/files\/ffopen\/index.html$/
  11. // @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=
  12. // @grant none
  13. // @namespace https://greasyfork.org/users/1184528
  14. // ==/UserScript==
  15. ;(() => {
  16. const a = loadlib("allfuncs")
  17. const run = {
  18. file: runfile,
  19. folder: runfolder,
  20. globals: window.ERwkOoQYn9C3jxDZdovIZoZ2DmGt5wKyTMPU2uck ?? [],
  21. }
  22. delete window.ERwkOoQYn9C3jxDZdovIZoZ2DmGt5wKyTMPU2uck
  23. ;(async () => {
  24. var cac = {}
  25. async function newglobaljs(name, func = (e) => e, newname) {
  26. if ((newname ?? name).startsWith("blob:http")) return
  27. var text = cac[name] ?? (await (await fetch(name)).text())
  28. if (newname) name = newname
  29. cac[name] ??= text
  30. run.globals.push({
  31. text: func(text),
  32. name: name,
  33. })
  34. }
  35. run.newglobaljs = newglobaljs
  36. })()
  37. function hashformat({ isglobal, name }) {
  38. const hashformat = "#__isglobal: filename"
  39. if (isglobal == true) isglobal = "global"
  40. if (isglobal == false) isglobal = "local"
  41. return _replaceall(hashformat, [
  42. ["isglobal", isglobal],
  43. ["filename", name],
  44. ])
  45. }
  46.  
  47. loadlib("libloader").savelib("file opener", run)
  48. async function runfile(file) {
  49. file = await formatfiles(await file.getFile())
  50. replaceglobalurls(file)
  51. await updateglobals(file)
  52. newurl(file, file.format)
  53. openfile(file, file.name)
  54. }
  55. async function updateglobals(file) {
  56. const tempglobals = JSON.stringify([
  57. ...run.globals.map((e) => {
  58. return { name: e.name, text: e.text }
  59. }),
  60. ])
  61. // .replaceAll("<", "&lt;")
  62. // .replaceAll("&", "&amp;")
  63. if (file.name.endsWith(".html"))
  64. file.text =
  65. `<script>window.ERwkOoQYn9C3jxDZdovIZoZ2DmGt5wKyTMPU2uck = ${tempglobals}<\/script>` +
  66. file.text
  67. }
  68. async function runfolder(folder, mainfile = "index.html") {
  69. var files = await getfilesfromfolder(folder)
  70. const name = files[0].path.match(/^([^\/]+)\//, "")[1]
  71. files = await formatfiles(files)
  72.  
  73. setupget(files)
  74. var index = files.get(mainfile)
  75. if (!index) {
  76. error(
  77. `folder ${name} doesn't contain ${mainfile}, searching for index.html instead`,
  78. )
  79. index = files.get("index.html")
  80. }
  81. if (!index) throw new Error(`folder ${name} doesn't contain index.html`)
  82. var htmls = files.get(/\.html/i)
  83. // error(a(files.get(/\.png/i)[0].file).readfile('DataURL'))
  84. {
  85. function updatebar(i, name) {
  86. progresstext.innerHTML = `${i}/${files.length + htmls.length}: ${name}`
  87. innerprogress.style.width =
  88. "calc(" +
  89. a(Number(i)).rerange(0, files.length + htmls.length, 0, 100) +
  90. "% - 2px)"
  91. }
  92. var progress = a(document.body)
  93. .createelem("div", {
  94. position: "fixed",
  95. top: "0",
  96. left: 0,
  97. border: "30px solid #999",
  98. backgroundColor: "black",
  99. color: "white",
  100. width: "calc(100vw - 60px)",
  101. height: "29px",
  102. })
  103. .createelem.same("div", {
  104. backgroundColor: "#777",
  105. width:
  106. a(files.length).rerange(0, files.length + htmls.length, 0, 100) +
  107. "%",
  108. height: "10px",
  109. })
  110. .createelem.same("div", {
  111. backgroundColor: "#555",
  112. width:
  113. 100 -
  114. a(files.length).rerange(0, files.length + htmls.length, 0, 100) +
  115. "%",
  116. position: "relative",
  117. top: "-10px",
  118. left:
  119. a(files.length).rerange(0, files.length + htmls.length, 0, 100) +
  120. "%",
  121. height: "10px",
  122. }).val
  123. var innerprogress = a(progress).createelem("div", {
  124. backgroundColor: "#aaa",
  125. width: 0,
  126. position: "relative",
  127. top: "-18px",
  128. left: "2px",
  129. height: "6px",
  130. }).val
  131. var progresstext = a(progress).createelem("span", {
  132. position: "relative",
  133. top: "-16px",
  134. }).val
  135. for (var i in files) {
  136. var file = files[i]
  137. updatebar(i, file.name)
  138. newurl(file, file.format)
  139. if (Number(i) % 15 == 0) await a(0).wait()
  140. }
  141. var f = files.get(/\./)
  142. f = f.filter((e) => ["js", "css"].includes(e.extension))
  143. for (var i in f) {
  144. var e = f[i]
  145. if (Number(i) % 15 == 0) {
  146. updatebar(Number(i), e.name)
  147. await a(0).wait()
  148. }
  149. replaceallurls(e, files)
  150. replaceglobalurls(e)
  151. newurl(e)
  152. }
  153. for (var i in htmls) {
  154. var e = htmls[i]
  155. if (Number(i) % 15 == 0) {
  156. updatebar(Number(i) + files.length, e.name)
  157. await a(0).wait()
  158. }
  159. replaceallurls(e, files)
  160. replaceglobalurls(e)
  161. newurl(e, "text/html")
  162. }
  163. }
  164. // warn(index, index.path.split("/"))
  165. replaceallurls(index, files, true)
  166. await updateglobals(index)
  167. newurl(index, "text/html")
  168. progress.remove()
  169. openfile(index, name)
  170. }
  171. function openfile(file, name) {
  172. name ??= file?.file?.name
  173. return open(file.url, location.href + name)
  174. }
  175. function getallgoodpaths(file, files, lll) {
  176. var p = file.path.split("/")
  177. var n = p.pop()
  178. return files.map((e) => {
  179. if (!e.path) error(e, file)
  180. var path = e.path.split("/")
  181. var name = path.pop()
  182. if (same(p, path)) {
  183. return { ...e, path: name }
  184. }
  185. var newpath = ""
  186. var rs = false
  187. p.forEach((e, i) => {
  188. if (same(e, path[i]) && !rs) return
  189. rs = true
  190. newpath += "../"
  191. })
  192. path.push("")
  193. return {
  194. ...e,
  195. path: newpath + path.join("/") + name,
  196. }
  197. })
  198. function same(a, s) {
  199. return JSON.stringify(a) == JSON.stringify(s)
  200. }
  201. }
  202. function replaceallurls(file, files, lll) {
  203. if (file.text.startsWith("#redirect")) {
  204. var redir = file.text.match(/^#redirect (.*)/)[1]
  205. var redirfile = files.get(redir)
  206. if (!redirfile)
  207. throw new Error(`failed to redirect from ${file.name} to ${redir}`)
  208. file.text =
  209. file.text.replace(`#redirect ${redir}`, "") + "\n" + redirfile.text
  210. }
  211. var goodfiles = getallgoodpaths(file, files, lll)
  212. goodfiles.forEach(({ path, url }) => {
  213. file.text = file.text.replaceAll(
  214. new RegExp(`(['"])(?:\\.\\/)*${regescape(path)}\\1`, "gi"),
  215. `"${url}${hashformat({ isglobal: false, name: path })}"`,
  216. )
  217. })
  218. replaceglobalurls(file)
  219. }
  220. function regescape(reg) {
  221. return reg.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")
  222. }
  223. function newurl(file, type) {
  224. type ??= file.format
  225. var blob =
  226. type && type.startsWith("image/")
  227. ? new Blob([file.file], { type })
  228. : new Blob([file.text], { type })
  229. file.url = URL.createObjectURL(blob)
  230. return file
  231. }
  232. async function replaceglobalurls(file) {
  233. run.globals.forEach((e) => {
  234. if (!e.regex)
  235. e.regex = new RegExp(
  236. `(['"])(?:\\.?\\.\\/)*${regescape(e.name)}\\1`,
  237. "gi",
  238. )
  239. if (!e.url)
  240. e.url = URL.createObjectURL(
  241. new Blob([e.text], { type: "text/javascript" }),
  242. )
  243. file.text = file.text.replaceAll(
  244. e.regex,
  245. `"${e.url}${hashformat({ isglobal: true, name: e.name })}"`,
  246. )
  247. })
  248. return file
  249. }
  250. async function formatfiles(files) {
  251. if (!a(files).gettype("array").val) return await format(files)
  252. return await Promise.all(files.map(format))
  253. async function format(file) {
  254. var data = await a(file).readfile()
  255. // if(file.name.match(/\.(\w+)$/)?.[1]=='svg'){
  256. // error(file)
  257. // }
  258. return {
  259. name: file.name,
  260. text: data,
  261. path: file?.path?.replace?.(/^[^\/]+\//, ""),
  262. extension: file.name.match(/\.(\w+)$/)?.[1],
  263. format: {
  264. js: "text/javascript",
  265. html: "text/html",
  266. css: "text/css",
  267. jpg: "image/jpg",
  268. jpeg: "image/jpeg",
  269. png: "image/png",
  270. svg: "image/svg+xml",
  271. }[file.name.match(/\.(\w+)$/)?.[1]],
  272. file,
  273. }
  274. }
  275. }
  276. function setupget(files) {
  277. files.get = function (name, skip = 0) {
  278. if (a(name).gettype("string").val)
  279. return files.find((e) => {
  280. return e.path == name
  281. })
  282. else return files.filter((e) => name.test(e.path))
  283. }
  284. }
  285.  
  286. async function getfilesfromfolder(dirHandle, path = dirHandle.name) {
  287. const dirs = []
  288. const files = []
  289. // warn(path)
  290. for await (const entry of dirHandle.values()) {
  291. const nestedPath = `${path}/${entry.name}`
  292. if (nestedPath.startsWith(dirHandle.name + "/codemirror/mode/ja"))
  293. error(nestedPath, entry)
  294. if (entry.kind === "file") {
  295. files.push(
  296. entry.getFile().then((file) => {
  297. file.directoryHandle = dirHandle
  298. file.handle = entry
  299. Object.defineProperty(file, "path", {
  300. configurable: true,
  301. enumerable: true,
  302. get: () => nestedPath,
  303. })
  304. return Object.defineProperty(file, "webkitRelativePath", {
  305. configurable: true,
  306. enumerable: true,
  307. get: () => nestedPath,
  308. })
  309. }),
  310. )
  311. } else if (entry.kind === "directory") {
  312. warn(entry, nestedPath)
  313. dirs.push(getfilesfromfolder(entry, nestedPath))
  314. } else {
  315. error(entry.kind)
  316. }
  317. }
  318. return [...(await Promise.all(dirs)).flat(), ...(await Promise.all(files))]
  319. }
  320. function _replaceall(q, w, e) {
  321. switch (a(w).gettype("array").val + " " + a(e).gettype("array").val) {
  322. case "true true":
  323. if (e.length == w.length) {
  324. w.forEach((ww, i) => {
  325. q = q.replaceAll(ww, e[i])
  326. })
  327. return q
  328. }
  329. throw new Error("when both are arrays the length must be the same")
  330. break
  331. case "true false":
  332. if (a(w[0]).gettype("array").val) {
  333. w.forEach(([ww, e]) => {
  334. q = q.replaceAll(ww, e)
  335. })
  336. } else {
  337. w.forEach((ww) => {
  338. q = q.replaceAll(ww, e)
  339. })
  340. }
  341. return q
  342. break
  343. case "false false":
  344. return q.replaceAll(w, e)
  345. break
  346. }
  347. }
  348. })()