Repository navigation
Expand file tree
/
Copy pathapp.ts
More file actions
183 lines (158 loc) · 6.14 KB
/
Copy pathapp.ts
File metadata and controls
183 lines (158 loc) · 6.14 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
/**
* Barista — keep your Mac awake, one click from the menu bar.
*
* The whole app is a template, a few endpoints and a tray menu; `createMenuBarApp`
* turns those into a native window.
*/
import type { BaristaPreferences } from './src/preferences'
import { existsSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { createMenuBarApp } from '@stacksjs/stx/menubar'
import pkg from './package.json' with { type: 'json' }
// Embedded at build time so the compiled binary carries the popup with it —
// a shipped .app has no src/barista.stx on disk to read.
import templateSource from './src/barista.stx' with { type: 'text' }
import { caffeinateSnapshot, disableCaffeinate, enableCaffeinate, isCaffeinated, toggleCaffeinate } from './src/caffeinate'
import { COLLAPSE_DELAYS, DURATIONS } from './src/durations'
import { DEFAULT_PREFERENCES } from './src/preferences'
import { buildTrayMenu, parseCraftVersion, supportsTrayIcon, trayGlyph, trayIcon, trayTooltip } from './src/tray'
import { createUpdateChecker } from './src/updates'
import { resolveCraftBinary } from '@stacksjs/stx/desktop'
/**
* Whether the menu bar is currently collapsed. Only the webview knows — it owns
* the Craft menu bar bridge — so it reports back here for the tray menu's label.
*/
let menuBarCollapsed = false
const updates = createUpdateChecker(pkg.version)
/**
* Whether the Craft binary rendering this app can draw a tray icon.
*
* Asked once, on first use rather than at import: probing spawns a subprocess,
* and doing that while the module graph is still evaluating is a poor place for
* something that can fail. An older binary silently ignores setIcon, which would
* leave an invisible menu bar item, so the tray falls back to a text cup then.
*/
const trayIconSupported = (() => {
let cached: boolean | null = null
return () => {
if (cached !== null)
return cached
cached = false
try {
// A packaged app carries its own copy beside the executable; otherwise ask
// Craft where it would look.
const bundled = join(dirname(process.execPath), 'craft')
const binary = existsSync(bundled) ? bundled : resolveCraftBinary(process.env.CRAFT_BINARY_PATH)
const probe = Bun.spawnSync([binary, '--version'])
// Craft prints its banner on stderr, so read both streams.
cached = supportsTrayIcon(parseCraftVersion(`${probe.stdout}${probe.stderr}`))
}
catch {
cached = false
}
return cached
}
})()
/** The shape both the popup and the tray read from. */
function baristaState(prefs: { getAll: () => BaristaPreferences }) {
const caffeinate = caffeinateSnapshot()
return {
...prefs.getAll(),
...caffeinate,
// The tray shows a cup, and spells the time out on hover.
trayGlyph: trayGlyph(caffeinate.active),
menuBarCollapsed,
}
}
const app = createMenuBarApp<BaristaPreferences>({
name: 'Barista',
template: resolve(import.meta.dir, 'src/barista.stx'),
templateSource,
preferences: DEFAULT_PREFERENCES,
launchAtLogin: 'autoLaunch',
window: {
width: 320,
height: 740,
hideDockIcon: !DEFAULT_PREFERENCES.showInDock,
},
context: (prefs) => {
// Exactly what GET /api/status returns, so the popup's signals and its
// first paint agree by construction.
const state = baristaState(prefs)
return {
...state,
durations: DURATIONS,
collapseDelays: COLLAPSE_DELAYS,
version: pkg.version,
// The popup seeds its signals from this rather than waiting a round trip
// and painting a stale panel first.
initialState: JSON.stringify(state),
}
},
menu: (prefs) => {
const caffeinate = caffeinateSnapshot()
return buildTrayMenu({
caffeinated: caffeinate.active,
remaining: caffeinate.remainingFormatted,
durationMinutes: prefs.get('caffeinateDurationMinutes'),
menuBarCollapsed,
isAutoCollapse: prefs.get('isAutoCollapse'),
})
},
routes: {
'/api/status': (_request, prefs) => baristaState(prefs),
/** Icon, tooltip and menu in one call — everything the tray needs to redraw. */
'/api/tray': (_request, prefs) => {
const caffeinate = caffeinateSnapshot()
const state = {
caffeinated: caffeinate.active,
remaining: caffeinate.remainingFormatted,
durationMinutes: prefs.get('caffeinateDurationMinutes'),
menuBarCollapsed,
isAutoCollapse: prefs.get('isAutoCollapse'),
}
return {
// An icon when the binary can draw one, a text cup when it cannot.
useIcon: trayIconSupported(),
icon: trayIcon(state.caffeinated),
glyph: trayGlyph(state.caffeinated),
tooltip: trayTooltip(state),
menu: buildTrayMenu(state),
}
},
'POST /api/caffeinate/toggle': (_request, prefs) => {
toggleCaffeinate(prefs.get('caffeinateDurationMinutes'))
return caffeinateSnapshot()
},
// Picking a duration also starts a session — choosing "4 hours" while
// asleep is a request to stay awake for four hours, not a bare preference.
'POST /api/caffeinate/duration': async (request, prefs) => {
const { minutes } = await request.json() as { minutes: number }
prefs.set('caffeinateDurationMinutes', minutes)
enableCaffeinate(minutes)
return caffeinateSnapshot()
},
'POST /api/caffeinate/disable': () => {
disableCaffeinate()
return caffeinateSnapshot()
},
'POST /api/menu-bar/state': async (request) => {
const { collapsed } = await request.json() as { collapsed: boolean }
menuBarCollapsed = collapsed
return { collapsed: menuBarCollapsed }
},
'/api/updates': () => updates.status(),
'POST /api/updates/check': () => updates.check(),
'POST /api/updates/install': async () => {
await updates.install()
return { installing: true }
},
},
})
if (app.preferences.get('caffeinateOnStartup'))
enableCaffeinate(app.preferences.get('caffeinateDurationMinutes'))
// Look for a new release in the background. No-ops when running from source,
// where there is no bundle to replace.
updates.start()
await app.start()
console.log(`Barista ${pkg.version} — ${app.url}`)