-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidget_display-book-excerpts.js
More file actions
77 lines (65 loc) · 2.44 KB
/
widget_display-book-excerpts.js
File metadata and controls
77 lines (65 loc) · 2.44 KB
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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: gray; icon-glyph: smile-wink;
const CONFIG = {
FILE_NAME: "book_excerpts.json", // generated by this shortcut: https://shortcutomation.com/get-book-excerpts-from-random-page
EXCERPTS: {
FONT: { NAME: "IowanOldStyle-BoldItalic", SIZE: 18 },
MINIMUM_SCALE_FACTOR: 0.1,
TEXT_OPACITY: 1,
TEXT_COLOR: Color.white(),
},
BOOK_NAME: {
FONT: { NAME: "IowanOldStyle-Italic", SIZE: 12 },
MINIMUM_SCALE_FACTOR: 0.1,
TEXT_OPACITY: 0.6,
TEXT_COLOR: Color.gray(),
},
SPACER: 15,
};
const allBooksData = await fetchAllBooksData();
const bookNames = Object.keys(allBooksData);
const randomBookName = bookNames[Math.floor(Math.random() * bookNames.length)];
const bookData = allBooksData[randomBookName];
const widget = await createWidget(randomBookName, bookData);
config.runsInWidget ? Script.setWidget(widget) : widget.presentLarge();
Script.complete();
// ================
// Helper functions
// ================
async function fetchAllBooksData() {
try {
const fm = FileManager.iCloud();
const filePath = fm.joinPath(fm.documentsDirectory(), CONFIG.FILE_NAME);
if (!fm.fileExists(filePath)) {
throw Error(`File not found: ${filePath}`);
}
await fm.downloadFileFromiCloud(filePath);
const allBooks = JSON.parse(fm.readString(filePath));
return allBooks;
} catch (e) {
throw Error(`Failed to load book excerpts: ${e}`);
}
}
async function createWidget(bookName, bookData) {
let widget = new ListWidget();
let a = widget.addText(bookData.excerpts);
a.centerAlignText();
a.textColor = CONFIG.EXCERPTS.TEXT_COLOR;
a.font = new Font(CONFIG.EXCERPTS.FONT.NAME, CONFIG.EXCERPTS.FONT.SIZE);
a.minimumScaleFactor = CONFIG.EXCERPTS.MINIMUM_SCALE_FACTOR;
a.textOpacity = CONFIG.EXCERPTS.TEXT_OPACITY;
widget.addSpacer(CONFIG.SPACER);
let b = widget.addText(`— ${bookName}`);
b.centerAlignText();
b.textColor = CONFIG.BOOK_NAME.TEXT_COLOR;
b.font = new Font(CONFIG.BOOK_NAME.FONT.NAME, CONFIG.BOOK_NAME.FONT.SIZE);
b.minimumScaleFactor = CONFIG.BOOK_NAME.MINIMUM_SCALE_FACTOR;
b.textOpacity = CONFIG.BOOK_NAME.TEXT_OPACITY;
// 👉 Download this shortcut: https://shortcutomation.com/add-to-inbox
widget.url =
`shortcuts://run-shortcut?` +
`name=${encodeURIComponent("📥 Add to Inbox")}&` +
`input=${encodeURIComponent(bookData.pageContent)}`;
return widget;
}