Convert multiple pages into SPA
This commit is contained in:
96
svelte/src/lib/Bookmarks.ts
Normal file
96
svelte/src/lib/Bookmarks.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { writable } from "svelte/store"
|
||||
import { fs_check_response, fs_path_url } from "./FilesystemAPI"
|
||||
import { loading_finish, loading_start } from "lib/Loading"
|
||||
|
||||
const bookmarks_file = "/me/.fnx/bookmarks.json"
|
||||
|
||||
export type Bookmark = {
|
||||
id: string,
|
||||
icon: string,
|
||||
label: string,
|
||||
}
|
||||
|
||||
export let bookmarks_store = writable<Bookmark[]>(
|
||||
[],
|
||||
(set: (value: Bookmark[]) => void) => {
|
||||
bookmarks_get().then((bm: Bookmark[]) => {
|
||||
set(bm)
|
||||
}).catch((err: any) => {
|
||||
alert("Could not fetch bookmarks:\n" + JSON.stringify(err))
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
export const bookmarks_get = async (): Promise<Bookmark[]> => {
|
||||
let bookmarks: Bookmark[] = []
|
||||
try {
|
||||
bookmarks = await fs_check_response(
|
||||
await fetch(fs_path_url(bookmarks_file), { cache: "no-store" })
|
||||
)
|
||||
} catch (err) {
|
||||
// If the bookmarks were not found when we return an empty bookmarks
|
||||
// list
|
||||
if (err.value !== "path_not_found") {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
console.debug("Fetched", bookmarks.length, "bookmarks:", bookmarks)
|
||||
bookmarks_store.set(bookmarks)
|
||||
return bookmarks
|
||||
}
|
||||
|
||||
export const bookmarks_save = async (bookmarks: Bookmark[]) => {
|
||||
await fs_check_response(
|
||||
await fetch(
|
||||
fs_path_url(bookmarks_file) + "?make_parents=true",
|
||||
{ method: "PUT", body: JSON.stringify(bookmarks) },
|
||||
)
|
||||
)
|
||||
console.debug("Saved", bookmarks.length, "bookmarks:", bookmarks)
|
||||
bookmarks_store.set(bookmarks)
|
||||
}
|
||||
|
||||
export const bookmark_add = async (bm: Bookmark): Promise<Bookmark[]> => {
|
||||
let bookmarks: Bookmark[] = []
|
||||
try {
|
||||
loading_start()
|
||||
|
||||
// Get bookmarks
|
||||
bookmarks = await bookmarks_get()
|
||||
|
||||
// Add new bookmark
|
||||
bookmarks.push(bm)
|
||||
|
||||
// Save new bookmarks
|
||||
await bookmarks_save(bookmarks)
|
||||
} finally {
|
||||
loading_finish()
|
||||
}
|
||||
return bookmarks
|
||||
}
|
||||
|
||||
export const bookmark_del = async (id: string): Promise<Bookmark[]> => {
|
||||
let bookmarks: Bookmark[] = []
|
||||
try {
|
||||
loading_start()
|
||||
|
||||
// Get bookmarks
|
||||
bookmarks = await bookmarks_get()
|
||||
|
||||
// Delete bookmark
|
||||
for (let i = 0; i < bookmarks.length; i++) {
|
||||
if (bookmarks[i].id === id) {
|
||||
console.debug("Deleting bookmark at index", i, bookmarks[i])
|
||||
bookmarks.splice(i, 1)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Save new bookmarks
|
||||
await bookmarks_save(bookmarks)
|
||||
} finally {
|
||||
loading_finish()
|
||||
}
|
||||
return bookmarks
|
||||
}
|
||||
Reference in New Issue
Block a user