Skip to content

Instantly share code, notes, and snippets.

@slaymaker1907
Last active January 26, 2022 10:47
Show Gist options
  • Save slaymaker1907/7a04a6188179bfe113b122b1f51e22b5 to your computer and use it in GitHub Desktop.
Save slaymaker1907/7a04a6188179bfe113b122b1f51e22b5 to your computer and use it in GitHub Desktop.
Example TiddlyWiki 5 Saver Using HTML 5 File System Access API
created: 20210424052412556
modified: 20210424052444872
module-type: saver
tags:
title: TestSaverModule
type: application/javascript
// Disable this to limit logging.
let debugEnabled = true;
let problemEncountered = false;
const logDebug = (...args) => {
if (debugEnabled) {
console.log(...args);
}
}
const getFileHandle = async () => {
let result;
for (let i = 0; i < 5; i++) {
result = await window.showSaveFilePicker({
types: [{
description: "HTML file",
accept: {
"text/html": [
".html",
".htm"
]
}
}]
});
logDebug("Received file handle: %o", result)
if (result.kind === "file") {
return result;
}
alert("File input must be a file, not a directory.");
}
return await Promise.reject("Could not get file for saving.");
}
class FileSystemSaver {
constructor() {
logDebug("Constructing a FileSystemSaver");
this.initError = null;
this.info = {
name: "nativesaver",
priority: 100000,
capabilities: ["save", "autosave"]
};
this.fileHandle = null;
}
userInteractionInit() {
if (this.fileHandle === null) {
logDebug("Attempting to get file handle.");
this.fileHandle = getFileHandle();
this.fileHandle.catch(err => {
problemEncountered = true;
this.initError = err;
logDebug("Could not get file handle due to error: %o", err);
});
}
}
save(text, method, callback) {
logDebug("Saving with method %o", method);
this.userInteractionInit();
if (this.initError !== null) {
logDebug("Encountered init, can't save");
callback(this.initError);
return false;
}
this.fileHandle.then(async handle => {
logDebug("Creating writable...");
const writable = await handle.createWritable();
logDebug("Created writable");
try {
await writable.write(text);
logDebug("Wrote data successfully");
} finally {
await writable.close();
logDebug("Closed writable");
}
}).then(() => {
logDebug("Successfully saved to file system");
callback(null);
}, err => {
problemEncountered = true;
logDebug("Encountered error while saving: %o", err);
callback(`Encountered error while saving to file system: [${err}]`);
});
return true;
}
}
// Has one parameter, wiki if necessary
const canSave = () => {
return (!!window.showOpenFilePicker) && window.isSecureContext && !problemEncountered;
};
// Also has access to wiki if necessary
const create = () => {
return new FileSystemSaver();
};
module.exports = {
canSave,
create
};
MIT License
Copyright (c) 2021 Dyllon Gagnier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
// Disable this to limit logging.
let debugEnabled = true;
let problemEncountered = false;
const logDebug = (...args) => {
if (debugEnabled) {
console.log(...args);
}
}
const getFileHandle = async () => {
let result;
for (let i = 0; i < 5; i++) {
result = await window.showSaveFilePicker({
types: [{
description: "HTML file",
accept: {
"text/html": [
".html",
".htm"
]
}
}]
});
logDebug("Received file handle: %o", result)
if (result.kind === "file") {
return result;
}
alert("File input must be a file, not a directory.");
}
return await Promise.reject("Could not get file for saving.");
}
class FileSystemSaver {
constructor() {
logDebug("Constructing a FileSystemSaver");
this.initError = null;
this.info = {
name: "nativesaver",
priority: 100000,
capabilities: ["save", "autosave"]
};
this.fileHandle = null;
}
userInteractionInit() {
if (this.fileHandle === null) {
logDebug("Attempting to get file handle.");
this.fileHandle = getFileHandle();
this.fileHandle.catch(err => {
problemEncountered = true;
this.initError = err;
logDebug("Could not get file handle due to error: %o", err);
});
}
}
save(text, method, callback) {
logDebug("Saving with method %o", method);
this.userInteractionInit();
if (this.initError !== null) {
logDebug("Encountered init, can't save");
callback(this.initError);
return false;
}
this.fileHandle.then(async handle => {
logDebug("Creating writable...");
const writable = await handle.createWritable();
logDebug("Created writable");
try {
await writable.write(text);
logDebug("Wrote data successfully");
} finally {
await writable.close();
logDebug("Closed writable");
}
}).then(() => {
logDebug("Successfully saved to file system");
callback(null);
}, err => {
problemEncountered = true;
logDebug("Encountered error while saving: %o", err);
callback(`Encountered error while saving to file system: [${err}]`);
});
return true;
}
}
// Has one parameter, wiki if necessary
const canSave = () => {
return (!!window.showOpenFilePicker) && window.isSecureContext && !problemEncountered;
};
// Also has access to wiki if necessary
const create = () => {
return new FileSystemSaver();
};
module.exports = {
canSave,
create
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment