@trippnology/mixshell 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +294 -2
  3. package/assets/mixshell-screenshot.png +0 -0
  4. package/package.json +73 -5
  5. package/src/alsa-pulse.conf +20 -0
  6. package/src/alsa-setup.js +15 -0
  7. package/src/components/browser.js +193 -0
  8. package/src/components/config.js +168 -0
  9. package/src/components/durations.js +151 -0
  10. package/src/components/library.js +679 -0
  11. package/src/components/mediakeys.js +222 -0
  12. package/src/components/mpris.js +309 -0
  13. package/src/components/player.js +412 -0
  14. package/src/components/playlist.js +335 -0
  15. package/src/components/session.js +96 -0
  16. package/src/constants.js +164 -0
  17. package/src/engines/ffmpeg.js +601 -0
  18. package/src/engines/index.js +14 -0
  19. package/src/engines/webaudio.js +317 -0
  20. package/src/index.js +188 -0
  21. package/src/mediakeys/macos-nowplaying.js +227 -0
  22. package/src/ui/app.js +56 -0
  23. package/src/ui/artPane.js +314 -0
  24. package/src/ui/confirmPrompt.js +34 -0
  25. package/src/ui/constants.js +133 -0
  26. package/src/ui/controller.js +1641 -0
  27. package/src/ui/dom.js +9 -0
  28. package/src/ui/goToPrompt.js +105 -0
  29. package/src/ui/index.html +78 -0
  30. package/src/ui/libraryPanel.js +415 -0
  31. package/src/ui/listView.js +209 -0
  32. package/src/ui/onboarding.js +353 -0
  33. package/src/ui/playlistPanel.js +207 -0
  34. package/src/ui/settingsPanel.js +473 -0
  35. package/src/ui/shortcuts.js +30 -0
  36. package/src/ui/splash.js +302 -0
  37. package/src/ui/style.css +532 -0
  38. package/src/ui/subtabs.js +31 -0
  39. package/src/ui/visualizer/bars.js +74 -0
  40. package/src/ui/visualizer/circles.js +64 -0
  41. package/src/ui/visualizer/color.js +61 -0
  42. package/src/ui/visualizer/cube.js +105 -0
  43. package/src/ui/visualizer/grid.js +68 -0
  44. package/src/ui/visualizer/index.js +65 -0
  45. package/src/ui/visualizer/onset.js +130 -0
  46. package/src/ui/visualizer/spectrum.js +34 -0
  47. package/src/ui/visualizer/vu.js +71 -0
  48. package/src/ui/visualizer/waveform.js +58 -0
  49. package/src/utils/audioAnalyzer.js +362 -0
  50. package/src/utils/audioDevices.js +222 -0
  51. package/src/utils/cellart.js +75 -0
  52. package/src/utils/debug.js +7 -0
  53. package/src/utils/durationProbe.js +48 -0
  54. package/src/utils/folderArt.js +46 -0
  55. package/src/utils/format.js +20 -0
  56. package/src/utils/id3.js +84 -0
  57. package/src/utils/pathInput.js +76 -0
  58. package/src/utils/playlistIO.js +176 -0
  59. package/src/utils/terminalGraphics.js +47 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Rikki Tripp - Trippnology
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,295 @@
1
- # Temporary Holding Version
1
+ # MixShell
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A console-based music player that is deliberately easy to use. No vim
4
+ keybindings, no command language, no modes to learn — browse with the
5
+ arrow keys, press `Enter` to play, and every shortcut is labelled in the
6
+ footer. If you can use a file manager, you already know how to drive it.
7
+
8
+ Under the hood it renders a full terminal UI
9
+ ([@b9g/termdom](https://github.com/bikeshaving/termdom)): plays everything
10
+ ffmpeg can decode (MP3, FLAC, WAV, OGG, m4a, …), shows
11
+ [album art](#album-art), and runs a live visualizer — all in the terminal.
12
+
13
+ ![MixShell's Main tab showing album art and keyboard shortcuts in the footer](assets/mixshell-screenshot.png)
14
+
15
+ MixShell is in beta. It works well for its author on Linux, but has had few
16
+ other users yet. Feedback, bug reports, and macOS reports (see
17
+ [Media keys](#macos)) are very welcome at
18
+ [github.com/Trippnology/mixshell/issues](https://github.com/Trippnology/mixshell/issues).
19
+
20
+ One thing to know before you ask, though: MixShell is deliberately simple
21
+ and will stay that way. It plays music and gets out of the way, and it
22
+ will not gain advanced features such as tag editing, an equaliser,
23
+ scrobbling, or smart playlists — requests for them will be politely
24
+ declined. Bugs and small improvements to what's already there are another
25
+ matter; those are very welcome.
26
+
27
+ ## Installation
28
+
29
+ You'll need [Node.js](https://nodejs.org) 22.12.0 or newer (check with
30
+ `node --version`). Then:
31
+
32
+ ```sh
33
+ npm install -g @trippnology/mixshell
34
+ ```
35
+
36
+ That's it — everything else MixShell needs, including its own copy of
37
+ ffmpeg, is downloaded automatically during install.
38
+
39
+ ## Usage
40
+
41
+ ```sh
42
+ mixshell # start in your saved media directory, or home on first run
43
+ mixshell -d /path/to/music # start in a media directory
44
+ mixshell -p ./playlist.json # load a saved playlist
45
+ ```
46
+
47
+ Everything on screen can be reached with the arrow keys and `Enter`, and
48
+ the keys you can press are always listed in the footer. The global keys:
49
+ `Space` play/pause, `n`/`p` next/previous, `s` stop, `m` mute. `1`–`5`
50
+ switch tabs in the order shown in the header (`6` with `--debug`); `q`
51
+ quits. The arrow keys depend on the tab: `↑`/`↓` volume and `←`/`→` seek
52
+ on Main; `↑`/`↓` select on Playlist, Library, Browser and Settings;
53
+ `←`/`→` Back/Open on Browser, step ±1 on Settings. `w` save playlist is
54
+ on Playlist only.
55
+
56
+ `Enter` plays what's under the cursor; `Alt+Enter` adds it to the queue
57
+ instead. In the browser, `a` adds every audio file under the browsed
58
+ directory — including subdirectories. Press `g` to type a directory path
59
+ (relative paths start from the directory you're viewing), `←` to go back or
60
+ up, and `→` to open the highlighted folder.
61
+
62
+ By default, queueing the first track into an empty queue starts it playing
63
+ straight away. To queue tracks without playback starting, switch off
64
+ **Settings → General → Auto-play First Queued** (or set
65
+ `"play_when_first_track_queued": false` in `~/mixshell/config.json`). The
66
+ change takes effect immediately.
67
+
68
+ ## Sound
69
+
70
+ MixShell ships two ways to play sound. The default works everywhere with
71
+ no extra setup, so you can skip this section unless something won't play
72
+ or you like tinkering. Switch in **Settings → General → Audio Engine** —
73
+ the choice is saved and takes effect the next time you press play.
74
+
75
+ | | `ffmpeg` (default) | `webaudio` |
76
+ | ------------ | ---------------------------------- | --------------------------------------------- |
77
+ | Extra setup | none | Linux: needs `pipewire-jack` (see below) |
78
+ | File types | anything ffmpeg can decode | MP3, FLAC, WAV, OGG, m4a |
79
+ | Memory use | streams the file, stays constant | loads the whole file into memory (~21 MB/min) |
80
+ | Sound device | pick any output device in Settings | system default only |
81
+
82
+ Which to pick? The default is the safe choice: no system dependencies,
83
+ small memory footprint, and any output device. The `webaudio` option can
84
+ play a little more smoothly when the terminal is busy, and it's the
85
+ automatic fallback on unusual platforms where the default's audio library
86
+ won't build. Both engines pass the same test suite, and holding down a
87
+ key to scroll fast through your library is glitch-free on both.
88
+
89
+ If `webaudio` can't start a sound session (for example, its optional
90
+ package didn't install), the current track is skipped with an error
91
+ message and playback carries on — switch back to `ffmpeg` and nothing
92
+ else changes.
93
+
94
+ ## Album art
95
+
96
+ Nothing to set up. MixShell checks what your terminal can draw when it
97
+ starts, and shows the cover the best way it can:
98
+
99
+ - In **kitty** or **Ghostty**, the cover is a real image, drawn at the
100
+ full resolution of the space it takes up.
101
+ - In every other terminal, the same cover is drawn with block characters
102
+ instead — the same picture in the same colours, just chunkier. Nothing
103
+ else changes.
104
+
105
+ Inside tmux, the real image needs tmux's `allow-passthrough` option
106
+ (`set -g allow-passthrough on`); with it off you get the block version.
107
+
108
+ Prefer the classic character look? **Settings → UI → Album Art Style**
109
+ (`"albumArtStyle"` in `config.json`) swaps the cover for a rendition in
110
+ plain characters — shade ramps, ones and zeros, or Braille — that doesn't
111
+ depend on which terminal you use. The change applies immediately.
112
+ `blocks`, the default, is the style that becomes a real image in kitty
113
+ and Ghostty.
114
+
115
+ ## Media keys and desktop remote control
116
+
117
+ ### Linux
118
+
119
+ On a Linux desktop your keyboard's media keys (play/pause, next,
120
+ previous), `playerctl`, and desktop tray controls work while MixShell is
121
+ running:
122
+
123
+ ```sh
124
+ playerctl -p mixshell status
125
+ playerctl -p mixshell play-pause
126
+ playerctl -p mixshell next
127
+ playerctl -p mixshell volume 0.8
128
+ ```
129
+
130
+ This uses the optional `dbus-next` package, which normally installs
131
+ automatically. If it's missing — or you're on a headless machine —
132
+ MixShell simply runs without it. Nothing else changes.
133
+
134
+ ### macOS
135
+
136
+ Your keyboard's media keys and the Control Center playback controls
137
+ drive MixShell while it runs, and Now Playing shows the current track.
138
+
139
+ It's off by default. Switch it on in **Settings → General → Media Keys**
140
+ (or set `"mediaKeys": true` in `~/mixshell/config.json`) and restart
141
+ MixShell. The setting only appears on macOS; elsewhere the
142
+ `"mediaKeys": false` line in `config.json` does nothing.
143
+
144
+ There's nothing to install — no npm package and no compiler. MixShell
145
+ runs a small built-in helper through macOS's own `osascript`. If the
146
+ helper can't start, MixShell logs one debug line and runs as usual.
147
+
148
+ This was written without access to a Mac and is untested on real
149
+ hardware. Reports from macOS users — working or not — are very welcome.
150
+
151
+ ### Windows
152
+
153
+ Not supported yet. The API to target is SMTC (System Media Transport
154
+ Controls); pull requests welcome.
155
+
156
+ ## Where MixShell keeps its data
157
+
158
+ All your settings and library data live in one folder, `~/mixshell/`.
159
+ Back it up, move it, or delete it as a unit. To put it somewhere else,
160
+ set the `MIXSHELL_DIR` environment variable.
161
+
162
+ ## Configuration
163
+
164
+ Every option below can be changed in Settings — you don't need to edit
165
+ `config.json` by hand. The headings match the Settings screens, and each
166
+ row names the setting you want. Changes are saved as soon as you make them
167
+ (except Media Keys, which takes effect on the next start).
168
+
169
+ ### General
170
+
171
+ - **Media Directory** — `mediaDirectory`: a path (default: your home dir).
172
+ - **Output device** — `audioDevice`: a device id, or `null` for the system
173
+ default. The `MIXSHELL_AUDIO_DEVICE` environment variable overrides it.
174
+ - **Audio Engine** — `audioEngine`: `ffmpeg` (default) or `webaudio`.
175
+ - **Volume Step** — `volumeStep`: `1`, `2`, `5` (default) or `10`, in percent.
176
+ - **Seek Step** — `seekStep`: `5` (default), `10`, `15` or `30` seconds.
177
+ - **Playlist Save Format** — `playlistSaveFormat`: `m3u` (default) or `pls`.
178
+ - **Auto-play First Queued** — `play_when_first_track_queued`: `true`
179
+ (default) or `false`.
180
+ - **Media Keys** (macOS only) — `mediaKeys`: `false` (default) or `true`.
181
+
182
+ ### UI
183
+
184
+ - **Theme** — `theme`: `default` (default), `terminal`, `nord`, `dracula`,
185
+ `gruvbox`, `monokai`, `tokyo-night`, `solarized-dark` or `night-owl`.
186
+ `terminal` has no palette of its own: it uses the colours of whatever
187
+ colour scheme your terminal is configured with (its default foreground
188
+ and background, plus blue and bright black).
189
+ - **Album Art Style** — `albumArtStyle`: `blocks` (default), `basic`,
190
+ `binary`, `braille`, `braille_plus`, `medium` or `complex`.
191
+
192
+ ### Visualiser
193
+
194
+ - **Visualizer Quality** — `visualizerQuality`: `low`, `medium` or `high`
195
+ (default).
196
+ - **Visualizer FPS** — `visualizerFPS`: `5`, `7`, `10`, `15`, `30` or `60`
197
+ (default).
198
+ - **Visualizer Smoothing** — `visualizerSmoothing`: `1` (Off, default),
199
+ `0.9`, `0.7`, `0.5`, `0.3` or `0.1`.
200
+ - **FPS Counter** — `showFPS`: `false` (default) or `true`.
201
+
202
+ ### Library
203
+
204
+ - **Library Dirs** — `libraryDirs`: a list of paths to scan (default:
205
+ empty). Add one with `Shift+L` in the Browser; remove one in Settings.
206
+ - **Scan on Start** — `libraryScanOnStart`: `false` (default) or `true`.
207
+
208
+ MixShell also writes a few values to `config.json` as you use it, rather
209
+ than offering them as Settings rows: `volume` (0–1) and `visualizerMode`
210
+ (`vu`, `bars`, `waveform`, `circles`, `cube`, `albumart`, the default).
211
+ Volume changes with `↑`/`↓` on Main; visualizer mode changes with `v`.
212
+ The `onboarded` flag tracks first-run setup and is maintained by
213
+ **Settings → Library → Run setup again**.
214
+
215
+ ## Troubleshooting and advanced setup
216
+
217
+ **Node version.** Below Node 22.12.0, npm only _warns_ during install —
218
+ it finishes anyway, and MixShell then fails at startup with a module
219
+ error. If you see that, update Node rather than debugging the error.
220
+
221
+ **Optional dependencies.** Two npm packages MixShell uses are marked
222
+ optional — npm tolerates their install failing and MixShell runs without
223
+ them: `dbus-next` (media keys, above) and `node-web-audio-api` (the
224
+ `webaudio` engine, above).
225
+
226
+ **Keys in different terminals.** kitty, Ghostty, tmux, and xterm (via its
227
+ extended-keys protocol) also accept `Shift+Enter` (queue at bottom) and
228
+ `Ctrl+Enter` (queue after current track); `Ctrl+J` works as
229
+ queue-after-current in any terminal. Other terminals can't tell
230
+ `Shift+Enter` from plain `Enter`, so MixShell doesn't guess — use the
231
+ `Alt` spellings there.
232
+
233
+ **Choosing a sound device.** Settings → General → Output device opens a list
234
+ of your output devices; pick one with `↑`/`↓` and `Enter`. `←`/`→` on the row
235
+ step through devices directly. As an override (for scripts and launchers),
236
+ the default engine also honours the `MIXSHELL_AUDIO_DEVICE` environment
237
+ variable, e.g. `MIXSHELL_AUDIO_DEVICE=pulse:my-sink mixshell`.
238
+
239
+ **`webaudio` on Linux (JACK).** The `webaudio` prebuilts use the JACK
240
+ audio API. Most desktops running PipeWire just need the `pipewire-jack`
241
+ package. On Debian/Ubuntu that package installs its `libjack` outside the
242
+ dynamic loader's search path, so starting a session fails with
243
+ `DeviceUnavailable` until you either launch under the wrapper:
244
+
245
+ ```sh
246
+ pw-jack mixshell
247
+ ```
248
+
249
+ or make it permanent:
250
+
251
+ ```sh
252
+ sudo cp /usr/share/doc/pipewire/examples/ld.so.conf.d/pipewire-jack-x86_64-linux-gnu.conf /etc/ld.so.conf.d/
253
+ sudo ldconfig
254
+ ```
255
+
256
+ ## Contributing
257
+
258
+ Start with [DEVELOPMENT.md](DEVELOPMENT.md) — it covers setup, testing,
259
+ architecture, and the conventions (and gotchas) that keep changes from
260
+ breaking things silently. Coding agents should read [AGENTS.md](AGENTS.md),
261
+ the condensed version of the same document.
262
+
263
+ 1. Fork it!
264
+ 2. Create your feature branch: `git checkout -b my-new-feature develop`
265
+ 3. Commit your changes: `git commit -am 'Add some feature'`
266
+ 4. Push to the branch: `git push origin my-new-feature`
267
+ 5. Submit a pull request :D
268
+
269
+ ## History
270
+
271
+ MixShell began on 2 March 2025 as a small terminal MP3 player built on
272
+ [terminal-kit](https://github.com/cronvel/terminal-kit), with album art
273
+ drawn as ASCII. terminal-kit served it well for a year and a half, but
274
+ TermDOM came along and was a lot more enjoyable to work with: HTML, CSS and
275
+ a real DOM, in the terminal. The UI was rewritten on TermDOM in August 2026.
276
+
277
+ The rest followed quickly: ffmpeg decoding and a SQLite library (October
278
+ 2026), MPRIS and media keys, a second audio engine, native album art, and
279
+ five visualizer modes.
280
+
281
+ ## Credits
282
+
283
+ MixShell was created by [Trippnology](https://trippnology.com/), but it would not be possible without:
284
+
285
+ - **[Brian Kim](https://github.com/brainkim)** — author of
286
+ [TermDOM](https://github.com/bikeshaving/termdom), the terminal UI engine
287
+ MixShell is built on.
288
+ - **[titanism](https://github.com/titanism)** ([Forward Email](https://forwardemail.net)) —
289
+ TermDOM's `<img>` and `<canvas>` support
290
+ ([PR #125](https://github.com/bikeshaving/termdom/pull/125)), which
291
+ MixShell's album art is drawn with.
292
+
293
+ ## License
294
+
295
+ MIT — see [LICENSE](LICENSE).
Binary file
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
- "name": "@trippnology/mixshell",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@trippnology/mixshell",
3
+ "version": "0.7.0",
4
+ "description": "Terminal-based music player",
5
+ "main": "src/index.js",
6
+ "type": "module",
7
+ "bin": {
8
+ "mixshell": "src/index.js"
9
+ },
10
+ "engines": {
11
+ "node": ">=22.12.0"
12
+ },
13
+ "scripts": {
14
+ "start": "node src/index.js",
15
+ "test": "node node_modules/mocha/bin/mocha.js",
16
+ "lint": "node node_modules/@biomejs/biome/bin/biome check .",
17
+ "lint:fix": "node node_modules/@biomejs/biome/bin/biome check --write ."
18
+ },
19
+ "prepublishOnly": "npm test && npm run lint",
20
+ "files": [
21
+ "src",
22
+ "assets"
23
+ ],
24
+ "keywords": [
25
+ "music",
26
+ "player",
27
+ "terminal",
28
+ "console",
29
+ "tui"
30
+ ],
31
+ "author": "Rikki Tripp - Trippnology",
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/Trippnology/mixshell.git"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/Trippnology/mixshell/issues"
39
+ },
40
+ "homepage": "https://github.com/Trippnology/mixshell#readme",
41
+ "publishConfig": {
42
+ "registry": "https://registry.npmjs.org/"
43
+ },
44
+ "dependencies": {
45
+ "@b9g/termdom": "0.2.7",
46
+ "@ffmpeg-installer/ffmpeg": "1.1.0",
47
+ "better-sqlite3": "13.2.0",
48
+ "commander": "15.1.0",
49
+ "fft.js": "4.0.4",
50
+ "music-metadata": "12.7.0",
51
+ "speaker": "0.5.5"
52
+ },
53
+ "devDependencies": {
54
+ "@biomejs/biome": "2.6.8",
55
+ "chai": "6.3.0",
56
+ "mocha": "12.0.3"
57
+ },
58
+ "optionalDependencies": {
59
+ "dbus-next": "0.10.2",
60
+ "node-web-audio-api": "2.2.0"
61
+ },
62
+ "overrides": {
63
+ "node-gyp": "12.4.0"
64
+ },
65
+ "allowScripts": {
66
+ "@ffmpeg-installer/linux-x64@4.1.0": true,
67
+ "@ffmpeg-installer/linux-arm64@4.1.0": true,
68
+ "@ffmpeg-installer/darwin-x64@4.1.0": true,
69
+ "@ffmpeg-installer/darwin-arm64@4.1.0": true,
70
+ "@ffmpeg-installer/win32-x64@4.1.0": true,
71
+ "speaker@0.5.5": true,
72
+ "better-sqlite3@13.2.0": true
73
+ }
74
+ }
@@ -0,0 +1,20 @@
1
+ # Load the distro's full ALSA configuration first, then override the
2
+ # default PCM to PulseAudio. Without the include, standard device-name
3
+ # syntaxes (`hw:CARD=x,DEV=n`, `default:CARD=x`, …) are unknown — ALSA_CONFIG_PATH
4
+ # replaces the top-level config entirely.
5
+ </usr/share/alsa/alsa.conf>
6
+ pcm.!default {
7
+ type pulse
8
+ }
9
+ pcm.pulse {
10
+ @args [ DEVICE ]
11
+ @args.DEVICE {
12
+ type string
13
+ default ""
14
+ }
15
+ type pulse
16
+ device $DEVICE
17
+ }
18
+ ctl.!default {
19
+ type pulse
20
+ }
@@ -0,0 +1,15 @@
1
+ // Must be the first import in index.js: sets ALSA_CONFIG_PATH before any
2
+ // module (e.g. `speaker`) loads native ALSA bindings. The `speaker` binding
3
+ // opens the ALSA "default" device at module load time; on systems where
4
+ // "default" is broken (e.g. card 0 is a capture-only USB camera), that probe
5
+ // crashes with an ALSA assertion. Routing default through PulseAudio fixes it.
6
+ // Skipped when the user provides an explicit ALSA_CONFIG_PATH.
7
+ import { existsSync } from 'node:fs';
8
+ import { fileURLToPath } from 'node:url';
9
+
10
+ if (process.platform === 'linux' && !process.env.ALSA_CONFIG_PATH) {
11
+ const conf = fileURLToPath(new URL('./alsa-pulse.conf', import.meta.url));
12
+ if (existsSync(conf)) {
13
+ process.env.ALSA_CONFIG_PATH = conf;
14
+ }
15
+ }
@@ -0,0 +1,193 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ import { setImmediate as nextTask } from 'node:timers/promises';
6
+
7
+ import { isAudioFile, isPlaylistFile } from '../constants.js';
8
+ import { DBG } from '../utils/debug.js';
9
+ import { resolveDirectoryInput } from '../utils/pathInput.js';
10
+
11
+ // Entries walked between event-loop yields. Mirrors the library scan
12
+ // walker (issues/031) so a big collectAudioFiles() pass keeps the TUI
13
+ // painting instead of freezing on one synchronous traversal.
14
+ const WALK_YIELD = 50;
15
+
16
+ export class Browser extends EventEmitter {
17
+ constructor(initialDirectory) {
18
+ super();
19
+ this.currentDirectory = initialDirectory || process.cwd();
20
+ this.entries = [];
21
+ this.selectedIndex = 0;
22
+ this.history = [];
23
+ this.previousDirectoryName = null;
24
+ // Reason for the last failed loadDirectory, as { path, error };
25
+ // null after a success (issues/054).
26
+ this.lastError = null;
27
+
28
+ // Load the initial directory
29
+ this.loadDirectory(this.currentDirectory);
30
+ }
31
+
32
+ loadDirectory(dirPath, skipHistory = false) {
33
+ this.lastError = null;
34
+ try {
35
+ // Reuse the shared validation so failures carry the same reason
36
+ // as the Go to prompt (issues/054).
37
+ const { error } = resolveDirectoryInput(dirPath);
38
+ if (error) {
39
+ DBG(`browser: invalid directory: ${dirPath}`);
40
+ this.lastError = { path: dirPath, error };
41
+ return false;
42
+ }
43
+
44
+ // Read and build the listing before mutating state: a failure
45
+ // keeps the current directory, entries and cursor intact.
46
+ const items = fs.readdirSync(dirPath, { withFileTypes: true });
47
+ const entries = items.map((item) => {
48
+ const fullPath = path.join(dirPath, item.name);
49
+ // Dirent.isDirectory() is false for symlinks; a guarded stat
50
+ // follows the link so linked folders list and open like real
51
+ // ones (issues/051). Broken links stay plain rows.
52
+ let isDirectory = item.isDirectory();
53
+ if (item.isSymbolicLink()) {
54
+ try {
55
+ isDirectory = fs.statSync(fullPath).isDirectory();
56
+ } catch {
57
+ isDirectory = false;
58
+ }
59
+ }
60
+ const isAudio = !isDirectory && isAudioFile(item.name);
61
+ // Playlist containers (issues/028) are listed and loadable but
62
+ // never decode as audio.
63
+ const isPlaylist = !isDirectory && isPlaylistFile(item.name);
64
+
65
+ return {
66
+ name: item.name,
67
+ path: fullPath,
68
+ isDirectory,
69
+ isAudio,
70
+ isPlaylist,
71
+ };
72
+ });
73
+
74
+ // Sort: directories first, then files
75
+ entries.sort((a, b) => {
76
+ if (a.isDirectory && !b.isDirectory) return -1;
77
+ if (!a.isDirectory && b.isDirectory) return 1;
78
+ return a.name.localeCompare(b.name);
79
+ });
80
+
81
+ // Add parent directory entry at the top (except for root paths)
82
+ if (path.resolve(dirPath) !== path.resolve('/')) {
83
+ entries.unshift({
84
+ name: '..',
85
+ path: path.join(dirPath, '..'),
86
+ isDirectory: true,
87
+ isAudio: false,
88
+ });
89
+ }
90
+
91
+ const oldDirectory = this.currentDirectory;
92
+ const goingUp = this.isParentDirectory(oldDirectory, dirPath);
93
+ if (oldDirectory !== dirPath && !skipHistory) {
94
+ this.history.push(oldDirectory);
95
+ }
96
+ if (oldDirectory && (skipHistory || !goingUp)) {
97
+ this.previousDirectoryName = path.basename(oldDirectory);
98
+ }
99
+ this.currentDirectory = dirPath;
100
+ this.entries = entries;
101
+ if (this.previousDirectoryName && goingUp) {
102
+ const previousIndex = entries.findIndex(
103
+ (entry) => entry.name === this.previousDirectoryName,
104
+ );
105
+ this.selectedIndex = Math.max(previousIndex, 0);
106
+ this.previousDirectoryName = null; // Clear after use
107
+ } else {
108
+ this.selectedIndex = 0;
109
+ }
110
+ this.emit('directoryLoaded', dirPath, this.entries);
111
+ return true;
112
+ } catch (error) {
113
+ DBG(`browser: load failed: ${error.message}`);
114
+ this.lastError = { path: dirPath, error: error.message };
115
+ return false;
116
+ }
117
+ }
118
+
119
+ goBack() {
120
+ if (this.history.length > 0) {
121
+ const previousDir = this.history.pop();
122
+ this.loadDirectory(previousDir, true); // true = skipHistory
123
+ return true;
124
+ }
125
+ // Fresh launch: ← climbs to the parent, same as the onboarding
126
+ // picker. At the filesystem root there is nowhere to go (issues/051).
127
+ const parent = path.resolve(this.currentDirectory, '..');
128
+ if (parent === path.resolve(this.currentDirectory)) return false;
129
+ return this.loadDirectory(parent, true);
130
+ }
131
+
132
+ isParentDirectory(child, parent) {
133
+ if (!parent) return false;
134
+ const resolvedChild = path.resolve(child);
135
+ const resolvedParent = path.resolve(parent);
136
+ const relative = path.relative(resolvedParent, resolvedChild);
137
+ // Parent if relative path doesn't start with '..'
138
+ return !relative.startsWith('..');
139
+ }
140
+
141
+ getSelected() {
142
+ return this.entries[this.selectedIndex] || null;
143
+ }
144
+
145
+ openSelected() {
146
+ const selected = this.getSelected();
147
+ if (!selected) return null;
148
+
149
+ if (selected.isDirectory) {
150
+ this.loadDirectory(selected.path);
151
+ return { type: 'directory', path: selected.path };
152
+ } else if (selected.isAudio) {
153
+ this.emit('fileSelected', selected);
154
+ return { type: 'file', path: selected.path };
155
+ }
156
+
157
+ return null;
158
+ }
159
+
160
+ findAudioFiles() {
161
+ return this.entries.filter((entry) => entry.isAudio);
162
+ }
163
+
164
+ // Recursive collector (issues/039): every audio file under dirPath,
165
+ // per-directory alphabetical, depth first, so repeated actions give
166
+ // stable queues. Traversal rules mirror the library scan walker
167
+ // (library.js #walk): only real directories are descended (Dirent
168
+ // isDirectory() is false for symlinks, so links never escape the
169
+ // tree), unreadable directories are skipped, and dot-prefixed
170
+ // files/directories are ignored. Playlist containers are parse
171
+ // targets, never decodeable audio.
172
+ async collectAudioFiles(dirPath = this.currentDirectory, out = []) {
173
+ let entries;
174
+ try {
175
+ entries = fs.readdirSync(dirPath, { withFileTypes: true });
176
+ } catch {
177
+ return out; // unreadable/missing directory — skip, don't fail
178
+ }
179
+ entries.sort((a, b) => a.name.localeCompare(b.name));
180
+ let walked = 0;
181
+ for (const entry of entries) {
182
+ if (entry.name.startsWith('.')) continue;
183
+ const fullPath = path.join(dirPath, entry.name);
184
+ if (entry.isDirectory()) {
185
+ await this.collectAudioFiles(fullPath, out);
186
+ } else if (entry.isFile() && isAudioFile(entry.name)) {
187
+ out.push({ path: fullPath });
188
+ }
189
+ if (++walked % WALK_YIELD === 0) await nextTask();
190
+ }
191
+ return out;
192
+ }
193
+ }