-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.html
341 lines (317 loc) · 12.3 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
<html>
<head>
<title>TiddlyStow - stow TiddlyWiki files locally using the browser file system api</title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
<link rel="manifest" href="manifest.json">
<script type="module">
/* From https://github.com/jakearchibald/idb-keyval */
/* Retreived 2020-04-10 */
let idbKeyval = (function (exports) {
'use strict';
class Store {
constructor(dbName = 'keyval-store', storeName = 'keyval') {
this.storeName = storeName;
this._dbp = new Promise((resolve, reject) => {
const openreq = indexedDB.open(dbName, 1);
openreq.onerror = () => reject(openreq.error);
openreq.onsuccess = () => resolve(openreq.result);
// First time setup: create an empty object store
openreq.onupgradeneeded = () => {
openreq.result.createObjectStore(storeName);
};
});
}
_withIDBStore(type, callback) {
return this._dbp.then(db => new Promise((resolve, reject) => {
const transaction = db.transaction(this.storeName, type);
transaction.oncomplete = () => resolve();
transaction.onabort = transaction.onerror = () => reject(transaction.error);
callback(transaction.objectStore(this.storeName));
}));
}
}
let store;
function getDefaultStore() {
if (!store)
store = new Store();
return store;
}
function get(key, store = getDefaultStore()) {
let req;
return store._withIDBStore('readonly', store => {
req = store.get(key);
}).then(() => req.result);
}
function set(key, value, store = getDefaultStore()) {
return store._withIDBStore('readwrite', store => {
store.put(value, key);
});
}
function del(key, store = getDefaultStore()) {
return store._withIDBStore('readwrite', store => {
store.delete(key);
});
}
function clear(store = getDefaultStore()) {
return store._withIDBStore('readwrite', store => {
store.clear();
});
}
function keys(store = getDefaultStore()) {
const keys = [];
return store._withIDBStore('readonly', store => {
// This would be store.getAllKeys(), but it isn't supported by Edge or Safari.
// And openKeyCursor isn't supported by Safari.
(store.openKeyCursor || store.openCursor).call(store).onsuccess = function () {
if (!this.result)
return;
keys.push(this.result.key);
this.result.continue();
};
}).then(() => keys);
}
exports.Store = Store;
exports.get = get;
exports.set = set;
exports.del = del;
exports.clear = clear;
exports.keys = keys;
return exports;
}({}));
/*
* Returns a function which can be used as a TiddlyWiki saver.
* The saver will write the given text to the given fileHandle
*/
function createTwCustomSaver(fileHandle) {
return function(text, method, callback) {
fileHandle.createWritable()
.then(writable => {
writable.write(text);
return writable;
}).then(writable => {
writable.close();
callback(null);
}).catch(error => {
callback(error);
});
return true;
}
}
/* This saver is used when a local file is opened from disk */
function setTwCustomSaver(fileHandle) {
// Tiddlywiki Version 5.1.23 introduced the "custom saver" which will call
// a window.$tw.customSaver.save function from its current frame
// or parent frame.
window.$tw = {customSaver: {save: createTwCustomSaver(fileHandle)}};
}
/*
* This "SaveAs" saver is used when new wiki is loaded from url.
* The user is not prompted for a file to save to until the first save
*/
function setTwCustomSaveAsSaver() {
let writeTw;
let save = function(text, method, callback) {
if (writeTw) {
writeTw(text, method, callback);
} else {
// writeTw function is empty, so prompt the user for file handle
// and create the writeTw function
window.showSaveFilePicker()
.then(fileHandle => {
writeTw = createTwCustomSaver(fileHandle);
writeTw(text, method, callback);
twFileManager.addRecent(fileHandle);
});
}
return true;
}
window.$tw = {customSaver: {save: save}};
}
const twFileManager = {
openFile: async function(fileHandle) {
if (fileHandle) {
// fileHandle may have come from indexDB in which case permission must be re-queried
const options = {mode: 'read'};
if ((await fileHandle.queryPermission(options)) !== 'granted') {
await fileHandle.requestPermission(options);
}
} else {
// No fileHandle given. Prompt user to choose one from disk
[fileHandle] = await window.showOpenFilePicker();
}
const file = await fileHandle.getFile();
const contents = await file.text();
setTwCustomSaver(fileHandle);
return {fileHandle, contents};
},
openFromUrl: async function(url) {
const contents = await fetch(url).then(res => res.text());
setTwCustomSaveAsSaver();
return {contents};
},
/* This code modified from https://github.com/GoogleChromeLabs/text-editor/blob/main/src/inline-scripts/menu-recent.js */
/* as retrieved on 2022/03/20 */
/*
* File handles can be serialized, but only to IndexDB. Localstorage is not supported.
*/
addRecent: async function(fileHandle) {
let recentFiles = (await idbKeyval.get('recentFiles')) || [];
// If isSameEntry isn't available, we can't store the file handle
if (!fileHandle.isSameEntry) {
console.warn('Saving of recents is unavailable.');
return recentFiles;
}
// Loop through the list of recent files and make sure the file we're
// adding isn't already there. This is gross.
const inList = await Promise.all(recentFiles.map((f) => {
return fileHandle.isSameEntry(f);
}));
if (inList.some((val) => val)) {
return recentFiles;
}
// Add the new file handle to the top of the list, and remove any old ones.
recentFiles.unshift(fileHandle);
if (recentFiles.length > 5) {
recentFiles.pop();
}
// Save the list of recent files.
idbKeyval.set('recentFiles', recentFiles);
return recentFiles;
},
getRecent: async function () {
return (await idbKeyval.get('recentFiles')) || [];
},
clearRecent: async function () {
await idbKeyval.del('recentFiles');
}
}
// Allow indexdb to be disabled
if (window.location.hash.search("norecent") >= 0) {
const noop = async () => {return []};
twFileManager.addRecent = noop;
twFileManager.getRecent = noop;
}
// Prevent errors if the browser doesn't support file system api
if (!window.showOpenFilePicker) {
twFileManager.openFile = async () => {
window.alert("This browser doesn't support opening files");
return {}
}
}
if (!window.showSaveFilePicker) {
setTwCustomSaveAsSaver = () => {}
}
function replacePageContents(contents) {
if (contents) {
document.open();
document.write(contents);
document.close();
}
}
window.openFile = async function (fileHandle) {
const file = await twFileManager.openFile(fileHandle);
replacePageContents(file.contents);
if (file.fileHandle) {
twFileManager.addRecent(file.fileHandle);
}
return file;
}
window.openFromUrl = async function (url) {
const file = await twFileManager.openFromUrl(url);
replacePageContents(file.contents);
return file;
}
function displayBrowserSupportMessage() {
const elem = document.getElementById("support-message");
if (elem) {
elem.innerHTML = window.showSaveFilePicker ?
"Good news, your browser supports it." :
"<b>Unfortunately your browser does not support it.</b>"
}
}
function clearRecent() {
twFileManager.clearRecent().then(() => {
const elem = document.getElementById("recent-files");
if (elem) {
elem.innerText = "";
}
});
}
function displayRecentFiles() {
const elem = document.getElementById("recent-files");
if (elem) {
twFileManager.getRecent().
then(recentFiles => {
if (recentFiles && recentFiles.length > 0) {
const list = document.createElement('ul');
for (const recent of recentFiles) {
const li = document.createElement('li'),
button = Object.assign(document.createElement('button'), {
type: 'button',
onclick: openFile.bind(null, recent),
innerText: recent.name
});
li.appendChild(button);
list.appendChild(li);
}
const clearButton = Object.assign(document.createElement('button'), {
type: 'button',
onclick: clearRecent,
innerText: 'Clear recent file list'
});
elem.innerText = 'Open existing from a recent file:';
elem.appendChild(list);
elem.appendChild(clearButton);
}
})
}
}
window.onload = () => {
displayBrowserSupportMessage();
displayRecentFiles();
}
</script>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./offline-service-worker.js')
.then(function(registration) {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(function(error) {
console.error('Service Worker registration failed:', error);
});
}
</script>
</head>
<body>
<div>
<h1>TiddlyStow</h1>
<p>This simple page is a helper for loading a local <a href="https://tiddlywiki.com">TiddlyWiki</a>
file and storing it back to the same local file.</p>
<ul>
<li>Be sure to have a backup of any file before opening it here!</li>
<li>Be sure to make frequent backups of your file!</li>
<li>
Not all browsers <a href="https://caniuse.com/mdn-api_window_showopenfilepicker">support the local files feature</a>.
<span id="support-message"></span>
</li>
<li>Only works with single file TiddlyWiki instances.</li>
<li>Requires the <a href="https://github.com/Jermolene/TiddlyWiki5/pull/4908">custom saver feature</a> introduced in TiddlyWiki version 5.1.23. Older versions will fall back to the download saver in which case using this page provides no benefit.</li>
<li>Prefer not to keep a list of recent files in your browser storage? Click <a href="#norecent">here</a> and refresh the page.</li>
<li><a href="https://github.com/slaymaker1907/TW5-browser-nativesaver">TW5 browser nativesaver</a> is a similar project, but has more features and is bundled as a TiddlyWiki plugin.</li>
<li>Source code available at <a href="https://github.com/btheado/tiddlystow">github</a> or use "view page source" in the browser.</li>
<li>After loading a Tiddlywiki file, refresh the page to get back to the file picker.</li>
</ul>
</p>
<button type="button" onclick="openFile()">open existing from a local file...</button>
<div id="recent-files"></div>
<div>
Open new from a remote url:
<ul>
<li><button type="button" onclick="openFromUrl('https://tiddlywiki.com/empty.html')">tiddlywiki.com/empty.html</button></li>
<li><button type="button" onclick="openFromUrl('https://tiddlywiki.com/prerelease')">tiddlywiki.com/prerelease</button></li>
</ul>
</div>
</div>
</body>
</html>