forked from sryo/scriptables
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZenTweak.js
More file actions
369 lines (310 loc) · 10.1 KB
/
ZenTweak.js
File metadata and controls
369 lines (310 loc) · 10.1 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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: deep-gray; icon-glyph: sliders-h;
// ZenTweak.js: Configuration editor for ZenTrate
const fm = FileManager.iCloud()
const CONFIG_FILE = fm.documentsDirectory() + "/zentrate_config.json"
const THEME_FILE = fm.documentsDirectory() + "/zentrate_theme.json"
// Load configuration
function loadConfig() {
if (fm.fileExists(CONFIG_FILE)) {
const configString = fm.readString(CONFIG_FILE)
let config = JSON.parse(configString)
config.items = config.items.filter(item =>
item && typeof item === 'object' && item.name && item.scheme && item.column
)
return config
}
return { items: [], sortMethod: "manual" }
}
// Save configuration
function saveConfig(config) {
fm.writeString(CONFIG_FILE, JSON.stringify(config, null, 2))
}
// Load theme configuration
function loadThemeConfig() {
if (fm.fileExists(THEME_FILE)) {
const configString = fm.readString(THEME_FILE)
return JSON.parse(configString)
}
return {
bgColor: "000000",
textColor: "FFFFFF",
fontName: "system",
fontWeight: "bold",
fontItalic: false,
minFontSize: 10,
maxFontSize: 30
}
}
// Get font based on theme configuration
function getFont(size, config = loadThemeConfig()) {
const fontName = config.fontName || "System";
const weight = config.fontWeight || "regular";
const isItalic = config.fontItalic || false;
let font;
if (fontName.toLowerCase() === "system") {
font = Font[weight + "SystemFont"](size);
} else {
font = new Font(fontName, size);
}
if (isItalic) {
font = Font.italicSystemFont(size);
}
return font;
}
// Validate and format time
function validateAndFormatTime(time) {
if (!time) return undefined;
// Support short time format
if (/^\d{1,2}$/.test(time)) {
time = time.padStart(2, '0') + ':00';
}
// Validate time format
const timeRegex = /^([01]\d|2[0-3]):?([0-5]\d)$/;
if (!timeRegex.test(time)) {
throw new Error(`Invalid time format: ${time}. Please use HH:MM or just HH.`);
}
// Ensure consistent format (HH:MM)
return time.length === 5 ? time : `${time}:00`;
}
// Validate day
function validateDay(day) {
if (day === '') return undefined;
const dayNum = parseInt(day);
if (isNaN(dayNum) || dayNum < 0 || dayNum > 6) {
throw new Error(`Invalid day: ${day}. Please use a number between 0 and 6.`);
}
return dayNum;
}
// WYSIWYG editor
async function createEditableWidget(config) {
let widget = new ListWidget()
const themeConfig = loadThemeConfig()
widget.backgroundColor = new Color("#" + themeConfig.bgColor)
let mainStack = widget.addStack()
mainStack.layoutHorizontally()
const columns = ['left', 'center', 'right']
for (let column of columns) {
let columnStack = mainStack.addStack()
columnStack.layoutVertically()
let columnItems = config.items.filter(item => item.column === column)
for (let item of columnItems) {
let itemStack = columnStack.addStack()
let itemText = itemStack.addText(item.name)
itemText.font = getFont(14)
itemText.textColor = new Color("#" + themeConfig.textColor)
itemText.lineLimit = 1
itemStack.setPadding(5, 5, 5, 5)
itemStack.backgroundColor = new Color("#444444")
itemStack.cornerRadius = 5
itemStack.url = `scriptable:///run?scriptName=${encodeURIComponent(Script.name())}&action=editItem&itemName=${encodeURIComponent(item.name)}`
}
if (columnItems.length > 0) {
let moveAllStack = columnStack.addStack()
let moveAllText = moveAllStack.addText("Move All")
moveAllText.font = getFont(12)
moveAllText.textColor = new Color("#" + themeConfig.textColor)
moveAllStack.backgroundColor = new Color("#666666")
moveAllStack.cornerRadius = 5
moveAllStack.setPadding(5, 5, 5, 5)
moveAllStack.url = `scriptable:///run?scriptName=${encodeURIComponent(Script.name())}&action=moveItems&fromColumn=${column}`
}
let addButton = columnStack.addText("+")
addButton.font = getFont(20)
addButton.textColor = new Color("#" + themeConfig.textColor)
addButton.url = `scriptable:///run?scriptName=${encodeURIComponent(Script.name())}&action=addItem&column=${column}`
if (column !== 'right') {
mainStack.addSpacer()
}
}
return widget
}
// Show editable widget
async function showEditableWidget() {
let config = loadConfig()
let widget = await createEditableWidget(config)
await widget.presentLarge()
}
// Edit an item
async function editItem(itemName) {
let config = loadConfig()
const item = config.items.find(i => i.name === itemName)
if (!item) {
console.error("Item not found")
return
}
const alert = new Alert()
alert.title = "Edit Item"
alert.message = `This item will show up from ${item.startDay !== undefined ? `day ${item.startDay}` : 'any day'} to ${item.endDay !== undefined ? `day ${item.endDay}` : 'any day'}, between ${item.startTime || 'any time'} and ${item.endTime || 'any time'}.`
alert.addTextField("Name", item.name)
alert.addTextField("Scheme URL", item.scheme)
alert.addAction("Save")
alert.addAction("Set Time Constraints")
alert.addAction("Move")
alert.addDestructiveAction("Delete")
alert.addCancelAction("Cancel")
const response = await alert.presentAlert()
switch (response) {
case 0: // Save
item.name = alert.textFieldValue(0)
item.scheme = alert.textFieldValue(1)
saveConfig(config)
break
case 1: // Set Time Constraints
await setTimeConstraints(item)
saveConfig(config)
break
case 2: // Move
await moveItems([item])
saveConfig(config)
break
case 3: // Delete
config.items = config.items.filter(i => i.name !== itemName)
saveConfig(config)
break
}
await showEditableWidget()
}
// Add a new item
async function addItem(column) {
const config = loadConfig()
const alert = new Alert()
alert.title = "Add New Item"
alert.addTextField("Name")
alert.addTextField("Scheme URL")
alert.addAction("Add")
alert.addCancelAction("Cancel")
const response = await alert.presentAlert()
if (response === 0) {
const newItem = {
name: alert.textFieldValue(0),
scheme: alert.textFieldValue(1),
column: column
}
config.items.push(newItem)
saveConfig(config)
}
await showEditableWidget()
}
// Set time constraints
async function setTimeConstraints(item) {
const alert = new Alert()
alert.title = "Set Time Constraints"
alert.message = "Leave fields blank for no constraint."
alert.addTextField("Start Time (HH:MM)", item.startTime || "")
alert.addTextField("End Time (HH:MM)", item.endTime || "")
alert.addTextField("Start Day (0-6, 0 is Sunday)", item.startDay !== undefined ? item.startDay.toString() : "")
alert.addTextField("End Day (0-6, 0 is Sunday)", item.endDay !== undefined ? item.endDay.toString() : "")
alert.addAction("Save")
alert.addAction("Clear Constraints")
alert.addCancelAction("Cancel")
const response = await alert.presentAlert()
if (response === 0) {
try {
item.startTime = validateAndFormatTime(alert.textFieldValue(0))
item.endTime = validateAndFormatTime(alert.textFieldValue(1))
item.startDay = validateDay(alert.textFieldValue(2))
item.endDay = validateDay(alert.textFieldValue(3))
} catch (error) {
const errorAlert = new Alert()
errorAlert.title = "Validation Error"
errorAlert.message = error.message
errorAlert.addAction("OK")
await errorAlert.presentAlert()
return await setTimeConstraints(item) // Try again
}
} else if (response === 1) {
delete item.startTime
delete item.endTime
delete item.startDay
delete item.endDay
}
}
// Move items (single item or all items from a column)
async function moveItems(items) {
const config = loadConfig()
const alert = new Alert()
alert.title = "Move Item(s)"
alert.message = `Move ${items.length === 1 ? 'item' : 'all items'} to:`
const currentColumn = items[0].column
const columns = ['left', 'center', 'right'].filter(col => col !== currentColumn)
columns.forEach(column => {
alert.addAction(column)
})
alert.addCancelAction("Cancel")
const response = await alert.presentAlert()
if (response !== -1) {
const toColumn = columns[response]
items.forEach(item => {
item.column = toColumn
})
saveConfig(config)
}
await showEditableWidget()
}
// Show the sort menu
async function showSortMenu() {
const config = loadConfig()
const alert = new Alert()
alert.title = "Sort Items"
alert.message = "Choose a sorting method"
alert.addAction("Manual")
alert.addAction("Alphabetical")
alert.addAction("Usage")
alert.addCancelAction("Cancel")
const response = await alert.presentAlert()
switch (response) {
case 0:
config.sortMethod = "manual"
break
case 1:
config.sortMethod = "alphabetical"
break
case 2:
config.sortMethod = "usage"
break
default:
return
}
saveConfig(config)
await showEditableWidget()
}
// Main function
async function run() {
const params = args.queryParameters
if (params && params.action) {
switch (params.action) {
case 'editItem':
await editItem(decodeURIComponent(params.itemName))
break
case 'addItem':
await addItem(decodeURIComponent(params.column))
break
case 'moveItems':
const config = loadConfig()
const fromColumn = decodeURIComponent(params.fromColumn)
const itemsToMove = config.items.filter(item => item.column === fromColumn)
await moveItems(itemsToMove)
break
default:
await showEditableWidget()
}
} else {
const menuAlert = new Alert()
menuAlert.title = "ZenTweak"
menuAlert.addAction("Edit Widget")
menuAlert.addAction("Sort Items")
menuAlert.addCancelAction("Exit")
const menuChoice = await menuAlert.presentAlert()
switch (menuChoice) {
case 0:
await showEditableWidget()
break
case 1:
await showSortMenu()
break
}
}
}
await run()