| 21 | * @returns {Promise<FileSystemDirectoryHandle>} |
| 22 | */ |
| 23 | export const getFileSystemDirectoryHandle = async (options) => { |
| 24 | if (!("showDirectoryPicker" in globalThis)) { |
| 25 | return Promise.reject( |
| 26 | new Error("showDirectoryPicker is not supported"), |
| 27 | ); |
| 28 | } |
| 29 | |
| 30 | const { promise, resolve, reject } = withResolvers(); |
| 31 | |
| 32 | const how = { id: "pyscript", mode: "readwrite", ...options }; |
| 33 | if (options.hint) how.startIn = options.hint; |
| 34 | |
| 35 | const transient = async () => { |
| 36 | try { |
| 37 | const handler = await showDirectoryPicker(how); |
| 38 | if ((await handler.requestPermission(how)) === "granted") { |
| 39 | resolve(handler); |
| 40 | return true; |
| 41 | } |
| 42 | } catch ({ message }) { |
| 43 | console.warn(message); |
| 44 | } |
| 45 | return false; |
| 46 | }; |
| 47 | |
| 48 | // in case the user decided to attach the event itself |
| 49 | // as opposite of relying our dialog walkthrough |
| 50 | if (navigator.userActivation?.isActive) { |
| 51 | if (!(await transient())) reject(new Error(ERROR)); |
| 52 | } else { |
| 53 | const dialog = assign(document.createElement("dialog"), { |
| 54 | className: "pyscript-fs", |
| 55 | innerHTML: [ |
| 56 | "<strong>ℹ️ Persistent FileSystem</strong><hr>", |
| 57 | "<p><small>PyScript would like to access a local folder.</small></p>", |
| 58 | "<div><button title='ok'>✅ Authorize</button>", |
| 59 | "<button title='cancel'>❌</button></div>", |
| 60 | ].join(""), |
| 61 | }); |
| 62 | |
| 63 | const [ok, cancel] = $$("button", dialog); |
| 64 | |
| 65 | ok.addEventListener("click", async (event) => { |
| 66 | stop(event); |
| 67 | if (await transient()) dialog.close(); |
| 68 | }); |
| 69 | |
| 70 | cancel.addEventListener("click", async (event) => { |
| 71 | stop(event); |
| 72 | reject(new Error(ERROR)); |
| 73 | dialog.close(); |
| 74 | }); |
| 75 | |
| 76 | document.body.appendChild(dialog).showModal(); |
| 77 | } |
| 78 | |
| 79 | return promise; |
| 80 | }; |