Compare commits

..

86 Commits

Author SHA1 Message Date
c63e9e1b9c bump VERSION to 0.2.1
Some checks failed
release / Attach to GitHub Release (push) Blocked by required conditions
release / build (macos-14 / arm64) (push) Waiting to run
release / build (ubuntu-24.04-arm / arm64) (push) Waiting to run
release / build (macos-15-intel / x64) (push) Waiting to run
release / build (ubuntu-latest / x64) (push) Failing after 51m15s
2026-08-08 08:02:53 -04:00
0facfff51b docs: document AUR packaging sync in release steps; CI uploads LICENSE asset 2026-08-08 07:17:27 -04:00
3ef19f80b8 drop oauth plan (copy config) 2026-08-08 07:10:59 -04:00
13a31aabdc docs: mark AUR package as pending registration reopen 2026-08-08 07:09:07 -04:00
8dbdebfd30 AUR: fetch LICENSE as release asset, install to licenses dir; sync .SRCINFO 2026-08-07 20:11:43 -04:00
529817323d add MIT license, podtui-bin AUR PKGBUILD, fix README install sections 2026-08-07 20:09:30 -04:00
ace883b505 docs: reference scripts/release-tag.sh in Releasing section 2026-08-07 19:38:20 -04:00
de01cedee0 add scripts/release-tag.sh: interactive vX.Y.Z bump, tag, dual-remote push
Some checks failed
release / build (ubuntu-latest / x64) (push) Failing after 51m26s
release / build (macos-14 / arm64) (push) Has been cancelled
release / build (ubuntu-24.04-arm / arm64) (push) Has been cancelled
release / build (macos-15-intel / x64) (push) Has been cancelled
release / Attach to GitHub Release (push) Has been cancelled
2026-08-07 19:36:07 -04:00
2730fa3cae bump VERSION to 0.2.0 2026-08-07 19:32:48 -04:00
91a831c5f9 audio playback fixes 2026-08-07 19:28:57 -04:00
52e9ae0ab7 fix(discover): correct 5 wrong RSS feed URLs in featured.json
The original featured.json had 5 entries pointing at the wrong podcasts
because verification only checked the feed's <title> loosely matched.
Each wrong URL happened to share a slug/name with the intended show:

  - All-In Podcast: feeds.transistor.fm/all-in was a Verizon internal
    comms show (6 eps from 2020), not the Chamath/Sacks/Friedberg/
    Calacanis show. -> allinchamathjason.libsyn.com/rss (405 eps)
  - Code Switch: NPR feed ID 510352 was 'I\'ll Be Seeing You'.
    -> 510312 (correct Code Switch feed, 637 eps)
  - Stuff You Should Know: rss.art19.com/stuff-you-should-know was a
    different show by 'Podgo' (7 eps). -> iHeart omnycontent URL
    (2855 eps, Josh Clark & Chuck Bryant)
  - Philosophize This!: feed.podbean.com/... returned 0 items.
    -> philosophizethis.libsyn.com/rss (189 eps, Stephen West)
  - Very Bad Wizards: feed.podbean.com/... returned 0 items.
    -> feeds.libsyn.com/474285/rss (345 eps, official feed)

Bumps version 1 -> 2 so the discover store re-fetches immediately.
All 5 corrected URLs verified: 200 OK, valid RSS, matching <title>
and <itunes:author>, sensible episode counts, recent pubDates.
2026-08-07 19:12:08 -04:00
64d8b40e61 actual featured page 2026-08-07 18:59:25 -04:00
0cc15c8d90 fix lint: make bun tsc --noEmit actually pass (was a TS crash + latent errors)
tsconfig used jsx:"preserve"+jsxImportSource, which trips a TS 5.9
internal crash ("Expected sourceFile.imports[0] to be the synthesized JSX
runtime import") so tsc could never run clean. Switch to jsx:"react-jsx"
with the package's real jsx-runtime types, and fix the real errors that
surfaced:
- delete dead src/components/Navigation.tsx (imported ./Tab that doesn't
  exist; the component has no importers)
- PlaybackControls: fix relative path to @/utils/audio-player
- SourceBadge: drop dead module-level typeColor (bare 'theme')
- command palette: bind to the real 'command' keybind (:) instead of the
  never-defined 'command_list' action (palette was unreachable)
- yazi-pane-row test: destroy() must return Promise<void> as typed

Also fold in the package.json lint fix (bun tsc --noEmit) and doc polish.
2026-08-07 18:18:25 -04:00
1d3abd53d4 docs: add human-oriented CONTRIBUTING.md (repo map, FFI notes, gotchas, release & tap auto-sync workflow) 2026-08-07 18:09:51 -04:00
592cfd4093 fix search navigation 2026-08-07 17:46:27 -04:00
69e12cf5b9 fix: podtui binary crashed with 'preload not found' when launched from repo root
The embedded runtime reads the CWD bunfig.toml at startup; the repo's
top-level 'preload = ["@opentui/solid/preload"]' made the standalone die
because that module isn't bundled. Removed the ambient preload from
bunfig.toml and moved the solid transform registration to explicit
--preload flags in the start/dev scripts ([test] preload untouched).

Verified: binary boots from repo root, from a clean dir, and dev/start
still work; bun test 54 pass. No new release needed — the binaries were
never config-dependent; this was purely the repo's bunfig trap.
2026-08-07 17:36:11 -04:00
c9e3aa92ec fix release pipeline: vendored cava source, fftw in CI, runner arch, smoke test
- Vendor cava/cavacore.c + header (MIT, from karlstav/cava) — the FFI build
  referenced cava/cavacore.c which was never committed, so every CI runner
  failed at scripts/build-cavacore.sh and no release was possible.
- build-cavacore.sh: discover libfftw3.a across Homebrew and Debian/Ubuntu
  multiarch paths (FFTW_PREFIX override preserved).
- release.yml: install fftw before building cavacore; run the boot smoke test
  from a bunfig-free dir (the embedded runtime reads the CWD bunfig.toml and
  this repo's preload entry breaks it — 'preload not found'); use
  macos-15-intel for darwin-x64 (macos-latest is arm64).
- Makefile/build.ts: drop the no-op BUN_CONFIG=bunfig.standalone.toml compile
  dance (Bun never honored it; compile output is config-independent); delete
  bunfig.standalone.toml.
2026-08-07 14:27:35 -04:00
25fe7f6ac9 theme rendering 2026-08-07 13:42:03 -04:00
85cb9fba26 ui cleanup 2026-08-07 13:38:32 -04:00
c8d29ed59d fix navigation flow 2026-08-07 00:28:24 -04:00
9e7a44309a Merge branch 'verify-remake' 2026-07-31 19:31:11 -04:00
6cd90ad6c0 docs(yazi-remake): mark task 07 blocked, file task 04 blocker for player/search panes
The verification gate found that Task 04's core deliverable was never
implemented: Player and Search pages are not routed through <YaziPaneRow>,
so Player renders a single full-width column and Search's three columns
sit at equal thirds (31/32/31) instead of the target 1:3:3 ratio
(~14/43/43).

- Mark task 07 status BLOCKED with a pointer to the blocker evidence
- Add 07-blocker-task-04-player-search.md documenting the missing
  implementation, evidence (player/search harness frames), failing exit
  criteria, and a fix plan for the task 04 do-over
2026-07-31 19:30:40 -04:00
6c0affc77b Merge branch 'rewire-keybinds' 2026-07-31 19:20:42 -04:00
b24c83711d refactor(keybinds): extract unified action dispatcher
Move the keybind router out of Shell into a reusable createDispatcher
in @/utils/dispatch, covering tabs (digits 1-6, [/]), h/l depth
drill/pop + fixed-pane swipe, modes, audio transport, quit/help, and
command, delegating pane/list actions over the nav.action event bus.

Shell now renders the active page full-width with a bottom status bar
carrying the tab strip; the old sidebar pane and its leftover sidebar
action handling are removed. Adds tests covering the dispatcher's
routing behavior.
2026-07-31 19:19:20 -04:00
866fcd7574 Merge branch 'rebuild-shell-chrome' 2026-07-31 19:06:18 -04:00
7c7d487ca6 refactor: move tab strip from left sidebar to bottom status bar
- Remove the left tab sidebar containing tab labels and now-playing
- Render tabs as compact labels in the command bar row instead
- Move now-playing display next to the selection count in the status bar
- All tabs remain functional; clicking a tab label switches the active tab
2026-07-31 19:05:43 -04:00
798178f21f Merge branch 'convert-list-tabs-to-primitive' 2026-07-31 17:55:37 -04:00
3f61303756 refactor(yazi): render depth-stack list tabs through YaziPaneRow primitive
Convert Discover, Feed, MyShows, and Settings pages from bespoke 3-column
flexbox JSX to render entirely via the shared <YaziPaneRow> parent|current|
preview primitive. Each page now supplies parent/current/preview content
accessors plus labels; the pane row handles layout, borders, focus styling,
and the muted placeholder for the blank parent slot at depth 0.

Replace Solid's children() helper in YaziPaneRow with a local normalizeContent
that hands the raw accessor to a reactive
expression. children() flattens to a stable resolved-nodes array and does not
re-resolve on truthy<->truthy root swaps (e.g. depth switching a pane's root
between a list fragment and an editor), which would freeze the previous
subtree. The insert effect from the reactive expression disposes and
remounts on element-identity change instead.

Add tests/yazi-pages-depth.test.ts covering the nav-store depth-stack
contract the pages depend on (push/pop stack growth, parent-slot data model
across root→child→grandchild→pop transitions).
2026-07-31 17:54:22 -04:00
139a258987 Merge branch 'rearchitect-nav-model'
# Conflicts:
#	src/utils/navigation.ts
2026-07-31 17:12:14 -04:00
cfa4ef0c47 refactor(nav): route tab switches through single switchTab path
Replace reactive / usage in the navigation
store with imperative functions so behavior is identical under both the
client JSX runtime and the server build used by unit tests (where
/ are no-ops).

- Centralize tab-switch side effects (root-frame seed, pane/mode/
  command/visual reset) in , invoked by a single
   helper used by gotoTab/nextTab/prevTab.
- Convert depthStack/currentDepth/topFrame/selectedIds from
  to plain functions that recompute on every read while still tracking
  underlying signals in reactive contexts.
2026-07-31 16:59:20 -04:00
5b667367a5 feat(layout): add YaziPaneRow 3-pane layout primitive
Add the shared parent | current | preview row primitive that implements
yazi's mgr.ratio = [1, 3, 3] contract via Yoga flexGrow, so every list
tab renders an identical, layout-stable shell regardless of terminal
size.

- New YaziPaneRow component: three bordered columns grow at 1/7 : 3/7
  : 3/7 with flexBasis=0 (content can never stretch its slot). The
  current column carries the accent focus ring when `focused` is
  truthy; parent and preview stay muted. The blank parent keeps its
  1/7 slot with a muted placeholder rather than collapsing.
- PANE_RATIO.current 4 -> 3 to match yazi's [1, 3, 3].
- Add render-based tests covering the 1:3:3 ratios (incl. null
  parent/preview) and the focused/unfocused accent ring behavior.
- Configure the bun test preload for the solid JSX transform.
2026-07-31 16:58:33 -04:00
b1bb9d9a1e refactor: rearchitect navigation model with pure store and no sidebar pane
- Extract navigation state and logic into navigation-store.ts for
  testability and separation of concerns
- NavigationContext now only wraps the store as a Solid provider
- Remove SIDEBAR_PANE from the model; depth-tabs have a single
  focusable content pane (center/current column)
- Split LayerGraph and page imports into layer-graph.ts so the
  navigation utils stay free of JSX (unit-testable)
- Update Shell keybind dispatch: remove sidebar pane handling,
  simplify swipe to fixed-pane tabs only, clarify depth-tab h/l
- Add nav-model.test.ts covering depth stack, tab/pane focus, and
  selection semantics
2026-07-31 10:24:45 -04:00
21b088b5a9 redesign tasks 2026-07-31 09:27:57 -04:00
97b2f61e5f pre-ui-rearch 2026-07-31 01:05:32 -04:00
89c5ca2f7e harness improvements 2026-07-30 21:30:37 -04:00
d8f11040bc start revive 2026-07-30 21:25:03 -04:00
b7c4938c54 Auto-commit 2026-03-11 16:27 2026-03-11 16:27:26 -04:00
256f112512 remove unneeded 2026-03-08 23:12:07 -04:00
8196ac8e31 fix: implement page-specific tab depth navigation
- Changed nextPane/prevPane to use current tab's pane count instead of global TabsCount
- Added Page-specific pane counts mapping for accurate depth calculation
- Pages with 1 pane (Feed, Player) now skip depth navigation
- Fixed wrapping logic to respect each page's layout structure
2026-03-08 21:01:33 -04:00
f003377f0d some nav cleanup 2026-03-08 19:25:48 -04:00
1618588a30 cycle 2026-02-22 19:07:07 -05:00
c9a370a424 more keyboard handling 2026-02-21 00:46:36 -05:00
b45e7bf538 temp keyboard handling 2026-02-20 23:42:29 -05:00
1e6618211a more indication 2026-02-20 22:42:15 -05:00
1a5efceebd device switch 2026-02-20 21:58:49 -05:00
0c16353e2e fix nav context 2026-02-20 01:28:46 -05:00
8d350d9eb5 navigation controls + starting indicators 2026-02-20 01:13:32 -05:00
cc09786592 sort fix 2026-02-19 21:15:38 -05:00
cedf099910 working indicator (simpler) 2026-02-19 20:45:48 -05:00
d1e1dd28b4 nonworking indicator, sort broken 2026-02-19 17:52:57 -05:00
1c65c85d02 redoing navigation logic to favor more local 2026-02-19 15:59:50 -05:00
8e0f90f449 nonworking keybinds 2026-02-13 17:25:32 -05:00
91fcaa9b9e getting keybinds going 2026-02-12 17:39:52 -05:00
0bbb327b29 using presets 2026-02-12 09:27:49 -05:00
276732d2a9 continued out the reuse 2026-02-12 00:11:56 -05:00
72000b362d use of selectable 2026-02-11 21:57:17 -05:00
9a2b790897 for consistency 2026-02-11 14:10:35 -05:00
2dfc96321b colors 2026-02-11 11:16:18 -05:00
3d5bc84550 set 2026-02-10 15:30:53 -05:00
f707594d0c more theme color integration 2026-02-10 15:10:07 -05:00
a405474f11 better themeing 2026-02-10 14:28:06 -05:00
ce022dc447 add explicit width 2026-02-10 13:15:25 -05:00
6053d4d02c keybinds 2026-02-10 01:26:18 -05:00
64a2ba2751 simple 2026-02-07 22:30:51 -05:00
bcf248f7dd renders 2026-02-07 19:05:45 -05:00
5bd393c9cd cooking 2026-02-07 18:45:13 -05:00
627fb65547 sketching out layout structure, cleaning Discover 2026-02-07 16:44:49 -05:00
73aa211229 janitorial work 2026-02-07 15:12:34 -05:00
7eb49ac1c7 on left 2026-02-07 14:53:22 -05:00
19a1f1a43b add agents file 2026-02-07 12:01:36 -05:00
2e323d283f needs testing 2026-02-07 00:45:14 -05:00
46f9135776 flatten 2026-02-07 00:44:52 -05:00
db74e20571 better copying 2026-02-06 16:51:00 -05:00
70f50eec2a covert html on fetch instead 2026-02-06 16:45:34 -05:00
1cee931913 understanding 2026-02-06 16:29:09 -05:00
bfea6816ef dead 2026-02-06 15:02:21 -05:00
75f1f7d6af remove migration code 2026-02-06 15:00:21 -05:00
1e3b794b8e file ordering 2026-02-06 14:55:42 -05:00
1293d30225 starting janitorial work 2026-02-06 13:41:44 -05:00
920042ee2a fix stream multiplaction 2026-02-06 11:47:48 -05:00
e1dc242b1d better visualizer 2026-02-06 11:08:41 -05:00
8d6b19582c implementing cava for real time visualization 2026-02-06 10:11:51 -05:00
63ded34a6b basic clean 2026-02-06 09:57:33 -05:00
0e4f47323f mulitmedia pass, downloads 2026-02-06 00:00:15 -05:00
42a1ddf458 meh 2026-02-05 23:43:19 -05:00
168e6d5a61 final feature set 2026-02-05 22:55:24 -05:00
247 changed files with 17627 additions and 12436 deletions

100
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,100 @@
name: release
# Builds standalone PodTui binaries for each supported OS/arch and attaches
# them to a GitHub Release. One runner per platform because Bun cannot
# cross-compile — each runner runs `make dist`, which emits a
# podtui-<platform>-<arch>.tar.gz (binary + native libs side by side).
#
# Trigger: push a tag like v0.1.0. Bump VERSION in src/index.tsx in the same
# commit as the tag so the released binary reports the tagged version.
on: # intentional: YAML `on` key
push:
tags:
- "v*"
permissions:
contents: write
jobs:
build:
name: build (${{ matrix.os }} / ${{ matrix.arch }})
runs-on: ${{ matrix.os }}
strategy:
matrix:
include:
- os: ubuntu-latest
arch: x64
plat: linux
- os: ubuntu-24.04-arm
arch: arm64
plat: linux
- os: macos-15-intel
arch: x64
plat: darwin
- os: macos-14
arch: arm64
plat: darwin
steps:
- name: Check out repo
uses: actions/checkout@v4
- name: Set up Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Install dependencies
run: bun install
- name: Install fftw (cavacore build dependency)
run: |
if uname -s | grep -qi darwin; then
brew install fftw
else
sudo apt-get update
sudo apt-get install -y libfftw3-dev
fi
- name: Build native cavacore library
run: scripts/build-cavacore.sh
- name: Build standalone binary + tarball
run: make dist
- name: Smoke-test binary boot
env:
DIST_TAR: podtui-${{ matrix.plat }}-${{ matrix.arch }}.tar.gz
run: |
# The embedded runtime reads the launching process's CWD bunfig.toml.
# This repo's bunfig lists a preload the standalone can't resolve
# ("preload not found"), so kicking the binary from the workspace root
# would falsely fail every build. cd into a clean dir first.
SMOKE_DIR=$(mktemp -d)
tar -xzf "dist/$DIST_TAR" -C "$SMOKE_DIR"
cd "$SMOKE_DIR"
./podtui-*/podtui --version
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: podtui-${{ matrix.plat }}-${{ matrix.arch }}
path: dist/podtui-*.tar.gz
upload:
name: Attach to GitHub Release
needs: build
runs-on: ubuntu-latest
steps:
- name: Download all binaries
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Publish release
uses: softprops/action-gh-release@v2
with:
generate_release_notes: true
files: |
artifacts/**/*.tar.gz
LICENSE

6
.gitignore vendored
View File

@@ -27,10 +27,10 @@ report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
.eslintcache .eslintcache
.cache .cache
*.tsbuildinfo *.tsbuildinfo
*.lockb *.lock
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config # Finder (MacOS) folder config
.DS_Store .DS_Store
.harness/
.ralpi

97
AGENTS.md Normal file
View File

@@ -0,0 +1,97 @@
# AGENTS.md
## Build, Lint, and Test Commands
### Development
- `bun start` - Run the application
- `bun run dev` - Run with hot reload (watch mode)
### Build
- `bun run build` - Build JavaScript bundle to `dist/`
- `bun run build:native` - Build native libraries (requires `scripts/build-cavacore.sh`)
### Testing
- `bun test` - Run all tests
- `bun tests/cavacore-smoke.ts` - Run specific native library smoke test
### Linting
- `bun run lint` - Run ESLint with TypeScript rules
## Code Style Guidelines
### TypeScript Configuration
- Target: ESNext with bundler module resolution
- Strict mode enabled
- Path alias: `@/*` maps to `src/*`
- JSX: Use `@opentui/solid` as import source
### Import Organization
1. Third-party framework imports (solid-js, @opentui/solid)
2. Local utility imports
3. Type imports (separate from value imports)
### Naming Conventions
- **Components**: PascalCase (e.g., `FeedPage`, `Player`)
- **Hooks**: `use*` prefix (e.g., `useAudio`, `useAppKeyboard`)
- **Stores**: `create*` factory + `use*` accessor (e.g., `createFeedStore`, `useFeedStore`)
- **Utilities**: camelCase (e.g., `parseRSSFeed`, `detectPlayers`)
- **Constants**: UPPER_SNAKE_CASE (e.g., `MAX_EPISODES_REFRESH`)
- **Types/interfaces**: PascalCase (e.g., `Feed`, `AudioBackend`)
- **Enums**: PascalCase (e.g., `FeedVisibility`)
### Code Structure
- **Section Dividers**: Use `// ── Section Name ────────────────────────────────────────────────────────────` format
- **Helper Functions**: Define before main logic
- **Factory Functions**: Use for store creation (return object with state, computed, actions)
- **Singleton Pattern**: Stores use module-level singleton with `use*` accessor
### Type Definitions
- Use `interface` for object shapes
- Use `type` for unions, intersections, and complex types
- Use `enum` for constant sets
- Export types from `src/types/` directory
- Include JSDoc comments for complex types
### Error Handling
- Use `try/catch` for async operations
- For expected failures, use `.catch(() => {})` to suppress errors
- Return default values on failure (e.g., `return []` or `return null`)
- Use `catch` blocks with descriptive comments for unexpected errors
- For UI components, wrap in `ErrorBoundary` with clear fallback
### Async Patterns
- Fire-and-forget async operations: `.catch(() => {})` with comment
- Async store initialization: IIFE `(async () => { ... })()`
- Promise handling: Use `.catch()` to return defaults
### Comments
- **File headers**: Brief description of file purpose
- **Complex functions**: JSDoc-style comments explaining behavior
- **Section dividers**: Visual separators for code organization
- **Inline comments**: Explain non-obvious logic, especially async patterns
### Code Formatting
- 2-space indentation
- No semicolons (Bun style)
- Arrow functions with implicit return where appropriate
- Object shorthand where possible
- Prefer `const` over `let`
### Reactivity (Solid.js)
- Use `createSignal` for primitive state
- Use `createMemo` for computed values
- Use `createEffect` for side effects
- Component functions return JSX
- Store functions return plain objects with state, computed, and actions
### Persistence
- Async persistence operations fire-and-forget
- Use `.catch(() => {})` to suppress errors
- Update state synchronously, persist asynchronously
- Use `setFeeds()` pattern to update state and trigger save
### Testing
- Test files in `tests/` directory
- Use Bun's test framework
- Include JSDoc comments explaining test purpose
- Native library tests use `bun:ffi` for FFI calls

204
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,204 @@
# Contributing to PodTui
This file is written **for humans**. If you're an AI agent or LLM working in
this repo, read [AGENTS.md](AGENTS.md) instead — it has the machine-oriented
build/test/lint contract and code-style rules. Both describe the same project;
CONTRIBUTING.md focuses on *understanding* and *navigating* the codebase.
PodTui is a keyboard-first, yazi-style terminal podcast client. TypeScript +
[OpenTUI](https://github.com/opentui/opentui) on top, [Bun](https://bun.sh)
as the runtime and toolchain.
---
## Quick start
```bash
brew install bun # or: curl -fsSL https://bun.sh/install | bash
git clone git@github.com:mikefreno/podtui.git
cd podtui
bun install # install JS dependencies
make native # build libcavacore.dylib from the vendored C source
bun run dev # launch with hot reload (alias: make dev)
```
The app is a TUI — it expects a real terminal (Ghostty, kitty, iTerm2,
WezTerm, tmux, …). It will not render in a plain captured `bash` session.
## What each command does
| Command | Purpose |
|--------------------|--------------------------------------------------------------------------|
| `bun install` | Install JS dependencies |
| `make native` | Compile `cava/cavacore.c``src/native/libcavacore.<dylib\|so>` |
| `bun run dev` | Run with hot reload |
| `bun run start` | Run once (no watch) |
| `bun test` | Run the test suite (see [Testing](#testing)) |
| `bun run lint` | Type-check |
| `bun run build` | Bundle JS into `dist/` + copy native libs (the `podtui` npm script path) |
| `make dist` | Compile the standalone binary + make the current platform's tarball |
| `make clean` | Remove `dist/` |
## Repository layout
```
src/
api/ Network + XML/RSS — client.ts, rss-parser.ts
components/ Reusable UI pieces: Shell, Navigation, YaziPaneRow, TabPanel…
config/ App config: keybinds.jsonc, shortcuts, auth
constants/ Static tables (sync formats, themes)
context/ Solid contexts: KeybindContext, NavigationContext, ThemeContext
hooks/ useAudio, useMultimediaKeys, useCachedData
native/ FFI glue + the built libcavacore.{dylib,so}
pages/ App screens: Feed, MyShows, Discover, Search, Player, Settings
stores/ Zustand stores — app, feed, audio-nav, search, auth, progress…
styles/ theme.css
themes/ catppuccin, gruvbox, nord, tokyo schemes + schema.json
types/ All shared interfaces (podcast, episode, feed, settings…)
ui/ Modal-adjacent UI: command.tsx, dialog.tsx, toast.tsx
utils/ Parser/persistence/audio helpers (audio-player, config-dir…)
scripts/
build-cavacore.sh C → shared lib; finds libfftw3.a on macOS & Debian
tui-harness.tsx Headless harness for scripted interaction (see below)
cava/ Vendored cavacore C source (MIT, from karlstav/cava)
tests/ bun test suite + cavacore smoke test
dist/ Build output (JS bundle + libs + tarballs)
```
## Native libraries: how the FFI layer works
PodTui loads **two** native libraries at runtime:
1. **libopentui** — the OpenTUI renderer (shipped inside the
`@opentui/core-<platform>-<arch>` npm packages, copied to `dist/` by
`build.ts`).
2. **libcavacore** — the audio spectrum renderer, built from C. The source is
vendored under `cava/` (it must stay committed — every CI runner builds it).
`libfftw3` is needed to build it:
- macOS: `brew install fftw`
- Debian/Ubuntu: `apt-get install libfftw3-dev`
(CI installs it for you; locally run `make native`.)
**Critical sibling rule**: both libraries are loaded *relative to the binary*,
so `podtui`, `libopentui.*` and `libcavacore.*` must sit in the **same
directory**. Never move a single binary out of the tarball. The Homebrew
formula keeps all three in `libexec/` and exposes only a `podtui` symlink.
Cavacore smoke test: `bun tests/cavacore-smoke.ts`
(FFI-calls `cava_init` / `cava_execute` / `cava_destroy` and prints results).
## Gotchas (read before touching anything)
1. **Never add a top-level `preload` to `bunfig.toml`.**
A compiled PodTui binary's embedded runtime reads the *launching process's*
CWD `bunfig.toml`, and a `preload` entry points at a module the standalone
can't resolve (`@opentui/solid/preload`) → the binary dies at startup with
`preload not found`. This is why `bunfig.toml` has **no** top-level
`preload`; dev-mode preloading happens via explicit `--preload` flags in
`package.json`. The `[test]` section *does* keep a preload — that only
affects `bun test`.
2. **Smoke-test the compiled binary from a bunfig-free dir.**
Because of (1), `./dist/podtui --version` run from the repo root launched
inside CI would fail. CI always unpacks the tarball into a `mktemp` dir
before booting. Do the same when testing a release build locally.
3. **Homebrew's dylib-repair warning is benign.**
`brew install` may print “load commands do not fit in the header … needs
`-headerpad`” for a prebuilt dylib. The app dlopens the libs by path, so
the warning is cosmetic; installs complete and the app boots.
## Testing
```bash
bun test # full suite (54 tests across 6 files today)
```
The suite covers the keyboard/nav model, keybind dispatch, and the yazi pane
logic; plus `tests/cavacore-smoke.ts` asserting the native lib exports.
For scripted end-to-end interaction there's a **headless harness**,
`scripts/tui-harness.tsx`: each invocation snapshot-rebuilds the app state
into a sandboxed `.harness/` config dir, replays the saved action log
(`.harness/actions.json`), executes one more key/action passed on the CLI, and
prints the resulting frame + a style summary — all without a real terminal.
Audio is a no-op during those snapshots. The last frame lands in
`.harness/last-frame.{json,txt}` for inspection.
## Releasing
Releases are built and published from **tags**
### Steps
1. Run `scripts/release-tag.sh` (interactive: pick major/minor/patch/custom,
confirms the plan, bumps `VERSION` in `src/index.tsx`, commits, tags
`vX.Y.Z`, and pushes branch + tag to every remote). If the version bump is
already committed but the tag is missing, it offers a tag-only path.
`--dry-run` prints the plan without doing anything.
2. Equivalent manual commands:
```bash
git tag -a v0.2.0 -m 'PodTUI v0.2.0' && git push gh v0.2.0
```
3. CI (`.github/workflows/release.yml`) runs four builds in parallel,
each producing `podtui-<platform>-<arch>.tar.gz`:
| Runner | Platform/Arch |
|---------------------|---------------|
| `ubuntu-latest` | linux-x64 |
| `ubuntu-24.04-arm` | linux-arm64 |
| `macos-15-intel` | darwin-x64 |
| `macos-14` | darwin-arm64 |
Each runner: installs deps → installs fftw → `scripts/build-cavacore.sh`
→ `make dist` → smoke-boots the binary from a temp dir → uploads the
tarball. (`macos-15-intel` matters: GitHub's `macos-latest` is arm64 now.)
4. A release is auto-created with all 4 tarballs attached. `brew` never
sees the new version: the **tap self-updates**: the
`mikefreno/homebrew-podtui` repo has a scheduled workflow (hourly) that
polls GitHub releases, and when a new tag appears, rewrites
`Formula/podtui.rb` (URLs + arm64/x64 `sha256`) and pushes it — no
secrets. See `scripts/sync-formula.sh` in that repo for the logic. Local
test: `brew install mikefreno/podtui/podtui`.
5. **AUR packaging** (`packaging/aur/PKGBUILD`): the `podtui-bin` package is
staged, not yet published (AUR account registrations are closed; see the
README note in section 3). On each release, keep the AUR sources in sync
with the new tag: bump `pkgver`, recompute the two tarball `sha256sums`
entries, keep the `LICENSE` asset source (the workflow above uploads
`LICENSE` to every release), and regenerate `packaging/aur/.SRCINFO` with
`bash packaging/aur/gen-srcinfo.sh`.
### Manual fallback
If you ever need to sync the tap by hand (or before the hourly job runs):
```bash
cd <clone of mikefreno/homebrew-podtui>
./scripts/sync-formula.sh 0.2.0
git commit -am 'podtui 0.2.0' && git push
```
### Local release build
```bash
make dist # builds the binary + tarball for THIS machine only
```
Bun cannot cross-compile — the other platforms come from CI.
---
## Open items / things to sort out
- **LICENSE**: `README.md` says "TBD — choose and document a license before
the first release". Pick one (MIT/BSD-3) and add `LICENSE` + update the
README footer.
- **Native libs in `dist/` still need committing?** No — they're built from
sources kept in the repo (`cava/`, `node_modules/@opentui/core-*`). Only
`src/native/libcavacore.dylib` is a committed binary artifact; macOS arm64
ships from it directly until a full rebuild replaces it. On other hosts the
`make native` build is required — see `scripts/build-cavacore.sh`.

30
LICENSE Normal file
View File

@@ -0,0 +1,30 @@
MIT License
Copyright (c) 2026 Michael Freno
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
This project bundles third-party components under their own licenses:
- **cava** (karlstav/cava, vendored under `cava/`) — MIT,
Copyright (c) 2015 Karl Stavestrand. See `cava/LICENSE-cava.txt`.
- **Bun runtime** (embedded in the standalone binary) — MIT.
- **OpenTUI** (`@opentui/core`) — MIT.

66
Makefile Normal file
View File

@@ -0,0 +1,66 @@
# PodTui — Makefile
#
# Development targets:
# make install install dependencies (bun install) + build native lib
# make dev run with hot reload
# make test run the test suite
# make build produce the JS bundle + native libs in dist/
# make native build the cavacore FFI library from C source
# make lint run typecheck-style checks (lsp), not eslint
#
# Packaging / release targets:
# make dist build a standalone compiled binary + tarball for the
# CURRENT platform (see dist/ for podtui + libs + tarball)
# make dist-mac alias for `dist` targeting macOS (run on macOS)
# make dist-linux alias for `dist` targeting Linux (run on Linux)
# make clean remove dist/ output
#
# Cross-platform binaries are produced by CI (GitHub Actions) with one runner
# per OS/arch — Bun cannot cross-compile, so dist:mac / dist:linux only produce
# the binary for the OS they run on. Each runner runs `make dist` and uploads
# its podtui-<platform>-<arch>.tar.gz artifact.
SHELL := /bin/bash
.PHONY: install dev build native dist dist-mac dist-linux test clean
## Install dependencies and build the native runtime library.
install:
bun install
make native
## Run the dev server with hot reload.
dev:
bun run dev
## Type-check the whole project. (See AGENTS.md: `bun run lint` points at a
## nonexistent lint.ts; LSP diagnostics are the maintained clean bar.)
lint:
bun tsc --noEmit
## Build the JS bundle + native libs into dist/ (the `podtui` npm bin target).
build:
bun run build
## Build the cavacore FFI library from src/native/cavacore.c.
native:
scripts/build-cavacore.sh
## Standalone binary + native-libs tarball for the current platform.
## Unaffected by bunfig.toml at build time. Note: the compiled runtime reads
## the launching process's CWD bunfig.toml, so smoke tests must run the binary
## from a bunfig-free dir (see release.yml).
dist:
bun run build.ts --compile
## macOS build (run on a macOS runner / host).
dist-mac:
bun run build.ts --compile
## Linux build (run on a Linux runner / host).
dist-linux:
bun run build.ts --compile
## Remove build artifacts.
clean:
rm -rf dist

232
README.md
View File

@@ -1,15 +1,237 @@
# solid # PodTui
To install dependencies: A keyboard-first, yazi-style terminal podcast client written in TypeScript and
built on [OpenTUI](https://github.com/opentui/opentui). Subscribe to RSS feeds,
browse episodes in a three-pane file-manager layout, and play audio through an
external player with full transport control — all from your terminal.
## Features
- **Vim/yazi-style navigation** — `j/k` to move, `h/l` to swipe between panes,
`Enter` to open, `16` / `[` `]` to switch tabs. The tab list is the app root:
at launch it fills the current pane, and drilling into a tab's contents slides
it into the parent pane.
- **Three-pane view** — parent / current / preview (Up | Current | Preview),
mirroring yazi's pane model.
- **Podcast feeds** — add feeds, browse episodes, and manage your library
(My Shows, Discover, Feed tabs).
- **Search** across your subscribed shows.
- **Audio playback** through an external player with full transport control:
play/pause, next/previous, seek, speed, and per-episode resume progress.
- **Themeable** and **remappable keybindings**.
- Ships as a **standalone compiled binary** — no runtime or install step beyond
a system audio player.
## Requirements
- A terminal with UTF-8 and modern color support (kitty, iTerm2, WezTerm,
tmux, GNOME Terminal, etc.).
- An **audio player** on `PATH`. PodTui auto-detects in priority order:
| Player | Platforms | Seek | Speed | Position tracking |
|----------|----------------|:----:|:-----:|:------------------|
| `mpv` | any | ✔ | ✔ | ✔ (recommended) |
| `ffplay` | any | ✔ | ✘ | ✘ |
| `afplay` | macOS built-in | ✔ | ✔ | ✘ |
| `open`/`xdg-open` | any | ✘ | ✘ | ✘ |
Install `mpv` for the best experience (`brew install mpv`,
`sudo apt install mpv`, `pacman -S mpv`). You can force a specific backend
with `PODTUI_AUDIO_BACKEND=mpv|ffplay|afplay|system|none`.
## Installation
PodTui distributes as a **self-contained binary** for macOS (arm64/x64) and
Linux (arm64/x64). Pick whichever fits your platform.
### 1. Homebrew (macOS)
```sh
brew install mikefreno/podtui/podtui # requires mpv: brew install mpv
```
> The formula installs the standalone binary plus its two native libraries
> side by side (see [Packaging model](#packaging-model)). It does **not**
> depend on Bun.
### 2. Standalone tarball (all platforms)
Grab `podtui-<platform>-<arch>.tar.gz` from the latest
[GitHub Release](https://github.com/mikefreno/podtui/releases), unpack it, and
put `podtui` on your `PATH`:
```bash ```bash
curl -sS -o /tmp/podtui.tar.gz \
https://github.com/mikefreno/podtui/releases/latest/download/podtui-linux-x64.tar.gz
sudo mkdir -p /opt/podtui
sudo tar -xzf /tmp/podtui.tar.gz -C /opt/podtui --strip-components=1
sudo ln -sf /opt/podtui/podtui /usr/local/bin/podtui
```
> The tarball contains `podtui` plus `libopentui.<ext>` and
> `libcavacore.<ext>` **beside it** — keep them together (don't move just the
> binary alone), or the native FFI libraries won't load.
>
> One caveat: the embedded runtime reads a `bunfig.toml` from the directory
> you launch from. If that file has a `preload` entry (as Bun project
> directories often do), startup fails with `preload not found`. Launching
> from a normal directory (home, `~/bin`, …) works fine.
### 3. Arch Linux (AUR)
```bash
# Status: PKGBUILD ready, not yet on the AUR (see note below)
yay -S podtui-bin # once published
```
Requires an AUR helper ([paru](https://github.com/morgan/paru)). The AUR
package (PKGBUILD lives in `packaging/aur/`) installs the released binary and
its two FFI sibling libraries into `/usr/lib/podtui/` with a `/usr/bin/podtui`
symlink, and pulls in `mpv` (the sole audio backend) as a dependency.
> **Not yet on the AUR.** The `podtui-bin` PKGBUILD and `.SRCINFO` are ready
> in `packaging/aur/` and can be built locally today:
>
> ```bash
> cd packaging/aur && makepkg -si
> ```
>
> Publishing is on hold until [AUR account registrations](https://aur.archlinux.org)
> reopen (suspended while the AUR team works on suspicious-package
> moderation). Once a key can be registered, push `PKGBUILD` + `.SRCINFO`
> with `git push ssh://aur@aur.archlinux.org/podtui-bin` and update this note.
### 4. From source
Requires [Bun](https://bun.sh) ≥ 1.2.
```bash
git clone https://github.com/mikefreno/podtui.git
cd podtui
bun install bun install
bun run build:native # build the cavacore FFI lib from C source
bun run dev # run with hot reload, or: bun start
``` ```
To run: ## Linux distribution notes
PodTUI deliberately does **not** ship `.deb`, `.rpm`, Flatpak, or Snap
packages. For a terminal application that's overwhelmingly installed through
repositories or archives, those formats add desktop-sandboxing overhead and a
packaging tax with little benefit. Instead:
- **GitHub Release tarballs** are the universal path — one upload, works on
any distro with `curl` + `tar`.
- **AUR (`podtui-bin`)** covers Arch. Anyone on Arch/Manjaro gets the same
binary through their native package manager.
- **Nix / cross-distro** users can build from source (or a Nix flake can be
added later).
This keeps maintenance to a single build per OS/arch and still reaches the
vast majority of desktop Linux users through their preferred path.
## Usage
Launch `podtui` (or `bun src/index.tsx` from the source tree). Press `~`
for the in-app help.
### Command-line flags
| Flag | Description |
|------|-------------|
| `-v`, `--version` | Print the version and exit |
| `-q`, `--query <term>` | Query feeds for a show title and print matching shows, without launching the TUI |
| `-p`, `--play <term>` | Play the matching show, without launching the TUI |
### Keybindings
All keys are remappable — edit `~/.config/podtui/keybinds.jsonc`.
| Keys | Action |
|------|--------|
| `j` / `k` | Move cursor down / up |
| `J` / `K` | Jump 5 lines |
| `ctrl-d` / `ctrl-u` | Page down / up |
| `gg` / `G` | Go to top / bottom |
| `h` / `l` | Swipe to parent pane / preview pane |
| `Enter` | Open the item under the cursor (a tab, episode, show…) |
| `Space` | Select / toggle selection |
| `v` | Visual mode (multi-select) |
| `1``6` | Jump to tab 16 (Feed, My Shows, Discover, Search, Player, Settings) |
| `[` / `]` | Previous / next tab |
| `P` (shift) | Play / pause |
| `N` / `B` | Next / previous episode |
| `shift-.` / `shift-,` | Seek forward / backward |
| `s` | Search (in a list) |
| `f` | Filter |
| `r` | Refresh |
| `:` | Command bar |
| `~`, `f1` | Help |
| `q`, `ctrl-c` | Quit |
| `Esc` | Escape / cancel |
## Configuration
Configuration lives under the XDG config directory — `~/.config/podtui` by
default (`$XDG_CONFIG_HOME/podtui` if set).
| File | Purpose |
|------|---------|
| `feeds.json` | Your subscribed feeds (RSS/podcast sources) |
| `sources.json` | Custom feed sources |
| `downloads.json` | Downloaded episode metadata |
| `keybinds.jsonc` | Keybinding remaps (see above) |
| `themes/` | Optional custom theme files |
Env overrides: `PODTUI_AUDIO_BACKEND`, `XDG_CONFIG_HOME`. Startup also reads
the same OpenTUI environment variables.
## Development
```bash ```bash
bun dev bun install # install dependencies
bun run dev # run with hot reload
bun test # run the test suite
bun run build # bundle JS + copy native libs into dist/
make native # rebuild cavacore from C source
make lint # type-check (tsc)
``` ```
This project was created using `bun create tui`. [create-tui](https://git.new/create-tui) is the easiest way to get started with OpenTUI. ### Releasing
Tag a release (e.g. `v0.1.0`); CI builds and uploads the per-platform tarballs
to your GitHub Release automatically:
```bash
make dist # build the standalone binary + tarball for THIS platform
make dist-mac # (run on macOS) → podtui-darwin-<arch>.tar.gz
make dist-linux # (run on Linux) → podtui-linux-<arch>.tar.gz
```
`make dist` emits a config-independent binary: Bun does not bake bunfig
settings into `--compile` output, and the solid JSX transform is registered in
`build.ts` itself. The binary then embeds the `preload`-free runtime, so launch
it from any normal directory.
## Packaging model
A release tarball is three files sitting side by side:
```
podtui # standalone compiled binary (embeds the Bun runtime)
libopentui.<dylib|so> # OpenTUI native renderer FFI library
libcavacore.<dylib|so> # cavacore spectrum FFI library (built from C)
```
PodTui loads its native libraries relative to the binary, so **keep them in
the same directory**. The compiled binary embeds the Bun runtime, so it runs
with no Bun installed. Each release builds one tarball per OS/arch in CI; there
is no cross-compilation.
## License
MIT. See [LICENSE](LICENSE).
## Related
- [OpenTUI](https://github.com/opentui/opentui) — the TUI framework driving the interface

142
build.ts
View File

@@ -1,6 +1,32 @@
import solidPlugin from "@opentui/solid/bun-plugin" import solidPlugin from "@opentui/solid/bun-plugin";
import { copyFileSync, existsSync, mkdirSync } from "node:fs" import { copyFileSync, existsSync, mkdirSync, rmSync } from "node:fs";
import { join, dirname } from "node:path" import { join } from "node:path";
import { plugin } from "bun";
// Register the solid transform globally (dedup'd by name). This is what makes
// `--compile` work: compile-mode builds only apply `onLoad` transform plugins
// that are registered via `plugin()`, not the `plugins:` array. The transform
// is fully embedded in the compiled binary.
plugin(solidPlugin);
const COMPILE =
process.argv.includes("--compile") || process.env.PODTUI_COMPILE === "1";
const platform = process.platform;
const arch = process.arch;
// Platform/arch → OpenTUI package name
const platformMap: Record<string, string> = {
"darwin-arm64": "darwin-arm64",
"darwin-x64": "darwin-x64",
"linux-x64": "linux-x64",
"linux-arm64": "linux-arm64",
"win32-x64": "win32-x64",
"win32-arm64": "win32-arm64",
};
const libExt =
platform === "win32" ? "dll" : platform === "darwin" ? "dylib" : "so";
// Build the JavaScript bundle // Build the JavaScript bundle
await Bun.build({ await Bun.build({
@@ -10,38 +36,94 @@ await Bun.build({
minify: true, minify: true,
sourcemap: "external", sourcemap: "external",
plugins: [solidPlugin], plugins: [solidPlugin],
}) });
// Copy the native library to dist for distribution // Copy the opentui native library to dist for distribution.
const platform = process.platform const platformKey = `${platform}-${arch}`;
const arch = process.arch const platformPkg = platformMap[platformKey];
// Map platform/arch to OpenTUI package names
const platformMap: Record<string, string> = {
"darwin-arm64": "darwin-arm64",
"darwin-x64": "darwin-x64",
"linux-x64": "linux-x64",
"linux-arm64": "linux-arm64",
"win32-x64": "win32-x64",
"win32-arm64": "win32-arm64",
}
const platformKey = `${platform}-${arch}`
const platformPkg = platformMap[platformKey]
if (platformPkg) { if (platformPkg) {
const libName = platform === "win32" const libName = `libopentui.${libExt}`;
? "opentui.dll" const srcPath = join("node_modules", `@opentui/core-${platformPkg}`, libName);
: platform === "darwin"
? "libopentui.dylib"
: "libopentui.so"
const srcPath = join("node_modules", `@opentui/core-${platformPkg}`, libName)
if (existsSync(srcPath)) { if (existsSync(srcPath)) {
const destPath = join("dist", libName) const destPath = join("dist", libName);
copyFileSync(srcPath, destPath) copyFileSync(srcPath, destPath);
console.log(`Copied native library: ${libName}`) console.log(`Copied native library: ${libName}`);
} }
} }
console.log("Build complete") // Copy cavacore native library to dist
const cavacoreLib = `libcavacore.${libExt}`;
const cavacoreSrc = join("src", "native", cavacoreLib);
if (existsSync(cavacoreSrc)) {
copyFileSync(cavacoreSrc, join("dist", cavacoreLib));
console.log(`Copied cavacore library: ${cavacoreLib}`);
} else {
console.warn(
`Warning: ${cavacoreSrc} not found — run scripts/build-cavacore.sh first`,
);
}
// ── Standalone compiled binary (dist/podtui + libs beside it) ──────────────
// `bun run build.ts --compile` (or PODTUI_COMPILE=1). Embeds the Bun runtime
// so end users need nothing installed; the two FFI libs are shipped as
// SIBLING FILES next to the binary (both loaders already resolve them that
// way: cavacore checks dirname(process.execPath); opentui embeds via its
// bun-plugin and handles the embedded-file path itself).
if (COMPILE) {
const outfile = join("dist", "podtui");
await Bun.build({
entrypoints: ["./src/index.tsx"],
target: "bun",
minify: true,
sourcemap: "external",
plugins: [solidPlugin],
compile: {
outfile,
},
});
console.log(`Compiled standalone binary: ${outfile}`);
// Ensure both native libs sit beside the binary.
const opentuiSrc = join(
"node_modules",
`@opentui/core-${platformPkg}`,
`libopentui.${libExt}`,
);
if (existsSync(opentuiSrc)) {
copyFileSync(opentuiSrc, join("dist", `libopentui.${libExt}`));
}
if (!existsSync(join("dist", cavacoreLib))) {
console.warn(
`Warning: ${cavacoreLib} missing beside the binary — run scripts/build-cavacore.sh`,
);
}
// Tarball: podtui + the two native libs (drop the JS bundle dir)
const tarRoot = join("dist", `podtui-${platform}-${arch}`);
rmSync(tarRoot, { recursive: true, force: true });
mkdirSync(tarRoot, { recursive: true });
copyFileSync(outfile, join(tarRoot, "podtui"));
for (const lib of [`libopentui.${libExt}`, cavacoreLib]) {
const s = join("dist", lib);
if (existsSync(s)) copyFileSync(s, join(tarRoot, lib));
}
const tar = Bun.spawnSync([
"tar",
"-czf",
`${tarRoot}.tar.gz`,
"-C",
"dist",
`podtui-${platform}-${arch}`,
]);
if (tar.exitCode !== 0) {
console.error(tar.stderr.toString());
process.exit(1);
}
console.log(`Tarball: ${tarRoot}.tar.gz`);
rmSync(tarRoot, { recursive: true, force: true });
}
console.log("Build complete");

BIN
bun.lockb Executable file

Binary file not shown.

2
bunfig.test.toml Normal file
View File

@@ -0,0 +1,2 @@
[test]
preload = ["./tests/preload/solid-test-plugin.ts"]

View File

@@ -1 +1,9 @@
preload = ["@opentui/solid/preload"] # NO top-level `preload` here — intentional. A compiled PodTUI binary's
# embedded Bun runtime reads the launching process's CWD bunfig.toml, and a
# top-level `preload` entry (e.g. "@opentui/solid/preload", which the
# standalone cannot resolve) makes the binary die at startup with
# "preload not found". Dev/test still get the solid transform via explicit
# `--preload` flags in package.json and the [test] section below.
[test]
preload = "@opentui/solid/preload"

19
cava/LICENSE-cava.txt Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) 2015 Karl Stavestrand <karl@stavestrand.no>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

588
cava/cavacore.c Normal file
View File

@@ -0,0 +1,588 @@
#include "cavacore.h"
#ifndef M_PI
#define M_PI 3.1415926535897932385
#endif
#include <fftw3.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#ifdef __ANDROID__
#include <jni.h>
struct cava_plan *plan;
double *cava_in;
double *cava_out;
#endif
static double amplitude_to_decibels(double value) {
// Magic number 20 comes from converting amplitude ratios to decibels.
return 20 * log10(value);
}
struct cava_plan *cava_init(int number_of_bars, unsigned int rate, int channels, int autosens,
double noise_reduction, int low_cut_off, int high_cut_off,
int scaling_mode) {
struct cava_plan *p = malloc(sizeof(struct cava_plan));
p->status = 0;
// sanity checks:
if (channels < 1 || channels > 2) {
snprintf(p->error_message, 1024,
"cava_init called with illegal number of channels: %d, number of channels "
"supported are "
"1 and 2",
channels);
p->status = -1;
return p;
}
if (rate < 1 || rate > 384000) {
snprintf(p->error_message, 1024, "cava_init called with illegal sample rate: %d\n", rate);
p->status = -1;
return p;
}
int fft_buffer_size = 512;
if (rate > 8125 && rate <= 16250)
fft_buffer_size *= 2;
else if (rate > 16250 && rate <= 32500)
fft_buffer_size *= 4;
else if (rate > 32500 && rate <= 75000)
fft_buffer_size *= 8;
else if (rate > 75000 && rate <= 150000)
fft_buffer_size *= 16;
else if (rate > 150000 && rate <= 300000)
fft_buffer_size *= 32;
else if (rate > 300000)
fft_buffer_size *= 64;
if (number_of_bars < 1) {
snprintf(p->error_message, 1024,
"cava_init called with illegal number of bars: %d, number of channels must be "
"positive integer\n",
number_of_bars);
p->status = -1;
return p;
}
if (number_of_bars > fft_buffer_size / 2 + 1) {
snprintf(p->error_message, 1024,
"cava_init called with illegal number of bars: %d, for %d sample rate number of "
"bars can't be more than %d\n",
number_of_bars, rate, fft_buffer_size / 2 + 1);
p->status = -1;
return p;
}
if (low_cut_off < 1 || high_cut_off < 1) {
snprintf(p->error_message, 1024, "low_cut_off must be a positive value\n");
p->status = -1;
return p;
}
if (low_cut_off >= high_cut_off) {
snprintf(p->error_message, 1024, "high_cut_off must be a higher than low_cut_off\n");
p->status = -1;
return p;
}
if ((unsigned int)high_cut_off > rate / 2) {
snprintf(p->error_message, 1024,
"high_cut_off can't be higher than sample rate / 2. (Nyquist Sampling Theorem)\n");
p->status = -1;
return p;
}
if (scaling_mode != CAVA_SCALING_LINEAR && scaling_mode != CAVA_SCALING_DECIBEL) {
snprintf(p->error_message, 1024, "unknown scaling mode: %d\n", scaling_mode);
p->status = -1;
return p;
}
p->number_of_bars = number_of_bars;
p->audio_channels = channels;
p->rate = rate;
p->autosens = 1;
p->sens_init = 1;
p->sens = 1.0;
p->autosens = autosens;
p->framerate = 75;
p->frame_skip = 1;
p->noise_reduction = noise_reduction;
p->scaling_mode = scaling_mode;
int fftw_flag = FFTW_MEASURE;
#ifdef __ANDROID__
fftw_flag = FFTW_ESTIMATE;
#endif
p->FFTbassbufferSize = fft_buffer_size * 2;
p->FFTbufferSize = fft_buffer_size;
p->input_buffer_size = p->FFTbassbufferSize * channels;
p->input_buffer = (double *)malloc(p->input_buffer_size * sizeof(double));
p->FFTbuffer_lower_cut_off = (int *)malloc((number_of_bars + 1) * sizeof(int));
p->FFTbuffer_upper_cut_off = (int *)malloc((number_of_bars + 1) * sizeof(int));
p->eq = (double *)malloc((number_of_bars + 1) * sizeof(double));
p->cut_off_frequency = (float *)malloc((number_of_bars + 1) * sizeof(float));
p->cava_fall = (double *)malloc(number_of_bars * channels * sizeof(double));
p->cava_mem = (double *)malloc(number_of_bars * channels * sizeof(double));
p->cava_peak = (double *)malloc(number_of_bars * channels * sizeof(double));
p->prev_cava_out = (double *)malloc(number_of_bars * channels * sizeof(double));
// Hann Window calculate multipliers
p->bass_multiplier = (double *)malloc(p->FFTbassbufferSize * sizeof(double));
p->multiplier = (double *)malloc(p->FFTbufferSize * sizeof(double));
for (int i = 0; i < p->FFTbassbufferSize; i++) {
p->bass_multiplier[i] = 0.5 * (1 - cos(2 * M_PI * i / (p->FFTbassbufferSize - 1)));
}
for (int i = 0; i < p->FFTbufferSize; i++) {
p->multiplier[i] = 0.5 * (1 - cos(2 * M_PI * i / (p->FFTbufferSize - 1)));
}
// BASS
p->in_bass_l = fftw_alloc_real(p->FFTbassbufferSize);
p->in_bass_l_raw = fftw_alloc_real(p->FFTbassbufferSize);
p->out_bass_l = fftw_alloc_complex(p->FFTbassbufferSize / 2 + 1);
p->p_bass_l =
fftw_plan_dft_r2c_1d(p->FFTbassbufferSize, p->in_bass_l, p->out_bass_l, fftw_flag);
// MID + TREBLE
p->in_l = fftw_alloc_real(p->FFTbufferSize);
p->in_l_raw = fftw_alloc_real(p->FFTbufferSize);
p->out_l = fftw_alloc_complex(p->FFTbufferSize / 2 + 1);
p->p_l = fftw_plan_dft_r2c_1d(p->FFTbufferSize, p->in_l, p->out_l, fftw_flag);
memset(p->in_bass_l, 0, sizeof(double) * p->FFTbassbufferSize);
memset(p->in_l, 0, sizeof(double) * p->FFTbufferSize);
memset(p->in_bass_l_raw, 0, sizeof(double) * p->FFTbassbufferSize);
memset(p->in_l_raw, 0, sizeof(double) * p->FFTbufferSize);
memset(p->out_bass_l, 0, (p->FFTbassbufferSize / 2 + 1) * sizeof(fftw_complex));
memset(p->out_l, 0, (p->FFTbufferSize / 2 + 1) * sizeof(fftw_complex));
if (p->audio_channels == 2) {
// BASS
p->in_bass_r = fftw_alloc_real(p->FFTbassbufferSize);
p->in_bass_r_raw = fftw_alloc_real(p->FFTbassbufferSize);
p->out_bass_r = fftw_alloc_complex(p->FFTbassbufferSize / 2 + 1);
p->p_bass_r =
fftw_plan_dft_r2c_1d(p->FFTbassbufferSize, p->in_bass_r, p->out_bass_r, fftw_flag);
// MID + TREBLE
p->in_r = fftw_alloc_real(p->FFTbufferSize);
p->in_r_raw = fftw_alloc_real(p->FFTbufferSize);
p->out_r = fftw_alloc_complex(p->FFTbufferSize / 2 + 1);
p->p_r = fftw_plan_dft_r2c_1d(p->FFTbufferSize, p->in_r, p->out_r, fftw_flag);
memset(p->in_bass_r, 0, sizeof(double) * p->FFTbassbufferSize);
memset(p->in_r, 0, sizeof(double) * p->FFTbufferSize);
memset(p->in_bass_r_raw, 0, sizeof(double) * p->FFTbassbufferSize);
memset(p->in_r_raw, 0, sizeof(double) * p->FFTbufferSize);
memset(p->out_bass_r, 0, (p->FFTbassbufferSize / 2 + 1) * sizeof(fftw_complex));
memset(p->out_r, 0, (p->FFTbufferSize / 2 + 1) * sizeof(fftw_complex));
}
memset(p->input_buffer, 0, sizeof(double) * p->input_buffer_size);
memset(p->cava_fall, 0, sizeof(double) * number_of_bars * channels);
memset(p->cava_mem, 0, sizeof(double) * number_of_bars * channels);
memset(p->cava_peak, 0, sizeof(double) * number_of_bars * channels);
memset(p->prev_cava_out, 0, sizeof(double) * number_of_bars * channels);
// process: calculate cutoff frequencies and eq
int lower_cut_off = low_cut_off;
int upper_cut_off = high_cut_off;
int bass_cut_off = 100;
// calculate frequency constant (used to distribute bars across the frequency band)
double frequency_constant = log10((float)lower_cut_off / (float)upper_cut_off) /
(1 / ((float)p->number_of_bars + 1) - 1);
float *relative_cut_off = (float *)malloc((p->number_of_bars + 1) * sizeof(float));
p->bass_cut_off_bar = 0;
int first_bar = 1;
float min_bandwidth = p->rate / p->FFTbassbufferSize;
for (int n = 0; n < p->number_of_bars + 1; n++) {
double bar_distribution_coefficient = frequency_constant * (-1);
bar_distribution_coefficient +=
((float)n + 1) / ((float)p->number_of_bars + 1) * frequency_constant;
p->cut_off_frequency[n] = upper_cut_off * pow(10, bar_distribution_coefficient);
if (n > 0) {
if (p->cut_off_frequency[n - 1] >= p->cut_off_frequency[n])
p->cut_off_frequency[n] = p->cut_off_frequency[n - 1] + min_bandwidth;
}
// remember nyquist!
relative_cut_off[n] = p->cut_off_frequency[n] / (p->rate / 2);
if (p->cut_off_frequency[n] < bass_cut_off) {
// BASS
p->FFTbuffer_lower_cut_off[n] = relative_cut_off[n] * (p->FFTbassbufferSize / 2);
p->bass_cut_off_bar++;
if (p->bass_cut_off_bar > 1)
first_bar = 0;
if (p->FFTbuffer_lower_cut_off[n] > p->FFTbassbufferSize / 2) {
p->FFTbuffer_lower_cut_off[n] = p->FFTbassbufferSize / 2;
}
} else {
// MID + TREBLE
p->FFTbuffer_lower_cut_off[n] =
ceil(relative_cut_off[n] * (float)(p->FFTbufferSize / 2));
if (n == p->bass_cut_off_bar) {
first_bar = 1;
if (n > 0) {
p->FFTbuffer_upper_cut_off[n - 1] =
relative_cut_off[n] * (p->FFTbassbufferSize / 2) - 1;
}
} else {
first_bar = 0;
}
if (p->FFTbuffer_lower_cut_off[n] > p->FFTbufferSize / 2) {
p->FFTbuffer_lower_cut_off[n] = p->FFTbufferSize / 2;
}
}
if (n > 0) {
if (!first_bar) {
p->FFTbuffer_upper_cut_off[n - 1] = p->FFTbuffer_lower_cut_off[n] - 1;
// pushing the spectrum up if the exponential function gets "clumped" in the
// bass and calculating new cut off frequencies
if (p->FFTbuffer_lower_cut_off[n] <= p->FFTbuffer_lower_cut_off[n - 1]) {
// check if there is room for more first
int room_for_more = 0;
if (n < p->bass_cut_off_bar) {
if (p->FFTbuffer_lower_cut_off[n - 1] + 1 < p->FFTbassbufferSize / 2 + 1)
room_for_more = 1;
} else {
if (p->FFTbuffer_lower_cut_off[n - 1] + 1 < p->FFTbufferSize / 2 + 1)
room_for_more = 1;
}
if (room_for_more) {
// push the spectrum up
p->FFTbuffer_lower_cut_off[n] = p->FFTbuffer_lower_cut_off[n - 1] + 1;
p->FFTbuffer_upper_cut_off[n - 1] = p->FFTbuffer_lower_cut_off[n] - 1;
}
}
} else {
if (p->FFTbuffer_upper_cut_off[n - 1] < p->FFTbuffer_lower_cut_off[n - 1])
p->FFTbuffer_upper_cut_off[n - 1] = p->FFTbuffer_lower_cut_off[n - 1] + 1;
}
}
// calculate actual cut off frequency
if (n < p->bass_cut_off_bar)
relative_cut_off[n] =
(float)(p->FFTbuffer_lower_cut_off[n]) / ((float)p->FFTbassbufferSize / 2);
else
relative_cut_off[n] =
(float)(p->FFTbuffer_lower_cut_off[n]) / ((float)p->FFTbufferSize / 2);
p->cut_off_frequency[n] = relative_cut_off[n] * ((float)p->rate / 2);
}
// hard coded eq
for (int n = 0; n < p->number_of_bars; n++) {
// the numbers that come out of the FFT are very high
// the EQ is used to "normalize" them by dividing with this very huge number
p->eq[n] = 1 / pow(2, 28);
// need to boost the EQ for higher frequencies
p->eq[n] *= pow(p->cut_off_frequency[n + 1], 0.85);
if (n < p->bass_cut_off_bar) {
p->eq[n] /= log2(p->FFTbassbufferSize);
} else {
p->eq[n] /= log2(p->FFTbufferSize);
}
p->eq[n] /= p->FFTbuffer_upper_cut_off[n] - p->FFTbuffer_lower_cut_off[n] + 1;
}
free(relative_cut_off);
return p;
}
void cava_execute(double *cava_in, int new_samples, double *cava_out, struct cava_plan *p) {
// do not overflow
if (new_samples > p->input_buffer_size) {
new_samples = p->input_buffer_size;
}
int silence = 1;
if (new_samples > 0) {
// process: approximate actual framerate. This will be off by +10% at 60 fps, but should be
// good enough for the autosens and smoothing algorithms to be adjusted accordingly if
// framerate is a lot more or less.
p->framerate -= p->framerate / 64.0;
p->framerate +=
(double)(p->rate * p->frame_skip) / (new_samples / p->audio_channels) / 64.0;
p->frame_skip = 1;
// shifting input buffer
for (int n = p->input_buffer_size - 1; n >= new_samples; n--) {
p->input_buffer[n] = p->input_buffer[n - new_samples];
}
// fill the input buffer
for (int n = 0; n < new_samples; n++) {
if (p->scaling_mode == CAVA_SCALING_DECIBEL) {
// Audio signals come in the range [-32768, 32768], normalize to [-1, 1].
p->input_buffer[new_samples - n - 1] = cava_in[n] / 32768.0;
} else {
p->input_buffer[new_samples - n - 1] = cava_in[n];
}
if (cava_in[n]) {
silence = 0;
}
}
} else {
p->frame_skip++;
}
// fill the bass, mid and treble buffers
for (int n = 0; n < p->FFTbassbufferSize; n++) {
if (p->audio_channels == 2) {
p->in_bass_r_raw[n] = p->input_buffer[n * 2];
p->in_bass_l_raw[n] = p->input_buffer[n * 2 + 1];
} else {
p->in_bass_l_raw[n] = p->input_buffer[n];
}
}
for (int n = 0; n < p->FFTbufferSize; n++) {
if (p->audio_channels == 2) {
p->in_r_raw[n] = p->input_buffer[n * 2];
p->in_l_raw[n] = p->input_buffer[n * 2 + 1];
} else {
p->in_l_raw[n] = p->input_buffer[n];
}
}
// Hann Window
for (int i = 0; i < p->FFTbassbufferSize; i++) {
p->in_bass_l[i] = p->bass_multiplier[i] * p->in_bass_l_raw[i];
if (p->audio_channels == 2)
p->in_bass_r[i] = p->bass_multiplier[i] * p->in_bass_r_raw[i];
}
for (int i = 0; i < p->FFTbufferSize; i++) {
p->in_l[i] = p->multiplier[i] * p->in_l_raw[i];
if (p->audio_channels == 2)
p->in_r[i] = p->multiplier[i] * p->in_r_raw[i];
}
// process: execute FFT and sort frequency bands
fftw_execute(p->p_bass_l);
fftw_execute(p->p_l);
if (p->audio_channels == 2) {
fftw_execute(p->p_bass_r);
fftw_execute(p->p_r);
}
// process: separate frequency bands
for (int n = 0; n < p->number_of_bars; n++) {
double temp_l = 0;
double temp_r = 0;
// process: add upp FFT values within bands
for (int i = p->FFTbuffer_lower_cut_off[n]; i <= p->FFTbuffer_upper_cut_off[n]; i++) {
if (n < p->bass_cut_off_bar) {
temp_l += hypot(p->out_bass_l[i][0], p->out_bass_l[i][1]);
if (p->audio_channels == 2)
temp_r += hypot(p->out_bass_r[i][0], p->out_bass_r[i][1]);
} else {
temp_l += hypot(p->out_l[i][0], p->out_l[i][1]);
if (p->audio_channels == 2)
temp_r += hypot(p->out_r[i][0], p->out_r[i][1]);
}
}
// getting average and applying configured scaling
if (p->scaling_mode == CAVA_SCALING_DECIBEL) {
const double max_db = 70;
temp_l = amplitude_to_decibels(temp_l) / max_db;
if (!isfinite(temp_l)) {
temp_l = 0;
}
} else {
temp_l *= p->eq[n];
}
cava_out[n] = temp_l;
if (p->audio_channels == 2) {
if (p->scaling_mode == CAVA_SCALING_DECIBEL) {
const double max_db = 70;
temp_r = amplitude_to_decibels(temp_r) / max_db;
if (!isfinite(temp_r)) {
temp_r = 0;
}
} else {
temp_r *= p->eq[n];
}
cava_out[n + p->number_of_bars] = temp_r;
}
}
// applying sens or getting max value
if (p->autosens) {
for (int n = 0; n < p->number_of_bars * p->audio_channels; n++) {
cava_out[n] *= p->sens;
}
}
// process [smoothing]
int overshoot = 0;
double framerate_mod = 66 / p->framerate;
double gravity_mod = pow((framerate_mod), 2.5) * 2 / p->noise_reduction;
double integral_mod = pow((framerate_mod), 0.1);
for (int n = 0; n < p->number_of_bars * p->audio_channels; n++) {
// process [smoothing]: falloff
if (cava_out[n] < p->prev_cava_out[n] && p->noise_reduction > 0.1) {
cava_out[n] =
p->cava_peak[n] * (1.0 - (p->cava_fall[n] * p->cava_fall[n] * gravity_mod));
if (cava_out[n] < 0.0)
cava_out[n] = 0.0;
p->cava_fall[n] += 0.028;
} else {
p->cava_peak[n] = cava_out[n];
p->cava_fall[n] = 0.0;
}
p->prev_cava_out[n] = cava_out[n];
// process [smoothing]: integral
cava_out[n] = p->cava_mem[n] * p->noise_reduction / integral_mod + cava_out[n];
p->cava_mem[n] = cava_out[n];
if (p->autosens) {
// check if we overshoot target height
if (cava_out[n] > 1.0) {
overshoot = 1;
cava_out[n] = 1.0;
}
}
}
// calculating automatic sense adjustment
if (p->autosens) {
if (overshoot) {
p->sens = p->sens * (1 - (0.02 * framerate_mod));
p->sens_init = 0;
} else {
if (!silence) {
p->sens = p->sens * (1 + (0.001 * framerate_mod * p->autosens));
if (p->sens_init)
p->sens = p->sens * (1 + (0.1 * framerate_mod));
}
}
}
}
void cava_destroy(struct cava_plan *p) {
free(p->input_buffer);
free(p->bass_multiplier);
free(p->multiplier);
free(p->eq);
free(p->cut_off_frequency);
free(p->FFTbuffer_lower_cut_off);
free(p->FFTbuffer_upper_cut_off);
free(p->cava_fall);
free(p->cava_mem);
free(p->cava_peak);
free(p->prev_cava_out);
fftw_free(p->in_bass_l);
fftw_free(p->in_bass_l_raw);
fftw_free(p->out_bass_l);
fftw_destroy_plan(p->p_bass_l);
fftw_free(p->in_l);
fftw_free(p->in_l_raw);
fftw_free(p->out_l);
fftw_destroy_plan(p->p_l);
if (p->audio_channels == 2) {
fftw_free(p->in_bass_r);
fftw_free(p->in_bass_r_raw);
fftw_free(p->out_bass_r);
fftw_destroy_plan(p->p_bass_r);
fftw_free(p->in_r);
fftw_free(p->out_r);
fftw_free(p->in_r_raw);
fftw_destroy_plan(p->p_r);
}
}
#ifdef __ANDROID__
JNIEXPORT jfloatArray JNICALL Java_com_karlstav_cava_MyGLRenderer_InitCava(
JNIEnv *env, jobject thiz, jint number_of_bars_set, jint refresh_rate, jint lower_cut_off,
jint higher_cut_off) {
jfloatArray cuttOffFreq = (*env)->NewFloatArray(env, number_of_bars_set + 1);
float noise_reduction = pow((float)refresh_rate / 130, 0.75);
plan = cava_init(number_of_bars_set, 44100, 1, 1, noise_reduction, lower_cut_off,
higher_cut_off, CAVA_SCALING_LINEAR);
cava_in = (double *)malloc(plan->FFTbassbufferSize * sizeof(double));
cava_out = (double *)malloc(plan->number_of_bars * sizeof(double));
(*env)->SetFloatArrayRegion(env, cuttOffFreq, 0, plan->number_of_bars + 1,
plan->cut_off_frequency);
return cuttOffFreq;
}
JNIEXPORT jdoubleArray JNICALL Java_com_karlstav_cava_MyGLRenderer_ExecCava(JNIEnv *env,
jobject thiz,
jdoubleArray cava_input,
jint new_samples) {
jdoubleArray cavaReturn = (*env)->NewDoubleArray(env, plan->number_of_bars);
cava_in = (*env)->GetDoubleArrayElements(env, cava_input, NULL);
cava_execute(cava_in, new_samples, cava_out, plan);
(*env)->SetDoubleArrayRegion(env, cavaReturn, 0, plan->number_of_bars, cava_out);
(*env)->ReleaseDoubleArrayElements(env, cava_input, cava_in, JNI_ABORT);
return cavaReturn;
}
JNIEXPORT int JNICALL Java_com_karlstav_cava_CavaCoreTest_InitCava(JNIEnv *env, jobject thiz,
jint number_of_bars_set) {
plan = cava_init(number_of_bars_set, 44100, 1, 1, 0.7, 50, 10000, CAVA_SCALING_LINEAR);
return 1;
}
JNIEXPORT jdoubleArray JNICALL Java_com_karlstav_cava_CavaCoreTest_ExecCava(JNIEnv *env,
jobject thiz,
jdoubleArray cava_input,
jint new_samples) {
jdoubleArray cavaReturn = (*env)->NewDoubleArray(env, plan->number_of_bars);
cava_in = (*env)->GetDoubleArrayElements(env, cava_input, NULL);
cava_execute(cava_in, new_samples, cava_out, plan);
(*env)->SetDoubleArrayRegion(env, cavaReturn, 0, plan->number_of_bars, cava_out);
(*env)->ReleaseDoubleArrayElements(env, cava_input, cava_in, JNI_ABORT);
return cavaReturn;
}
JNIEXPORT void JNICALL Java_com_karlstav_cava_MyGLRenderer_DestroyCava(JNIEnv *env, jobject thiz) {
cava_destroy(plan);
}
#endif

139
cava/cavacore.h Normal file
View File

@@ -0,0 +1,139 @@
/*
Copyright (c) 2022 Karl Stavestrand <karl@stavestrand.no>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifdef __cplusplus
extern "C" {
#endif
#pragma once
#include <stdint.h>
#include <fftw3.h>
#define CAVA_SCALING_LINEAR 0
#define CAVA_SCALING_DECIBEL 1
// cava_plan, parameters used internally by cavacore, do not modify these directly
// only the cut off frequencies is of any potential interest to read out,
// the rest should most likely be hidden somehow
struct cava_plan {
int FFTbassbufferSize;
int FFTbufferSize;
int number_of_bars;
int audio_channels;
int input_buffer_size;
int rate;
int bass_cut_off_bar;
int sens_init;
int autosens;
int frame_skip;
int status;
int scaling_mode;
char error_message[1024];
double sens;
double framerate;
double noise_reduction;
fftw_plan p_bass_l, p_bass_r;
fftw_plan p_l, p_r;
fftw_complex *out_bass_l, *out_bass_r;
fftw_complex *out_l, *out_r;
double *bass_multiplier;
double *multiplier;
double *in_bass_r_raw, *in_bass_l_raw;
double *in_r_raw, *in_l_raw;
double *in_bass_r, *in_bass_l;
double *in_r, *in_l;
double *prev_cava_out, *cava_mem;
double *input_buffer, *cava_peak;
double *eq;
float *cut_off_frequency;
int *FFTbuffer_lower_cut_off;
int *FFTbuffer_upper_cut_off;
double *cava_fall;
};
// cava_init, initialize visualization, takes the following parameters:
// number_of_bars, number of wanted bars per channel
// rate, sample rate of input signal
// channels, number of interleaved channels in input
// autosens, toggle automatic sensitivity adjustment 1 = on, 0 = off
// on, gives a dynamically adjusted output signal from 0 to 1
// the output is continuously adjusted to use the entire range
// off, will pass the raw values from cava directly to the output
// the max values will then be dependent on the input
// noise_reduction, adjust noise reduction filters. 0 - 1, recommended 0.77
// the raw visualization is very noisy, this factor adjusts the integral
// and gravity filters inside cavacore to keep the signal smooth
// 1 will be very slow and smooth, 0 will be fast but noisy.
// low_cut_off, high_cut_off cut off frequencies for visualization in Hz
// recommended: 50, 10000
// scaling_mode, output scaling mode:
// CAVA_SCALING_LINEAR = legacy linear scaling
// CAVA_SCALING_DECIBEL = dB-based logarithmic scaling
// returns a cava_plan to be used by cava_execute. If cava_plan.status is 0 all is OK.
// If cava_plan.status is -1, cava_init was called with an illegal parameter, see error string in
// cava_plan.error_message
extern struct cava_plan *cava_init(int number_of_bars, unsigned int rate, int channels,
int autosens, double noise_reduction, int low_cut_off,
int high_cut_off, int scaling_mode);
// cava_execute, executes visualization
// cava_in, input buffer can be any size. internal buffers in cavacore is
// 4096 * number of channels at 44100 samples rate, if new_samples is greater
// then samples will be discarded. However it is recommended to use less
// new samples per execution as this determines your framerate.
// 512 samples at 44100 sample rate mono, gives about 86 frames per second.
// new_samples, the number of samples in cava_in to be processed per execution
// in case of async reading of data this number is allowed to vary from execution to execution
// cava_out, output buffer. Size must be number of bars * number of channels. Bars will
// be sorted from lowest to highest frequency. If stereo input channels are configured
// then all left channel bars will be first then the right.
// plan, the cava_plan struct returned from cava_init
// cava_execute assumes cava_in samples to be interleaved if more than one channel
// only up to two channels are supported.
extern void cava_execute(double *cava_in, int new_samples, double *cava_out,
struct cava_plan *plan);
// cava_destroy, destroys the plan, frees up memory
extern void cava_destroy(struct cava_plan *plan);
#ifdef __cplusplus
}
#endif

547
discover/featured.json Normal file
View File

@@ -0,0 +1,547 @@
{
"version": 3,
"podcasts": [
{
"id": "discover-daily",
"title": "The Daily",
"description": "This is how the news should sound. Twenty minutes a day, five days a week, hosted by Michael Barbaro and Sabrina Tavernise. Powered by New York Times journalism.",
"feedUrl": "http://rss.art19.com/the-daily",
"author": "The New York Times",
"categories": [
"News & Politics"
]
},
{
"id": "discover-up-first",
"title": "Up First",
"description": "NPR's Up First covers the three biggest stories of the day, with reporting and analysis from NPR News — in 10 minutes.",
"feedUrl": "https://feeds.npr.org/510318/podcast.xml",
"author": "NPR",
"categories": [
"News & Politics"
]
},
{
"id": "discover-npr-politics",
"title": "The NPR Politics Podcast",
"description": "Where everyone gathers for the political conversation of the day. NPR's political reporters talk through the biggest news of the week.",
"feedUrl": "https://feeds.npr.org/510310/podcast.xml",
"author": "NPR",
"categories": [
"News & Politics"
]
},
{
"id": "discover-ben-shapiro",
"title": "The Ben Shapiro Show",
"description": "Ben Shapiro delivers unapologetically conservative commentary on the biggest news stories of the day, blending sharp analysis with his trademark fact-based approach.",
"feedUrl": "https://feeds.megaphone.fm/benshow",
"author": "The Daily Wire",
"categories": [
"News & Politics"
]
},
{
"id": "discover-advisory-opinions",
"title": "Advisory Opinions",
"description": "Host Sarah Isgur and permanent guest David French have twice-weekly conversations about the law, the courts, their collision with politics, and why it all matters — from The Dispatch.",
"feedUrl": "https://feeds.megaphone.fm/DISPME4573820108",
"author": "The Dispatch",
"categories": [
"News & Politics"
]
},
{
"id": "discover-crime-junkie",
"title": "Crime Junkie",
"description": "Crime Junkie satisfies true crime cravings with host Ashley Flowers' obsessed yet accessible approach to real-life mysteries — from unsolved murders to missing persons.",
"feedUrl": "https://feeds.simplecast.com/qm_9xx0g",
"author": "audiochuck",
"categories": [
"True Crime"
]
},
{
"id": "discover-serial",
"title": "Serial",
"description": "Serial Productions makes narrative podcasts that have transformed the medium. From the team that brought you the original Serial, one of the most influential podcasts of all time.",
"feedUrl": "https://feeds.simplecast.com/PpzWFGhg",
"author": "Serial Productions & The New York Times",
"categories": [
"True Crime",
"Storytelling"
]
},
{
"id": "discover-intelligence-matters",
"title": "Intelligence Matters",
"description": "A deep dive into national security, intelligence, and foreign policy with top former officials and experts hosted by CBS News senior correspondent.",
"feedUrl": "https://rss.art19.com/intelligence-matters",
"author": "CBS News",
"categories": [
"True Crime",
"News & Politics"
]
},
{
"id": "discover-smartless",
"title": "SmartLess",
"description": "Jason Bateman, Sean Hayes, and Will Arnett bring you unscripted conversations with surprise celebrity guests — each episode one host reveals the guest to the others.",
"feedUrl": "https://rss.art19.com/smartless",
"author": "Jason Bateman, Sean Hayes, Will Arnett",
"categories": [
"Comedy",
"Entertainment"
]
},
{
"id": "discover-this-past-weekend",
"title": "This Past Weekend w/ Theo Von",
"description": "Comedian Theo Von's uniquely southern perspective blends heartfelt vulnerability and offbeat humor in conversations ranging from celebrity interviews to solo musings.",
"feedUrl": "https://feeds.megaphone.fm/thispastweekend",
"author": "Theo Von",
"categories": [
"Comedy"
]
},
{
"id": "discover-joe-rogan",
"title": "The Joe Rogan Experience",
"description": "The official podcast of comedian Joe Rogan. Long-form conversations with guests from every corner of culture, science, comedy, and beyond.",
"feedUrl": "https://feeds.megaphone.fm/GLT1412515089",
"author": "Joe Rogan",
"categories": [
"Comedy",
"Entertainment"
]
},
{
"id": "discover-comedy-bang-bang",
"title": "Comedy Bang Bang: The Podcast",
"description": "A weekly comedy podcast hosted by Scott Aukerman featuring improv, games, and hilarious conversations with celebrities and the world's best comedians.",
"feedUrl": "https://rss.art19.com/comedy-bang-bang",
"author": "Earwolf",
"categories": [
"Comedy"
]
},
{
"id": "discover-office-ladies",
"title": "Office Ladies",
"description": "The Office stars Jenna Fischer and Angela Kinsey break down each episode of The Office with behind-the-scenes stories, fun facts, and fan Q&A.",
"feedUrl": "https://rss.art19.com/office-ladies",
"author": "Earwolf",
"categories": [
"Comedy",
"Entertainment"
]
},
{
"id": "discover-how-did-this-get-made",
"title": "How Did This Get Made?",
"description": "Comedians Paul Scheer, June Diane Raphael, and Jason Mantzoukas break down the very best of the worst films ever made — blockbuster flops, cult classics, and Nic Cage movies.",
"feedUrl": "https://rss.art19.com/how-did-this-get-made",
"author": "Earwolf",
"categories": [
"Comedy",
"Film"
]
},
{
"id": "discover-wait-wait",
"title": "Wait Wait... Don't Tell Me!",
"description": "NPR's weekly news quiz show. Test your knowledge against the week's biggest news, with panelists and celebrity guests competing in hilarious trivia.",
"feedUrl": "https://feeds.npr.org/344098539/podcast.xml",
"author": "NPR",
"categories": [
"Comedy",
"News & Politics"
]
},
{
"id": "discover-new-heights",
"title": "New Heights with Jason & Travis Kelce",
"description": "Football's funniest family duo — Super Bowl champions Jason and Travis Kelce — drop weekly insights about the NFL and share inside perspectives on sports headlines.",
"feedUrl": "https://rss.art19.com/new-heights",
"author": "Jason & Travis Kelce",
"categories": [
"Sports",
"Comedy"
]
},
{
"id": "discover-bill-simmons",
"title": "The Bill Simmons Podcast",
"description": "Bill Simmons and his cadre of opinionated guests discuss sports, pop culture, and everything in between on The Ringer's flagship podcast.",
"feedUrl": "https://rss.art19.com/the-bill-simmons-podcast",
"author": "The Ringer",
"categories": [
"Sports",
"Entertainment"
]
},
{
"id": "discover-acquired",
"title": "Acquired",
"description": "Acquired tells the stories and strategies of the world's greatest companies. Each episode is a deep dive into a single company's history and the playbooks behind its success.",
"feedUrl": "https://feeds.transistor.fm/acquired",
"author": "Ben Gilbert & David Rosenthal",
"categories": [
"Business",
"Technology"
]
},
{
"id": "discover-all-in",
"title": "All-In Podcast",
"description": "Four tech industry veterans share their unfiltered perspectives on technology, economics, politics, and culture. Insightful, opinionated, and occasionally controversial.",
"feedUrl": "https://allinchamathjason.libsyn.com/rss",
"author": "Chamath Palihapitiya, Jason Calacanis, David Sacks & David Friedberg",
"categories": [
"Business",
"Technology",
"Politics"
]
},
{
"id": "discover-planet-money",
"title": "Planet Money",
"description": "The economy explained. NPR's Planet Money breaks down the economy with creative storytelling that makes sense of a complicated, ever-changing world.",
"feedUrl": "https://feeds.npr.org/510289/podcast.xml",
"author": "NPR",
"categories": [
"Business",
"Economics"
]
},
{
"id": "discover-how-i-built-this",
"title": "How I Built This with Guy Raz",
"description": "Guy Raz interviews the world's best-known entrepreneurs to learn how they built their iconic brands. A master-class on innovation, creativity, and leadership.",
"feedUrl": "https://feeds.npr.org/510313/podcast.xml",
"author": "NPR / Wondery",
"categories": [
"Business",
"Technology"
]
},
{
"id": "discover-freakonomics",
"title": "Freakonomics Radio",
"description": "Discover the hidden side of everything with Stephen Dubner. Each episode explores the riddles of everyday life using the tools of economics.",
"feedUrl": "https://feeds.feedburner.com/freakonomicsradio",
"author": "Stephen J. Dubner",
"categories": [
"Business",
"Economics",
"Society"
]
},
{
"id": "discover-darknet-diaries",
"title": "Darknet Diaries",
"description": "True stories from the dark side of the Internet. Host Jack Rhysider investigates hacks, data breaches, cybercrime, and digital espionage with rigorous journalism and captivating storytelling.",
"feedUrl": "https://podcast.darknetdiaries.com/",
"author": "Jack Rhysider",
"categories": [
"Technology",
"True Crime"
]
},
{
"id": "discover-changelog",
"title": "The Changelog",
"description": "Software's best weekly news brief, deep technical interviews, and talk show. Conversations with the hackers, leaders, and innovators of the open source and software world.",
"feedUrl": "https://changelog.fm/rss",
"author": "Changelog Media",
"categories": [
"Technology",
"Software Engineering"
]
},
{
"id": "discover-twit",
"title": "This Week in Tech (TWiT)",
"description": "Your first podcast of the week, the last word in tech. Leo Laporte and a rotating panel of tech experts discuss the week's biggest tech news.",
"feedUrl": "https://feeds.twit.tv/twit.xml",
"author": "TWiT",
"categories": [
"Technology"
]
},
{
"id": "discover-radiolab",
"title": "Radiolab",
"description": "Radiolab is on a curiosity bender. Each episode weaves together science, legal history, and deeply human stories with innovative sound design. Hosted by Lulu Miller and Latif Nasser.",
"feedUrl": "http://feeds.wnyc.org/radiolab",
"author": "WNYC Studios",
"categories": [
"Science",
"Storytelling"
]
},
{
"id": "discover-huberman-lab",
"title": "Huberman Lab",
"description": "Regularly ranked as the #1 health podcast in the world. Dr. Andrew Huberman discusses science and science-based tools for everyday life: sleep, focus, fitness, and performance.",
"feedUrl": "https://feeds.megaphone.fm/hubermanlab",
"author": "Scicomm Media",
"categories": [
"Health",
"Science"
]
},
{
"id": "discover-skeptics-guide",
"title": "The Skeptics' Guide to the Universe",
"description": "Your guide to reality. A weekly science and critical thinking podcast that explores myths, conspiracies, pseudoscience, and the latest scientific discoveries — with a skeptical eye.",
"feedUrl": "https://feeds.feedburner.com/TheSkepticsGuideToTheUniverse",
"author": "Steven Novella",
"categories": [
"Science",
"Philosophy"
]
},
{
"id": "discover-throughline",
"title": "Throughline",
"description": "The past is never past. NPR's Throughline travels beyond the headlines to answer the question 'How did we get here?' Each episode brings history to life from ancient civilizations to forgotten figures.",
"feedUrl": "https://feeds.npr.org/510333/podcast.xml",
"author": "NPR",
"categories": [
"History",
"Politics"
]
},
{
"id": "discover-hardcore-history",
"title": "Dan Carlin's Hardcore History",
"description": "In Hardcore History, journalist and broadcaster Dan Carlin applies his unorthodox, 'Martian' way of thinking to the past. Multi-hour deep dives into pivotal events that blend high drama with masterful narration.",
"feedUrl": "https://feeds.feedburner.com/dancarlin/history",
"author": "Dan Carlin",
"categories": [
"History"
]
},
{
"id": "discover-history-of-rome",
"title": "The History of Rome",
"description": "A weekly chronological podcast tracing the entire history of Rome, from its mythical founding to the fall of the Western Empire. A masterclass in narrative history.",
"feedUrl": "https://feeds.feedburner.com/TheHistoryOfRome",
"author": "Mike Duncan",
"categories": [
"History"
]
},
{
"id": "discover-philosophize-this",
"title": "Philosophize This!",
"description": "Stephen West walks through the entire history of philosophy chronologically, from the pre-Socratics to contemporary thinkers. Making profound ideas accessible without dumbing them down.",
"feedUrl": "https://philosophizethis.libsyn.com/rss",
"author": "Stephen West",
"categories": [
"Philosophy",
"Education"
]
},
{
"id": "discover-very-bad-wizards",
"title": "Very Bad Wizards",
"description": "A philosopher (Tamler Sommers) and a psychologist (David Pizarro) discuss human nature, ethics, free will, and whatever movie they just watched. Irreverent, insightful, and intellectually honest.",
"feedUrl": "https://feeds.libsyn.com/474285/rss",
"author": "Tamler Sommers & David Pizarro",
"categories": [
"Philosophy",
"Science"
]
},
{
"id": "discover-big-picture",
"title": "The Big Picture",
"description": "The Ringer's Sean Fennessey and Amanda Dobbins discuss the week in movies, TV, and streaming — from box office analysis to what's worth your time.",
"feedUrl": "https://rss.art19.com/the-big-picture",
"author": "The Ringer",
"categories": [
"Film",
"Entertainment"
]
},
{
"id": "discover-all-songs-considered",
"title": "All Songs Considered",
"description": "NPR's flagship music discovery podcast, delivering the best new releases every week across indie rock, jazz, electronic, and everything in between. Discover music you wouldn't stumble across on your own.",
"feedUrl": "https://feeds.npr.org/510019/podcast.xml",
"author": "NPR Music",
"categories": [
"Music"
]
},
{
"id": "discover-switched-on-pop",
"title": "Switched on Pop",
"description": "Musicologist Nate Sloan and songwriter Charlie Harding explain why pop music sounds the way it does — pulling apart chord progressions, production tricks, and cultural trends with zero snobbery.",
"feedUrl": "https://feeds.megaphone.fm/switchedonpop",
"author": "Vox Media / Panoply",
"categories": [
"Music"
]
},
{
"id": "discover-hit-parade",
"title": "Hit Parade",
"description": "Slate's Chris Molanphy traces how songs and genres conquered the Billboard charts, weaving chart history, cultural context, and pure trivia into each episode.",
"feedUrl": "https://feeds.megaphone.fm/hitparade",
"author": "Slate",
"categories": [
"Music",
"History"
]
},
{
"id": "discover-song-exploder",
"title": "Song Exploder",
"description": "Musicians take apart their songs, piece by piece, and tell the story of how they were made. Past guests include Billie Eilish, Fleetwood Mac, and Lin-Manuel Miranda.",
"feedUrl": "https://songexploder.net/rss",
"author": "Hrishikesh Hirway",
"categories": [
"Music",
"Arts"
]
},
{
"id": "discover-blank-check",
"title": "Blank Check with Griffin & David",
"description": "Reviews of directors' complete filmographies, episode by episode. Specifically, auteurs whose early successes afforded them the rare 'blank check' from Hollywood. Painstakingly hilarious detail.",
"feedUrl": "https://audioboom.com/channels/4278829.rss",
"author": "Griffin Newman & David Sims",
"categories": [
"Film",
"Comedy"
]
},
{
"id": "discover-99-invisible",
"title": "99% Invisible",
"description": "A sound-rich, narrative podcast about all the thought that goes into the things we don't think about — the unnoticed architecture and design that shape our world. Hosted by Roman Mars.",
"feedUrl": "https://feeds.simplecast.com/BqbsxVfO",
"author": "Roman Mars",
"categories": [
"Design",
"Arts",
"Culture"
]
},
{
"id": "discover-gastropod",
"title": "Gastropod",
"description": "Food with a side of science and history. Co-hosts Cynthia Graber and Nicola Twilley explore the hidden history and surprising science behind a different food or farming topic every other week.",
"feedUrl": "https://gastropod.com/feed",
"author": "Cynthia Graber & Nicola Twilley",
"categories": [
"Food",
"Science",
"History"
]
},
{
"id": "discover-this-american-life",
"title": "This American Life",
"description": "Hosted by Ira Glass, each episode weaves together stories around a single theme. Combining investigative reporting with intimate personal narratives, it sets the gold standard for audio storytelling.",
"feedUrl": "https://www.thisamericanlife.org/podcast/rss.xml",
"author": "This American Life",
"categories": [
"Storytelling",
"Culture"
]
},
{
"id": "discover-ted-talks-daily",
"title": "TED Talks Daily",
"description": "Thought-provoking ideas on every subject imaginable from the world's leading thinkers and creators. A new TED Talk every weekday.",
"feedUrl": "https://feeds.feedburner.com/TEDTalks_audio",
"author": "TED",
"categories": [
"Education",
"Storytelling"
]
},
{
"id": "discover-tim-ferriss",
"title": "The Tim Ferriss Show",
"description": "Tim Ferriss deconstructs world-class performers — from billionaires to chess prodigies to athletes — to extract the tools, tactics, and routines you can apply to your own life.",
"feedUrl": "https://rss.art19.com/tim-ferriss-show",
"author": "Tim Ferriss",
"categories": [
"Self-Improvement",
"Business"
]
},
{
"id": "discover-jordan-harbinger",
"title": "The Jordan Harbinger Show",
"description": "In-depth conversations with fascinating minds — from Ray Dalio to arms traffickers. Jordan Harbinger unpacks guests' wisdom into practical nuggets for work, life, and relationships.",
"feedUrl": "https://rss.art19.com/the-jordan-harbinger-show",
"author": "Jordan Harbinger",
"categories": [
"Self-Improvement"
]
},
{
"id": "discover-on-purpose",
"title": "On Purpose with Jay Shetty",
"description": "Jay Shetty hosts conversations and workshops designed to make you happier, healthier, and more healed. Interviews with experts, celebrities, and thought leaders on mindset and habit-building.",
"feedUrl": "https://rss.art19.com/on-purpose-with-jay-shetty",
"author": "Jay Shetty",
"categories": [
"Self-Improvement",
"Health"
]
},
{
"id": "discover-10-percent-happier",
"title": "10% Happier with Dan Harris",
"description": "Self-help for the skeptical. ABC News anchor Dan Harris explores meditation and mindfulness with scientists, monks, and teachers, born from his own panic attack on live TV.",
"feedUrl": "https://rss.art19.com/ten-percent-happier",
"author": "Dan Harris",
"categories": [
"Self-Improvement",
"Health",
"Philosophy"
]
},
{
"id": "discover-school-of-greatness",
"title": "The School of Greatness",
"description": "Former pro athlete Lewis Howes interviews successful people across business, sports, science, and literature to help you unlock your inner greatness and live your best life.",
"feedUrl": "https://rss.art19.com/the-school-of-greatness",
"author": "Lewis Howes",
"categories": [
"Self-Improvement",
"Business"
]
},
{
"id": "discover-sysk",
"title": "Stuff You Should Know",
"description": "If you've ever wanted to know about champagne, satanism, the Stonewall Uprising, chaos theory, LSD, El Nino, true crime or Roswell — Josh and Chuck have got you covered.",
"feedUrl": "https://www.omnycontent.com/d/playlist/e73c998e-6e60-432f-8610-ae210140c5b1/A91018A4-EA4F-4130-BF55-AE270180C327/44710ECC-10BB-48D1-93C7-AE270180C33E/podcast.rss",
"author": "iHeartPodcasts (Josh Clark & Chuck Bryant)",
"categories": [
"Education",
"Comedy"
]
},
{
"id": "discover-in-our-time",
"title": "In Our Time",
"description": "Melvyn Bragg and guests on BBC Radio 4 discuss the history of ideas — from the Peloponnesian War to the science of photography. A weekly graduate seminar in audio form since 1998.",
"feedUrl": "https://podcasts.files.bbci.co.uk/b006qykl.rss",
"author": "BBC Radio 4",
"categories": [
"History",
"Education",
"Philosophy"
]
}
]
}

View File

@@ -1,5 +1,6 @@
{ {
"name": "podcast-tui-app", "name": "podcast-tui-app",
"version": "0.1.0",
"module": "src/index.tsx", "module": "src/index.tsx",
"type": "module", "type": "module",
"private": true, "private": true,
@@ -7,12 +8,13 @@
"podtui": "./dist/index.js" "podtui": "./dist/index.js"
}, },
"scripts": { "scripts": {
"start": "bun src/index.tsx", "start": "bun --preload @opentui/solid/preload src/index.tsx",
"dev": "bun --watch src/index.tsx", "dev": "bun --preload @opentui/solid/preload --watch src/index.tsx",
"build:native": "bash scripts/build-cavacore.sh",
"build": "bun run build.ts", "build": "bun run build.ts",
"dist": "bun dist/index.js", "dist": "bun dist/index.js",
"test": "bun test", "test": "bun test",
"lint": "bun run lint.ts" "lint": "bun tsc --noEmit"
}, },
"devDependencies": { "devDependencies": {
"@types/bun": "latest", "@types/bun": "latest",

41
packaging/aur/.SRCINFO Normal file
View File

@@ -0,0 +1,41 @@
pkgbase = podtui-bin
pkgdesc = Terminal podcast and audio player with synchronized audio-waveform visualization
pkgver = 0.2.0
pkgrel = 1
url = https://github.com/mikefreno/podtui
arch = x86_64
arch = aarch64
license = MIT
depends = mpv
provides = podtui
conflicts = podtui
options = !strip
source_x86_64 = https://github.com/mikefreno/podtui/releases/download/v0.2.0/podtui-linux-x64.tar.gz
source_x86_64 = https://github.com/mikefreno/podtui/releases/download/v0.2.0/LICENSE
sha256sums_x86_64 = 5c2be309341bda9550ad7669b48d3f46341c687234ddfaa0c84a6a9177f049fc
sha256sums_x86_64 = 106a1290f2b9942a43785938cc8ccb1f72cf360babc58316f8d7feee829e98fc
source_aarch64 = https://github.com/mikefreno/podtui/releases/download/v0.2.0/podtui-linux-arm64.tar.gz
source_aarch64 = https://github.com/mikefreno/podtui/releases/download/v0.2.0/LICENSE
sha256sums_aarch64 = c9c22d3a18cd192f89fbd5ff712d3502c4de0cce7550156c6a0d48d76e56e0d5
sha256sums_aarch64 = 106a1290f2b9942a43785938cc8ccb1f72cf360babc58316f8d7feee829e98fc
pkgname = podtui-bin
pkgver = 0.2.0
pkgrel = 1
url = https://github.com/mikefreno/podtui
pkgdesc = Terminal podcast and audio player with synchronized audio-waveform visualization
arch = x86_64
arch = aarch64
license = MIT
depends = mpv
provides = podtui
conflicts = podtui
options = !strip
source_x86_64 = https://github.com/mikefreno/podtui/releases/download/v0.2.0/podtui-linux-x64.tar.gz
source_x86_64 = https://github.com/mikefreno/podtui/releases/download/v0.2.0/LICENSE
sha256sums_x86_64 = 5c2be309341bda9550ad7669b48d3f46341c687234ddfaa0c84a6a9177f049fc
sha256sums_x86_64 = 106a1290f2b9942a43785938cc8ccb1f72cf360babc58316f8d7feee829e98fc
source_aarch64 = https://github.com/mikefreno/podtui/releases/download/v0.2.0/podtui-linux-arm64.tar.gz
source_aarch64 = https://github.com/mikefreno/podtui/releases/download/v0.2.0/LICENSE
sha256sums_aarch64 = c9c22d3a18cd192f89fbd5ff712d3502c4de0cce7550156c6a0d48d76e56e0d5
sha256sums_aarch64 = 106a1290f2b9942a43785938cc8ccb1f72cf360babc58316f8d7feee829e98fc

55
packaging/aur/PKGBUILD Normal file
View File

@@ -0,0 +1,55 @@
# Maintainer: Michael Freno <michael.freno@gmail.com>
# Contributor: Michael Freno <michael.freno@gmail.com>
# podtui-bin — TUI podcast/audiobook player with synchronized audio-waveform
# visualization. Serves the official standalone release binary and its two FFI
# sibling libraries (libcavacore.so + libopentui.so) from GitHub Releases.
#
# The embedded Bun runtime is statically linked into the binary — no Bun, no
# fftw needed at runtime (fftw3 is linked statically into libcavacore.so).
pkgname=podtui-bin
_pkgname=podtui
pkgver=0.2.0
pkgrel=1
pkgdesc="Terminal podcast and audio player with synchronized audio-waveform visualization"
url="https://github.com/mikefreno/podtui"
arch=('x86_64' 'aarch64')
license=('MIT')
depends=('mpv') # sole audio backend; no-op without it
provides=("${_pkgname}")
conflicts=("${_pkgname}")
options=('!strip') # standalone binary, pre-minified
source_x86_64=(
"https://github.com/mikefreno/podtui/releases/download/v${pkgver}/podtui-linux-x64.tar.gz"
"https://github.com/mikefreno/podtui/releases/download/v${pkgver}/LICENSE"
)
source_aarch64=(
"https://github.com/mikefreno/podtui/releases/download/v${pkgver}/podtui-linux-arm64.tar.gz"
"https://github.com/mikefreno/podtui/releases/download/v${pkgver}/LICENSE"
)
sha256sums_x86_64=(
'5c2be309341bda9550ad7669b48d3f46341c687234ddfaa0c84a6a9177f049fc'
'106a1290f2b9942a43785938cc8ccb1f72cf360babc58316f8d7feee829e98fc'
)
sha256sums_aarch64=(
'c9c22d3a18cd192f89fbd5ff712d3502c4de0cce7550156c6a0d48d76e56e0d5'
'106a1290f2b9942a43785938cc8ccb1f72cf360babc58316f8d7feee829e98fc'
)
package() {
local libdir
case "$CARCH" in
x86_64) libdir="podtui-linux-x64" ;;
aarch64) libdir="podtui-linux-arm64" ;;
esac
# Binary + native FFI libs must stay side by side in /usr/lib/podtui/;
# a /usr/bin symlink works because the embedded Bun runtime resolves
# process.execPath through symlinks (verified against the compiled binary).
install -Dm755 "${srcdir}/${libdir}/podtui" "${pkgdir}/usr/lib/podtui/podtui"
install -Dm644 "${srcdir}/${libdir}/libcavacore.so" "${pkgdir}/usr/lib/podtui/libcavacore.so"
install -Dm644 "${srcdir}/${libdir}/libopentui.so" "${pkgdir}/usr/lib/podtui/libopentui.so"
ln -s /usr/lib/podtui/podtui "${pkgdir}/usr/bin/podtui"
install -Dm644 "${srcdir}/LICENSE" "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
}

View File

@@ -0,0 +1,60 @@
#!/bin/bash
# gen-srcinfo.sh — emit .SRCINFO for the podtui-bin PKGBUILD without makepkg.
# Emits the same field set/ordering makepkg --printsrcinfo produces for this
# PKGBUILD shape (single package, per-arch source + sha256sums arrays).
set -euo pipefail
cd "$(dirname "$0")"
# shellcheck disable=SC1091
. ./PKGBUILD
emit() { printf '\t%s = %s\n' "$1" "$2"; }
emit_multi() { # $1 field, rest values
local f="$1"
shift
for v in "$@"; do emit "$f" "$v"; done
}
pkgbase_section() {
echo "pkgbase = ${pkgname}"
for f in pkgdesc pkgver pkgrel url; do
v="${!f}"
[ -n "${v:-}" ] && emit "$f" "$v"
done
[ -n "${install:-}" ] && emit install "$install"
[ "${#arch[@]}" -gt 0 ] && emit_multi arch "${arch[@]}"
[ "${#license[@]}" -gt 0 ] && emit_multi license "${license[@]}"
[ "${#depends[@]}" -gt 0 ] && emit_multi depends "${depends[@]}"
[ "${#provides[@]}" -gt 0 ] && emit_multi provides "${provides[@]}"
[ "${#conflicts[@]}" -gt 0 ] && emit_multi conflicts "${conflicts[@]}"
[ "${#options[@]}" -gt 0 ] && emit_multi options "${options[@]}"
emit_arch_arrays
}
emit_arch_arrays() {
for a in "${arch[@]}"; do
src_name="source_${a}"
sha_name="sha256sums_${a}"
src_val="${src_name}[@]"
sha_val="${sha_name}[@]"
[ "${#src_name}" -gt 0 ] && emit_multi "source_${a}" "${!src_val}"
emit_multi "sha256sums_${a}" "${!sha_val}"
done
}
pkgbase_section
echo ""
echo "pkgname = ${pkgname}"
for v in pkgver pkgrel url; do
val="${!v}"
[ -n "${val:-}" ] && emit "$v" "$val"
done
emit pkgdesc "$pkgdesc"
[ "${#arch[@]}" -gt 0 ] && emit_multi arch "${arch[@]}"
[ "${#license[@]}" -gt 0 ] && emit_multi license "${license[@]}"
[ "${#depends[@]}" -gt 0 ] && emit_multi depends "${depends[@]}"
[ "${#provides[@]}" -gt 0 ] && emit_multi provides "${provides[@]}"
[ "${#conflicts[@]}" -gt 0 ] && emit_multi conflicts "${conflicts[@]}"
[ "${#options[@]}" -gt 0 ] && emit_multi options "${options[@]}"
emit_arch_arrays

101
scripts/build-cavacore.sh Executable file
View File

@@ -0,0 +1,101 @@
#!/usr/bin/env bash
#
# Build cavacore as a shared library with fftw3 statically linked.
#
# Prerequisites:
# macOS: brew install fftw
# Linux: apt install libfftw3-dev (or equivalent)
#
# Output: src/native/libcavacore.{dylib,so}
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SRC="$ROOT/cava/cavacore.c"
OUT_DIR="$ROOT/src/native"
mkdir -p "$OUT_DIR"
OS="$(uname -s)"
ARCH="$(uname -m)"
# Resolve fftw3 paths. The static archive lives in different places per
# platform: Homebrew (/opt/homebrew on arm64, /usr/local on Intel) and, on
# Debian/Ubuntu, the multiarch dir /usr/lib/<triplet> (e.g.
# x86_64-linux-gnu, aarch64-linux-gnu).
if [ "$OS" = "Darwin" ]; then
LIB_EXT="dylib"
SHARED_FLAG="-dynamiclib"
INSTALL_NAME="-install_name @rpath/libcavacore.dylib"
if [ "$ARCH" = "arm64" ]; then
FFTW_HINTS="/opt/homebrew /usr/local"
else
FFTW_HINTS="/usr/local /opt/homebrew"
fi
else
LIB_EXT="so"
SHARED_FLAG="-shared"
INSTALL_NAME=""
FFTW_HINTS="/usr /usr/local"
fi
FFTW_PREFIX="${FFTW_PREFIX:-}"
FFTW_STATIC=""
if [ -n "$FFTW_PREFIX" ]; then
FFTW_STATIC="$FFTW_PREFIX/lib/libfftw3.a"
else
for hint in $FFTW_HINTS; do
for cand in "$hint/lib/libfftw3.a" "$hint/lib/${ARCH}-linux-gnu/libfftw3.a"; do
if [ -f "$cand" ]; then
FFTW_STATIC="$cand"
FFTW_PREFIX="$hint"
break 2
fi
done
done
fi
if [ -z "$FFTW_STATIC" ] || [ ! -f "$FFTW_STATIC" ]; then
echo "Error: libfftw3.a not found (searched: ${FFTW_HINTS})"
echo "Install fftw3: brew install fftw (macOS) or apt install libfftw3-dev (Linux)"
echo "or point FFTW_PREFIX at a prefix containing lib/libfftw3.a."
exit 1
fi
FFTW_INCLUDE="$FFTW_PREFIX/include"
if [ ! -d "$FFTW_INCLUDE" ]; then
FFTW_INCLUDE="$FFTW_PREFIX/include/$(basename "$(dirname "$FFTW_STATIC")")"
fi
if [ ! -f "$SRC" ]; then
echo "Error: cavacore.c not found at $SRC"
echo "The cava source is vendored under cava/ (from github.com/karlstav/cava, MIT)."
exit 1
fi
OUT="$OUT_DIR/libcavacore.$LIB_EXT"
echo "Building libcavacore.$LIB_EXT ($OS $ARCH)"
echo " Source: $SRC"
echo " FFTW3: $FFTW_STATIC"
echo " Output: $OUT"
cc -O2 \
$SHARED_FLAG \
$INSTALL_NAME \
-fPIC \
-I"$FFTW_INCLUDE" \
-I"$ROOT/cava" \
-o "$OUT" \
"$SRC" \
"$FFTW_STATIC" \
-lm
echo "Built: $OUT"
# Verify exported symbols
if [ "$OS" = "Darwin" ]; then
echo ""
echo "Exported symbols:"
nm -gU "$OUT" | grep "cava_"
fi

240
scripts/release-tag.sh Executable file
View File

@@ -0,0 +1,240 @@
#!/bin/bash
# release-tag.sh — PodTui version bump, commit, tag, and push.
#
# Mirrors the release flow from FlexLove's scripts/make-tag.sh, adapted for
# PodTui's single version source (src/index.tsx) and dual remotes (gh, gt).
#
# Usage:
# scripts/release-tag.sh interactive release
# scripts/release-tag.sh --dry-run plan the bump/tag/pushes without doing
#
# Pushing a v* tag to the `gh` remote triggers .github/workflows/release.yml
# (4-platform tarball builds) — the release and the Homebrew tap update then
# happen automatically and need no further local action.
set -e
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"
DRY_RUN=0
for arg in "$@"; do
case "$arg" in
--dry-run | -n) DRY_RUN=1 ;;
--help | -h)
echo "Usage: scripts/release-tag.sh [--dry-run]"
echo " --dry-run, -n show the plan without committing, tagging, or pushing"
exit 0
;;
*)
echo -e "${RED}Unknown option: ${arg}${NC}" >&2
exit 2
;;
esac
done
if [ ! -d .git ] && [ ! -f .git ]; then
echo -e "${RED}Error: Not in a git repository${NC}"
exit 1
fi
if ! git diff-index --quiet HEAD --; then
echo -e "${YELLOW}You have uncommitted changes:${NC}"
git status --short
echo ""
read -p "Continue anyway? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo -e "${RED}Aborted${NC}"
exit 1
fi
echo ""
fi
# Current version from the latest tag; fall back to src/index.tsx.
CURRENT_VERSION=$(git describe --tags --abbrev=0 2>/dev/null | sed 's/^v//')
if [ -z "$CURRENT_VERSION" ]; then
CURRENT_VERSION=$(grep -m 1 "^const VERSION" src/index.tsx | sed -E 's/.*"([0-9]+\.[0-9]+\.[0-9]+)".*/\1/')
if [ -z "$CURRENT_VERSION" ]; then
echo -e "${RED}Error: could not extract version from git tags or src/index.tsx${NC}"
exit 1
fi
echo -e "${YELLOW}No tags found; using VERSION from src/index.tsx (${CURRENT_VERSION})${NC}"
fi
echo -e "${CYAN}Current version:${NC} ${GREEN}v${CURRENT_VERSION}${NC}"
echo ""
IFS='.' read -r MAJOR MINOR PATCH <<<"$CURRENT_VERSION"
MAJOR=$(echo "$MAJOR" | sed 's/[^0-9].*//')
MINOR=$(echo "$MINOR" | sed 's/[^0-9].*//')
PATCH=$(echo "$PATCH" | sed 's/[^0-9].*//')
echo -e "${CYAN}Select version bump type:${NC}"
echo " 1) Major (breaking changes) ${MAJOR}.${MINOR}.${PATCH}$((MAJOR + 1)).0.0"
echo " 2) Minor (new features) ${MAJOR}.${MINOR}.${PATCH}${MAJOR}.$((MINOR + 1)).0"
echo " 3) Patch (bug fixes) ${MAJOR}.${MINOR}.${PATCH}${MAJOR}.${MINOR}.$((PATCH + 1))"
echo " 4) Custom version"
echo " 5) Cancel"
echo ""
read -p "Enter choice (1-5): " -n 1 -r CHOICE
echo ""
echo ""
case $CHOICE in
1)
NEW_VERSION="$((MAJOR + 1)).0.0"
;;
2)
NEW_VERSION="${MAJOR}.$((MINOR + 1)).0"
;;
3)
NEW_VERSION="${MAJOR}.${MINOR}.$((PATCH + 1))"
;;
4)
read -p "Enter custom version (e.g., 1.0.0-beta): " -r NEW_VERSION
;;
5)
echo -e "${RED}Cancelled${NC}"
exit 0
;;
*)
echo -e "${RED}Invalid choice${NC}"
exit 1
;;
esac
# Version sanity check (tags are vMAJOR.MINOR.PATCH).
if ! echo "$NEW_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo -e "${RED}Error: ${NEW_VERSION} is not a valid X.Y.Z version (v tags only)${NC}"
exit 1
fi
echo -e "${CYAN}New version:${NC} ${GREEN}v${NEW_VERSION}${NC}"
echo ""
echo -e "${YELLOW}This will:${NC}"
echo " 1. Set src/index.tsx → VERSION = \"${NEW_VERSION}\""
echo " 2. Commit the bump"
echo " 3. Create annotated tag v${NEW_VERSION}"
echo " 4. Push master and the tag to every remote"
REMOTES=$(git remote)
for r in $REMOTES; do
echo "$r"
done
echo ""
echo -e "${YELLOW}Note: pushing the tag to ${BLUE}gh${YELLOW} triggers release.yml CI (4-platform"
echo "binaries + GitHub Release) and the homebrew-podtui tap update.${NC}"
echo ""
read -p "Proceed? (y/n) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo -e "${YELLOW}Aborted — no changes made${NC}"
exit 0
fi
if [ "$DRY_RUN" -eq 1 ]; then
echo ""
echo -e "${CYAN}[dry-run]${NC} would have:"
echo " sed src/index.tsx: VERSION \"${CURRENT_VERSION}\" → \"${NEW_VERSION}\""
echo " git commit -m \"bump VERSION to ${NEW_VERSION}\""
echo " git tag -a v${NEW_VERSION} -m \"PodTUI v${NEW_VERSION}\""
for r in $REMOTES; do echo " push $r master"; done
for r in $REMOTES; do echo " push $r v${NEW_VERSION}"; done
echo ""
echo -e "${GREEN}Plan only — nothing written${NC}"
exit 0
fi
# ── Apply the bump ───────────────────────────────────────────────────────────
echo ""
echo -e "${CYAN}[1/4]${NC} Updating src/index.tsx..."
sed -i.bak "s/const VERSION = \"[^\"]*\"/const VERSION = \"${NEW_VERSION}\"/" src/index.tsx
rm -f src/index.tsx.bak
echo -e "${GREEN}✓ src/index.tsx updated${NC}"
if git diff --quiet -- src/index.tsx; then
if git rev-parse -q --verify "refs/tags/v${NEW_VERSION}" >/dev/null; then
echo -e "${YELLOW}Already at ${NEW_VERSION} and tag v${NEW_VERSION} exists — nothing to release.${NC}"
exit 0
fi
echo -e "${YELLOW}VERSION is already ${NEW_VERSION} (bump already committed).${NC}"
echo -e "${YELLOW}Will skip the commit and just create the missing tag + push.${NC}"
read -p "Tag v${NEW_VERSION} on current HEAD and push? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo -e "${YELLOW}Aborted — no changes made${NC}"
exit 0
fi
else
git add src/index.tsx
echo -e "${GREEN}✓ staged${NC}"
echo -e "${CYAN}[2/4]${NC} Committing..."
DEFAULT_COMMIT_MSG="bump VERSION to ${NEW_VERSION}"
echo -e "Default commit message: ${CYAN}${DEFAULT_COMMIT_MSG}${NC}"
read -p "Use default? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Nn]$ ]]; then
read -p "Enter commit message: " -r COMMIT_MSG
else
COMMIT_MSG="$DEFAULT_COMMIT_MSG"
fi
git commit -m "$COMMIT_MSG"
echo -e "${GREEN}✓ committed: ${COMMIT_MSG}${NC}"
fi
echo -e "${CYAN}[3/4]${NC} Tagging..."
git tag -a "v${NEW_VERSION}" -m "PodTUI v${NEW_VERSION}"
echo -e "${GREEN}✓ tagged v${NEW_VERSION}${NC}"
echo ""
echo -e "${CYAN}[4/4]${NC} Pushing..."
FAILED=""
for r in $REMOTES; do
if ! git push "$r" master; then
FAILED="${FAILED}${r} (branch) "
fi
if ! git push "$r" tag "v${NEW_VERSION}"; then
FAILED="${FAILED}${r} (tag) "
fi
done
echo ""
if [ -n "$FAILED" ]; then
echo -e "${RED}═══════════════════════════════════════${NC}"
echo -e "${RED}✗ Push failed for: ${FAILED}${NC}"
echo -e "${RED}═══════════════════════════════════════${NC}"
echo ""
echo -e "${YELLOW}The commit and tag exist locally. To retry:${NC}"
for r in $REMOTES; do
echo " git push ${r} master"
echo " git push ${r} v${NEW_VERSION}"
done
echo ""
echo -e "${YELLOW}To undo:${NC}"
echo " git tag -d v${NEW_VERSION}"
echo " git reset --soft HEAD~1"
exit 1
fi
echo -e "${GREEN}═══════════════════════════════════════${NC}"
echo -e "${GREEN}✓ PodTui v${NEW_VERSION} released${NC}"
echo -e "${GREEN}═══════════════════════════════════════${NC}"
echo ""
echo -e "${CYAN}Version:${NC} ${CURRENT_VERSION}${GREEN}${NEW_VERSION}${NC}"
echo -e "${CYAN}Tag:${NC} v${NEW_VERSION}"
echo ""
echo -e "${BLUE}Next steps (automatic, nothing to do):${NC}"
echo " 1. GitHub Action release.yml builds 4 tarballs and attaches them:"
echo -e " ${CYAN}gh run watch \$(gh run list --limit 1 --json databaseId -q .[0].databaseId)${NC}"
echo " 2. mikefreno/homebrew-podtui self-updates within the hour (Formula"
echo " URLs + sha256s); brew upgrade podtui afterwards."

612
scripts/tui-harness.tsx Normal file
View File

@@ -0,0 +1,612 @@
#!/usr/bin/env bun
/**
* PodTUI LLM-interactive harness — stateless per-turn snapshot bridge.
*
* Each invocation:
* 1. Points XDG_CONFIG_HOME / XDG_DATA_HOME / PODTUI_AUDIO_BACKEND at a
* sandbox dir under .harness so your real ~/.config/podtui is never touched.
* 2. Replays the saved action log (.harness/actions.json) from scratch.
* 3. Appends + executes the new action passed on the CLI.
* 4. Renders, captures structured spans, and prints: plain frame + distinct
* style summary (colors/attrs) + selected store state + captured issues
* (stderr / uncaught rejections). Full structured spans are dumped to
* .harness/last-frame.json every turn.
*
* Audio is silent (Noop) by default during the snapshot model so replaying the
* log each turn doesn't re-trigger real playback. Pass --audio (or set
* PODTUI_AUDIO_BACKEND) to flip to a real backend for the new action only.
*
* Import order mirrors src/index.tsx (lazy) to avoid a NavigationContext cycle.
*
* Usage:
* bun scripts/tui-harness.tsx init [--size 100x30] [--seed]
* bun scripts/tui-harness.tsx key <key> [mods...] # mods: ctrl shift meta
* bun scripts/tui-harness.tsx arrow <up|down|left|right> [mods...]
* bun scripts/tui-harness.tsx enter|escape|tab|space|backspace
* bun scripts/tui-harness.tsx type "<text>"
* bun scripts/tui-harness.tsx wait <ms>
* bun scripts/tui-harness.tsx resize <w> <h>
* bun scripts/tui-harness.tsx frame # re-render, no new action
* bun scripts/tui-harness.tsx state [all|nav|audio|feed|app]
* bun scripts/tui-harness.tsx actions # print action log
* bun scripts/tui-harness.tsx reset
* bun scripts/tui-harness.tsx seed [--from ~/.config/podtui]
*
* Flags (after the subcommand):
* --size WxH terminal size (default 100x30)
* --audio enable real audio backend for the new action only
* --no-settle skip the extra render-settle loops
* --styles print the distinct-styles sample block (off by default)
* --verbose restore the original multi-line pretty output
*/
import { testRender } from "@opentui/solid";
import {
existsSync,
mkdirSync,
cpSync,
writeFileSync,
readFileSync,
} from "node:fs";
import { join } from "node:path";
// ── Paths & sandbox ────────────────────────────────────────────────────────
const HANDLES_DIR = ".harness";
const CONFIG_HOME = join(HANDLES_DIR, "config-home");
const DATA_HOME = join(HANDLES_DIR, "data-home");
const ACTIONS_FILE = join(HANDLES_DIR, "actions.json");
const FRAME_JSON = join(HANDLES_DIR, "last-frame.json");
const FRAME_TXT = join(HANDLES_DIR, "last-frame.txt");
const STATE_JSON = join(HANDLES_DIR, "state.json");
// Sandbox must be active BEFORE any app module is imported, so the app's
// config-dir / persistence reads resolve into .harness/*.
function activateSandbox(): void {
mkdirSync(CONFIG_HOME, { recursive: true });
mkdirSync(DATA_HOME, { recursive: true });
process.env.XDG_CONFIG_HOME = join(process.cwd(), CONFIG_HOME);
process.env.XDG_DATA_HOME = join(process.cwd(), DATA_HOME);
// Silent audio during replay by default; --audio flips this after import.
if (!process.env.PODTUI_AUDIO_BACKEND)
process.env.PODTUI_AUDIO_BACKEND = "none";
}
// ── Action log ─────────────────────────────────────────────────────────────
type Mod = "ctrl" | "shift" | "meta" | "super" | "hyper";
type Action =
| { t: "key"; k: string; mods?: Mod[] }
| { t: "arrow"; d: "up" | "down" | "left" | "right"; mods?: Mod[] }
| { t: "enter" | "escape" | "tab" | "space" | "backspace"; mods?: Mod[] }
| { t: "type"; s: string }
| { t: "wait"; ms: number }
| { t: "resize"; w: number; h: number };
function loadActions(): Action[] {
try {
return JSON.parse(readFileSync(ACTIONS_FILE, "utf8") || "[]");
} catch {
return [];
}
}
function saveActions(a: Action[]): void {
writeFileSync(ACTIONS_FILE, JSON.stringify(a, null, 2));
}
// ── Issue capture ──────────────────────────────────────────────────────────
const issues: string[] = [];
// Captured by the StateProbe component rendered inside the provider tree —
// Solid contexts can only be read from within the tree, not from outside.
let navRef: any = null;
function captureIssues(): void {
const origErr = console.error;
const origWarn = console.warn;
console.error = (...args: unknown[]) => {
issues.push("stderr: " + args.map(String).join(" "));
origErr(...(args as any[]));
};
console.warn = (...args: unknown[]) => {
issues.push("warn: " + args.map(String).join(" "));
origWarn(...(args as any[]));
};
process.on("uncaughtException", (e) =>
issues.push("uncaught: " + ((e as Error)?.stack || String(e))),
);
process.on("unhandledRejection", (e) =>
issues.push("unhandledRejection: " + ((e as Error)?.stack || String(e))),
);
}
// ── Span rendering ─────────────────────────────────────────────────────────
type RGBA = { r: number; g: number; b: number; a: number };
type Span = {
text: string;
fg: RGBA | null;
bg: RGBA | null;
attributes: number;
width: number;
};
const ATTR_NAMES: Record<string, number> = {
BOLD: 1,
DIM: 2,
ITALIC: 4,
UNDERLINE: 8,
BLINK: 16,
INVERSE: 32,
HIDDEN: 64,
STRIKETHROUGH: 128,
};
function hex(c: RGBA | null): string | null {
if (!c) return null;
if (c.a === 0) return null; // transparent → "default"
const [r, g, b] = [c.r, c.g, c.b].map((v) =>
Math.max(0, Math.min(255, Math.round(v))),
);
return "#" + [r, g, b].map((n) => n.toString(16).padStart(2, "0")).join("");
}
function attrLabels(attr: number): string[] {
const out: string[] = [];
for (const [name, bit] of Object.entries(ATTR_NAMES))
if (attr & bit) out.push(name.toLowerCase());
return out;
}
// (Plain frame text comes from captureCharFrame instead of span reconstruction.)
function distinctStyles(spans: {
lines: { spans: Span[] }[];
}): { tag: string; sample: string; n: number }[] {
const map = new Map<string, { tag: string; sample: string; n: number }>();
for (const line of spans.lines) {
for (const s of line.spans) {
if (!s.text || s.text.trim() === "") continue;
const fg = hex(s.fg as any);
const bg = hex(s.bg as any);
if (!fg && !bg && s.attributes === 0) continue; // default — skip
const tags = attrLabels(s.attributes);
const tag = `[fg=${fg ?? "·"} bg=${bg ?? "·"}${tags.length ? " " + tags.join("+") : ""}]`;
const ex = map.get(tag);
const sample = s.text.replace(/\n/g, "\\n").slice(0, 28);
if (ex) {
ex.n++;
if (ex.sample.length < 14 && sample.length > ex.sample.length)
ex.sample = sample;
} else {
map.set(tag, { tag, sample, n: 1 });
}
}
}
return [...map.values()].sort((a, b) => b.n - a.n).slice(0, 20);
}
// ── Arg parsing ────────────────────────────────────────────────────────────
function parseFlags(rest: string[]): {
flags: Record<string, string | boolean>;
positional: string[];
} {
const flags: Record<string, string | boolean> = {};
const positional: string[] = [];
for (let i = 0; i < rest.length; i++) {
const a = rest[i];
if (a.startsWith("--")) {
if (a === "--audio") flags.audio = true;
else if (a === "--no-settle") flags["no-settle"] = true;
else if (a === "--styles") flags.styles = true;
else if (a === "--verbose") flags.verbose = true;
else if (a === "--size") {
flags.size = rest[++i];
const m = /(\d+)x(\d+)/.exec(String(flags.size));
if (m) {
flags.w = m[1];
flags.h = m[2];
}
} else if (a === "--from") {
flags.from = rest[++i];
} else {
flags[a.slice(2)] = rest[++i] ?? true;
}
} else {
positional.push(a);
}
}
return { flags, positional };
}
function parseMods(positional: string[]): Mod[] {
const mods: Mod[] = [];
for (const p of positional)
if (["ctrl", "shift", "meta", "super", "hyper"].includes(p))
mods.push(p as Mod);
return mods;
}
function buildAction(cmd: string, positional: string[]): Action | null {
const mods = parseMods(positional);
const first = positional[0];
switch (cmd) {
case "key":
if (!first) throw new Error("key requires a <key> argument");
return { t: "key", k: first, mods: mods.length ? mods : undefined };
case "arrow":
if (!first || !["up", "down", "left", "right"].includes(first))
throw new Error("arrow requires up|down|left|right");
return {
t: "arrow",
d: first as any,
mods: mods.length ? mods : undefined,
};
case "enter":
case "escape":
case "tab":
case "space":
case "backspace":
return { t: cmd, mods: mods.length ? mods : undefined };
case "type":
if (first === undefined) throw new Error("type requires <text>");
// Re-join the rest in case text had spaces; positional[0] already is first token,
// caller should quote. We join all positional as the text.
return { t: "type", s: positional.join(" ") };
case "wait":
if (!first) throw new Error("wait requires <ms>");
return { t: "wait", ms: parseInt(first, 10) || 0 };
case "resize":
if (!first || !positional[1]) throw new Error("resize requires <w> <h>");
return {
t: "resize",
w: parseInt(first, 10) || 100,
h: parseInt(positional[1], 10) || 30,
};
case "frame":
case "state":
case "reset":
case "actions":
case "init":
case "seed":
return null;
default:
throw new Error(`unknown command: ${cmd}`);
}
}
// ── Execute one action against a mounted setup ──────────────────────────────
function fmtMods(mods?: Mod[]): Record<string, boolean> | undefined {
if (!mods || !mods.length) return undefined;
const o: Record<string, boolean> = {};
for (const m of mods) o[m] = true;
return o;
}
async function execAction(setup: any, a: Action): Promise<void> {
const mi = setup.mockInput;
switch (a.t) {
case "key":
mi.pressKey(a.k, fmtMods(a.mods));
break;
case "arrow":
mi.pressArrow(a.d, fmtMods(a.mods));
break;
case "enter":
mi.pressEnter(fmtMods(a.mods));
break;
case "escape":
mi.pressEscape(fmtMods(a.mods));
break;
case "tab":
mi.pressTab(fmtMods(a.mods));
break;
case "space":
mi.pressKey("space");
break;
case "backspace":
mi.pressBackspace(fmtMods(a.mods));
break;
case "type":
await mi.typeText(a.s, 0);
break;
case "wait":
await new Promise((r) => setTimeout(r, a.ms));
break;
case "resize":
setup.resize(a.w, a.h);
break;
}
await setup.renderOnce();
// tiny settle for reactive updates
await new Promise((r) => setTimeout(r, 40));
}
// ── Main ───────────────────────────────────────────────────────────────────
async function main() {
activateSandbox();
captureIssues();
const argv = process.argv.slice(2);
const cmd = argv[0] ?? "frame";
const { flags, positional } = parseFlags(argv.slice(1));
// Local-only commands that don't mount.
if (cmd === "reset") {
saveActions([]);
console.log("✔ actions log cleared.");
return;
}
if (cmd === "actions") {
const a = loadActions();
console.log(`Action log (${a.length}):`);
console.log(JSON.stringify(a, null, 2));
return;
}
if (cmd === "seed") {
const from = String(
flags.from || join(process.env.HOME || "~", ".config", "podtui"),
);
if (!existsSync(from)) {
console.error(`seed source not found: ${from}`);
process.exit(1);
}
const dest = join(process.env.XDG_CONFIG_HOME!, "podtui");
cpSync(from, dest, { recursive: true });
console.log(`✔ seeded sandbox config from ${from}${dest}`);
return;
}
// Size settings.
let width = 100;
let height = 30;
if (flags.w) width = parseInt(String(flags.w), 10);
if (flags.h) height = parseInt(String(flags.h), 10);
let newAction: Action | null = null;
let actions: Action[] = [];
if (cmd !== "init" && cmd !== "frame" && cmd !== "state") {
newAction = buildAction(cmd, positional);
}
if (cmd === "init") {
saveActions([]);
actions = [];
} else {
actions = loadActions();
}
// Mount the real app. Lazy imports (order matters — see NavigationContext cycle).
const { App } = await import("../src/App");
const { ThemeProvider } = await import("../src/context/ThemeContext");
const toast = await import("../src/ui/toast");
const { KeybindProvider } = await import("../src/context/KeybindContext");
const { NavigationProvider, useNavigation } = await import(
"../src/context/NavigationContext"
);
const { DialogProvider } = await import("../src/ui/dialog");
const { CommandProvider } = await import("../src/ui/command");
// Probe rendered inside the provider tree so context hooks resolve.
const StateProbe = () => {
try {
navRef = useNavigation();
} catch (e) {
issues.push("StateProbe: " + String(e));
}
return null;
};
const HarnessRoot = () => (
<toast.ToastProvider>
<ThemeProvider mode="dark">
<KeybindProvider>
<NavigationProvider>
<StateProbe />
<DialogProvider>
<CommandProvider>
<App />
<toast.Toast />
</CommandProvider>
</DialogProvider>
</NavigationProvider>
</KeybindProvider>
</ThemeProvider>
</toast.ToastProvider>
);
const setup = await testRender(() => <HarnessRoot />, {
width,
height,
useThread: false,
});
(setup.renderer as any).disableStdoutInterception?.();
// Wait for providers (keybinds/theme/feeds) to settle.
const settleLoops = flags["no-settle"] ? 2 : 12;
for (let i = 0; i < settleLoops; i++) {
await setup.renderOnce();
await new Promise((r) => setTimeout(r, 60));
}
// Replay history silently (audio already Noop via env).
for (const a of actions) await execAction(setup, a);
// For the *new* action: if --audio, flip to a real backend just for it.
let audioControls: any = null;
try {
const { useAudio } = await import("../src/hooks/useAudio");
audioControls = useAudio();
} catch (e) {
issues.push("useAudio import: " + String(e));
}
if (newAction) {
if (flags.audio && audioControls?.switchBackend) {
// Force (re)creation of a real backend; useAudio caches, switchBackend resets.
delete process.env.PODTUI_AUDIO_BACKEND;
await audioControls.switchBackend("mpv").catch(() => {});
}
actions.push(newAction);
saveActions(actions);
await execAction(setup, newAction);
}
// Final settle + capture.
await setup.renderOnce();
await new Promise((r) => setTimeout(r, 60));
const spans = setup.captureSpans() as {
lines: { spans: Span[] }[];
cols: number;
rows: number;
cursor: [number, number];
};
const plainFrame = setup.captureCharFrame();
// Dump structured spans + plain frame.
try {
writeFileSync(FRAME_JSON, JSON.stringify(spans));
writeFileSync(FRAME_TXT, plainFrame);
} catch {}
// Store state snapshot.
const state: Record<string, unknown> = {};
try {
const nav = navRef;
if (nav) {
state.nav = {
tab: nav.activeTab?.(),
pane: nav.activePane?.(),
mode: nav.mode?.(),
input: nav.inputFocused?.(),
sel: nav.selectedIds?.()?.length ?? 0,
ready: nav.ready,
};
} else {
state.nav = "NAV_REF not captured (probe did not run)";
}
} catch (e) {
state.nav = "ERR: " + String(e);
}
try {
if (audioControls) {
state.audio = {
backend: audioControls.backendName ? audioControls.backendName() : null,
playing: audioControls.isPlaying ? audioControls.isPlaying() : null,
pos: audioControls.position ? audioControls.position() : null,
dur: audioControls.duration ? audioControls.duration() : null,
vol: audioControls.volume ? audioControls.volume() : null,
err: audioControls.error ? audioControls.error() : null,
ep: audioControls.currentEpisode
? audioControls.currentEpisode()?.title
: null,
};
}
} catch (e) {
state.audio = "ERR: " + String(e);
}
try {
const { useFeedStore } = await import("../src/stores/feed");
const fs_ = useFeedStore();
const feeds = fs_.feeds ? fs_.feeds() : [];
state.feed = {
count: feeds?.length ?? 0,
sel: fs_.selectedFeedId ? fs_.selectedFeedId() : null,
loading: fs_.isLoadingFeeds ? fs_.isLoadingFeeds() : null,
titles: (feeds ?? []).slice(0, 8).map((f: any) => f?.podcast?.title),
};
} catch (e) {
state.feed = "ERR: " + String(e);
}
try {
writeFileSync(STATE_JSON, JSON.stringify(state));
} catch {}
// ── Output ──────────────────────────────────────────────────────────────
// Compact by default: trimmed frame, one-line state per section, no styles
// block, no boilerplate footer. Use --styles / --verbose to opt back in.
const verbose = !!flags.verbose;
const scope = cmd === "state" ? String(positional[0] || "all") : "all";
// A line is "visually empty" if it's either fully blank OR contains only
// box-drawing chars + whitespace (i.e. empty-pane interior padding like
// "│ │"). Runs of these collapse to a single `…N` marker so an empty
// 24-row pane costs 1 line, not 18.
const BOX_CHARS = "│┌┐└─┤├┬┴┼┐┘┌└┤├┬┴┼┌┐└┘─│┤├┬┴┼";
const isVisuallyEmpty = (l: string): boolean =>
l === "" || [...l].every((ch) => ch === " " || BOX_CHARS.includes(ch));
const frameTrimmed = (() => {
const lines = plainFrame
.replace(/\n+$/, "")
.split("\n")
.map((l) => l.replace(/\s+$/, ""));
while (lines.length && isVisuallyEmpty(lines[lines.length - 1]))
lines.pop();
const out: string[] = [];
let blank = 0;
const flushBlanks = () => {
if (blank >= 3) out.push(`${blank} empty`);
else for (let i = 0; i < blank; i++) out.push("");
blank = 0;
};
for (const l of lines) {
if (isVisuallyEmpty(l)) {
blank++;
} else {
flushBlanks();
out.push(l);
}
}
flushBlanks();
return out.join("\n");
})();
console.log(
`FRAME ${spans.cols}x${spans.rows} cur=${spans.cursor[0]},${spans.cursor[1]} acts=${actions.length} ${cmd}`,
);
console.log(frameTrimmed);
// ── distinct styles: opt-in only (--styles OR --verbose) ──
if (scope === "all" && (flags.styles || verbose)) {
const styles = distinctStyles(spans);
if (styles.length) {
console.log("-- styles (top 20) --");
for (const s of styles) console.log(` ${s.tag} ×${s.n}${s.sample}`);
}
}
// ── state: one compact line per requested section ──
const want = (k: string) => scope === "all" || scope === k;
const compact = (obj: unknown): string =>
verbose ? JSON.stringify(obj, null, 2) : JSON.stringify(obj);
if (want("nav")) console.log("nav " + compact(state.nav));
if (want("audio")) console.log("audio " + compact(state.audio));
if (want("feed")) console.log("feed " + compact(state.feed));
if (want("app")) console.log("app (not dumped in v1)");
// ── issues: terse ──
if (issues.length) {
console.log(`issues:${issues.length}`);
for (const i of issues.slice(0, 20)) console.log(" ! " + i);
} else {
console.log("issues:none");
}
// Footer is identical every run — only print on init or --verbose.
if (cmd === "init" || verbose) {
console.log(
`(spans ${FRAME_JSON} | frame ${FRAME_TXT} | state ${STATE_JSON})`,
);
}
// Tear down child processes (audio backend) before exit to avoid orphans.
try {
if (audioControls?.stop) await audioControls.stop().catch(() => {});
} catch (e) {
issues.push("teardown audio: " + String(e));
}
try {
setup.renderer.destroy();
} catch (e) {
issues.push("teardown renderer: " + String(e));
}
process.exit(0);
}
main().catch((err) => {
console.error("HARNESS FAILED:", err?.stack || err);
process.exit(1);
});

View File

@@ -1,307 +1,93 @@
import { createSignal, ErrorBoundary } from "solid-js"; import { ErrorBoundary } from "solid-js";
import { Layout } from "./components/Layout"; import { useSelectionHandler, useRenderer } from "@opentui/solid";
import { Navigation } from "./components/Navigation"; import { useAudio } from "@/hooks/useAudio";
import { TabNavigation } from "./components/TabNavigation"; import { useMultimediaKeys } from "@/hooks/useMultimediaKeys";
import { FeedPage } from "./components/FeedPage"; import { Clipboard } from "@/utils/clipboard";
import { MyShowsPage } from "./components/MyShowsPage"; import { useToast } from "@/ui/toast";
import { LoginScreen } from "./components/LoginScreen"; import { useTheme, ThemeProvider } from "./context/ThemeContext";
import { CodeValidation } from "./components/CodeValidation"; import { KeybindProvider, useKeybinds } from "./context/KeybindContext";
import { OAuthPlaceholder } from "./components/OAuthPlaceholder"; import {
import { SyncProfile } from "./components/SyncProfile"; NavigationProvider,
import { SearchPage } from "./components/SearchPage"; useNavigation,
import { DiscoverPage } from "./components/DiscoverPage"; NavMode,
import { Player } from "./components/Player"; } from "./context/NavigationContext";
import { SettingsScreen } from "./components/SettingsScreen"; import { TABS } from "./utils/navigation";
import { useAuthStore } from "./stores/auth"; import { Shell } from "./components/Shell";
import { useFeedStore } from "./stores/feed";
import { useAppStore } from "./stores/app"; const DEBUG = import.meta.env.DEBUG;
import { useAudio } from "./hooks/useAudio";
import { FeedVisibility } from "./types/feed";
import { useAppKeyboard } from "./hooks/useAppKeyboard";
import type { TabId } from "./components/Tab";
import type { AuthScreen } from "./types/auth";
import type { Episode } from "./types/episode";
export function App() { export function App() {
const [activeTab, setActiveTab] = createSignal<TabId>("feed"); const nav = useNavigation();
const [authScreen, setAuthScreen] = createSignal<AuthScreen>("login");
const [showAuthPanel, setShowAuthPanel] = createSignal(false);
const [inputFocused, setInputFocused] = createSignal(false);
const [layerDepth, setLayerDepth] = createSignal(0);
const auth = useAuthStore();
const feedStore = useFeedStore();
const appStore = useAppStore();
const audio = useAudio(); const audio = useAudio();
const toast = useToast();
const renderer = useRenderer();
const themeContext = useTheme();
const theme = themeContext.theme;
const keybind = useKeybinds();
const handlePlayEpisode = (episode: Episode) => { // Multimedia keys (physical play/seek keys) still feed the audio backend
audio.play(episode); // regardless of the on-screen yazi keybinds.
setActiveTab("player"); useMultimediaKeys({
setLayerDepth(1); playerFocused: () =>
}; nav.activeTab() === TABS.PLAYER && nav.mode() !== NavMode.NORMAL
? true
// My Shows page returns panel renderers : false,
const myShows = MyShowsPage({ inputFocused: () => nav.inputFocused(),
get focused() { return activeTab() === "shows" && layerDepth() > 0 }, hasEpisode: () => !!audio.currentEpisode(),
onPlayEpisode: (episode, feed) => {
handlePlayEpisode(episode);
},
onExit: () => setLayerDepth(0),
}); });
// Centralized keyboard handler for all tab navigation and shortcuts // Mouse text-selection → clipboard (unchanged from the old shell).
useAppKeyboard({ useSelectionHandler((selection: any) => {
get activeTab() { if (!selection) return;
return activeTab(); const text = selection.getSelectedText?.();
}, if (!text || text.trim().length === 0) return;
onTabChange: (tab: TabId) => { Clipboard.copy(text)
setActiveTab(tab); .then(() =>
setInputFocused(false); toast.show({ message: "Copied to Clipboard!", variant: "info" }),
}, )
get inputFocused() { return inputFocused() }, .catch(toast.error)
get navigationEnabled() { return layerDepth() === 0 }, .finally(() => renderer.clearSelection());
layerDepth,
onLayerChange: (newDepth) => {
setLayerDepth(newDepth);
},
onAction: (action) => {
if (action === "escape") {
if (layerDepth() > 0) {
setLayerDepth(0);
setInputFocused(false);
} else {
setShowAuthPanel(false);
setInputFocused(false);
}
}
if (action === "enter" && layerDepth() === 0) {
setLayerDepth(1);
}
},
}); });
const getPanels = () => { const backgroundColor = () =>
const tab = activeTab(); themeContext.selected === "system"
? "transparent"
switch (tab) { : themeContext.theme.surface;
case "feed":
return {
panels: [
{
title: "Feed - Latest Episodes",
content: (
<FeedPage
focused={layerDepth() > 0}
onPlayEpisode={(episode, feed) => {
handlePlayEpisode(episode);
}}
onExit={() => setLayerDepth(0)}
/>
),
},
],
activePanelIndex: 0,
hint: "j/k navigate | Enter play | r refresh | Esc back",
};
case "shows":
return {
panels: [
{
title: "My Shows",
width: 35,
content: myShows.showsPanel(),
focused: myShows.focusPane() === "shows",
},
{
title: myShows.selectedShow()
? `${myShows.selectedShow()!.podcast.title} - Episodes`
: "Episodes",
content: myShows.episodesPanel(),
focused: myShows.focusPane() === "episodes",
},
],
activePanelIndex: myShows.focusPane() === "shows" ? 0 : 1,
hint: "h/l switch panes | j/k navigate | Enter play | r refresh | d unsubscribe | Esc back",
};
case "settings":
if (showAuthPanel()) {
if (auth.isAuthenticated) {
return {
panels: [{
title: "Account",
content: (
<SyncProfile
focused={layerDepth() > 0}
onLogout={() => {
auth.logout();
setShowAuthPanel(false);
}}
onManageSync={() => setShowAuthPanel(false)}
/>
),
}],
activePanelIndex: 0,
hint: "Esc back",
};
}
const authContent = () => {
switch (authScreen()) {
case "code":
return (
<CodeValidation
focused={layerDepth() > 0}
onBack={() => setAuthScreen("login")}
/>
);
case "oauth":
return (
<OAuthPlaceholder
focused={layerDepth() > 0}
onBack={() => setAuthScreen("login")}
onNavigateToCode={() => setAuthScreen("code")}
/>
);
default:
return (
<LoginScreen
focused={layerDepth() > 0}
onNavigateToCode={() => setAuthScreen("code")}
onNavigateToOAuth={() => setAuthScreen("oauth")}
/>
);
}
};
return {
panels: [{
title: "Sign In",
content: authContent(),
}],
activePanelIndex: 0,
hint: "Esc back",
};
}
return {
panels: [{
title: "Settings",
content: (
<SettingsScreen
onOpenAccount={() => setShowAuthPanel(true)}
accountLabel={
auth.isAuthenticated
? `Signed in as ${auth.user?.email}`
: "Not signed in"
}
accountStatus={auth.isAuthenticated ? "signed-in" : "signed-out"}
onExit={() => setLayerDepth(0)}
/>
),
}],
activePanelIndex: 0,
hint: "j/k navigate | Enter select | Esc back",
};
case "discover":
return {
panels: [{
title: "Discover",
content: (
<DiscoverPage
focused={layerDepth() > 0}
onExit={() => setLayerDepth(0)}
/>
),
}],
activePanelIndex: 0,
hint: "Tab switch focus | j/k navigate | Enter subscribe | r refresh | Esc back",
};
case "search":
return {
panels: [{
title: "Search",
content: (
<SearchPage
focused={layerDepth() > 0}
onInputFocusChange={setInputFocused}
onExit={() => setLayerDepth(0)}
onSubscribe={(result) => {
const feeds = feedStore.feeds();
const alreadySubscribed = feeds.some(
(feed) =>
feed.podcast.id === result.podcast.id ||
feed.podcast.feedUrl === result.podcast.feedUrl,
);
if (!alreadySubscribed) {
feedStore.addFeed(
{ ...result.podcast, isSubscribed: true },
result.sourceId,
FeedVisibility.PUBLIC,
);
}
}}
/>
),
}],
activePanelIndex: 0,
hint: "Tab switch focus | / search | Enter select | Esc back",
};
case "player":
return {
panels: [{
title: "Player",
content: (
<Player focused={layerDepth() > 0} onExit={() => setLayerDepth(0)} />
),
}],
activePanelIndex: 0,
hint: "Space play/pause | Esc back",
};
default:
return {
panels: [{
title: tab,
content: (
<box padding={2}>
<text>Coming soon</text>
</box>
),
}],
activePanelIndex: 0,
hint: "",
};
}
};
return ( return (
<ErrorBoundary fallback={(err) => ( <ErrorBoundary
<box border padding={2}> fallback={(err) => (
<text fg="red"> <box border padding={2} borderColor={theme.error}>
Error: {err?.message ?? String(err)}{"\n"} <text fg={theme.error}>
Press a number key (1-6) to switch tabs. Error: {err?.message ?? String(err)}
{"\n"}
Press 1-6 to switch tabs, or : to open the command bar.
</text> </text>
</box> </box>
)}> )}
<Layout >
header={ <box
<TabNavigation activeTab={activeTab()} onTabSelect={setActiveTab} /> flexDirection="column"
} width="100%"
footer={ height="100%"
<box flexDirection="row" justifyContent="space-between" width="100%"> backgroundColor={backgroundColor()}
<Navigation activeTab={activeTab()} onTabSelect={setActiveTab} /> >
<text fg="gray">{getPanels().hint}</text> {DEBUG && (
<box flexDirection="row" width="100%" height={1}>
<text fg={theme.primary}></text>
<text fg={theme.secondary}></text>
<text fg={theme.accent}></text>
<text fg={theme.error}></text>
<text fg={theme.warning}></text>
<text fg={theme.success}></text>
<text fg={theme.info}></text>
<text fg={theme.text}></text>
<text fg={theme.textMuted}></text>
<text fg={theme.surface}></text>
</box>
)}
<Shell />
</box> </box>
}
panels={getPanels().panels}
activePanelIndex={getPanels().activePanelIndex}
/>
</ErrorBoundary> </ErrorBoundary>
); );
} }

View File

@@ -1,5 +1,7 @@
import type { Podcast } from "../types/podcast" import type { Podcast } from "../types/podcast"
import type { Episode, EpisodeType } from "../types/episode" import type { Episode, EpisodeType } from "../types/episode"
import { detectContentType, ContentType } from "../utils/rss-content-detector"
import { htmlToText } from "../utils/html-to-text"
const getTagValue = (xml: string, tag: string): string => { const getTagValue = (xml: string, tag: string): string => {
const match = xml.match(new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, "i")) const match = xml.match(new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, "i"))
@@ -22,6 +24,20 @@ const decodeEntities = (value: string) =>
.replace(/&quot;/g, '"') .replace(/&quot;/g, '"')
.replace(/&#39;/g, "'") .replace(/&#39;/g, "'")
/**
* Clean a field (description or title): detect HTML vs plain text, and convert
* HTML to readable plain text. Plain text just gets entity decoding.
*/
const cleanField = (raw: string): string => {
if (!raw) return ""
const decoded = decodeEntities(raw)
const type = detectContentType(decoded)
if (type === ContentType.HTML) {
return htmlToText(decoded)
}
return decoded
}
/** /**
* Parse an itunes:duration value which can be: * Parse an itunes:duration value which can be:
* - "HH:MM:SS" * - "HH:MM:SS"
@@ -60,15 +76,15 @@ const parseEpisodeType = (raw: string): EpisodeType | undefined => {
export const parseRSSFeed = (xml: string, feedUrl: string): Podcast & { episodes: Episode[] } => { export const parseRSSFeed = (xml: string, feedUrl: string): Podcast & { episodes: Episode[] } => {
const channel = xml.match(/<channel[\s\S]*?<\/channel>/i)?.[0] ?? xml const channel = xml.match(/<channel[\s\S]*?<\/channel>/i)?.[0] ?? xml
const title = decodeEntities(getTagValue(channel, "title")) || "Untitled Podcast" const title = cleanField(getTagValue(channel, "title")) || "Untitled Podcast"
const description = decodeEntities(getTagValue(channel, "description")) const description = cleanField(getTagValue(channel, "description"))
const author = decodeEntities(getTagValue(channel, "itunes:author")) const author = decodeEntities(getTagValue(channel, "itunes:author"))
const lastUpdated = new Date() const lastUpdated = new Date()
const items = channel.match(/<item[\s\S]*?<\/item>/gi) ?? [] const items = channel.match(/<item[\s\S]*?<\/item>/gi) ?? []
const episodes = items.map((item, index) => { const episodes = items.map((item, index) => {
const epTitle = decodeEntities(getTagValue(item, "title")) || `Episode ${index + 1}` const epTitle = cleanField(getTagValue(item, "title")) || `Episode ${index + 1}`
const epDescription = decodeEntities(getTagValue(item, "description")) const epDescription = cleanField(getTagValue(item, "description"))
const pubDate = new Date(getTagValue(item, "pubDate") || Date.now()) const pubDate = new Date(getTagValue(item, "pubDate") || Date.now())
// Audio URL + file size + MIME type from <enclosure> // Audio URL + file size + MIME type from <enclosure>

View File

@@ -1,42 +0,0 @@
import type { JSX } from "solid-js"
type BoxLayoutProps = {
children?: JSX.Element
flexDirection?: "row" | "column" | "row-reverse" | "column-reverse"
justifyContent?:
| "flex-start"
| "flex-end"
| "center"
| "space-between"
| "space-around"
| "space-evenly"
alignItems?: "flex-start" | "flex-end" | "center" | "stretch" | "baseline"
gap?: number
width?: number | "auto" | `${number}%`
height?: number | "auto" | `${number}%`
padding?: number
margin?: number
border?: boolean
title?: string
}
export function BoxLayout(props: BoxLayoutProps) {
return (
<box
style={{
flexDirection: props.flexDirection,
justifyContent: props.justifyContent,
alignItems: props.alignItems,
gap: props.gap,
width: props.width,
height: props.height,
padding: props.padding,
margin: props.margin,
}}
border={props.border}
title={props.title}
>
{props.children}
</box>
)
}

View File

@@ -1,40 +0,0 @@
/**
* CategoryFilter component - Horizontal category filter tabs
*/
import { For } from "solid-js"
import type { DiscoverCategory } from "../stores/discover"
type CategoryFilterProps = {
categories: DiscoverCategory[]
selectedCategory: string
focused: boolean
onSelect?: (categoryId: string) => void
}
export function CategoryFilter(props: CategoryFilterProps) {
return (
<box flexDirection="row" gap={1} flexWrap="wrap">
<For each={props.categories}>
{(category) => {
const isSelected = () => props.selectedCategory === category.id
return (
<box
padding={0}
paddingLeft={1}
paddingRight={1}
border={isSelected()}
backgroundColor={isSelected() ? "#444" : undefined}
onMouseDown={() => props.onSelect?.(category.id)}
>
<text fg={isSelected() ? "cyan" : "gray"}>
{category.icon} {category.name}
</text>
</box>
)
}}
</For>
</box>
)
}

View File

@@ -1,172 +0,0 @@
/**
* Code validation component for PodTUI
* 8-character alphanumeric code input for sync authentication
*/
import { createSignal } from "solid-js"
import { useAuthStore } from "../stores/auth"
import { AUTH_CONFIG } from "../config/auth"
interface CodeValidationProps {
focused?: boolean
onBack?: () => void
}
type FocusField = "code" | "submit" | "back"
export function CodeValidation(props: CodeValidationProps) {
const auth = useAuthStore()
const [code, setCode] = createSignal("")
const [focusField, setFocusField] = createSignal<FocusField>("code")
const [codeError, setCodeError] = createSignal<string | null>(null)
const fields: FocusField[] = ["code", "submit", "back"]
/** Format code as user types (uppercase, alphanumeric only) */
const handleCodeInput = (value: string) => {
const formatted = value.toUpperCase().replace(/[^A-Z0-9]/g, "")
// Limit to max length
const limited = formatted.slice(0, AUTH_CONFIG.codeValidation.codeLength)
setCode(limited)
// Clear error when typing
if (codeError()) {
setCodeError(null)
}
}
const validateCode = (value: string): boolean => {
if (!value) {
setCodeError("Code is required")
return false
}
if (value.length !== AUTH_CONFIG.codeValidation.codeLength) {
setCodeError(`Code must be ${AUTH_CONFIG.codeValidation.codeLength} characters`)
return false
}
if (!AUTH_CONFIG.codeValidation.allowedChars.test(value)) {
setCodeError("Code must contain only letters and numbers")
return false
}
setCodeError(null)
return true
}
const handleSubmit = async () => {
if (!validateCode(code())) {
return
}
const success = await auth.validateCode(code())
if (!success && auth.error) {
setCodeError(auth.error.message)
}
}
const handleKeyPress = (key: { name: string; shift?: boolean }) => {
if (key.name === "tab") {
const currentIndex = fields.indexOf(focusField())
const nextIndex = key.shift
? (currentIndex - 1 + fields.length) % fields.length
: (currentIndex + 1) % fields.length
setFocusField(fields[nextIndex])
} else if (key.name === "return" || key.name === "enter") {
if (focusField() === "submit") {
handleSubmit()
} else if (focusField() === "back" && props.onBack) {
props.onBack()
}
} else if (key.name === "escape" && props.onBack) {
props.onBack()
}
}
const codeProgress = () => {
const len = code().length
const max = AUTH_CONFIG.codeValidation.codeLength
return `${len}/${max}`
}
const codeDisplay = () => {
const current = code()
const max = AUTH_CONFIG.codeValidation.codeLength
const filled = current.split("")
const empty = Array(max - filled.length).fill("_")
return [...filled, ...empty].join(" ")
}
return (
<box flexDirection="column" border padding={2} gap={1}>
<text>
<strong>Enter Sync Code</strong>
</text>
<box height={1} />
<text fg="gray">Enter your 8-character sync code to link your account.</text>
<text fg="gray">You can get this code from the web portal.</text>
<box height={1} />
{/* Code display */}
<box flexDirection="column" gap={0}>
<text fg={focusField() === "code" ? "cyan" : undefined}>
Code ({codeProgress()}):
</text>
<box border padding={1}>
<text fg={code().length === AUTH_CONFIG.codeValidation.codeLength ? "green" : "yellow"}>
{codeDisplay()}
</text>
</box>
{/* Hidden input for actual typing */}
<input
value={code()}
onInput={handleCodeInput}
placeholder=""
focused={props.focused && focusField() === "code"}
width={30}
/>
{codeError() && (
<text fg="red">{codeError()}</text>
)}
</box>
<box height={1} />
{/* Action buttons */}
<box flexDirection="row" gap={2}>
<box
border
padding={1}
backgroundColor={focusField() === "submit" ? "#333" : undefined}
>
<text fg={focusField() === "submit" ? "cyan" : undefined}>
{auth.isLoading ? "Validating..." : "[Enter] Validate Code"}
</text>
</box>
<box
border
padding={1}
backgroundColor={focusField() === "back" ? "#333" : undefined}
>
<text fg={focusField() === "back" ? "yellow" : "gray"}>
[Esc] Back to Login
</text>
</box>
</box>
{/* Auth error message */}
{auth.error && (
<text fg="red">{auth.error.message}</text>
)}
<box height={1} />
<text fg="gray">Tab to navigate, Enter to select, Esc to go back</text>
</box>
)
}

View File

@@ -1,35 +0,0 @@
import type { JSX } from "solid-js"
type ColumnProps = {
children?: JSX.Element
gap?: number
alignItems?: "flex-start" | "flex-end" | "center" | "stretch" | "baseline"
justifyContent?:
| "flex-start"
| "flex-end"
| "center"
| "space-between"
| "space-around"
| "space-evenly"
width?: number | "auto" | `${number}%`
height?: number | "auto" | `${number}%`
padding?: number
}
export function Column(props: ColumnProps) {
return (
<box
style={{
flexDirection: "column",
gap: props.gap,
alignItems: props.alignItems,
justifyContent: props.justifyContent,
width: props.width,
height: props.height,
padding: props.padding,
}}
>
{props.children}
</box>
)
}

View File

@@ -1,201 +0,0 @@
/**
* DiscoverPage component - Main discover/browse interface for PodTUI
*/
import { createSignal } from "solid-js"
import { useKeyboard } from "@opentui/solid"
import { useDiscoverStore, DISCOVER_CATEGORIES } from "../stores/discover"
import { CategoryFilter } from "./CategoryFilter"
import { TrendingShows } from "./TrendingShows"
type DiscoverPageProps = {
focused: boolean
onExit?: () => void
}
type FocusArea = "categories" | "shows"
export function DiscoverPage(props: DiscoverPageProps) {
const discoverStore = useDiscoverStore()
const [focusArea, setFocusArea] = createSignal<FocusArea>("shows")
const [showIndex, setShowIndex] = createSignal(0)
const [categoryIndex, setCategoryIndex] = createSignal(0)
// Keyboard navigation
useKeyboard((key) => {
if (!props.focused) return
const area = focusArea()
// Tab switches focus between categories and shows
if (key.name === "tab") {
if (key.shift) {
setFocusArea((a) => (a === "categories" ? "shows" : "categories"))
} else {
setFocusArea((a) => (a === "categories" ? "shows" : "categories"))
}
return
}
if ((key.name === "return" || key.name === "enter") && area === "categories") {
setFocusArea("shows")
return
}
// Category navigation
if (area === "categories") {
if (key.name === "left" || key.name === "h") {
const nextIndex = Math.max(0, categoryIndex() - 1)
setCategoryIndex(nextIndex)
const cat = DISCOVER_CATEGORIES[nextIndex]
if (cat) discoverStore.setSelectedCategory(cat.id)
setShowIndex(0)
return
}
if (key.name === "right" || key.name === "l") {
const nextIndex = Math.min(DISCOVER_CATEGORIES.length - 1, categoryIndex() + 1)
setCategoryIndex(nextIndex)
const cat = DISCOVER_CATEGORIES[nextIndex]
if (cat) discoverStore.setSelectedCategory(cat.id)
setShowIndex(0)
return
}
if (key.name === "return" || key.name === "enter") {
// Select category and move to shows
setFocusArea("shows")
return
}
if (key.name === "down" || key.name === "j") {
setFocusArea("shows")
return
}
}
// Shows navigation
if (area === "shows") {
const shows = discoverStore.filteredPodcasts()
if (key.name === "down" || key.name === "j") {
if (shows.length === 0) return
setShowIndex((i) => Math.min(i + 1, shows.length - 1))
return
}
if (key.name === "up" || key.name === "k") {
if (shows.length === 0) {
setFocusArea("categories")
return
}
const newIndex = showIndex() - 1
if (newIndex < 0) {
setFocusArea("categories")
} else {
setShowIndex(newIndex)
}
return
}
if (key.name === "return" || key.name === "enter") {
// Subscribe/unsubscribe
const podcast = shows[showIndex()]
if (podcast) {
discoverStore.toggleSubscription(podcast.id)
}
return
}
}
if (key.name === "escape") {
if (area === "shows") {
setFocusArea("categories")
key.stopPropagation()
} else {
props.onExit?.()
}
return
}
// Refresh with 'r'
if (key.name === "r") {
discoverStore.refresh()
return
}
})
const handleCategorySelect = (categoryId: string) => {
discoverStore.setSelectedCategory(categoryId)
const index = DISCOVER_CATEGORIES.findIndex((c) => c.id === categoryId)
if (index >= 0) setCategoryIndex(index)
setShowIndex(0)
}
const handleShowSelect = (index: number) => {
setShowIndex(index)
setFocusArea("shows")
}
const handleSubscribe = (podcast: { id: string }) => {
discoverStore.toggleSubscription(podcast.id)
}
return (
<box flexDirection="column" height="100%" gap={1}>
{/* Header */}
<box flexDirection="row" justifyContent="space-between" alignItems="center">
<text>
<strong>Discover Podcasts</strong>
</text>
<box flexDirection="row" gap={2}>
<text fg="gray">
{discoverStore.filteredPodcasts().length} shows
</text>
<box onMouseDown={() => discoverStore.refresh()}>
<text fg="cyan">[R] Refresh</text>
</box>
</box>
</box>
{/* Category Filter */}
<box border padding={1}>
<box flexDirection="column" gap={1}>
<text fg={focusArea() === "categories" ? "cyan" : "gray"}>
Categories:
</text>
<CategoryFilter
categories={discoverStore.categories}
selectedCategory={discoverStore.selectedCategory()}
focused={focusArea() === "categories"}
onSelect={handleCategorySelect}
/>
</box>
</box>
{/* Trending Shows */}
<box flexDirection="column" flexGrow={1} border>
<box padding={1}>
<text fg={focusArea() === "shows" ? "cyan" : "gray"}>
Trending in {
DISCOVER_CATEGORIES.find(
(c) => c.id === discoverStore.selectedCategory()
)?.name ?? "All"
}
</text>
</box>
<TrendingShows
podcasts={discoverStore.filteredPodcasts()}
selectedIndex={showIndex()}
focused={focusArea() === "shows"}
isLoading={discoverStore.isLoading()}
onSelect={handleShowSelect}
onSubscribe={handleSubscribe}
/>
</box>
{/* Footer Hints */}
<box flexDirection="row" gap={2}>
<text fg="gray">[Tab] Switch focus</text>
<text fg="gray">[j/k] Navigate</text>
<text fg="gray">[Enter] Subscribe</text>
<text fg="gray">[Esc] Up</text>
<text fg="gray">[R] Refresh</text>
</box>
</box>
)
}

View File

@@ -1,178 +0,0 @@
/**
* Feed detail view component for PodTUI
* Shows podcast info and episode list
*/
import { createSignal, For, Show } from "solid-js"
import { useKeyboard } from "@opentui/solid"
import type { Feed } from "../types/feed"
import type { Episode } from "../types/episode"
import { format } from "date-fns"
interface FeedDetailProps {
feed: Feed
focused?: boolean
onBack?: () => void
onPlayEpisode?: (episode: Episode) => void
}
export function FeedDetail(props: FeedDetailProps) {
const [selectedIndex, setSelectedIndex] = createSignal(0)
const [showInfo, setShowInfo] = createSignal(true)
const episodes = () => {
// Sort episodes by publication date (newest first)
return [...props.feed.episodes].sort(
(a, b) => b.pubDate.getTime() - a.pubDate.getTime()
)
}
const formatDuration = (seconds: number): string => {
const mins = Math.floor(seconds / 60)
const hrs = Math.floor(mins / 60)
if (hrs > 0) {
return `${hrs}h ${mins % 60}m`
}
return `${mins}m`
}
const formatDate = (date: Date): string => {
return format(date, "MMM d, yyyy")
}
const handleKeyPress = (key: { name: string }) => {
const eps = episodes()
if (key.name === "escape" && props.onBack) {
props.onBack()
return
}
if (key.name === "i") {
setShowInfo((v) => !v)
return
}
if (key.name === "up" || key.name === "k") {
setSelectedIndex((i) => Math.max(0, i - 1))
} else if (key.name === "down" || key.name === "j") {
setSelectedIndex((i) => Math.min(eps.length - 1, i + 1))
} else if (key.name === "return" || key.name === "enter") {
const episode = eps[selectedIndex()]
if (episode && props.onPlayEpisode) {
props.onPlayEpisode(episode)
}
} else if (key.name === "home" || key.name === "g") {
setSelectedIndex(0)
} else if (key.name === "end") {
setSelectedIndex(eps.length - 1)
} else if (key.name === "pageup") {
setSelectedIndex((i) => Math.max(0, i - 10))
} else if (key.name === "pagedown") {
setSelectedIndex((i) => Math.min(eps.length - 1, i + 10))
}
}
useKeyboard((key) => {
if (!props.focused) return
handleKeyPress(key)
})
return (
<box flexDirection="column" gap={1}>
{/* Header with back button */}
<box flexDirection="row" justifyContent="space-between">
<box border padding={0} onMouseDown={props.onBack}>
<text fg="cyan">[Esc] Back</text>
</box>
<box border padding={0} onMouseDown={() => setShowInfo((v) => !v)}>
<text fg="cyan">[i] {showInfo() ? "Hide" : "Show"} Info</text>
</box>
</box>
{/* Podcast info section */}
<Show when={showInfo()}>
<box border padding={1} flexDirection="column" gap={0}>
<text>
<strong>{props.feed.customName || props.feed.podcast.title}</strong>
</text>
{props.feed.podcast.author && (
<box flexDirection="row" gap={1}>
<text fg="gray">by</text>
<text fg="cyan">{props.feed.podcast.author}</text>
</box>
)}
<box height={1} />
<text fg="gray">
{props.feed.podcast.description?.slice(0, 200)}
{(props.feed.podcast.description?.length || 0) > 200 ? "..." : ""}
</text>
<box height={1} />
<box flexDirection="row" gap={2}>
<box flexDirection="row" gap={1}>
<text fg="gray">Episodes:</text>
<text fg="white">{props.feed.episodes.length}</text>
</box>
<box flexDirection="row" gap={1}>
<text fg="gray">Updated:</text>
<text fg="white">{formatDate(props.feed.lastUpdated)}</text>
</box>
<text fg={props.feed.visibility === "public" ? "green" : "yellow"}>
{props.feed.visibility === "public" ? "[Public]" : "[Private]"}
</text>
{props.feed.isPinned && (
<text fg="yellow">[Pinned]</text>
)}
</box>
</box>
</Show>
{/* Episodes header */}
<box flexDirection="row" justifyContent="space-between">
<text>
<strong>Episodes</strong>
</text>
<text fg="gray">({episodes().length} total)</text>
</box>
{/* Episode list */}
<scrollbox height={showInfo() ? 10 : 15} focused={props.focused}>
<For each={episodes()}>
{(episode, index) => (
<box
flexDirection="column"
gap={0}
padding={1}
backgroundColor={index() === selectedIndex() ? "#333" : undefined}
onMouseDown={() => {
setSelectedIndex(index())
if (props.onPlayEpisode) {
props.onPlayEpisode(episode)
}
}}
>
<box flexDirection="row" gap={1}>
<text fg={index() === selectedIndex() ? "cyan" : "gray"}>
{index() === selectedIndex() ? ">" : " "}
</text>
<text fg={index() === selectedIndex() ? "white" : undefined}>
{episode.episodeNumber ? `#${episode.episodeNumber} - ` : ""}
{episode.title}
</text>
</box>
<box flexDirection="row" gap={2} paddingLeft={2}>
<text fg="gray">{formatDate(episode.pubDate)}</text>
<text fg="gray">{formatDuration(episode.duration)}</text>
</box>
</box>
)}
</For>
</scrollbox>
{/* Help text */}
<text fg="gray">
j/k to navigate, Enter to play, i to toggle info, Esc to go back
</text>
</box>
)
}

View File

@@ -1,169 +0,0 @@
/**
* Feed filter component for PodTUI
* Toggle and filter options for feed list
*/
import { createSignal } from "solid-js"
import { FeedVisibility, FeedSortField } from "../types/feed"
import type { FeedFilter } from "../types/feed"
interface FeedFilterProps {
filter: FeedFilter
focused?: boolean
onFilterChange: (filter: FeedFilter) => void
}
type FilterField = "visibility" | "sort" | "pinned" | "search"
export function FeedFilterComponent(props: FeedFilterProps) {
const [focusField, setFocusField] = createSignal<FilterField>("visibility")
const [searchValue, setSearchValue] = createSignal(props.filter.searchQuery || "")
const fields: FilterField[] = ["visibility", "sort", "pinned", "search"]
const handleKeyPress = (key: { name: string; shift?: boolean }) => {
if (key.name === "tab") {
const currentIndex = fields.indexOf(focusField())
const nextIndex = key.shift
? (currentIndex - 1 + fields.length) % fields.length
: (currentIndex + 1) % fields.length
setFocusField(fields[nextIndex])
} else if (key.name === "return" || key.name === "enter") {
if (focusField() === "visibility") {
cycleVisibility()
} else if (focusField() === "sort") {
cycleSort()
} else if (focusField() === "pinned") {
togglePinned()
}
} else if (key.name === "space") {
if (focusField() === "pinned") {
togglePinned()
}
}
}
const cycleVisibility = () => {
const current = props.filter.visibility
let next: FeedVisibility | "all"
if (current === "all") next = FeedVisibility.PUBLIC
else if (current === FeedVisibility.PUBLIC) next = FeedVisibility.PRIVATE
else next = "all"
props.onFilterChange({ ...props.filter, visibility: next })
}
const cycleSort = () => {
const sortOptions: FeedSortField[] = [
FeedSortField.UPDATED,
FeedSortField.TITLE,
FeedSortField.EPISODE_COUNT,
FeedSortField.LATEST_EPISODE,
]
const currentIndex = sortOptions.indexOf(props.filter.sortBy as FeedSortField)
const nextIndex = (currentIndex + 1) % sortOptions.length
props.onFilterChange({ ...props.filter, sortBy: sortOptions[nextIndex] })
}
const togglePinned = () => {
props.onFilterChange({
...props.filter,
pinnedOnly: !props.filter.pinnedOnly,
})
}
const handleSearchInput = (value: string) => {
setSearchValue(value)
props.onFilterChange({ ...props.filter, searchQuery: value })
}
const visibilityLabel = () => {
const vis = props.filter.visibility
if (vis === "all") return "All"
if (vis === "public") return "Public"
return "Private"
}
const visibilityColor = () => {
const vis = props.filter.visibility
if (vis === "public") return "green"
if (vis === "private") return "yellow"
return "white"
}
const sortLabel = () => {
const sort = props.filter.sortBy
switch (sort) {
case "title":
return "Title"
case "episodeCount":
return "Episodes"
case "latestEpisode":
return "Latest"
case "updated":
default:
return "Updated"
}
}
return (
<box flexDirection="column" border padding={1} gap={1}>
<text>
<strong>Filter Feeds</strong>
</text>
<box flexDirection="row" gap={2} flexWrap="wrap">
{/* Visibility filter */}
<box
border
padding={0}
backgroundColor={focusField() === "visibility" ? "#333" : undefined}
>
<box flexDirection="row" gap={1}>
<text fg={focusField() === "visibility" ? "cyan" : "gray"}>Show:</text>
<text fg={visibilityColor()}>{visibilityLabel()}</text>
</box>
</box>
{/* Sort filter */}
<box
border
padding={0}
backgroundColor={focusField() === "sort" ? "#333" : undefined}
>
<box flexDirection="row" gap={1}>
<text fg={focusField() === "sort" ? "cyan" : "gray"}>Sort:</text>
<text fg="white">{sortLabel()}</text>
</box>
</box>
{/* Pinned filter */}
<box
border
padding={0}
backgroundColor={focusField() === "pinned" ? "#333" : undefined}
>
<box flexDirection="row" gap={1}>
<text fg={focusField() === "pinned" ? "cyan" : "gray"}>Pinned:</text>
<text fg={props.filter.pinnedOnly ? "yellow" : "gray"}>
{props.filter.pinnedOnly ? "Yes" : "No"}
</text>
</box>
</box>
</box>
{/* Search box */}
<box flexDirection="row" gap={1}>
<text fg={focusField() === "search" ? "cyan" : "gray"}>Search:</text>
<input
value={searchValue()}
onInput={handleSearchInput}
placeholder="Filter by name..."
focused={props.focused && focusField() === "search"}
width={25}
/>
</box>
<text fg="gray">Tab to navigate, Enter/Space to toggle</text>
</box>
)
}

View File

@@ -1,109 +0,0 @@
/**
* Feed item component for PodTUI
* Displays a single feed/podcast in the list
*/
import type { Feed, FeedVisibility } from "../types/feed"
import { format } from "date-fns"
interface FeedItemProps {
feed: Feed
isSelected: boolean
showEpisodeCount?: boolean
showLastUpdated?: boolean
compact?: boolean
}
export function FeedItem(props: FeedItemProps) {
const formatDate = (date: Date): string => {
return format(date, "MMM d")
}
const episodeCount = () => props.feed.episodes.length
const unplayedCount = () => {
// This would be calculated based on episode status
return props.feed.episodes.length
}
const visibilityIcon = () => {
return props.feed.visibility === "public" ? "[P]" : "[*]"
}
const visibilityColor = () => {
return props.feed.visibility === "public" ? "green" : "yellow"
}
const pinnedIndicator = () => {
return props.feed.isPinned ? "*" : " "
}
if (props.compact) {
// Compact single-line view
return (
<box
flexDirection="row"
gap={1}
backgroundColor={props.isSelected ? "#333" : undefined}
paddingLeft={1}
paddingRight={1}
>
<text fg={props.isSelected ? "cyan" : "gray"}>
{props.isSelected ? ">" : " "}
</text>
<text fg={visibilityColor()}>{visibilityIcon()}</text>
<text fg={props.isSelected ? "white" : undefined}>
{props.feed.customName || props.feed.podcast.title}
</text>
{props.showEpisodeCount && (
<text fg="gray">({episodeCount()})</text>
)}
</box>
)
}
// Full view with details
return (
<box
flexDirection="column"
gap={0}
border={props.isSelected}
borderColor={props.isSelected ? "cyan" : undefined}
backgroundColor={props.isSelected ? "#222" : undefined}
padding={1}
>
{/* Title row */}
<box flexDirection="row" gap={1}>
<text fg={props.isSelected ? "cyan" : "gray"}>
{props.isSelected ? ">" : " "}
</text>
<text fg={visibilityColor()}>{visibilityIcon()}</text>
<text fg="yellow">{pinnedIndicator()}</text>
<text fg={props.isSelected ? "white" : undefined}>
<strong>{props.feed.customName || props.feed.podcast.title}</strong>
</text>
</box>
{/* Details row */}
<box flexDirection="row" gap={2} paddingLeft={4}>
{props.showEpisodeCount && (
<text fg="gray">
{episodeCount()} episodes ({unplayedCount()} new)
</text>
)}
{props.showLastUpdated && (
<text fg="gray">Updated: {formatDate(props.feed.lastUpdated)}</text>
)}
</box>
{/* Description (truncated) */}
{props.feed.podcast.description && (
<box paddingLeft={4} paddingTop={0}>
<text fg="gray">
{props.feed.podcast.description.slice(0, 60)}
{props.feed.podcast.description.length > 60 ? "..." : ""}
</text>
</box>
)}
</box>
)
}

View File

@@ -1,193 +0,0 @@
/**
* Feed list component for PodTUI
* Scrollable list of feeds with keyboard navigation and mouse support
*/
import { createSignal, For, Show } from "solid-js"
import { useKeyboard } from "@opentui/solid"
import { FeedItem } from "./FeedItem"
import { useFeedStore } from "../stores/feed"
import { FeedVisibility, FeedSortField } from "../types/feed"
import type { Feed } from "../types/feed"
interface FeedListProps {
focused?: boolean
compact?: boolean
showEpisodeCount?: boolean
showLastUpdated?: boolean
onSelectFeed?: (feed: Feed) => void
onOpenFeed?: (feed: Feed) => void
onFocusChange?: (focused: boolean) => void
}
export function FeedList(props: FeedListProps) {
const feedStore = useFeedStore()
const [selectedIndex, setSelectedIndex] = createSignal(0)
const filteredFeeds = () => feedStore.getFilteredFeeds()
const handleKeyPress = (key: { name: string }) => {
if (key.name === "escape") {
props.onFocusChange?.(false)
return
}
const feeds = filteredFeeds()
if (key.name === "up" || key.name === "k") {
setSelectedIndex((i) => Math.max(0, i - 1))
} else if (key.name === "down" || key.name === "j") {
setSelectedIndex((i) => Math.min(feeds.length - 1, i + 1))
} else if (key.name === "return" || key.name === "enter") {
const feed = feeds[selectedIndex()]
if (feed && props.onOpenFeed) {
props.onOpenFeed(feed)
}
} else if (key.name === "home" || key.name === "g") {
setSelectedIndex(0)
} else if (key.name === "end") {
setSelectedIndex(feeds.length - 1)
} else if (key.name === "pageup") {
setSelectedIndex((i) => Math.max(0, i - 5))
} else if (key.name === "pagedown") {
setSelectedIndex((i) => Math.min(feeds.length - 1, i + 5))
} else if (key.name === "p") {
// Toggle pin on selected feed
const feed = feeds[selectedIndex()]
if (feed) {
feedStore.togglePinned(feed.id)
}
} else if (key.name === "f") {
// Cycle visibility filter
cycleVisibilityFilter()
} else if (key.name === "s") {
// Cycle sort
cycleSortField()
}
// Notify selection change
const selectedFeed = feeds[selectedIndex()]
if (selectedFeed && props.onSelectFeed) {
props.onSelectFeed(selectedFeed)
}
}
useKeyboard((key) => {
if (!props.focused) return
handleKeyPress(key)
})
const cycleVisibilityFilter = () => {
const current = feedStore.filter().visibility
let next: FeedVisibility | "all"
if (current === "all") next = FeedVisibility.PUBLIC
else if (current === FeedVisibility.PUBLIC) next = FeedVisibility.PRIVATE
else next = "all"
feedStore.setFilter({ ...feedStore.filter(), visibility: next })
}
const cycleSortField = () => {
const sortOptions: FeedSortField[] = [
FeedSortField.UPDATED,
FeedSortField.TITLE,
FeedSortField.EPISODE_COUNT,
FeedSortField.LATEST_EPISODE,
]
const current = feedStore.filter().sortBy as FeedSortField
const idx = sortOptions.indexOf(current)
const next = sortOptions[(idx + 1) % sortOptions.length]
feedStore.setFilter({ ...feedStore.filter(), sortBy: next })
}
const visibilityLabel = () => {
const vis = feedStore.filter().visibility
if (vis === "all") return "All"
if (vis === "public") return "Public"
return "Private"
}
const sortLabel = () => {
const sort = feedStore.filter().sortBy
switch (sort) {
case "title": return "Title"
case "episodeCount": return "Episodes"
case "latestEpisode": return "Latest"
default: return "Updated"
}
}
const handleFeedClick = (feed: Feed, index: number) => {
setSelectedIndex(index)
if (props.onSelectFeed) {
props.onSelectFeed(feed)
}
}
const handleFeedDoubleClick = (feed: Feed) => {
if (props.onOpenFeed) {
props.onOpenFeed(feed)
}
}
return (
<box flexDirection="column" gap={1}>
{/* Header with filter controls */}
<box flexDirection="row" justifyContent="space-between" paddingBottom={0}>
<text>
<strong>My Feeds</strong>
</text>
<text fg="gray">({filteredFeeds().length} feeds)</text>
<box flexDirection="row" gap={1}>
<box
border
padding={0}
onMouseDown={cycleVisibilityFilter}
>
<text fg="cyan">[f] {visibilityLabel()}</text>
</box>
<box
border
padding={0}
onMouseDown={cycleSortField}
>
<text fg="cyan">[s] {sortLabel()}</text>
</box>
</box>
</box>
{/* Feed list in scrollbox */}
<Show
when={filteredFeeds().length > 0}
fallback={
<box border padding={2}>
<text fg="gray">
No feeds found. Add podcasts from the Discover or Search tabs.
</text>
</box>
}
>
<scrollbox height={15} focused={props.focused}>
<For each={filteredFeeds()}>
{(feed, index) => (
<box onMouseDown={() => handleFeedClick(feed, index())}>
<FeedItem
feed={feed}
isSelected={index() === selectedIndex()}
compact={props.compact}
showEpisodeCount={props.showEpisodeCount ?? true}
showLastUpdated={props.showLastUpdated ?? true}
/>
</box>
)}
</For>
</scrollbox>
</Show>
{/* Navigation help */}
<box paddingTop={0}>
<text fg="gray">
Enter open | Esc up | j/k navigate | p pin | f filter | s sort
</text>
</box>
</box>
)
}

View File

@@ -1,121 +0,0 @@
/**
* FeedPage - Shows latest episodes across all subscribed shows
* Reverse chronological order, like an inbox/timeline
*/
import { createSignal, For, Show } from "solid-js"
import { useKeyboard } from "@opentui/solid"
import { useFeedStore } from "../stores/feed"
import { format } from "date-fns"
import type { Episode } from "../types/episode"
import type { Feed } from "../types/feed"
type FeedPageProps = {
focused: boolean
onPlayEpisode?: (episode: Episode, feed: Feed) => void
onExit?: () => void
}
export function FeedPage(props: FeedPageProps) {
const feedStore = useFeedStore()
const [selectedIndex, setSelectedIndex] = createSignal(0)
const [isRefreshing, setIsRefreshing] = createSignal(false)
const allEpisodes = () => feedStore.getAllEpisodesChronological()
const formatDate = (date: Date): string => {
return format(date, "MMM d, yyyy")
}
const formatDuration = (seconds: number): string => {
const mins = Math.floor(seconds / 60)
const hrs = Math.floor(mins / 60)
if (hrs > 0) return `${hrs}h ${mins % 60}m`
return `${mins}m`
}
const handleRefresh = async () => {
setIsRefreshing(true)
await feedStore.refreshAllFeeds()
setIsRefreshing(false)
}
useKeyboard((key) => {
if (!props.focused) return
const episodes = allEpisodes()
if (key.name === "down" || key.name === "j") {
setSelectedIndex((i) => Math.min(episodes.length - 1, i + 1))
} else if (key.name === "up" || key.name === "k") {
setSelectedIndex((i) => Math.max(0, i - 1))
} else if (key.name === "return" || key.name === "enter") {
const item = episodes[selectedIndex()]
if (item) props.onPlayEpisode?.(item.episode, item.feed)
} else if (key.name === "home" || key.name === "g") {
setSelectedIndex(0)
} else if (key.name === "end") {
setSelectedIndex(episodes.length - 1)
} else if (key.name === "pageup") {
setSelectedIndex((i) => Math.max(0, i - 10))
} else if (key.name === "pagedown") {
setSelectedIndex((i) => Math.min(episodes.length - 1, i + 10))
} else if (key.name === "r") {
handleRefresh()
} else if (key.name === "escape") {
props.onExit?.()
}
})
return (
<box flexDirection="column" height="100%">
{/* Status line */}
<Show when={isRefreshing()}>
<text fg="yellow">Refreshing feeds...</text>
</Show>
{/* Episode list */}
<Show
when={allEpisodes().length > 0}
fallback={
<box padding={2}>
<text fg="gray">
No episodes yet. Subscribe to shows from Discover or Search.
</text>
</box>
}
>
<scrollbox height="100%" focused={props.focused}>
<For each={allEpisodes()}>
{(item, index) => (
<box
flexDirection="column"
gap={0}
paddingLeft={1}
paddingRight={1}
paddingTop={0}
paddingBottom={0}
backgroundColor={index() === selectedIndex() ? "#333" : undefined}
onMouseDown={() => setSelectedIndex(index())}
>
<box flexDirection="row" gap={1}>
<text fg={index() === selectedIndex() ? "cyan" : "gray"}>
{index() === selectedIndex() ? ">" : " "}
</text>
<text fg={index() === selectedIndex() ? "white" : undefined}>
{item.episode.title}
</text>
</box>
<box flexDirection="row" gap={2} paddingLeft={2}>
<text fg="cyan">{item.feed.podcast.title}</text>
<text fg="gray">{formatDate(item.episode.pubDate)}</text>
<text fg="gray">{formatDuration(item.episode.duration)}</text>
</box>
</box>
)}
</For>
</scrollbox>
</Show>
</box>
)
}

View File

@@ -1,17 +0,0 @@
type FileInfoProps = {
path: string
format: string
size: string
modifiedAt: string
}
export function FileInfo(props: FileInfoProps) {
return (
<box border title="File Info" style={{ padding: 1, flexDirection: "column" }}>
<text>Path: {props.path}</text>
<text>Format: {props.format}</text>
<text>Size: {props.size}</text>
<text>Modified: {props.modifiedAt}</text>
</box>
)
}

View File

@@ -1,17 +0,0 @@
import type { JSX } from "solid-js"
import type { TabId } from "./Tab"
/**
* @deprecated Use useAppKeyboard hook directly instead.
* This component is kept for backwards compatibility.
*/
type KeyboardHandlerProps = {
children?: JSX.Element
onTabSelect?: (tab: TabId) => void
}
export function KeyboardHandler(props: KeyboardHandlerProps) {
// Keyboard handling has been moved to useAppKeyboard hook
// This component is now just a passthrough
return <>{props.children}</>
}

View File

@@ -1,30 +0,0 @@
import { useTheme } from "../context/ThemeContext"
export function LayerIndicator({ layerDepth }: { layerDepth: number }) {
const { theme } = useTheme()
const getLayerIndicator = () => {
const indicators = []
for (let i = 0; i < 4; i++) {
const isActive = i <= layerDepth
const color = isActive ? theme.accent : theme.textMuted
const size = isActive ? "●" : "○"
indicators.push(
<text fg={color} marginRight={1}>
{size}
</text>
)
}
return indicators
}
return (
<box flexDirection="row" alignItems="center">
<text fg={theme.textMuted} marginRight={1}>Depth:</text>
{getLayerIndicator()}
<text fg={theme.textMuted} marginLeft={1}>
{layerDepth}
</text>
</box>
)
}

View File

@@ -1,137 +0,0 @@
import type { JSX } from "solid-js"
import type { RGBA } from "@opentui/core"
import { Show, For, createMemo } from "solid-js"
import { useTheme } from "../context/ThemeContext"
type PanelConfig = {
/** Panel content */
content: JSX.Element
/** Panel title shown in header */
title?: string
/** Fixed width (leave undefined for flex) */
width?: number
/** Whether this panel is currently focused */
focused?: boolean
}
type LayoutProps = {
/** Top tab bar */
header?: JSX.Element
/** Bottom status bar */
footer?: JSX.Element
/** Panels to display left-to-right like a file explorer */
panels: PanelConfig[]
/** Index of the currently active/focused panel */
activePanelIndex?: number
}
export function Layout(props: LayoutProps) {
const context = useTheme()
const panelBg = (index: number): RGBA => {
const backgrounds = context.theme.layerBackgrounds
const layers = [
backgrounds?.layer0 ?? context.theme.background,
backgrounds?.layer1 ?? context.theme.backgroundPanel,
backgrounds?.layer2 ?? context.theme.backgroundElement,
backgrounds?.layer3 ?? context.theme.backgroundMenu,
]
return layers[Math.min(index, layers.length - 1)]
}
const borderColor = (index: number): RGBA | string => {
const isActive = index === (props.activePanelIndex ?? 0)
return isActive
? (context.theme.accent ?? context.theme.primary)
: (context.theme.border ?? context.theme.textMuted)
}
return (
<box
flexDirection="column"
width="100%"
height="100%"
backgroundColor={context.theme.background}
>
{/* Header - tab bar */}
<Show when={props.header}>
<box
style={{
height: 3,
backgroundColor: context.theme.surface ?? context.theme.backgroundPanel,
}}
>
<box style={{ paddingLeft: 1, paddingTop: 0, paddingBottom: 0 }}>
{props.header}
</box>
</box>
</Show>
{/* Main content: side-by-side panels */}
<box
flexDirection="row"
style={{ flexGrow: 1 }}
>
<For each={props.panels}>
{(panel, index) => (
<box
flexDirection="column"
border
borderColor={borderColor(index())}
backgroundColor={panelBg(index())}
style={{
flexGrow: panel.width ? 0 : 1,
width: panel.width,
height: "100%",
}}
>
{/* Panel header */}
<Show when={panel.title}>
<box
style={{
height: 1,
paddingLeft: 1,
paddingRight: 1,
backgroundColor: index() === (props.activePanelIndex ?? 0)
? (context.theme.accent ?? context.theme.primary)
: (context.theme.surface ?? context.theme.backgroundPanel),
}}
>
<text
fg={index() === (props.activePanelIndex ?? 0) ? "black" : undefined}
>
<strong>{panel.title}</strong>
</text>
</box>
</Show>
{/* Panel body */}
<box
style={{
flexGrow: 1,
padding: 1,
}}
>
{panel.content}
</box>
</box>
)}
</For>
</box>
{/* Footer - status/nav bar */}
<Show when={props.footer}>
<box
style={{
height: 2,
backgroundColor: context.theme.surface ?? context.theme.backgroundPanel,
}}
>
<box style={{ padding: 1 }}>
{props.footer}
</box>
</box>
</Show>
</box>
)
}

View File

@@ -0,0 +1,24 @@
import { createSignal, createMemo, onCleanup } from "solid-js";
import { useTheme } from "@/context/ThemeContext";
const spinnerChars = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
//TODO: Watch for actual loading state (fetching feeds)
export function LoadingIndicator() {
const { theme } = useTheme();
const [index, setIndex] = createSignal(0);
const interval = setInterval(() => {
setIndex((i) => (i + 1) % spinnerChars.length);
}, 65);
onCleanup(() => clearInterval(interval));
const currentChar = createMemo(() => spinnerChars[index()]);
return (
<box flexDirection="row" justifyContent="flex-end" alignItems="flex-start">
<text fg={theme.primary} content={currentChar()} />
</box>
);
}

View File

@@ -1,177 +0,0 @@
/**
* Login screen component for PodTUI
* Email/password login with links to code validation and OAuth
*/
import { createSignal } from "solid-js"
import { useAuthStore } from "../stores/auth"
import { useTheme } from "../context/ThemeContext"
import { AUTH_CONFIG } from "../config/auth"
interface LoginScreenProps {
focused?: boolean
onNavigateToCode?: () => void
onNavigateToOAuth?: () => void
}
type FocusField = "email" | "password" | "submit" | "code" | "oauth"
export function LoginScreen(props: LoginScreenProps) {
const auth = useAuthStore()
const { theme } = useTheme()
const [email, setEmail] = createSignal("")
const [password, setPassword] = createSignal("")
const [focusField, setFocusField] = createSignal<FocusField>("email")
const [emailError, setEmailError] = createSignal<string | null>(null)
const [passwordError, setPasswordError] = createSignal<string | null>(null)
const fields: FocusField[] = ["email", "password", "submit", "code", "oauth"]
const validateEmail = (value: string): boolean => {
if (!value) {
setEmailError("Email is required")
return false
}
if (!AUTH_CONFIG.email.pattern.test(value)) {
setEmailError("Invalid email format")
return false
}
setEmailError(null)
return true
}
const validatePassword = (value: string): boolean => {
if (!value) {
setPasswordError("Password is required")
return false
}
if (value.length < AUTH_CONFIG.password.minLength) {
setPasswordError(`Minimum ${AUTH_CONFIG.password.minLength} characters`)
return false
}
setPasswordError(null)
return true
}
const handleSubmit = async () => {
const isEmailValid = validateEmail(email())
const isPasswordValid = validatePassword(password())
if (!isEmailValid || !isPasswordValid) {
return
}
await auth.login({ email: email(), password: password() })
}
const handleKeyPress = (key: { name: string; shift?: boolean }) => {
if (key.name === "tab") {
const currentIndex = fields.indexOf(focusField())
const nextIndex = key.shift
? (currentIndex - 1 + fields.length) % fields.length
: (currentIndex + 1) % fields.length
setFocusField(fields[nextIndex])
} else if (key.name === "return" || key.name === "enter") {
if (focusField() === "submit") {
handleSubmit()
} else if (focusField() === "code" && props.onNavigateToCode) {
props.onNavigateToCode()
} else if (focusField() === "oauth" && props.onNavigateToOAuth) {
props.onNavigateToOAuth()
}
}
}
return (
<box flexDirection="column" border padding={2} gap={1}>
<text>
<strong>Sign In</strong>
</text>
<box height={1} />
{/* Email field */}
<box flexDirection="column" gap={0}>
<text fg={focusField() === "email" ? theme.primary : undefined}>Email:</text>
<input
value={email()}
onInput={setEmail}
placeholder="your@email.com"
focused={props.focused && focusField() === "email"}
width={30}
/>
{emailError() && (
<text fg={theme.error}>{emailError()}</text>
)}
</box>
{/* Password field */}
<box flexDirection="column" gap={0}>
<text fg={focusField() === "password" ? theme.primary : undefined}>
Password:
</text>
<input
value={password()}
onInput={setPassword}
placeholder="********"
focused={props.focused && focusField() === "password"}
width={30}
/>
{passwordError() && (
<text fg={theme.error}>{passwordError()}</text>
)}
</box>
<box height={1} />
{/* Submit button */}
<box flexDirection="row" gap={2}>
<box
border
padding={1}
backgroundColor={focusField() === "submit" ? theme.primary : undefined}
>
<text fg={focusField() === "submit" ? theme.text : undefined}>
{auth.isLoading ? "Signing in..." : "[Enter] Sign In"}
</text>
</box>
</box>
{/* Auth error message */}
{auth.error && (
<text fg={theme.error}>{auth.error.message}</text>
)}
<box height={1} />
{/* Alternative auth options */}
<text fg={theme.textMuted}>Or authenticate with:</text>
<box flexDirection="row" gap={2}>
<box
border
padding={1}
backgroundColor={focusField() === "code" ? theme.primary : undefined}
>
<text fg={focusField() === "code" ? theme.accent : theme.textMuted}>
[C] Sync Code
</text>
</box>
<box
border
padding={1}
backgroundColor={focusField() === "oauth" ? theme.primary : undefined}
>
<text fg={focusField() === "oauth" ? theme.accent : theme.textMuted}>
[O] OAuth Info
</text>
</box>
</box>
<box height={1} />
<text fg={theme.textMuted}>Tab to navigate, Enter to select</text>
</box>
)
}

View File

@@ -1,243 +0,0 @@
/**
* MyShowsPage - Two-panel file-explorer style view
* Left panel: list of subscribed shows
* Right panel: episodes for the selected show
*/
import { createSignal, For, Show, createMemo } from "solid-js"
import { useKeyboard } from "@opentui/solid"
import { useFeedStore } from "../stores/feed"
import { format } from "date-fns"
import type { Episode } from "../types/episode"
import type { Feed } from "../types/feed"
type MyShowsPageProps = {
focused: boolean
onPlayEpisode?: (episode: Episode, feed: Feed) => void
onExit?: () => void
}
type FocusPane = "shows" | "episodes"
export function MyShowsPage(props: MyShowsPageProps) {
const feedStore = useFeedStore()
const [focusPane, setFocusPane] = createSignal<FocusPane>("shows")
const [showIndex, setShowIndex] = createSignal(0)
const [episodeIndex, setEpisodeIndex] = createSignal(0)
const [isRefreshing, setIsRefreshing] = createSignal(false)
const shows = () => feedStore.getFilteredFeeds()
const selectedShow = createMemo(() => {
const s = shows()
const idx = showIndex()
return idx < s.length ? s[idx] : undefined
})
const episodes = createMemo(() => {
const show = selectedShow()
if (!show) return []
return [...show.episodes].sort(
(a, b) => b.pubDate.getTime() - a.pubDate.getTime()
)
})
const formatDate = (date: Date): string => {
return format(date, "MMM d, yyyy")
}
const formatDuration = (seconds: number): string => {
const mins = Math.floor(seconds / 60)
const hrs = Math.floor(mins / 60)
if (hrs > 0) return `${hrs}h ${mins % 60}m`
return `${mins}m`
}
const handleRefresh = async () => {
const show = selectedShow()
if (!show) return
setIsRefreshing(true)
await feedStore.refreshFeed(show.id)
setIsRefreshing(false)
}
const handleUnsubscribe = () => {
const show = selectedShow()
if (!show) return
feedStore.removeFeed(show.id)
setShowIndex((i) => Math.max(0, i - 1))
setEpisodeIndex(0)
}
useKeyboard((key) => {
if (!props.focused) return
const pane = focusPane()
// Navigate between panes
if (key.name === "right" || key.name === "l") {
if (pane === "shows" && selectedShow()) {
setFocusPane("episodes")
setEpisodeIndex(0)
}
return
}
if (key.name === "left" || key.name === "h") {
if (pane === "episodes") {
setFocusPane("shows")
}
return
}
if (key.name === "tab") {
if (pane === "shows" && selectedShow()) {
setFocusPane("episodes")
setEpisodeIndex(0)
} else {
setFocusPane("shows")
}
return
}
if (pane === "shows") {
const s = shows()
if (key.name === "down" || key.name === "j") {
setShowIndex((i) => Math.min(s.length - 1, i + 1))
setEpisodeIndex(0)
} else if (key.name === "up" || key.name === "k") {
setShowIndex((i) => Math.max(0, i - 1))
setEpisodeIndex(0)
} else if (key.name === "return" || key.name === "enter") {
if (selectedShow()) {
setFocusPane("episodes")
setEpisodeIndex(0)
}
} else if (key.name === "d") {
handleUnsubscribe()
} else if (key.name === "r") {
handleRefresh()
} else if (key.name === "escape") {
props.onExit?.()
}
} else if (pane === "episodes") {
const eps = episodes()
if (key.name === "down" || key.name === "j") {
setEpisodeIndex((i) => Math.min(eps.length - 1, i + 1))
} else if (key.name === "up" || key.name === "k") {
setEpisodeIndex((i) => Math.max(0, i - 1))
} else if (key.name === "return" || key.name === "enter") {
const ep = eps[episodeIndex()]
const show = selectedShow()
if (ep && show) props.onPlayEpisode?.(ep, show)
} else if (key.name === "pageup") {
setEpisodeIndex((i) => Math.max(0, i - 10))
} else if (key.name === "pagedown") {
setEpisodeIndex((i) => Math.min(eps.length - 1, i + 10))
} else if (key.name === "r") {
handleRefresh()
} else if (key.name === "escape") {
setFocusPane("shows")
key.stopPropagation()
}
}
})
return {
showsPanel: () => (
<box flexDirection="column" height="100%">
<Show when={isRefreshing()}>
<text fg="yellow">Refreshing...</text>
</Show>
<Show
when={shows().length > 0}
fallback={
<box padding={1}>
<text fg="gray">
No shows yet. Subscribe from Discover or Search.
</text>
</box>
}
>
<scrollbox height="100%" focused={props.focused && focusPane() === "shows"}>
<For each={shows()}>
{(feed, index) => (
<box
flexDirection="row"
gap={1}
paddingLeft={1}
paddingRight={1}
backgroundColor={index() === showIndex() ? "#333" : undefined}
onMouseDown={() => {
setShowIndex(index())
setEpisodeIndex(0)
}}
>
<text fg={index() === showIndex() ? "cyan" : "gray"}>
{index() === showIndex() ? ">" : " "}
</text>
<text fg={index() === showIndex() ? "white" : undefined}>
{feed.customName || feed.podcast.title}
</text>
<text fg="gray">({feed.episodes.length})</text>
</box>
)}
</For>
</scrollbox>
</Show>
</box>
),
episodesPanel: () => (
<box flexDirection="column" height="100%">
<Show
when={selectedShow()}
fallback={
<box padding={1}>
<text fg="gray">Select a show</text>
</box>
}
>
<Show
when={episodes().length > 0}
fallback={
<box padding={1}>
<text fg="gray">No episodes. Press [r] to refresh.</text>
</box>
}
>
<scrollbox height="100%" focused={props.focused && focusPane() === "episodes"}>
<For each={episodes()}>
{(episode, index) => (
<box
flexDirection="column"
gap={0}
paddingLeft={1}
paddingRight={1}
backgroundColor={index() === episodeIndex() ? "#333" : undefined}
onMouseDown={() => setEpisodeIndex(index())}
>
<box flexDirection="row" gap={1}>
<text fg={index() === episodeIndex() ? "cyan" : "gray"}>
{index() === episodeIndex() ? ">" : " "}
</text>
<text fg={index() === episodeIndex() ? "white" : undefined}>
{episode.episodeNumber ? `#${episode.episodeNumber} ` : ""}
{episode.title}
</text>
</box>
<box flexDirection="row" gap={2} paddingLeft={2}>
<text fg="gray">{formatDate(episode.pubDate)}</text>
<text fg="gray">{formatDuration(episode.duration)}</text>
</box>
</box>
)}
</For>
</scrollbox>
</Show>
</Show>
</box>
),
focusPane,
selectedShow,
}
}

View File

@@ -1,26 +0,0 @@
import type { TabId } from "./Tab"
type NavigationProps = {
activeTab: TabId
onTabSelect: (tab: TabId) => void
}
export function Navigation(props: NavigationProps) {
return (
<box style={{ flexDirection: "row", width: "100%", height: 1 }}>
<text>
{props.activeTab === "feed" ? "[" : " "}Feed{props.activeTab === "feed" ? "]" : " "}
<span> </span>
{props.activeTab === "shows" ? "[" : " "}My Shows{props.activeTab === "shows" ? "]" : " "}
<span> </span>
{props.activeTab === "discover" ? "[" : " "}Discover{props.activeTab === "discover" ? "]" : " "}
<span> </span>
{props.activeTab === "search" ? "[" : " "}Search{props.activeTab === "search" ? "]" : " "}
<span> </span>
{props.activeTab === "player" ? "[" : " "}Player{props.activeTab === "player" ? "]" : " "}
<span> </span>
{props.activeTab === "settings" ? "[" : " "}Settings{props.activeTab === "settings" ? "]" : " "}
</text>
</box>
)
}

View File

@@ -1,125 +0,0 @@
/**
* OAuth placeholder component for PodTUI
* Displays OAuth limitations and alternative authentication methods
*/
import { createSignal } from "solid-js"
import { OAUTH_PROVIDERS, OAUTH_LIMITATION_MESSAGE } from "../config/auth"
interface OAuthPlaceholderProps {
focused?: boolean
onBack?: () => void
onNavigateToCode?: () => void
}
type FocusField = "code" | "back"
export function OAuthPlaceholder(props: OAuthPlaceholderProps) {
const [focusField, setFocusField] = createSignal<FocusField>("code")
const fields: FocusField[] = ["code", "back"]
const handleKeyPress = (key: { name: string; shift?: boolean }) => {
if (key.name === "tab") {
const currentIndex = fields.indexOf(focusField())
const nextIndex = key.shift
? (currentIndex - 1 + fields.length) % fields.length
: (currentIndex + 1) % fields.length
setFocusField(fields[nextIndex])
} else if (key.name === "return" || key.name === "enter") {
if (focusField() === "code" && props.onNavigateToCode) {
props.onNavigateToCode()
} else if (focusField() === "back" && props.onBack) {
props.onBack()
}
} else if (key.name === "escape" && props.onBack) {
props.onBack()
}
}
return (
<box flexDirection="column" border padding={2} gap={1}>
<text>
<strong>OAuth Authentication</strong>
</text>
<box height={1} />
{/* OAuth providers list */}
<text fg="cyan">Available OAuth Providers:</text>
<box flexDirection="column" gap={0} paddingLeft={2}>
{OAUTH_PROVIDERS.map((provider) => (
<box flexDirection="row" gap={1}>
<text fg={provider.enabled ? "green" : "gray"}>
{provider.enabled ? "[+]" : "[-]"} {provider.name}
</text>
<text fg="gray">- {provider.description}</text>
</box>
))}
</box>
<box height={1} />
{/* Limitation message */}
<box border padding={1} borderColor="yellow">
<text fg="yellow">Terminal Limitations</text>
</box>
<box paddingLeft={1}>
{OAUTH_LIMITATION_MESSAGE.split("\n").map((line) => (
<text fg="gray">{line}</text>
))}
</box>
<box height={1} />
{/* Alternative options */}
<text fg="cyan">Recommended Alternatives:</text>
<box flexDirection="column" gap={0} paddingLeft={2}>
<box flexDirection="row" gap={1}>
<text fg="green">[1]</text>
<text fg="white">Use a sync code from the web portal</text>
</box>
<box flexDirection="row" gap={1}>
<text fg="green">[2]</text>
<text fg="white">Use email/password authentication</text>
</box>
<box flexDirection="row" gap={1}>
<text fg="green">[3]</text>
<text fg="white">Use file-based sync (no account needed)</text>
</box>
</box>
<box height={1} />
{/* Action buttons */}
<box flexDirection="row" gap={2}>
<box
border
padding={1}
backgroundColor={focusField() === "code" ? "#333" : undefined}
>
<text fg={focusField() === "code" ? "cyan" : undefined}>
[C] Enter Sync Code
</text>
</box>
<box
border
padding={1}
backgroundColor={focusField() === "back" ? "#333" : undefined}
>
<text fg={focusField() === "back" ? "yellow" : "gray"}>
[Esc] Back to Login
</text>
</box>
</box>
<box height={1} />
<text fg="gray">Tab to navigate, Enter to select, Esc to go back</text>
</box>
)
}

210
src/components/PaneRow.tsx Normal file
View File

@@ -0,0 +1,210 @@
/**
* PaneRow — the shared parent | current | preview 3-pane layout primitive.
*
* Implements yazi's `mgr.ratio = [1, 3, 3]` contract: three bordered columns
* grow at 1/7 : 3/7 : 3/7 of the row width via Yoga `flexGrow`, so every list
* tab renders an identical, layout-stable shell. Columns use `flexBasis={0}`
* so the ratio is exact regardless of content width — a column's content can
* never stretch its slot.
*
* Column semantics (per the yazi depth model):
* parent — the previous-depth list. Renders a muted `—` placeholder and
* KEEPS its 1/7 slot when blank (never collapses to width 0).
* current — the current-depth list. The only focusable content column; it
* carries the active-border focus ring when `focused` is truthy.
* preview — detail of the hovered item in `current`; always muted border.
*
* The primitive is purely structural: callers pass their own JSX per column
* (static elements or accessors) plus header labels. Theme colors are resolved
* internally via `useTheme()`. Only the current column's `<scrollbox>` receives
* `focused`, so scroll focus follows the cursor (j/k stay in the current pane).
*
* Example:
* <PaneRow
* parent={parentList}
* current={currentList}
* preview={detail}
* parentLabel="Up"
* currentLabel="List · 42"
* previewLabel="Detail"
* focused={isActive}
* />
*/
import { createMemo, Show } from "solid-js";
import type { JSX } from "solid-js";
import type { RGBA } from "@opentui/core";
import { useTheme } from "@/context/ThemeContext";
import { PANE_RATIO } from "@/utils/navigation";
// ── Types ───────────────────────────────────────────────────────────────────
type PaneContent = JSX.Element | (() => JSX.Element);
type PaneLabel = string | (() => string);
export type PaneRowProps = {
/** Parent column content (previous-depth list, or null for a muted
* placeholder — the 1/7 slot is always preserved). */
parent?: PaneContent;
/** Current column content (the focused list). */
current?: PaneContent;
/** Preview column content (detail of the hovered item). Omit/undefined
* together with `panes={2}` to render a 2-pane parent|current row. */
preview?: PaneContent;
parentLabel?: PaneLabel;
currentLabel?: PaneLabel;
previewLabel?: PaneLabel;
/** Whether the current column carries the active-border focus ring. Defaults to
* true; pass `false` (or a signal) when the row is inactive. Parent and
* preview columns always render muted borders. */
focused?: boolean | (() => boolean);
/** Number of visible columns. `3` (default) = parent|current|preview;
* `2` = parent|current (preview omitted, current grows to fill). */
panes?: 2 | 3;
};
// ── Helpers ─────────────────────────────────────────────────────────────────
function resolveLabel(v: PaneLabel | undefined): string {
if (v == null) return "";
return typeof v === "function" ? v() : v;
}
/** Normalize a PaneContent (static JSX or accessor) into a reactive accessor.
* We deliberately do NOT use Solid's `children()` helper here: that helper
* flattens accessor children into a stable resolved-nodes array and is the
* wrong tool for content whose ROOT swaps at runtime (e.g. the current pane
* switching between a depth-1 list fragment and a depth-2 editor — both
* truthy JSX roots). `children()` would not re-resolve on a truthy<@->truthy
* root swap, freezing the previous subtree in place. Instead we hand the
* raw accessor to a reactive `{ expr ?? <Placeholder/> }` expression below,
* which Solid compiles into a tracked `insert` effect that disposes the old
* subtree and mounts the new whenever the accessor returns a different
* element identity. */
function normalizeContent(
v: PaneContent | undefined,
): () => JSX.Element | undefined {
if (v == null) return () => undefined;
return typeof v === "function" ? (v as () => JSX.Element) : () => v;
}
function Placeholder(props: { color: () => RGBA }) {
return (
<box padding={1}>
<text fg={props.color()}></text>
</box>
);
}
// ── Pane column ─────────────────────────────────────────────────────────────
function Pane(props: {
grow: number;
label: () => string;
content: () => JSX.Element | undefined;
borderColor: () => RGBA;
scrollFocused: () => boolean;
}) {
const { theme } = useTheme();
const muted = () => theme.muted ?? theme.textMuted ?? theme.text;
// Memoize accessor results so the prop expressions below stay reactive
// when the underlying signals (e.g. `focused`) change.
const borderColor = createMemo(() => props.borderColor());
const scrollFocused = createMemo(() => props.scrollFocused());
return (
<box
flexDirection="column"
flexGrow={props.grow}
flexBasis={0}
height="100%"
>
{/* ── slim header label row ─────────────────────────────────────────── */}
<box height={1} paddingLeft={1} backgroundColor={theme.background}>
<text fg={theme.textSecondary}>{props.label()}</text>
</box>
{/* ── bordered scrollbox ────────────────────────────────────────────── */}
<scrollbox
height="100%"
focused={scrollFocused()}
border
borderColor={borderColor()}
backgroundColor={theme.background}
>
{/*
* Render the content accessor directly via a reactive expression.
* `{ accessor() ?? <Placeholder/> }` compiles to a Solid `insert`
* effect that re-runs whenever the accessor's tracked signals
* change (e.g. `depth()` swapping the root from a list fragment to
* an editor). Solid disposes the previously-rendered subtree and
* mounts the new element identity. `null`/`undefined` falls back
* to the muted placeholder so the parent pane keeps its 1/7 slot
* visibly blank at depth 0. This is the correct tool for root
* swapping — unlike Solid's `children()` / `<Show>`-children,
* which only react to truthiness flips, not truthy<@->truthy root
* identity changes.
*/}
{props.content() ?? <Placeholder color={muted} />}
</scrollbox>
</box>
);
}
// ── Row primitive ───────────────────────────────────────────────────────────
export function PaneRow(props: PaneRowProps) {
const { theme } = useTheme();
/** true → the current column gets the active-border focus ring. */
const focused = createMemo(() => {
const f = props.focused;
return typeof f === "function" ? f() : (f ?? true);
});
// Normalize static JSX and accessor children into reactive accessors
// (see normalizeContent for why we avoid Solid's `children()` helper).
const parentContent = normalizeContent(props.parent);
const currentContent = normalizeContent(props.current);
const previewContent = normalizeContent(props.preview);
const parentLabel = createMemo(() => resolveLabel(props.parentLabel));
const currentLabel = createMemo(() => resolveLabel(props.currentLabel));
const previewLabel = createMemo(() => resolveLabel(props.previewLabel));
// 2-pane mode (parent|current) grows the current column to fill the
// preview slot. Defaults to 3 (parent|current|preview).
const panes = createMemo(() => props.panes ?? 3);
const currentGrow = createMemo(() =>
panes() === 2
? PANE_RATIO.current + PANE_RATIO.preview
: PANE_RATIO.current,
);
return (
<box flexDirection="row" flexGrow={1} width="100%" height="100%">
{/* ── parent (1/7) — previous-depth list; always muted ─────────────── */}
<Pane
grow={PANE_RATIO.parent}
label={parentLabel}
content={parentContent}
borderColor={() => theme.border}
scrollFocused={() => false}
/>
{/* ── current — the focused list; active-border ring when focused ──────────── */}
<Pane
grow={currentGrow()}
label={currentLabel}
content={currentContent}
borderColor={() => (focused() ? theme.borderActive : theme.border)}
scrollFocused={() => focused()}
/>
{/* ── preview (3/7) — hovered-item detail; always muted ────────────── */}
<Show when={panes() === 3}>
<Pane
grow={PANE_RATIO.preview}
label={previewLabel}
content={previewContent}
borderColor={() => theme.border}
scrollFocused={() => false}
/>
</Show>
</box>
);
}

View File

@@ -1,62 +0,0 @@
import type { BackendName } from "../utils/audio-player"
type PlaybackControlsProps = {
isPlaying: boolean
volume: number
speed: number
backendName?: BackendName
hasAudioUrl?: boolean
onToggle: () => void
onPrev: () => void
onNext: () => void
onVolumeChange: (value: number) => void
onSpeedChange: (value: number) => void
}
const BACKEND_LABELS: Record<BackendName, string> = {
mpv: "mpv",
ffplay: "ffplay",
afplay: "afplay",
system: "system",
none: "none",
}
export function PlaybackControls(props: PlaybackControlsProps) {
return (
<box flexDirection="row" gap={1} alignItems="center" border padding={1}>
<box border padding={0} onMouseDown={props.onPrev}>
<text fg="cyan">[Prev]</text>
</box>
<box border padding={0} onMouseDown={props.onToggle}>
<text fg="cyan">{props.isPlaying ? "[Pause]" : "[Play]"}</text>
</box>
<box border padding={0} onMouseDown={props.onNext}>
<text fg="cyan">[Next]</text>
</box>
<box flexDirection="row" gap={1} marginLeft={2}>
<text fg="gray">Vol</text>
<text fg="white">{Math.round(props.volume * 100)}%</text>
</box>
<box flexDirection="row" gap={1} marginLeft={2}>
<text fg="gray">Speed</text>
<text fg="white">{props.speed}x</text>
</box>
{props.backendName && props.backendName !== "none" && (
<box flexDirection="row" gap={1} marginLeft={2}>
<text fg="gray">via</text>
<text fg="cyan">{BACKEND_LABELS[props.backendName]}</text>
</box>
)}
{props.backendName === "none" && (
<box marginLeft={2}>
<text fg="yellow">No audio player found</text>
</box>
)}
{props.hasAudioUrl === false && (
<box marginLeft={2}>
<text fg="yellow">No audio URL</text>
</box>
)}
</box>
)
}

View File

@@ -1,149 +0,0 @@
import { useKeyboard } from "@opentui/solid"
import { PlaybackControls } from "./PlaybackControls"
import { Waveform } from "./Waveform"
import { createWaveform } from "../utils/waveform"
import { useAudio } from "../hooks/useAudio"
import type { Episode } from "../types/episode"
type PlayerProps = {
focused: boolean
episode?: Episode | null
onExit?: () => void
}
const SAMPLE_EPISODE: Episode = {
id: "sample-ep",
podcastId: "sample-podcast",
title: "A Tour of the Productive Mind",
description: "A short guided session on building creative focus.",
audioUrl: "",
duration: 2780,
pubDate: new Date(),
}
export function Player(props: PlayerProps) {
const audio = useAudio()
const waveform = () => createWaveform(64)
// The episode to display — prefer a passed-in episode, then the
// currently-playing episode, then fall back to the sample.
const episode = () => props.episode ?? audio.currentEpisode() ?? SAMPLE_EPISODE
const dur = () => audio.duration() || episode().duration || 1
useKeyboard((key: { name: string }) => {
if (!props.focused) return
if (key.name === "space") {
if (audio.currentEpisode()) {
audio.togglePlayback()
} else {
// Nothing loaded yet — start playing the displayed episode
const ep = episode()
if (ep.audioUrl) {
audio.play(ep)
}
}
return
}
if (key.name === "escape") {
props.onExit?.()
return
}
if (key.name === "left") {
audio.seekRelative(-10)
}
if (key.name === "right") {
audio.seekRelative(10)
}
if (key.name === "up") {
audio.setVolume(Math.min(1, Number((audio.volume() + 0.05).toFixed(2))))
}
if (key.name === "down") {
audio.setVolume(Math.max(0, Number((audio.volume() - 0.05).toFixed(2))))
}
if (key.name === "s") {
const next = audio.speed() >= 2 ? 0.5 : Number((audio.speed() + 0.25).toFixed(2))
audio.setSpeed(next)
}
})
const progressPercent = () => {
const d = dur()
if (d <= 0) return 0
return Math.min(100, Math.round((audio.position() / d) * 100))
}
const formatTime = (seconds: number) => {
const m = Math.floor(seconds / 60)
const s = Math.floor(seconds % 60)
return `${m}:${String(s).padStart(2, "0")}`
}
return (
<box flexDirection="column" gap={1}>
<box flexDirection="row" justifyContent="space-between">
<text>
<strong>Now Playing</strong>
</text>
<text fg="gray">
{formatTime(audio.position())} / {formatTime(dur())}
</text>
</box>
{audio.error() && (
<text fg="red">{audio.error()}</text>
)}
<box border padding={1} flexDirection="column" gap={1}>
<text fg="white">
<strong>{episode().title}</strong>
</text>
<text fg="gray">{episode().description}</text>
<box flexDirection="column" gap={1}>
<box flexDirection="row" gap={1} alignItems="center">
<text fg="gray">Progress:</text>
<box flexGrow={1} height={1} backgroundColor="#2a2f3a">
<box
width={`${progressPercent()}%`}
height={1}
backgroundColor={audio.isPlaying() ? "#6fa8ff" : "#7d8590"}
/>
</box>
<text fg="gray">{progressPercent()}%</text>
</box>
<Waveform
data={waveform()}
position={audio.position()}
duration={dur()}
isPlaying={audio.isPlaying()}
onSeek={(next: number) => audio.seek(next)}
/>
</box>
</box>
<PlaybackControls
isPlaying={audio.isPlaying()}
volume={audio.volume()}
speed={audio.speed()}
backendName={audio.backendName()}
hasAudioUrl={!!episode().audioUrl}
onToggle={() => {
if (audio.currentEpisode()) {
audio.togglePlayback()
} else {
const ep = episode()
if (ep.audioUrl) audio.play(ep)
}
}}
onPrev={() => audio.seek(0)}
onNext={() => audio.seek(dur())}
onSpeedChange={(s: number) => audio.setSpeed(s)}
onVolumeChange={(v: number) => audio.setVolume(v)}
/>
<text fg="gray">Space play/pause | Left/Right seek 10s | Up/Down volume | S speed | Esc back</text>
</box>
)
}

View File

@@ -1,73 +0,0 @@
/**
* PodcastCard component - Reusable card for displaying podcast info
*/
import { Show, For } from "solid-js"
import type { Podcast } from "../types/podcast"
type PodcastCardProps = {
podcast: Podcast
selected: boolean
compact?: boolean
onSelect?: () => void
onSubscribe?: () => void
}
export function PodcastCard(props: PodcastCardProps) {
const handleSubscribeClick = () => {
props.onSubscribe?.()
}
return (
<box
flexDirection="column"
padding={1}
backgroundColor={props.selected ? "#333" : undefined}
onMouseDown={props.onSelect}
>
{/* Title Row */}
<box flexDirection="row" gap={2} alignItems="center">
<text fg={props.selected ? "cyan" : "white"}>
<strong>{props.podcast.title}</strong>
</text>
<Show when={props.podcast.isSubscribed}>
<text fg="green">[+]</text>
</Show>
</box>
{/* Author */}
<Show when={props.podcast.author && !props.compact}>
<text fg="gray">by {props.podcast.author}</text>
</Show>
{/* Description */}
<Show when={props.podcast.description && !props.compact}>
<text fg={props.selected ? "white" : "gray"}>
{props.podcast.description!.length > 80
? props.podcast.description!.slice(0, 80) + "..."
: props.podcast.description}
</text>
</Show>
{/* Categories and Subscribe Button */}
<box flexDirection="row" justifyContent="space-between" marginTop={props.compact ? 0 : 1}>
<box flexDirection="row" gap={1}>
<Show when={(props.podcast.categories ?? []).length > 0}>
<For each={(props.podcast.categories ?? []).slice(0, 2)}>
{(cat) => <text fg="yellow">[{cat}]</text>}
</For>
</Show>
</box>
<Show when={props.selected}>
<box onMouseDown={handleSubscribeClick}>
<text fg={props.podcast.isSubscribed ? "red" : "green"}>
{props.podcast.isSubscribed ? "[Unsubscribe]" : "[Subscribe]"}
</text>
</box>
</Show>
</box>
</box>
)
}

View File

@@ -1,132 +0,0 @@
import { createSignal } from "solid-js"
import { useKeyboard } from "@opentui/solid"
import { useAppStore } from "../stores/app"
import { useTheme } from "../context/ThemeContext"
import type { ThemeName } from "../types/settings"
type FocusField = "theme" | "font" | "speed" | "explicit" | "auto"
const THEME_LABELS: Array<{ value: ThemeName; label: string }> = [
{ value: "system", label: "System" },
{ value: "catppuccin", label: "Catppuccin" },
{ value: "gruvbox", label: "Gruvbox" },
{ value: "tokyo", label: "Tokyo" },
{ value: "nord", label: "Nord" },
{ value: "custom", label: "Custom" },
]
export function PreferencesPanel() {
const appStore = useAppStore()
const { theme } = useTheme()
const [focusField, setFocusField] = createSignal<FocusField>("theme")
const settings = () => appStore.state().settings
const preferences = () => appStore.state().preferences
const handleKey = (key: { name: string; shift?: boolean }) => {
if (key.name === "tab") {
const fields: FocusField[] = ["theme", "font", "speed", "explicit", "auto"]
const idx = fields.indexOf(focusField())
const next = key.shift
? (idx - 1 + fields.length) % fields.length
: (idx + 1) % fields.length
setFocusField(fields[next])
return
}
if (key.name === "left" || key.name === "h") {
stepValue(-1)
}
if (key.name === "right" || key.name === "l") {
stepValue(1)
}
if (key.name === "space" || key.name === "return" || key.name === "enter") {
toggleValue()
}
}
const stepValue = (delta: number) => {
const field = focusField()
if (field === "theme") {
const idx = THEME_LABELS.findIndex((t) => t.value === settings().theme)
const next = (idx + delta + THEME_LABELS.length) % THEME_LABELS.length
appStore.setTheme(THEME_LABELS[next].value)
return
}
if (field === "font") {
const next = Math.min(20, Math.max(10, settings().fontSize + delta))
appStore.updateSettings({ fontSize: next })
return
}
if (field === "speed") {
const next = Math.min(2, Math.max(0.5, settings().playbackSpeed + delta * 0.1))
appStore.updateSettings({ playbackSpeed: Number(next.toFixed(1)) })
}
}
const toggleValue = () => {
const field = focusField()
if (field === "explicit") {
appStore.updatePreferences({ showExplicit: !preferences().showExplicit })
}
if (field === "auto") {
appStore.updatePreferences({ autoDownload: !preferences().autoDownload })
}
}
useKeyboard(handleKey)
return (
<box flexDirection="column" gap={1}>
<text fg={theme.textMuted}>Preferences</text>
<box flexDirection="column" gap={1}>
<box flexDirection="row" gap={1} alignItems="center">
<text fg={focusField() === "theme" ? theme.primary : theme.textMuted}>Theme:</text>
<box border padding={0}>
<text fg={theme.text}>{THEME_LABELS.find((t) => t.value === settings().theme)?.label}</text>
</box>
<text fg={theme.textMuted}>[Left/Right]</text>
</box>
<box flexDirection="row" gap={1} alignItems="center">
<text fg={focusField() === "font" ? theme.primary : theme.textMuted}>Font Size:</text>
<box border padding={0}>
<text fg={theme.text}>{settings().fontSize}px</text>
</box>
<text fg={theme.textMuted}>[Left/Right]</text>
</box>
<box flexDirection="row" gap={1} alignItems="center">
<text fg={focusField() === "speed" ? theme.primary : theme.textMuted}>Playback:</text>
<box border padding={0}>
<text fg={theme.text}>{settings().playbackSpeed}x</text>
</box>
<text fg={theme.textMuted}>[Left/Right]</text>
</box>
<box flexDirection="row" gap={1} alignItems="center">
<text fg={focusField() === "explicit" ? theme.primary : theme.textMuted}>Show Explicit:</text>
<box border padding={0}>
<text fg={preferences().showExplicit ? theme.success : theme.textMuted}>
{preferences().showExplicit ? "On" : "Off"}
</text>
</box>
<text fg={theme.textMuted}>[Space]</text>
</box>
<box flexDirection="row" gap={1} alignItems="center">
<text fg={focusField() === "auto" ? theme.primary : theme.textMuted}>Auto Download:</text>
<box border padding={0}>
<text fg={preferences().autoDownload ? theme.success : theme.textMuted}>
{preferences().autoDownload ? "On" : "Off"}
</text>
</box>
<text fg={theme.textMuted}>[Space]</text>
</box>
</box>
<text fg={theme.textMuted}>Tab to move focus, Left/Right to adjust</text>
</box>
)
}

View File

@@ -1,19 +0,0 @@
import { createMemo, type JSX } from "solid-js"
import { useTerminalDimensions } from "@opentui/solid"
type ResponsiveContainerProps = {
children?: (size: "small" | "medium" | "large") => JSX.Element
}
export function ResponsiveContainer(props: ResponsiveContainerProps) {
const dimensions = useTerminalDimensions()
const size = createMemo<"small" | "medium" | "large">(() => {
const width = dimensions().width
if (width < 60) return "small"
if (width < 100) return "medium"
return "large"
})
return <>{props.children?.(size())}</>
}

View File

@@ -1,79 +0,0 @@
import { Show } from "solid-js"
import type { SearchResult } from "../types/source"
import { SourceBadge } from "./SourceBadge"
type ResultCardProps = {
result: SearchResult
selected: boolean
onSelect: () => void
onSubscribe?: () => void
}
export function ResultCard(props: ResultCardProps) {
const podcast = () => props.result.podcast
return (
<box
flexDirection="column"
padding={1}
border={props.selected}
borderColor={props.selected ? "cyan" : undefined}
backgroundColor={props.selected ? "#222" : undefined}
onMouseDown={props.onSelect}
>
<box flexDirection="row" justifyContent="space-between" alignItems="center">
<box flexDirection="row" gap={2} alignItems="center">
<text fg={props.selected ? "cyan" : "white"}>
<strong>{podcast().title}</strong>
</text>
<SourceBadge
sourceId={props.result.sourceId}
sourceName={props.result.sourceName}
sourceType={props.result.sourceType}
/>
</box>
<Show when={podcast().isSubscribed}>
<text fg="green">[Subscribed]</text>
</Show>
</box>
<Show when={podcast().author}>
<text fg="gray">by {podcast().author}</text>
</Show>
<Show when={podcast().description}>
{(description) => (
<text fg={props.selected ? "white" : "gray"}>
{description().length > 120
? description().slice(0, 120) + "..."
: description()}
</text>
)}
</Show>
<Show when={(podcast().categories ?? []).length > 0}>
<box flexDirection="row" gap={1}>
{(podcast().categories ?? []).slice(0, 3).map((category) => (
<text fg="yellow">[{category}]</text>
))}
</box>
</Show>
<Show when={!podcast().isSubscribed}>
<box
border
padding={0}
paddingLeft={1}
paddingRight={1}
width={18}
onMouseDown={(event) => {
event.stopPropagation?.()
props.onSubscribe?.()
}}
>
<text fg="cyan">[+] Add to Feeds</text>
</box>
</Show>
</box>
)
}

View File

@@ -1,75 +0,0 @@
import { Show } from "solid-js"
import { format } from "date-fns"
import type { SearchResult } from "../types/source"
import { SourceBadge } from "./SourceBadge"
type ResultDetailProps = {
result?: SearchResult
onSubscribe?: (result: SearchResult) => void
}
export function ResultDetail(props: ResultDetailProps) {
return (
<box flexDirection="column" border padding={1} gap={1} height="100%">
<Show
when={props.result}
fallback={
<text fg="gray">Select a result to see details.</text>
}
>
{(result) => (
<>
<text fg="white">
<strong>{result().podcast.title}</strong>
</text>
<SourceBadge
sourceId={result().sourceId}
sourceName={result().sourceName}
sourceType={result().sourceType}
/>
<Show when={result().podcast.author}>
<text fg="gray">by {result().podcast.author}</text>
</Show>
<Show when={result().podcast.description}>
<text fg="gray">{result().podcast.description}</text>
</Show>
<Show when={(result().podcast.categories ?? []).length > 0}>
<box flexDirection="row" gap={1}>
{(result().podcast.categories ?? []).map((category) => (
<text fg="yellow">[{category}]</text>
))}
</box>
</Show>
<text fg="gray">Feed: {result().podcast.feedUrl}</text>
<text fg="gray">
Updated: {format(result().podcast.lastUpdated, "MMM d, yyyy")}
</text>
<Show when={!result().podcast.isSubscribed}>
<box
border
padding={0}
paddingLeft={1}
paddingRight={1}
width={18}
onMouseDown={() => props.onSubscribe?.(result())}
>
<text fg="cyan">[+] Add to Feeds</text>
</box>
</Show>
<Show when={result().podcast.isSubscribed}>
<text fg="green">Already subscribed</text>
</Show>
</>
)}
</Show>
</box>
)
}

View File

@@ -1,35 +0,0 @@
import type { JSX } from "solid-js"
type RowProps = {
children?: JSX.Element
gap?: number
alignItems?: "flex-start" | "flex-end" | "center" | "stretch" | "baseline"
justifyContent?:
| "flex-start"
| "flex-end"
| "center"
| "space-between"
| "space-around"
| "space-evenly"
width?: number | "auto" | `${number}%`
height?: number | "auto" | `${number}%`
padding?: number
}
export function Row(props: RowProps) {
return (
<box
style={{
flexDirection: "row",
gap: props.gap,
alignItems: props.alignItems,
justifyContent: props.justifyContent,
width: props.width,
height: props.height,
padding: props.padding,
}}
>
{props.children}
</box>
)
}

View File

@@ -1,266 +0,0 @@
/**
* SearchPage component - Main search interface for PodTUI
*/
import { createSignal, createEffect, Show } from "solid-js"
import { useKeyboard } from "@opentui/solid"
import { useSearchStore } from "../stores/search"
import { SearchResults } from "./SearchResults"
import { SearchHistory } from "./SearchHistory"
import type { SearchResult } from "../types/source"
type SearchPageProps = {
focused: boolean
onSubscribe?: (result: SearchResult) => void
onInputFocusChange?: (focused: boolean) => void
onExit?: () => void
}
type FocusArea = "input" | "results" | "history"
export function SearchPage(props: SearchPageProps) {
const searchStore = useSearchStore()
const [focusArea, setFocusArea] = createSignal<FocusArea>("input")
const [inputValue, setInputValue] = createSignal("")
const [resultIndex, setResultIndex] = createSignal(0)
const [historyIndex, setHistoryIndex] = createSignal(0)
// Keep parent informed about input focus state
createEffect(() => {
const isInputFocused = props.focused && focusArea() === "input"
props.onInputFocusChange?.(isInputFocused)
})
const handleSearch = async () => {
const query = inputValue().trim()
if (query) {
await searchStore.search(query)
if (searchStore.results().length > 0) {
setFocusArea("results")
setResultIndex(0)
}
}
}
const handleHistorySelect = async (query: string) => {
setInputValue(query)
await searchStore.search(query)
if (searchStore.results().length > 0) {
setFocusArea("results")
setResultIndex(0)
}
}
const handleResultSelect = (result: SearchResult) => {
props.onSubscribe?.(result)
searchStore.markSubscribed(result.podcast.id)
}
// Keyboard navigation
useKeyboard((key) => {
if (!props.focused) return
const area = focusArea()
// Enter to search from input
if ((key.name === "return" || key.name === "enter") && area === "input") {
handleSearch()
return
}
// Tab to cycle focus areas
if (key.name === "tab" && !key.shift) {
if (area === "input") {
if (searchStore.results().length > 0) {
setFocusArea("results")
} else if (searchStore.history().length > 0) {
setFocusArea("history")
}
} else if (area === "results") {
if (searchStore.history().length > 0) {
setFocusArea("history")
} else {
setFocusArea("input")
}
} else {
setFocusArea("input")
}
return
}
if (key.name === "tab" && key.shift) {
if (area === "input") {
if (searchStore.history().length > 0) {
setFocusArea("history")
} else if (searchStore.results().length > 0) {
setFocusArea("results")
}
} else if (area === "history") {
if (searchStore.results().length > 0) {
setFocusArea("results")
} else {
setFocusArea("input")
}
} else {
setFocusArea("input")
}
return
}
// Up/Down for results and history
if (area === "results") {
const results = searchStore.results()
if (key.name === "down" || key.name === "j") {
setResultIndex((i) => Math.min(i + 1, results.length - 1))
return
}
if (key.name === "up" || key.name === "k") {
setResultIndex((i) => Math.max(i - 1, 0))
return
}
if (key.name === "return" || key.name === "enter") {
const result = results[resultIndex()]
if (result) handleResultSelect(result)
return
}
}
if (area === "history") {
const history = searchStore.history()
if (key.name === "down" || key.name === "j") {
setHistoryIndex((i) => Math.min(i + 1, history.length - 1))
return
}
if (key.name === "up" || key.name === "k") {
setHistoryIndex((i) => Math.max(i - 1, 0))
return
}
if (key.name === "return" || key.name === "enter") {
const query = history[historyIndex()]
if (query) handleHistorySelect(query)
return
}
}
// Escape goes back to input or up one level
if (key.name === "escape") {
if (area === "input") {
props.onExit?.()
} else {
setFocusArea("input")
key.stopPropagation()
}
return
}
// "/" focuses search input
if (key.name === "/" && area !== "input") {
setFocusArea("input")
return
}
})
return (
<box flexDirection="column" height="100%" gap={1}>
{/* Search Header */}
<box flexDirection="column" gap={1}>
<text>
<strong>Search Podcasts</strong>
</text>
{/* Search Input */}
<box flexDirection="row" gap={1} alignItems="center">
<text fg="gray">Search:</text>
<input
value={inputValue()}
onInput={(value) => {
setInputValue(value)
}}
placeholder="Enter podcast name, topic, or author..."
focused={props.focused && focusArea() === "input"}
width={50}
/>
<box
border
padding={0}
paddingLeft={1}
paddingRight={1}
onMouseDown={handleSearch}
>
<text fg="cyan">[Enter] Search</text>
</box>
</box>
{/* Status */}
<Show when={searchStore.isSearching()}>
<text fg="yellow">Searching...</text>
</Show>
<Show when={searchStore.error()}>
<text fg="red">{searchStore.error()}</text>
</Show>
</box>
{/* Main Content - Results or History */}
<box flexDirection="row" height="100%" gap={2}>
{/* Results Panel */}
<box flexDirection="column" flexGrow={1} border>
<box padding={1}>
<text fg={focusArea() === "results" ? "cyan" : "gray"}>
Results ({searchStore.results().length})
</text>
</box>
<Show
when={searchStore.results().length > 0}
fallback={
<box padding={2}>
<text fg="gray">
{searchStore.query()
? "No results found"
: "Enter a search term to find podcasts"}
</text>
</box>
}
>
<SearchResults
results={searchStore.results()}
selectedIndex={resultIndex()}
focused={focusArea() === "results"}
onSelect={handleResultSelect}
onChange={setResultIndex}
isSearching={searchStore.isSearching()}
error={searchStore.error()}
/>
</Show>
</box>
{/* History Sidebar */}
<box width={30} border>
<box padding={1} flexDirection="column">
<box paddingBottom={1}>
<text fg={focusArea() === "history" ? "cyan" : "gray"}>
History
</text>
</box>
<SearchHistory
history={searchStore.history()}
selectedIndex={historyIndex()}
focused={focusArea() === "history"}
onSelect={handleHistorySelect}
onRemove={searchStore.removeFromHistory}
onClear={searchStore.clearHistory}
onChange={setHistoryIndex}
/>
</box>
</box>
</box>
{/* Footer Hints */}
<box flexDirection="row" gap={2}>
<text fg="gray">[Tab] Switch focus</text>
<text fg="gray">[/] Focus search</text>
<text fg="gray">[Enter] Select</text>
<text fg="gray">[Esc] Up</text>
</box>
</box>
)
}

View File

@@ -0,0 +1,81 @@
import { useTheme } from "@/context/ThemeContext";
import { children as solidChildren } from "solid-js";
import type { ParentComponent } from "solid-js";
import type { BoxOptions, TextOptions } from "@opentui/core";
export const SelectableBox: ParentComponent<
{
selected: () => boolean;
} & BoxOptions
> = (props) => {
const themeContext = useTheme();
const { theme } = themeContext;
const child = solidChildren(() => props.children);
return (
<box
border={!!props.border}
borderColor={props.selected() ? theme.surface : theme.border}
backgroundColor={
props.selected()
? theme.primary
: themeContext.selected === "system"
? "transparent"
: themeContext.theme.surface
}
{...props}
>
{child()}
</box>
);
};
enum ColorSet {
PRIMARY,
SECONDARY,
TERTIARY,
DEFAULT,
}
function getTextColor(set: ColorSet, selected: () => boolean) {
const { theme } = useTheme();
switch (set) {
case ColorSet.PRIMARY:
return selected() ? theme.textSelectedPrimary : theme.textPrimary;
case ColorSet.SECONDARY:
return selected() ? theme.textSelectedSecondary : theme.textSecondary;
case ColorSet.TERTIARY:
return selected() ? theme.textSelectedTertiary : theme.textTertiary;
default:
return theme.textPrimary;
}
}
export const SelectableText: ParentComponent<
{
selected: () => boolean;
primary?: boolean;
secondary?: boolean;
tertiary?: boolean;
} & TextOptions
> = (props) => {
const child = solidChildren(() => props.children);
return (
<text
fg={getTextColor(
props.primary
? ColorSet.PRIMARY
: props.secondary
? ColorSet.SECONDARY
: props.tertiary
? ColorSet.TERTIARY
: ColorSet.DEFAULT,
props.selected,
)}
{...props}
>
{child()}
</text>
);
};

View File

@@ -1,98 +0,0 @@
import { createSignal, For } from "solid-js"
import { useKeyboard } from "@opentui/solid"
import { SourceManager } from "./SourceManager"
import { useTheme } from "../context/ThemeContext"
import { PreferencesPanel } from "./PreferencesPanel"
import { SyncPanel } from "./SyncPanel"
type SettingsScreenProps = {
accountLabel: string
accountStatus: "signed-in" | "signed-out"
onOpenAccount?: () => void
onExit?: () => void
}
type SectionId = "sync" | "sources" | "preferences" | "account"
const SECTIONS: Array<{ id: SectionId; label: string }> = [
{ id: "sync", label: "Sync" },
{ id: "sources", label: "Sources" },
{ id: "preferences", label: "Preferences" },
{ id: "account", label: "Account" },
]
export function SettingsScreen(props: SettingsScreenProps) {
const { theme } = useTheme()
const [activeSection, setActiveSection] = createSignal<SectionId>("sync")
useKeyboard((key) => {
if (key.name === "escape") {
props.onExit?.()
return
}
if (key.name === "tab") {
const idx = SECTIONS.findIndex((s) => s.id === activeSection())
const next = key.shift
? (idx - 1 + SECTIONS.length) % SECTIONS.length
: (idx + 1) % SECTIONS.length
setActiveSection(SECTIONS[next].id)
return
}
if (key.name === "1") setActiveSection("sync")
if (key.name === "2") setActiveSection("sources")
if (key.name === "3") setActiveSection("preferences")
if (key.name === "4") setActiveSection("account")
})
return (
<box flexDirection="column" gap={1} height="100%">
<box flexDirection="row" justifyContent="space-between" alignItems="center">
<text>
<strong>Settings</strong>
</text>
<text fg={theme.textMuted}>[Tab] Switch section | 1-4 jump | Esc up</text>
</box>
<box flexDirection="row" gap={1}>
<For each={SECTIONS}>
{(section, index) => (
<box
border
padding={0}
backgroundColor={activeSection() === section.id ? theme.primary : undefined}
onMouseDown={() => setActiveSection(section.id)}
>
<text fg={activeSection() === section.id ? theme.text : theme.textMuted}>
[{index() + 1}] {section.label}
</text>
</box>
)}
</For>
</box>
<box border flexGrow={1} padding={1} flexDirection="column" gap={1}>
{activeSection() === "sync" && <SyncPanel />}
{activeSection() === "sources" && <SourceManager focused />}
{activeSection() === "preferences" && <PreferencesPanel />}
{activeSection() === "account" && (
<box flexDirection="column" gap={1}>
<text fg={theme.textMuted}>Account</text>
<box flexDirection="row" gap={2} alignItems="center">
<text fg={theme.textMuted}>Status:</text>
<text fg={props.accountStatus === "signed-in" ? theme.success : theme.warning}>
{props.accountLabel}
</text>
</box>
<box border padding={0} onMouseDown={() => props.onOpenAccount?.()}>
<text fg={theme.primary}>[A] Manage Account</text>
</box>
</box>
)}
</box>
<text fg={theme.textMuted}>Enter to dive | Esc up</text>
</box>
)
}

475
src/components/Shell.tsx Normal file
View File

@@ -0,0 +1,475 @@
/**
* Shell — yazi-style application chrome.
*
* Renders the active page (which owns its own three-column parent | current |
* preview panes) full-width, with a bottom status/command bar that also
* carries the tab strip. A single `useKeyboard` router translates keystrokes
* (via the sequence-aware keybind matcher) into actions: the unified router
* in `@/utils/dispatch` handles tabs (digits `1`-`6`, `[`/`]`), h/l depth
* drill/pop + fixed-pane swipe, modes, audio, quit, help, and command; the
* pane/list ones are dispatched to the active page over the `nav.action`
* event bus. There is no sidebar pane.
*/
import { createSignal, Show, For } from "solid-js";
import { useKeyboard } from "@opentui/solid";
import { useTheme } from "@/context/ThemeContext";
import { useKeybinds, type KeybindActionName } from "@/context/KeybindContext";
import { useNavigation, NavMode } from "@/context/NavigationContext";
import { useAudio } from "@/hooks/useAudio";
import { useAudioNavStore, AudioSource } from "@/stores/audio-nav";
import { useFeedStore } from "@/stores/feed";
import { useToast } from "@/ui/toast";
import { emit } from "@/utils/event-bus";
import { LayerGraph } from "@/utils/layer-graph";
import { TABS, TabPaneCount } from "@/utils/navigation";
import { createDispatcher } from "@/utils/dispatch";
import { TabListPane } from "@/components/TabPanel";
import { PaneRow } from "@/components/PaneRow";
const TAB_LABEL: Record<TABS, string> = {
[TABS.FEED]: "Feed",
[TABS.MYSHOWS]: "My Shows",
[TABS.DISCOVER]: "Discover",
[TABS.SEARCH]: "Search",
[TABS.PLAYER]: "Player",
[TABS.SETTINGS]: "Settings",
};
export function Shell() {
const theme = useTheme();
const t = theme.theme;
const nav = useNavigation();
const k = useKeybinds();
const audio = useAudio();
const audioNav = useAudioNavStore();
const toast = useToast();
const feedStore = useFeedStore();
const [showHelp, setShowHelp] = createSignal(false);
/** Play the episode adjacent (offset ±1) to the currently-playing one,
* within its feed's episode list. Updates audio-nav context accordingly. */
function advanceEpisode(offset: number) {
const cur = audio.currentEpisode();
if (!cur) {
toast.show({ message: "Nothing playing", variant: "warning" });
return;
}
const pid = audioNav.getPodcastId();
const feeds = feedStore.getFilteredFeeds();
const feed =
feeds.find((f) => f.podcast.id === pid) ??
feeds.find((f) => f.episodes.some((e) => e.id === cur.id));
if (!feed) {
toast.show({ message: "Show not found", variant: "warning" });
return;
}
const eps = [...feed.episodes].sort(
(a, b) => b.pubDate.getTime() - a.pubDate.getTime(),
);
const idx = eps.findIndex((e) => e.id === cur.id);
const next = eps[idx + offset];
if (!next) {
toast.show({
message: offset > 0 ? "No next episode" : "No previous episode",
variant: "warning",
});
return;
}
audio.play(next).catch(() => {});
audioNav.next(eps.length - 1 - (idx + offset) >= 0 ? idx + offset : idx);
toast.show({ message: `${next.title}`.slice(0, 60), variant: "info" });
}
// ── Command bar dispatch ────────────────────────────────────────────────────
function runCommand(raw: string) {
const cmd = raw.trim();
if (!cmd) return;
const name = cmd.split(/\s+/)[0].toLowerCase();
const arg = cmd.slice(name.length).trim();
switch (name) {
case "q":
case "quit":
case "exit":
return process.exit(0);
case "refresh":
case "r":
emit("nav.action", {
action: "refresh",
tab: nav.activeTab(),
pane: nav.activePane(),
mode: nav.mode(),
});
break;
case "play":
case "pause":
case "p":
audio.togglePlayback().catch(() => {});
break;
case "next":
case "n":
advanceEpisode(1);
break;
case "prev":
advanceEpisode(-1);
break;
case "seek": {
const n = Number(arg) || 0;
audio.seek(n).catch(() => {});
break;
}
case "feed":
case "f":
nav.setActiveTab(TABS.FEED);
break;
case "shows":
case "myshows":
nav.setActiveTab(TABS.MYSHOWS);
break;
case "discover":
case "d":
nav.setActiveTab(TABS.DISCOVER);
break;
case "search":
nav.setActiveTab(TABS.SEARCH);
break;
case "player":
nav.setActiveTab(TABS.PLAYER);
break;
case "settings":
case "set":
nav.setActiveTab(TABS.SETTINGS);
break;
case "help":
case "h":
setShowHelp((v) => !v);
break;
default:
nav.setCommandError(`unknown command: ${name}`);
// re-enter command mode so the user sees the error + can correct
nav.enterCommand();
nav.setCommandBuffer(cmd);
}
}
// ── Command-mode key handling ───────────────────────────────────────────────
function handleCommandKey(evt: any) {
if (k.match("escape", evt) || evt.name === "ctrl-c") {
evt.preventDefault();
nav.exitCommand();
return;
}
if (evt.name === "return" || evt.name === "enter") {
evt.preventDefault();
const cmd = nav.commandBuffer();
runCommand(cmd);
nav.exitCommand();
return;
}
if (evt.name === "backspace") {
evt.preventDefault();
const buf = nav.commandBuffer();
if (buf.length === 0) {
nav.exitCommand();
return;
}
nav.backspaceCommand();
return;
}
// printable char
if (evt.name && evt.name.length === 1 && !evt.ctrl && !evt.meta) {
evt.preventDefault();
nav.appendCommand(evt.name);
return;
}
}
// ── Unified router (normal + visual) ───────────────────────────────────────
const { dispatch } = createDispatcher({
nav,
audio: {
togglePlayback: audio.togglePlayback,
seekRelative: audio.seekRelative,
},
k,
setShowHelp,
advanceEpisode,
});
useKeyboard(
(evt: any) => {
// Input fields (search boxes, dialogs) own their keys — except Escape,
// which defocuses the input so j/k/h navigation resumes (search: h back
// to the tab root, j/k to move the recent-searches list).
if (nav.inputFocused() && nav.mode() !== NavMode.COMMAND) {
if (evt.name === "escape") {
evt.preventDefault();
nav.setInputFocused(false);
}
return;
}
if (nav.mode() === NavMode.COMMAND) {
handleCommandKey(evt);
return;
}
const action = k.tryMatch(evt);
if (action) dispatch(action, evt);
},
{ release: false },
);
// ── Status bar fragments ──────────────────────────────────────────────────
const nowPlaying = () => {
const ep = audio.currentEpisode();
if (!ep) return null;
const title = ep.title.length > 40 ? ep.title.slice(0, 38) + "…" : ep.title;
return `${title}`;
};
const modeLabel = () =>
nav.mode() === NavMode.NORMAL ? "" : `-- ${nav.mode()} --`;
const pendingLabel = () =>
k
.pending()
.map((s) => s.key)
.join(" ");
return (
<box
flexDirection="column"
width="100%"
height="100%"
backgroundColor={t.surface}
>
{/* ── Middle row: tab list (pane 0) + active tab content (panes 1..n) ─ */}
<box flexDirection="row" flexGrow={1} width="100%">
<Show
when={nav.atRootTab()}
fallback={
<box flexGrow={1} width="100%">
{LayerGraph[nav.activeTab()]()}
</box>
}
>
{/* app root: the tab list is the CURRENT pane, nothing in UP */}
<PaneRow
parent={
<box padding={1}>
<text fg={t.textMuted}></text>
</box>
}
current={<TabListPane />}
preview={
<box padding={1}>
<text fg={t.textMuted}>j/k move · l/Enter open a tab</text>
</box>
}
parentLabel="Up"
currentLabel="Tabs"
previewLabel=""
focused
/>
</Show>
</box>
{/* ── Bottom status / command bar ─────────────────────────────────────── */}
<box
flexDirection="row"
height={1}
width="100%"
backgroundColor={t.backgroundPanel ?? t.background}
>
<Show
when={nav.mode() === NavMode.COMMAND}
fallback={
<>
<text fg={t.accent} paddingLeft={1}>
{modeLabel()}
</text>
<text fg={t.textMuted} paddingLeft={1}>
{nav.atRootTab()
? "Tabs · root"
: `${TAB_LABEL[nav.activeTab()]} · ${
nav.isDepthTab()
? `depth ${nav.currentDepth()}`
: `pane ${nav.activePane()}/${TabPaneCount[nav.activeTab()]}`
}`}
</text>
<Show when={nav.selectedIds().length > 0}>
<text fg={t.warning} paddingLeft={1}>
{nav.selectedIds().length}
</text>
</Show>
<Show when={nowPlaying()}>
<text fg={t.primary} paddingLeft={1}>
{nowPlaying()}
</text>
</Show>
<box flexGrow={1} />
<text fg={t.textMuted} paddingRight={1}>
{pendingLabel()}
</text>
<text fg={t.textMuted} paddingRight={1}>
~
</text>
</>
}
>
<text fg={t.accent} paddingLeft={1}>
:
</text>
<text fg={t.text}>{nav.commandBuffer()}</text>
<text fg={t.textMuted}></text>
<Show when={nav.commandError()}>
<text fg={t.error} paddingLeft={1}>
{nav.commandError()}
</text>
</Show>
</Show>
</box>
{/* ── Help overlay ─────────────────────────────────────────────────────── */}
<Show when={showHelp()}>
<HelpOverlay
onClose={() => setShowHelp(false)}
sections={helpSections(k)}
theme={t as any}
/>
</Show>
</box>
);
}
function helpSections(k: ReturnType<typeof useKeybinds>) {
const p = (a: KeybindActionName) => k.print(a);
return [
{
group: "Move",
items: [
["j/k", "move"],
["J/K", "5 lines"],
["ctrl-d/u", "half page"],
["gg/G", "top/bottom"],
],
},
{
group: "Panes",
items: [
["j/k", "switch tab (tab panel)"],
["l/enter", "enter tab content"],
["h", "back to tab panel"],
["1-6 / [ ]", "switch tabs"],
[":", "command"],
["~", "help"],
],
},
{
group: "Select",
items: [
["space", "toggle"],
["v", "visual"],
["ctrl-a", "all"],
["esc", "clear"],
],
},
{
group: "Audio",
items: [
[p("audio-toggle"), "play/pause"],
[p("audio-next"), "next"],
[p("audio-seek-forward"), "fwd 10s"],
[p("audio-seek-backward"), "back 10s"],
],
},
{
group: "List",
items: [
["enter", "open"],
["r", "refresh"],
["s", "search"],
["f", "filter"],
[",", "sort"],
[".", "hidden"],
],
},
];
}
function HelpOverlay(props: {
onClose: () => void;
sections: { group: string; items: string[][] }[];
theme: any;
}) {
useKeyboard((evt: any) => {
if (k_match_escape(evt)) {
evt.preventDefault();
props.onClose();
}
});
const th = props.theme;
return (
<box
position="absolute"
top={2}
left={0}
width="100%"
alignItems="center"
backgroundColor="rgba(0,0,0,160)"
onMouseUp={() => props.onClose()}
>
<box
flexDirection="column"
border
borderColor={th.border}
backgroundColor={th.backgroundPanel ?? th.background}
padding={1}
width={60}
onMouseUp={(e: any) => e.stopPropagation()}
>
<text fg={th.accent}>
Yazi-style keybinds press ~ or Esc to close
</text>
<For each={props.sections}>
{(sec) => (
<box flexDirection="column" marginTop={1}>
<text fg={th.textSecondary}>{sec.group}</text>
<For each={sec.items}>
{(it) => (
<box flexDirection="row" gap={2}>
<text fg={th.accent}>{String(it[0]).padEnd(14, " ")}</text>
<text fg={th.textPrimary ?? th.text}>{it[1]}</text>
</box>
)}
</For>
</box>
)}
</For>
<box marginTop={1}>
<text fg={th.textMuted}>
Edit ~/.config/podtui/keybinds.jsonc to remap.
</text>
</box>
</box>
</box>
);
}
function k_match_escape(evt: any): boolean {
return (
evt.name === "escape" || evt.name === "~" || (evt.ctrl && evt.name === "[")
);
}
/** Exposed so App can route an externally-triggered "play episode" (e.g. from
* search) into the player tab. */
export function playEpisodeAndSwitch(
nav: ReturnType<typeof useNavigation>,
audio: ReturnType<typeof useAudio>,
episode: import("@/types/episode").Episode,
) {
audio.play(episode);
nav.setActiveTab(TABS.PLAYER);
nav.enterTabContent(); // PLAYER is a depth-tab — drop into its content pane.
useAudioNavStore().setSource(AudioSource.FEED);
}
// Re-export Episode type for callers building pane trees.
export type { Episode } from "@/types/episode";

View File

@@ -1,26 +1,27 @@
import { shortcuts } from "../config/shortcuts" import { For } from "solid-js";
import { shortcuts } from "@/config/shortcuts";
import { useTheme } from "@/context/ThemeContext";
/** Yazi-style keybind reference. The Shell has its own overlay; this component
* is kept for embedding inside Settings or other surfaces. */
export function ShortcutHelp() { export function ShortcutHelp() {
const { theme } = useTheme();
return ( return (
<box border title="Shortcuts" style={{ padding: 1 }}> <box
border
title="Shortcuts"
style={{ flexDirection: "column", padding: 1 }}
>
<box style={{ flexDirection: "column" }}> <box style={{ flexDirection: "column" }}>
<box style={{ flexDirection: "row" }}> <For each={shortcuts}>
<text>{shortcuts[0]?.keys ?? ""} </text> {(s) => (
<text>{shortcuts[0]?.action ?? ""}</text> <box style={{ flexDirection: "row" }} gap={2}>
<text fg={theme.accent}>{s.keys}</text>
<text fg={theme.text}>{s.action}</text>
</box> </box>
<box style={{ flexDirection: "row" }}> )}
<text>{shortcuts[1]?.keys ?? ""} </text> </For>
<text>{shortcuts[1]?.action ?? ""}</text>
</box>
<box style={{ flexDirection: "row" }}>
<text>{shortcuts[2]?.keys ?? ""} </text>
<text>{shortcuts[2]?.action ?? ""}</text>
</box>
<box style={{ flexDirection: "row" }}>
<text>{shortcuts[3]?.keys ?? ""} </text>
<text>{shortcuts[3]?.action ?? ""}</text>
</box> </box>
</box> </box>
</box> );
)
} }

View File

@@ -1,34 +0,0 @@
import { SourceType } from "../types/source"
type SourceBadgeProps = {
sourceId: string
sourceName?: string
sourceType?: SourceType
}
const typeLabel = (sourceType?: SourceType) => {
if (sourceType === SourceType.API) return "API"
if (sourceType === SourceType.RSS) return "RSS"
if (sourceType === SourceType.CUSTOM) return "Custom"
return "Source"
}
const typeColor = (sourceType?: SourceType) => {
if (sourceType === SourceType.API) return "cyan"
if (sourceType === SourceType.RSS) return "green"
if (sourceType === SourceType.CUSTOM) return "yellow"
return "gray"
}
export function SourceBadge(props: SourceBadgeProps) {
const label = () => props.sourceName || props.sourceId
return (
<box flexDirection="row" gap={1} padding={0}>
<text fg={typeColor(props.sourceType)}>
[{typeLabel(props.sourceType)}]
</text>
<text fg="gray">{label()}</text>
</box>
)
}

View File

@@ -1,302 +0,0 @@
/**
* Source management component for PodTUI
* Add, remove, and configure podcast sources
*/
import { createSignal, For } from "solid-js"
import { useFeedStore } from "../stores/feed"
import { useTheme } from "../context/ThemeContext"
import { SourceType } from "../types/source"
import type { PodcastSource } from "../types/source"
interface SourceManagerProps {
focused?: boolean
onClose?: () => void
}
type FocusArea = "list" | "add" | "url" | "country" | "explicit" | "language"
export function SourceManager(props: SourceManagerProps) {
const feedStore = useFeedStore()
const { theme } = useTheme()
const [selectedIndex, setSelectedIndex] = createSignal(0)
const [focusArea, setFocusArea] = createSignal<FocusArea>("list")
const [newSourceUrl, setNewSourceUrl] = createSignal("")
const [newSourceName, setNewSourceName] = createSignal("")
const [error, setError] = createSignal<string | null>(null)
const sources = () => feedStore.sources()
const handleKeyPress = (key: { name: string; shift?: boolean }) => {
if (key.name === "escape") {
if (focusArea() !== "list") {
setFocusArea("list")
setError(null)
} else if (props.onClose) {
props.onClose()
}
return
}
if (key.name === "tab") {
const areas: FocusArea[] = [
"list",
"country",
"language",
"explicit",
"add",
"url",
]
const idx = areas.indexOf(focusArea())
const nextIdx = key.shift
? (idx - 1 + areas.length) % areas.length
: (idx + 1) % areas.length
setFocusArea(areas[nextIdx])
return
}
if (focusArea() === "list") {
if (key.name === "up" || key.name === "k") {
setSelectedIndex((i) => Math.max(0, i - 1))
} else if (key.name === "down" || key.name === "j") {
setSelectedIndex((i) => Math.min(sources().length - 1, i + 1))
} else if (key.name === "return" || key.name === "enter" || key.name === "space") {
const source = sources()[selectedIndex()]
if (source) {
feedStore.toggleSource(source.id)
}
} else if (key.name === "d" || key.name === "delete") {
const source = sources()[selectedIndex()]
if (source) {
const removed = feedStore.removeSource(source.id)
if (!removed) {
setError("Cannot remove default sources")
}
}
} else if (key.name === "a") {
setFocusArea("add")
}
}
if (focusArea() === "country") {
if (key.name === "enter" || key.name === "return" || key.name === "space") {
const source = sources()[selectedIndex()]
if (source && source.type === SourceType.API) {
const next = source.country === "US" ? "GB" : "US"
feedStore.updateSource(source.id, { country: next })
}
}
}
if (focusArea() === "explicit") {
if (key.name === "enter" || key.name === "return" || key.name === "space") {
const source = sources()[selectedIndex()]
if (source && source.type === SourceType.API) {
feedStore.updateSource(source.id, { allowExplicit: !source.allowExplicit })
}
}
}
if (focusArea() === "language") {
if (key.name === "enter" || key.name === "return" || key.name === "space") {
const source = sources()[selectedIndex()]
if (source && source.type === SourceType.API) {
const next = source.language === "ja_jp" ? "en_us" : "ja_jp"
feedStore.updateSource(source.id, { language: next })
}
}
}
}
const handleAddSource = () => {
const url = newSourceUrl().trim()
const name = newSourceName().trim() || `Custom Source`
if (!url) {
setError("URL is required")
return
}
try {
new URL(url)
} catch {
setError("Invalid URL format")
return
}
feedStore.addSource({
name,
type: "rss" as SourceType,
baseUrl: url,
enabled: true,
description: `Custom RSS feed: ${url}`,
})
setNewSourceUrl("")
setNewSourceName("")
setFocusArea("list")
setError(null)
}
const getSourceIcon = (source: PodcastSource) => {
if (source.type === SourceType.API) return "[API]"
if (source.type === SourceType.RSS) return "[RSS]"
return "[?]"
}
const selectedSource = () => sources()[selectedIndex()]
const isApiSource = () => selectedSource()?.type === SourceType.API
const sourceCountry = () => selectedSource()?.country || "US"
const sourceExplicit = () => selectedSource()?.allowExplicit !== false
const sourceLanguage = () => selectedSource()?.language || "en_us"
return (
<box flexDirection="column" border padding={1} gap={1}>
<box flexDirection="row" justifyContent="space-between">
<text>
<strong>Podcast Sources</strong>
</text>
<box border padding={0} onMouseDown={props.onClose}>
<text fg={theme.primary}>[Esc] Close</text>
</box>
</box>
<text fg={theme.textMuted}>Manage where to search for podcasts</text>
{/* Source list */}
<box border padding={1} flexDirection="column" gap={1}>
<text fg={focusArea() === "list" ? theme.primary : theme.textMuted}>Sources:</text>
<scrollbox height={6}>
<For each={sources()}>
{(source, index) => (
<box
flexDirection="row"
gap={1}
padding={0}
backgroundColor={
focusArea() === "list" && index() === selectedIndex()
? theme.primary
: undefined
}
onMouseDown={() => {
setSelectedIndex(index())
setFocusArea("list")
feedStore.toggleSource(source.id)
}}
>
<text fg={
focusArea() === "list" && index() === selectedIndex()
? theme.primary
: theme.textMuted
}>
{focusArea() === "list" && index() === selectedIndex()
? ">"
: " "}
</text>
<text fg={source.enabled ? theme.success : theme.error}>
{source.enabled ? "[x]" : "[ ]"}
</text>
<text fg={theme.accent}>{getSourceIcon(source)}</text>
<text
fg={
focusArea() === "list" && index() === selectedIndex()
? theme.text
: undefined
}
>
{source.name}
</text>
</box>
)}
</For>
</scrollbox>
<text fg={theme.textMuted}>Space/Enter to toggle, d to delete, a to add</text>
{/* API settings */}
<box flexDirection="column" gap={1}>
<text fg={isApiSource() ? theme.textMuted : theme.accent}>
{isApiSource() ? "API Settings" : "API Settings (select an API source)"}
</text>
<box flexDirection="row" gap={2}>
<box
border
padding={0}
backgroundColor={focusArea() === "country" ? theme.primary : undefined}
>
<text fg={focusArea() === "country" ? theme.primary : theme.textMuted}>
Country: {sourceCountry()}
</text>
</box>
<box
border
padding={0}
backgroundColor={focusArea() === "language" ? theme.primary : undefined}
>
<text fg={focusArea() === "language" ? theme.primary : theme.textMuted}>
Language: {sourceLanguage() === "ja_jp" ? "Japanese" : "English"}
</text>
</box>
<box
border
padding={0}
backgroundColor={focusArea() === "explicit" ? theme.primary : undefined}
>
<text fg={focusArea() === "explicit" ? theme.primary : theme.textMuted}>
Explicit: {sourceExplicit() ? "Yes" : "No"}
</text>
</box>
</box>
<text fg={theme.textMuted}>Enter/Space to toggle focused setting</text>
</box>
</box>
{/* Add new source form */}
<box border padding={1} flexDirection="column" gap={1}>
<text fg={focusArea() === "add" || focusArea() === "url" ? theme.primary : theme.textMuted}>
Add New Source:
</text>
<box flexDirection="row" gap={1}>
<text fg={theme.textMuted}>Name:</text>
<input
value={newSourceName()}
onInput={setNewSourceName}
placeholder="My Custom Feed"
focused={props.focused && focusArea() === "add"}
width={25}
/>
</box>
<box flexDirection="row" gap={1}>
<text fg={theme.textMuted}>URL:</text>
<input
value={newSourceUrl()}
onInput={(v) => {
setNewSourceUrl(v)
setError(null)
}}
placeholder="https://example.com/feed.rss"
focused={props.focused && focusArea() === "url"}
width={35}
/>
</box>
<box
border
padding={0}
width={15}
onMouseDown={handleAddSource}
>
<text fg={theme.success}>[+] Add Source</text>
</box>
</box>
{/* Error message */}
{error() && (
<text fg={theme.error}>{error()}</text>
)}
<text fg={theme.textMuted}>Tab to switch sections, Esc to close</text>
</box>
)
}

View File

@@ -1,15 +0,0 @@
type SyncErrorProps = {
message: string
onRetry: () => void
}
export function SyncError(props: SyncErrorProps) {
return (
<box border title="Error" style={{ padding: 1, flexDirection: "column", gap: 1 }}>
<text>{props.message}</text>
<box border onMouseDown={props.onRetry}>
<text>Retry</text>
</box>
</box>
)
}

View File

@@ -1,30 +0,0 @@
const createSignal = <T,>(value: T): [() => T, (next: T) => void] => {
let current = value
return [() => current, (next) => {
current = next
}]
}
import { ImportDialog } from "./ImportDialog"
import { ExportDialog } from "./ExportDialog"
import { SyncStatus } from "./SyncStatus"
export function SyncPanel() {
const mode = createSignal<"import" | "export" | null>(null)
return (
<box style={{ flexDirection: "column", gap: 1 }}>
<box style={{ flexDirection: "row", gap: 1 }}>
<box border onMouseDown={() => mode[1]("import")}>
<text>Import</text>
</box>
<box border onMouseDown={() => mode[1]("export")}>
<text>Export</text>
</box>
</box>
<SyncStatus />
{mode[0]() === "import" ? <ImportDialog /> : null}
{mode[0]() === "export" ? <ExportDialog /> : null}
</box>
)
}

View File

@@ -1,148 +0,0 @@
/**
* Sync profile component for PodTUI
* Displays user profile information and sync status
*/
import { createSignal } from "solid-js"
import { useAuthStore } from "../stores/auth"
import { format } from "date-fns"
interface SyncProfileProps {
focused?: boolean
onLogout?: () => void
onManageSync?: () => void
}
type FocusField = "sync" | "export" | "logout"
export function SyncProfile(props: SyncProfileProps) {
const auth = useAuthStore()
const [focusField, setFocusField] = createSignal<FocusField>("sync")
const [lastSyncTime] = createSignal<Date | null>(new Date())
const fields: FocusField[] = ["sync", "export", "logout"]
const handleKeyPress = (key: { name: string; shift?: boolean }) => {
if (key.name === "tab") {
const currentIndex = fields.indexOf(focusField())
const nextIndex = key.shift
? (currentIndex - 1 + fields.length) % fields.length
: (currentIndex + 1) % fields.length
setFocusField(fields[nextIndex])
} else if (key.name === "return" || key.name === "enter") {
if (focusField() === "sync" && props.onManageSync) {
props.onManageSync()
} else if (focusField() === "logout" && props.onLogout) {
handleLogout()
}
}
}
const handleLogout = () => {
auth.logout()
if (props.onLogout) {
props.onLogout()
}
}
const formatDate = (date: Date | null | undefined): string => {
if (!date) return "Never"
return format(date, "MMM d, yyyy HH:mm")
}
const user = () => auth.state().user
// Get user initials for avatar
const userInitials = () => {
const name = user()?.name || "?"
return name.slice(0, 2).toUpperCase()
}
return (
<box flexDirection="column" border padding={2} gap={1}>
<text>
<strong>User Profile</strong>
</text>
<box height={1} />
{/* User avatar and info */}
<box flexDirection="row" gap={2}>
{/* ASCII avatar */}
<box border padding={1} width={8} height={4} justifyContent="center" alignItems="center">
<text fg="cyan">{userInitials()}</text>
</box>
{/* User details */}
<box flexDirection="column" gap={0}>
<text fg="white">{user()?.name || "Guest User"}</text>
<text fg="gray">{user()?.email || "No email"}</text>
<text fg="gray">Joined: {formatDate(user()?.createdAt)}</text>
</box>
</box>
<box height={1} />
{/* Sync status section */}
<box border padding={1} flexDirection="column" gap={0}>
<text fg="cyan">Sync Status</text>
<box flexDirection="row" gap={1}>
<text fg="gray">Status:</text>
<text fg={user()?.syncEnabled ? "green" : "yellow"}>
{user()?.syncEnabled ? "Enabled" : "Disabled"}
</text>
</box>
<box flexDirection="row" gap={1}>
<text fg="gray">Last Sync:</text>
<text fg="white">{formatDate(lastSyncTime())}</text>
</box>
<box flexDirection="row" gap={1}>
<text fg="gray">Method:</text>
<text fg="white">File-based (JSON/XML)</text>
</box>
</box>
<box height={1} />
{/* Action buttons */}
<box flexDirection="row" gap={2}>
<box
border
padding={1}
backgroundColor={focusField() === "sync" ? "#333" : undefined}
>
<text fg={focusField() === "sync" ? "cyan" : undefined}>
[S] Manage Sync
</text>
</box>
<box
border
padding={1}
backgroundColor={focusField() === "export" ? "#333" : undefined}
>
<text fg={focusField() === "export" ? "cyan" : undefined}>
[E] Export Data
</text>
</box>
<box
border
padding={1}
backgroundColor={focusField() === "logout" ? "#333" : undefined}
>
<text fg={focusField() === "logout" ? "red" : "gray"}>
[L] Logout
</text>
</box>
</box>
<box height={1} />
<text fg="gray">Tab to navigate, Enter to select</text>
</box>
)
}

View File

@@ -1,40 +0,0 @@
import { useTheme } from "../context/ThemeContext"
export type TabId = "feed" | "shows" | "discover" | "search" | "player" | "settings"
export type TabDefinition = {
id: TabId
label: string
}
export const tabs: TabDefinition[] = [
{ id: "feed", label: "Feed" },
{ id: "shows", label: "My Shows" },
{ id: "discover", label: "Discover" },
{ id: "search", label: "Search" },
{ id: "player", label: "Player" },
{ id: "settings", label: "Settings" },
]
type TabProps = {
tab: TabDefinition
active: boolean
onSelect: (tab: TabId) => void
}
export function Tab(props: TabProps) {
const { theme } = useTheme()
return (
<box
border
onMouseDown={() => props.onSelect(props.tab.id)}
style={{ padding: 1, backgroundColor: props.active ? theme.primary : "transparent" }}
>
<text>
{props.active ? "[" : " "}
{props.tab.label}
{props.active ? "]" : " "}
</text>
</box>
)
}

View File

@@ -1,19 +1,55 @@
import { Tab, type TabId } from "./Tab" import { useTheme } from "@/context/ThemeContext";
import { TABS, TabsCount } from "@/utils/navigation";
import { For } from "solid-js";
import { SelectableBox, SelectableText } from "@/components/Selectable";
import { useNavigation } from "@/context/NavigationContext";
type TabNavigationProps = { export const tabs: TabDefinition[] = [
activeTab: TabId { id: TABS.FEED, label: "Feed" },
onTabSelect: (tab: TabId) => void { id: TABS.MYSHOWS, label: "My Shows" },
} { id: TABS.DISCOVER, label: "Discover" },
{ id: TABS.SEARCH, label: "Search" },
{ id: TABS.PLAYER, label: "Player" },
{ id: TABS.SETTINGS, label: "Settings" },
];
export function TabNavigation(props: TabNavigationProps) { export function TabNavigation() {
const { theme } = useTheme();
const { activeTab, setActiveTab, activeDepth } = useNavigation();
return ( return (
<box style={{ flexDirection: "row", gap: 1 }}> <box
<Tab tab={{ id: "feed", label: "Feed" }} active={props.activeTab === "feed"} onSelect={props.onTabSelect} /> border
<Tab tab={{ id: "shows", label: "My Shows" }} active={props.activeTab === "shows"} onSelect={props.onTabSelect} /> borderColor={activeDepth() !== 0 ? theme.border : theme.accent}
<Tab tab={{ id: "discover", label: "Discover" }} active={props.activeTab === "discover"} onSelect={props.onTabSelect} /> backgroundColor={"transparent"}
<Tab tab={{ id: "search", label: "Search" }} active={props.activeTab === "search"} onSelect={props.onTabSelect} /> style={{
<Tab tab={{ id: "player", label: "Player" }} active={props.activeTab === "player"} onSelect={props.onTabSelect} /> flexDirection: "column",
<Tab tab={{ id: "settings", label: "Settings" }} active={props.activeTab === "settings"} onSelect={props.onTabSelect} /> width: 12,
height: TabsCount * 3 + 2,
}}
>
<For each={tabs}>
{(tab) => (
<SelectableBox
border
height={3}
selected={() => tab.id == activeTab()}
onMouseDown={() => setActiveTab(tab.id)}
>
<SelectableText
selected={() => tab.id == activeTab()}
primary
alignSelf="center"
>
{tab.label}
</SelectableText>
</SelectableBox>
)}
</For>
</box> </box>
) );
} }
export type TabDefinition = {
id: TABS;
label: string;
};

View File

@@ -0,0 +1,92 @@
/**
* TabListPane — the tab list as a pane you can drop into the UP | CURRENT |
* PREVIEW flow (replaces the old fixed chrome tab column).
*
* Renders one row per tab (digit + label) using the same selection UI every
* other yazi pane uses: the CURSOR row (the one j/k hovers) gets a `` marker
* and the focus background (`theme.primary` when this pane is the CURRENT
* column, `theme.border` when it is the muted UP/parent column). The ACTIVE
* tab (the one whose content is open) always carries a `●` marker in accent so
* it stays readable in both positions.
*
* `muted` marks the parent-column rendering: the highlight is dimmed (border
* bg, text fg) rather than suppressed, so the Up pane still shows the cursor
* and active tab — matching how every other pane's parent column renders its
* focused row.
*/
import { For } from "solid-js";
import { useTheme } from "@/context/ThemeContext";
import { useNavigation } from "@/context/NavigationContext";
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
import { TABS } from "@/utils/navigation";
const TAB_LABEL: Record<TABS, string> = {
[TABS.FEED]: "Feed",
[TABS.MYSHOWS]: "My Shows",
[TABS.DISCOVER]: "Discover",
[TABS.SEARCH]: "Search",
[TABS.PLAYER]: "Player",
[TABS.SETTINGS]: "Settings",
};
/** Numeric TABS values, in declaration order (1..TabsCount). */
const TAB_ORDER = Object.values(TABS).filter(
(v): v is TABS => typeof v === "number",
) as TABS[];
export function TabListPane(props: { muted?: boolean }) {
const { theme } = useTheme();
const nav = useNavigation();
const cursor = () => nav.tabCursor();
const activeTab = () => nav.activeTab();
/** `active=true` when this pane is the CURRENT column (Shell root);
* `false` when it is the muted UP/parent column (pages' parent pane). */
const active = () => !props.muted;
// Same focus-bg / focus-fg contract every other pane uses.
const focusBg = (t: TABS) =>
t === cursor() && active()
? theme.primary
: t === cursor()
? theme.border
: undefined;
const focusFg = (t: TABS) =>
t === cursor() && active() ? theme.surface : theme.text;
return (
<For each={TAB_ORDER}>
{(tab) => {
const isCursor = () => cursor() === tab;
const isActive = () => activeTab() === tab;
// The active tab is only accented in the Up/parent position — when this
// pane is CURRENT, the cursor highlight is the only highlight.
const labelFg = () =>
isCursor()
? focusFg(tab)
: isActive() && !active()
? theme.accent
: theme.text;
const ref = useScrollIntoView(isCursor);
return (
<box
ref={ref}
width="100%"
height={1}
flexDirection="row"
paddingRight={1}
backgroundColor={focusBg(tab)}
>
{/* ── selection marker (j/k cursor) ─────────────────────────── */}
<text fg={focusFg(tab)}>{isCursor() ? "" : " "}</text>
<text fg={isCursor() ? focusFg(tab) : theme.textMuted}>{tab}</text>
<text fg={labelFg()} paddingLeft={1}>
{TAB_LABEL[tab]}
</text>
</box>
);
}}
</For>
);
}

View File

@@ -1,51 +0,0 @@
/**
* TrendingShows component - Grid/list of trending podcasts
*/
import { For, Show } from "solid-js"
import type { Podcast } from "../types/podcast"
import { PodcastCard } from "./PodcastCard"
type TrendingShowsProps = {
podcasts: Podcast[]
selectedIndex: number
focused: boolean
isLoading: boolean
onSelect?: (index: number) => void
onSubscribe?: (podcast: Podcast) => void
}
export function TrendingShows(props: TrendingShowsProps) {
return (
<box flexDirection="column" height="100%">
<Show when={props.isLoading}>
<box padding={2}>
<text fg="yellow">Loading trending shows...</text>
</box>
</Show>
<Show when={!props.isLoading && props.podcasts.length === 0}>
<box padding={2}>
<text fg="gray">No podcasts found in this category.</text>
</box>
</Show>
<Show when={!props.isLoading && props.podcasts.length > 0}>
<scrollbox height={15}>
<box flexDirection="column">
<For each={props.podcasts}>
{(podcast, index) => (
<PodcastCard
podcast={podcast}
selected={index() === props.selectedIndex && props.focused}
onSelect={() => props.onSelect?.(index())}
onSubscribe={() => props.onSubscribe?.(podcast)}
/>
)}
</For>
</box>
</scrollbox>
</Show>
</box>
)
}

View File

@@ -1,52 +0,0 @@
type WaveformProps = {
data: number[]
position: number
duration: number
isPlaying: boolean
onSeek?: (next: number) => void
}
const bars = [".", "-", "~", "=", "#"]
export function Waveform(props: WaveformProps) {
const playedRatio = () => (props.duration === 0 ? 0 : props.position / props.duration)
const renderLine = () => {
const playedCount = Math.floor(props.data.length * playedRatio())
const playedColor = props.isPlaying ? "#6fa8ff" : "#7d8590"
const futureColor = "#3b4252"
const played = props.data
.map((value, index) =>
index <= playedCount
? bars[Math.min(bars.length - 1, Math.floor(value * bars.length))]
: ""
)
.join("")
const upcoming = props.data
.map((value, index) =>
index > playedCount
? bars[Math.min(bars.length - 1, Math.floor(value * bars.length))]
: ""
)
.join("")
return (
<box flexDirection="row" gap={0}>
<text fg={playedColor}>{played || " "}</text>
<text fg={futureColor}>{upcoming || " "}</text>
</box>
)
}
const handleClick = (event: { x: number }) => {
const ratio = props.data.length === 0 ? 0 : event.x / props.data.length
const next = Math.max(0, Math.min(props.duration, Math.round(props.duration * ratio)))
props.onSeek?.(next)
}
return (
<box border padding={1} onMouseDown={handleClick}>
{renderLine()}
</box>
)
}

View File

@@ -1,75 +0,0 @@
/**
* Authentication configuration for PodTUI
* Authentication is DISABLED by default - users can opt-in
*/
import { OAuthProvider, type OAuthProviderConfig } from "../types/auth"
/** Default auth enabled state - DISABLED by default */
export const DEFAULT_AUTH_ENABLED = false
/** Authentication configuration */
export const AUTH_CONFIG = {
/** Whether auth is enabled by default */
defaultEnabled: DEFAULT_AUTH_ENABLED,
/** Code validation settings */
codeValidation: {
/** Code length (8 characters) */
codeLength: 8,
/** Allowed characters (alphanumeric) */
allowedChars: /^[A-Z0-9]+$/,
/** Code expiration time in minutes */
expirationMinutes: 15,
},
/** Password requirements */
password: {
minLength: 8,
requireUppercase: false,
requireLowercase: false,
requireNumber: false,
requireSpecial: false,
},
/** Email validation */
email: {
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
},
/** Local storage keys */
storage: {
authState: "podtui_auth_state",
user: "podtui_user",
lastLogin: "podtui_last_login",
},
} as const
/** OAuth provider configurations */
export const OAUTH_PROVIDERS: OAuthProviderConfig[] = [
{
id: OAuthProvider.GOOGLE,
name: "Google",
enabled: false, // Not feasible in terminal
description: "Sign in with Google (requires browser redirect)",
},
{
id: OAuthProvider.APPLE,
name: "Apple",
enabled: false, // Not feasible in terminal
description: "Sign in with Apple (requires browser redirect)",
},
]
/** Terminal OAuth limitation message */
export const OAUTH_LIMITATION_MESSAGE = `
OAuth authentication (Google, Apple) is not directly available in terminal applications.
To use OAuth:
1. Visit the web portal in your browser
2. Sign in with your preferred provider
3. Generate a sync code
4. Enter the code here to link your account
Alternatively, use email/password authentication or file-based sync.
`.trim()

74
src/config/keybinds.jsonc Normal file
View File

@@ -0,0 +1,74 @@
{
// ── Yazi-style keybinds for PodTui ──────────────────────────────────────
// Notation:
// "j" single lowercase key
// "G" shift + g (uppercase letter = shift)
// "ctrl-d" ctrl modifier
// "shift-j" shift modifier (equivalent to "J")
// "meta-x" alt/meta modifier (macOS users: map Option to Alt)
// ["g","g"] a two-key sequence (matches only when pressed in order)
// "return" special key (also: escape tab space backspace up down left right)
//
// Yazi heritage: j/k move, h/l swipe between panes, Enter open, Space select,
// v visual mode, gg/G top/bottom, [ ] switch tabs, 1-6 goto tab,
// : command bar, q quit, ~ help. Audio transport kept on shifted keys / ctrl.
// ── Movement (within a pane) ─────────────────────────────────────────────
"move-down": ["j", "down"],
"move-up": ["k", "up"],
"page-down": ["ctrl-d"],
"page-up": ["ctrl-u"],
"full-down": ["ctrl-f"],
"full-up": ["ctrl-b"],
"jump-down": ["J"], // 5 lines down (shift+j)
"jump-up": ["K"], // 5 lines up (shift+k)
"goto-top": [["g", "g"]],
"goto-bottom": ["G"],
// ── Pane focus / swipe (yazi h/l) ────────────────────────────────────────
"swipe-prev": ["h", "left"], // focus left pane (parent)
"swipe-next": ["l", "right"], // focus right pane (preview)
// ── Open / activate ──────────────────────────────────────────────────────
"open": ["return", "enter"],
"open-interactive": ["shift-return"],
// ── Selection & visual mode ──────────────────────────────────────────────
"toggle-select": ["space"],
"visual-mode": ["v"],
"toggle-all": ["ctrl-a"],
"invert-all": ["ctrl-r"],
"escape": ["escape", "ctrl-["],
// ── Tabs ──────────────────────────────────────────────────────────────────
"tab-prev": ["["],
"tab-next": ["]"],
"tab-goto-1": ["1"],
"tab-goto-2": ["2"],
"tab-goto-3": ["3"],
"tab-goto-4": ["4"],
"tab-goto-5": ["5"],
"tab-goto-6": ["6"],
// ── Command bar & help & quit ────────────────────────────────────────────
"command": [":"],
"quit": ["q", "ctrl-c"],
"help": ["~", "f1"],
// ── List operations (yazi: s search, f filter, , sort, . hidden, r refresh)
"search": ["s"],
"filter": ["f"],
"sort": [","],
"toggle-hidden": ["."],
"refresh": ["r"],
"unsubscribe": ["x"], // unsubscribe focused show in My Shows
// ── Audio transport (preserved) ──────────────────────────────────────────
// Kept on shifted single keys so they never collide with the yazi core
// (space=select, s=search, f=filter, etc.). Edit freely in this file.
"audio-toggle": ["P"], // play / pause (shift+p)
"audio-next": ["N"], // next episode (shift+n)
"audio-prev": ["B"], // prev episode (shift+b)
"audio-seek-forward": ["shift-."], // seek forward (shift+.)
"audio-seek-backward": ["shift-,"] // seek backward (shift+,)
}

View File

@@ -1,6 +1,27 @@
/**
* Yazi-style keybind reference (mirrors src/config/keybinds.jsonc).
* Shown in help overlays; the canonical source remains keybinds.jsonc.
* Edit that file (or ~/.config/podtui/keybinds.jsonc) to remap.
*/
export const shortcuts = [ export const shortcuts = [
{ keys: "Ctrl+Q", action: "Quit" }, { keys: "j / k", action: "Move down / up (within pane)" },
{ keys: "Ctrl+S", action: "Save" }, { keys: "h / l", action: "Swipe to prev / next pane" },
{ keys: "Left/Right", action: "Switch tabs" }, { keys: "J / K", action: "Jump 5 lines down / up" },
{ keys: "Esc", action: "Close modal" }, { keys: "ctrl-d / u", action: "Half page down / up" },
] as const { keys: "g g / G", action: "Go to top / bottom of list" },
{ keys: "1-6", action: "Go to tab 1-6" },
{ keys: "[ / ]", action: "Previous / next tab" },
{ keys: "Enter", action: "Open / activate focused item" },
{ keys: "Space", action: "Toggle selection on item" },
{ keys: "v", action: "Enter visual (range) select mode" },
{ keys: "ctrl-a / ctrl-r", action: "Select all / invert selection" },
{ keys: "Esc", action: "Clear selection / exit visual / cancel" },
{ keys: ":", action: "Open command bar (:quit :refresh :play …)" },
{ keys: "r / s / f", action: "Refresh / search / filter" },
{ keys: "x", action: "Unsubscribe focused show (My Shows)" },
{ keys: ", / .", action: "Sort / toggle hidden" },
{ keys: "P / N / B", action: "Play-pause / next / prev episode" },
{ keys: "< / >", action: "Seek backward / forward 10s" },
{ keys: "~ / F1", action: "Help" },
{ keys: "q", action: "Quit" },
] as const;

View File

@@ -1,20 +1,25 @@
import type { ThemeColors, ThemeDefinition, ThemeName } from "../types/settings" import type {
import { BASE_THEME_COLORS, BASE_LAYER_BACKGROUND } from "../types/desktop-theme" ThemeColors,
import catppuccin from "../themes/catppuccin.json" with { type: "json" } ThemeDefinition,
import gruvbox from "../themes/gruvbox.json" with { type: "json" } ThemeName,
import tokyo from "../themes/tokyo.json" with { type: "json" } } from "../types/settings";
import nord from "../themes/nord.json" with { type: "json" } import {
import opencode from "../themes/opencode.json" with { type: "json" } BASE_THEME_COLORS,
BASE_LAYER_BACKGROUND,
} from "../types/desktop-theme";
import catppuccin from "../themes/catppuccin.json" with { type: "json" };
import gruvbox from "../themes/gruvbox.json" with { type: "json" };
import tokyo from "../themes/tokyo.json" with { type: "json" };
import nord from "../themes/nord.json" with { type: "json" };
export const DEFAULT_THEME: ThemeColors = { export const DEFAULT_THEME: ThemeColors = {
...BASE_THEME_COLORS, ...BASE_THEME_COLORS,
layerBackgrounds: BASE_LAYER_BACKGROUND, layerBackgrounds: BASE_LAYER_BACKGROUND,
} };
export const THEME_JSON: Record<string, ThemeDefinition> = { export const THEME_JSON: Record<string, ThemeDefinition> = {
opencode: opencode as ThemeDefinition,
catppuccin: catppuccin as ThemeDefinition, catppuccin: catppuccin as ThemeDefinition,
gruvbox: gruvbox as ThemeDefinition, gruvbox: gruvbox as ThemeDefinition,
tokyo: tokyo as ThemeDefinition, tokyo: tokyo as ThemeDefinition,
nord: nord as ThemeDefinition, nord: nord as ThemeDefinition,
} };

View File

@@ -1,134 +1,376 @@
import { createMemo } from "solid-js" import { createSignal, onMount } from "solid-js";
import type { ParsedKey, Renderable } from "@opentui/core" import { createSimpleContext } from "./helper";
import { createStore } from "solid-js/store" import {
import { useKeyboard, useRenderer } from "@opentui/solid" copyKeybindsIfNeeded,
import { createSimpleContext } from "./helper" loadKeybindsFromFile,
import { Keybind, DEFAULT_KEYBINDS, type KeybindsConfig } from "../utils/keybind" saveKeybindsToFile,
} from "../utils/keybinds-persistence";
import { createStore } from "solid-js/store";
/** // ── Keybind model ───────────────────────────────────────────────────────────
* Keybind context provider for managing keyboard shortcuts. // Yazi-style: every binding is one or more "strokes". A stroke is a single
* // key press (key + optional ctrl/shift/meta). Multi-stroke bindings form a
* Features: // sequence (e.g. ["g","g"] = gg, ["space","n"] = <leader>n). The matcher
* - Leader key support (like vim's leader key) // buffers keystrokes, prefers the longest matching sequence, and exposes the
* - Configurable keybindings // pending buffer reactively so the status bar can show it (very yazi).
* - Key parsing and matching
* - Display-friendly key representations
*/
export const { use: useKeybind, provider: KeybindProvider } = createSimpleContext({
name: "Keybind",
init: (props: { keybinds?: Partial<KeybindsConfig> }) => {
// Merge default keybinds with custom keybinds
const customKeybinds = props.keybinds ?? {}
const mergedKeybinds = { ...DEFAULT_KEYBINDS, ...customKeybinds }
const keybinds = createMemo(() => { /** A single key press. `key` is the lowercase logical key name
const result: Record<string, Keybind.Info[]> = {} * ("j", "return", "space", "up", "f1", ...). */
for (const [key, value] of Object.entries(mergedKeybinds)) { export interface Stroke {
result[key] = Keybind.parse(value) key: string;
} ctrl?: boolean;
return result shift?: boolean;
}) meta?: boolean;
}
const [store, setStore] = createStore({ /** Raw config spec for one action: a list of alternative sequences. Each
leader: false, * alternative is itself a list of stroke-notation strings. So
}) * "j" -> [[ {key:"j"} ]]
* ["j","down"] -> [[ {key:"j"} ], [ {key:"down"} ]]
* [["g","g"],"G"] -> [[ {key:"g"},{key:"g"} ], [ {key:"g",shift:true} ]] */
export type KeybindSpec = string | (string | string[])[];
const renderer = useRenderer() /** Canonical action names. Must match keys in keybinds.jsonc. */
export type KeybindActionName =
| "move-down"
| "move-up"
| "page-down"
| "page-up"
| "full-down"
| "full-up"
| "jump-down"
| "jump-up"
| "goto-top"
| "goto-bottom"
| "swipe-prev"
| "swipe-next"
| "open"
| "open-interactive"
| "toggle-select"
| "visual-mode"
| "toggle-all"
| "invert-all"
| "escape"
| "tab-prev"
| "tab-next"
| "tab-goto-1"
| "tab-goto-2"
| "tab-goto-3"
| "tab-goto-4"
| "tab-goto-5"
| "tab-goto-6"
| "command"
| "quit"
| "help"
| "search"
| "filter"
| "sort"
| "toggle-hidden"
| "refresh"
| "unsubscribe"
| "audio-toggle"
| "audio-next"
| "audio-prev"
| "audio-seek-forward"
| "audio-seek-backward"
// legacy compat (kept so older callers don't crash)
| "select"
| "leader"
| "inverseModifier"
| "cycle"
| "dive"
| "out"
| "up"
| "down"
| "left"
| "right"
| "audio-pause"
| "audio-play";
let focus: Renderable | null = null /** Resolved config: action -> list of alternative stroke-sequences. */
let timeout: NodeJS.Timeout | undefined export type KeybindsResolved = Partial<Record<KeybindActionName, KeybindSpec>>;
function leader(active: boolean) { const SEQ_TIMEOUT_MS = 600;
if (active) {
setStore("leader", true)
focus = renderer.currentFocusedRenderable
focus?.blur()
if (timeout) clearTimeout(timeout)
timeout = setTimeout(() => {
if (!store.leader) return
leader(false)
if (!focus || focus.isDestroyed) return
focus.focus()
}, 2000) // Leader key timeout
return
}
if (!active) { // ── Stroke parsing ───────────────────────────────────────────────────────────
if (focus && !renderer.currentFocusedRenderable) { // Notation: "ctrl-d", "shift-j", "meta-x", "C-d", "M-x", "S-j".
focus.focus() // uppercase letter "G" => {key:"g", shift:true}
} // special: return/enter/escape/tab/space/backspace/up/down/left/right
setStore("leader", false)
export function parseStroke(notation: string): Stroke {
const raw = notation.trim();
let ctrl = false,
shift = false,
meta = false;
let key = raw;
const parts = raw.split(/[-+]/);
if (parts.length > 1) {
key = parts[parts.length - 1];
for (const mod of parts.slice(0, -1)) {
const m = mod.toLowerCase();
if (m === "ctrl" || m === "c") ctrl = true;
else if (m === "shift" || m === "s") shift = true;
else if (m === "meta" || m === "alt" || m === "m") meta = true;
} }
} }
// Uppercase single letter w/o modifier => shift+letter (vim convention)
if (
parts.length === 1 &&
key.length === 1 &&
key >= "A" &&
key <= "Z" &&
!ctrl &&
!shift &&
!meta
) {
shift = true;
key = key.toLowerCase();
}
return { key: key.toLowerCase(), ctrl, shift, meta };
}
// Handle leader key /** Turn one raw spec into a list of alternative stroke-sequences. */
useKeyboard(async (evt) => { export function parseBindingSpec(spec: KeybindSpec | undefined): Stroke[][] {
// Don't intercept leader key when a text-editing renderable (input/textarea) if (spec == null) return [];
// has focus — let it handle text input (including space for the leader key). const alts: Stroke[][] = [];
const focused = renderer.currentFocusedRenderable const push = (item: string | string[]) => {
if (focused && "insertText" in focused) return const seq = Array.isArray(item) ? item : [item];
alts.push(seq.map(parseStroke));
};
if (Array.isArray(spec)) {
for (const item of spec) push(item);
} else {
push(spec);
}
return alts;
}
if (!store.leader && result.match("leader", evt)) { /** Build a Stroke from a keyboard event (opentui shape: name + ctrl/shift/meta). */
leader(true) export function strokeFromEvent(evt: {
return name: string;
ctrl?: boolean;
meta?: boolean;
shift?: boolean;
}): Stroke {
// Uppercase letter events from opentui arrive as name="q" + shift; normalize.
return {
key: (evt.name ?? "").toLowerCase(),
ctrl: !!evt.ctrl,
shift: !!evt.shift,
meta: !!evt.meta,
};
}
function strokeEq(a: Stroke, b: Stroke): boolean {
return (
a.key === b.key &&
!!a.ctrl === !!b.ctrl &&
!!a.shift === !!b.shift &&
!!a.meta === !!b.meta
);
}
/** A human label for a stroke, for the status bar / help. */
export function strokeLabel(s: Stroke): string {
let out = "";
if (s.ctrl) out += "C-";
if (s.meta) out += "M-";
if (s.shift) out += "S-";
out += s.key;
return out;
}
export function sequenceLabel(seq: Stroke[]): string {
return seq.map(strokeLabel).join(" ");
}
export const { use: useKeybinds, provider: KeybindProvider } =
createSimpleContext({
name: "Keybinds",
init: () => {
const [store, setStore] = createStore<KeybindsResolved>({});
// Resolved sequences per action, recomputed when store changes.
const [resolved, setResolved] = createSignal<Record<string, Stroke[][]>>(
{},
);
const [ready, setReady] = createSignal(false);
const [pending, setPending] = createSignal<Stroke[]>([]);
let pendingTimer: ReturnType<typeof setTimeout> | undefined;
function recompute() {
const out: Record<string, Stroke[][]> = {};
for (const name of Object.keys(store) as string[]) {
out[name] = parseBindingSpec((store as any)[name]);
}
setResolved(out);
} }
if (store.leader && evt.name) { async function load() {
setImmediate(() => { await copyKeybindsIfNeeded();
if (focus && renderer.currentFocusedRenderable === focus) { const keybinds = await loadKeybindsFromFile();
focus.focus() setStore(keybinds);
recompute();
setReady(true);
} }
leader(false)
})
}
})
const result = { async function save() {
get all() { saveKeybindsToFile(store as KeybindsResolved);
return keybinds() }
function print(input: KeybindActionName): string {
const alts = resolved()[input] ?? [];
return alts.map(sequenceLabel).join(" / ") || "—";
}
function clearPending() {
if (pendingTimer) {
clearTimeout(pendingTimer);
pendingTimer = undefined;
}
if (pending().length > 0) setPending([]);
}
function armTimer() {
if (pendingTimer) clearTimeout(pendingTimer);
pendingTimer = setTimeout(() => clearPending(), SEQ_TIMEOUT_MS);
}
/** Look up every action whose sequence-list the candidate is a prefix of
* (i.e. a longer match is still possible) and every action that the
* candidate exactly equals. */
function classify(candidate: Stroke[]) {
const exact: KeybindActionName[] = [];
const prefix: KeybindActionName[] = [];
const map = resolved();
for (const name of Object.keys(map) as KeybindActionName[]) {
for (const seq of map[name] ?? []) {
if (seq.length < candidate.length) continue;
let isPrefix = true;
for (let i = 0; i < candidate.length; i++) {
if (!strokeEq(seq[i], candidate[i])) {
isPrefix = false;
break;
}
}
if (!isPrefix) continue;
if (seq.length === candidate.length) exact.push(name);
else prefix.push(name);
}
}
return { exact, prefix };
}
/** Legacy single-key matcher (used by command-palette registrations and
* older call sites). Returns true iff `name`'s sequence list contains a
* single-stroke alternative equal to the event. */
function match(
name: KeybindActionName,
evt: { name: string; ctrl?: boolean; meta?: boolean; shift?: boolean },
): boolean {
const alts = resolved()[name] ?? [];
const s = strokeFromEvent(evt);
// skip in command/input mode unless explicitly handled by caller
for (const seq of alts) {
if (seq.length === 1 && strokeEq(seq[0], s)) return true;
}
return false;
}
/** New sequence-aware matcher. Returns the resolved action or null.
* Callers should invoke this once per keypress in a single router. */
function tryMatch(evt: {
name: string;
ctrl?: boolean;
meta?: boolean;
shift?: boolean;
}): KeybindActionName | null {
const stroke = strokeFromEvent(evt);
const candidate = [...pending(), stroke];
const { exact, prefix } = classify(candidate);
// Still mid-sequence: wait for more keys (unless this stroke also
// exactly matches something AND nothing depends on a longer prefix).
if (prefix.length > 0) {
setPending(candidate);
armTimer();
// If there's also an exact match, we *could* fire now — but yazi
// prefers to wait for the longer sequence within the timeout, then
// falls through. We honor that: only fire exact if no prefix.
if (exact.length > 0) {
// ambiguous prefix+exact: keep waiting (e.g. `g` could be gg)
}
return null;
}
// No longer-match possible: decide on exact.
clearPending();
if (exact.length === 0) {
// The new stroke might itself begin a fresh sequence.
const fresh = classify([stroke]);
if (fresh.prefix.length > 0) {
setPending([stroke]);
armTimer();
return null;
}
if (fresh.exact.length > 0) {
// prefer longest-sequence match among fresh.exact
return pickLongest(fresh.exact);
}
return null;
}
return pickLongest(exact);
}
function pickLongest(names: KeybindActionName[]): KeybindActionName {
const map = resolved();
let best = names[0];
let bestLen = 0;
for (const n of names) {
for (const seq of map[n] ?? []) {
if (seq.length > bestLen) {
bestLen = seq.length;
best = n;
}
}
}
return best;
}
// `isInverting` kept for legacy callers; yazi model has no inverse mod,
// so it always reports false. Migrated callers should use tryMatch().
function isInverting(_evt: {
name: string;
ctrl?: boolean;
meta?: boolean;
shift?: boolean;
}): boolean {
return false;
}
onMount(() => {
load().catch(() => {});
});
return {
get ready() {
return ready();
}, },
get leader() { get keybinds() {
return store.leader return store;
}, },
/** get resolved() {
* Parse a keyboard event into a Keybind.Info. return resolved();
*/
parse(evt: ParsedKey): Keybind.Info {
// Handle special case for Ctrl+Underscore (represented as \x1F)
if (evt.name === "\x1F") {
return Keybind.fromParsedKey({ ...evt, name: "_", ctrl: true }, store.leader)
}
return Keybind.fromParsedKey(evt, store.leader)
}, },
/** pending,
* Check if a keyboard event matches a registered keybind. match,
*/ tryMatch,
match(key: keyof KeybindsConfig, evt: ParsedKey): boolean { isInverting,
const keybind = keybinds()[key] print,
if (!keybind) return false save,
const parsed: Keybind.Info = result.parse(evt) load,
for (const kb of keybind) { clearPending,
if (Keybind.match(kb, parsed)) { };
return true
}
}
return false
}, },
/** });
* Get a display string for a registered keybind.
*/
print(key: keyof KeybindsConfig): string {
const first = keybinds()[key]?.at(0)
if (!first) return ""
const display = Keybind.toString(first)
// Replace leader placeholder with actual leader key
const leaderKey = keybinds().leader?.[0]
if (leaderKey) {
return display.replace("<leader>", Keybind.toString(leaderKey))
}
return display
},
}
return result
},
})

View File

@@ -0,0 +1,22 @@
/**
* NavigationContext — Solid provider wrapper around the pure nav store in
* `./navigation-store`. Re-exports the nav model (`createNavigation`, the
* enums/types, `DEPTH_CENTER_PANE`, etc.) so the rest of the app keeps
* importing everything from `@/context/NavigationContext`, and binds the
* store into a Solid context (`useNavigation` / `NavigationProvider`).
*
* See `./navigation-store` for the model documentation (parent | current |
* preview, depth-stack vs fixed-pane tabs, no sidebar pane).
*/
import { createSimpleContext } from "./helper";
import { createNavigation } from "./navigation-store";
// Re-export the entire nav model surface so existing imports from
// `@/context/NavigationContext` keep resolving.
export * from "./navigation-store";
export const { use: useNavigation, provider: NavigationProvider } =
createSimpleContext({
name: "Navigation",
init: () => createNavigation(),
});

View File

@@ -1,8 +0,0 @@
import { describe, expect, it } from "bun:test"
import { ThemeProvider } from "./ThemeContext"
describe("ThemeContext", () => {
it("exports provider", () => {
expect(typeof ThemeProvider).toBe("function")
})
})

View File

@@ -1,80 +1,98 @@
import { createEffect, createMemo, onMount, onCleanup } from "solid-js" import { createEffect, createMemo, onMount, onCleanup } from "solid-js";
import { createStore, produce } from "solid-js/store" import { createStore, produce } from "solid-js/store";
import { useRenderer } from "@opentui/solid" import { useRenderer } from "@opentui/solid";
import type { ThemeName } from "../types/settings" import type { ThemeName } from "../types/settings";
import type { ThemeJson } from "../types/theme-schema" import type { ThemeJson } from "../types/theme-schema";
import { useAppStore } from "../stores/app" import { useAppStore } from "../stores/app";
import { THEME_JSON } from "../constants/themes" import { THEME_JSON } from "../constants/themes";
import { generateSyntax, generateSubtleSyntax } from "../utils/syntax-highlighter" import {
import { resolveTerminalTheme, loadThemes } from "../utils/theme" generateSyntax,
import { createSimpleContext } from "./helper" generateSubtleSyntax,
import { setupThemeSignalHandler, emitThemeChanged, emitThemeModeChanged } from "../utils/theme-observer" } from "../utils/syntax-highlighter";
import { createTerminalPalette, type RGBA, type TerminalColors } from "@opentui/core" import { resolveTerminalTheme, loadThemes } from "../utils/theme";
import { createSimpleContext } from "./helper";
import {
setupThemeSignalHandler,
emitThemeChanged,
emitThemeModeChanged,
} from "../utils/theme-observer";
import {
createTerminalPalette,
type RGBA,
type TerminalColors,
} from "@opentui/core";
type ThemeResolved = { export type ThemeResolved = {
primary: RGBA primary: RGBA;
secondary: RGBA secondary: RGBA;
accent: RGBA accent: RGBA;
error: RGBA error: RGBA;
warning: RGBA warning: RGBA;
success: RGBA success: RGBA;
info: RGBA info: RGBA;
text: RGBA text: RGBA;
textMuted: RGBA textMuted: RGBA;
selectedListItemText: RGBA textPrimary: RGBA;
background: RGBA textSecondary: RGBA;
backgroundPanel: RGBA textTertiary: RGBA;
backgroundElement: RGBA textSelectedPrimary: RGBA;
backgroundMenu: RGBA textSelectedSecondary: RGBA;
border: RGBA textSelectedTertiary: RGBA;
borderActive: RGBA
borderSubtle: RGBA background: RGBA;
diffAdded: RGBA backgroundPanel: RGBA;
diffRemoved: RGBA backgroundElement: RGBA;
diffContext: RGBA backgroundMenu: RGBA;
diffHunkHeader: RGBA border: RGBA;
diffHighlightAdded: RGBA borderActive: RGBA;
diffHighlightRemoved: RGBA borderSubtle: RGBA;
diffAddedBg: RGBA diffAdded: RGBA;
diffRemovedBg: RGBA diffRemoved: RGBA;
diffContextBg: RGBA diffContext: RGBA;
diffLineNumber: RGBA diffHunkHeader: RGBA;
diffAddedLineNumberBg: RGBA diffHighlightAdded: RGBA;
diffRemovedLineNumberBg: RGBA diffHighlightRemoved: RGBA;
markdownText: RGBA diffAddedBg: RGBA;
markdownHeading: RGBA diffRemovedBg: RGBA;
markdownLink: RGBA diffContextBg: RGBA;
markdownLinkText: RGBA diffLineNumber: RGBA;
markdownCode: RGBA diffAddedLineNumberBg: RGBA;
markdownBlockQuote: RGBA diffRemovedLineNumberBg: RGBA;
markdownEmph: RGBA markdownText: RGBA;
markdownStrong: RGBA markdownHeading: RGBA;
markdownHorizontalRule: RGBA markdownLink: RGBA;
markdownListItem: RGBA markdownLinkText: RGBA;
markdownListEnumeration: RGBA markdownCode: RGBA;
markdownImage: RGBA markdownBlockQuote: RGBA;
markdownImageText: RGBA markdownEmph: RGBA;
markdownCodeBlock: RGBA markdownStrong: RGBA;
syntaxComment: RGBA markdownHorizontalRule: RGBA;
syntaxKeyword: RGBA markdownListItem: RGBA;
syntaxFunction: RGBA markdownListEnumeration: RGBA;
syntaxVariable: RGBA markdownImage: RGBA;
syntaxString: RGBA markdownImageText: RGBA;
syntaxNumber: RGBA markdownCodeBlock: RGBA;
syntaxType: RGBA syntaxComment: RGBA;
syntaxOperator: RGBA syntaxKeyword: RGBA;
syntaxPunctuation: RGBA syntaxFunction: RGBA;
muted?: RGBA syntaxVariable: RGBA;
surface?: RGBA syntaxString: RGBA;
syntaxNumber: RGBA;
syntaxType: RGBA;
syntaxOperator: RGBA;
syntaxPunctuation: RGBA;
muted?: RGBA;
surface?: RGBA;
selectedListItemText?: RGBA;
layerBackgrounds?: { layerBackgrounds?: {
layer0: RGBA layer0: RGBA;
layer1: RGBA layer1: RGBA;
layer2: RGBA layer2: RGBA;
layer3: RGBA layer3: RGBA;
} };
_hasSelectedListItemText?: boolean _hasSelectedListItemText?: boolean;
thinkingOpacity?: number thinkingOpacity?: number;
} };
/** /**
* Theme context using the createSimpleContext pattern. * Theme context using the createSimpleContext pattern.
@@ -82,95 +100,107 @@ type ThemeResolved = {
* This ensures children are NOT rendered until the theme is ready, * This ensures children are NOT rendered until the theme is ready,
* preventing "useTheme must be used within a ThemeProvider" errors. * preventing "useTheme must be used within a ThemeProvider" errors.
* *
* The key insight from opencode's implementation is that the provider
* uses `<Show when={ready}>` to gate rendering, so components can
* safely call useTheme() without checking ready state.
*/ */
export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
name: "Theme", name: "Theme",
init: (props: { mode: "dark" | "light" }) => { init: (props: { mode: "dark" | "light" }) => {
const appStore = useAppStore() const appStore = useAppStore();
const renderer = useRenderer() const renderer = useRenderer();
const [store, setStore] = createStore({ const [store, setStore] = createStore({
themes: THEME_JSON as Record<string, ThemeJson>, themes: THEME_JSON as Record<string, ThemeJson>,
mode: props.mode, mode: props.mode,
active: appStore.state().settings.theme as string, active: appStore.state().settings.theme as string,
system: undefined as undefined | TerminalColors, system: undefined as undefined | TerminalColors,
ready: false, ready: false,
}) });
function init() { function init() {
resolveSystemTheme() resolveSystemTheme();
loadThemes() loadThemes()
.then((custom) => { .then((custom) => {
setStore( setStore(
produce((draft) => { produce((draft) => {
Object.assign(draft.themes, custom) Object.assign(draft.themes, custom);
}) }),
) );
}) })
.catch(() => { .catch(() => {
// If custom themes fail to load, fall back to opencode theme setStore("active", "catppuccin");
setStore("active", "opencode")
}) })
.finally(() => { .finally(() => {
// Only set ready if not waiting for system theme // Only set ready if not waiting for system theme
if (store.active !== "system") { if (store.active !== "system") {
setStore("ready", true) setStore("ready", true);
} }
}) });
} }
async function waitForCapabilities(timeoutMs = 300) { async function waitForCapabilities(timeoutMs = 300) {
if (renderer.capabilities) return if (renderer.capabilities) return;
await new Promise<void>((resolve) => { await new Promise<void>((resolve) => {
let done = false let done = false;
const onCaps = () => { const onCaps = () => {
if (done) return if (done) return;
done = true done = true;
renderer.off("capabilities", onCaps) renderer.off("capabilities", onCaps);
clearTimeout(timer) clearTimeout(timer);
resolve() resolve();
} };
const timer = setTimeout(() => { const timer = setTimeout(() => {
if (done) return if (done) return;
done = true done = true;
renderer.off("capabilities", onCaps) renderer.off("capabilities", onCaps);
resolve() resolve();
}, timeoutMs) }, timeoutMs);
renderer.on("capabilities", onCaps) renderer.on("capabilities", onCaps);
}) });
} }
async function resolveSystemTheme() { async function resolveSystemTheme() {
if (process.env.TMUX) { if (process.env.TMUX) {
await waitForCapabilities() await waitForCapabilities();
} }
let colors: TerminalColors | null = null let colors: TerminalColors | null = null;
try { try {
colors = await renderer.getPalette({ size: 16 }) colors = await renderer.getPalette({ size: 16 });
} catch { } catch {
colors = null colors = null;
} }
if (!colors?.palette?.[0] && process.env.TMUX) { if (!colors?.palette?.[0] && process.env.TMUX) {
const writeOut = (renderer as unknown as { writeOut?: (data: string | Buffer) => boolean }).writeOut const writeOut = (
const writeFn = typeof writeOut === "function" ? writeOut.bind(renderer) : process.stdout.write.bind(process.stdout) renderer as unknown as {
const detector = createTerminalPalette(process.stdin, process.stdout, writeFn, true) writeOut?: (data: string | Buffer) => boolean;
}
).writeOut;
const writeFn =
typeof writeOut === "function"
? writeOut.bind(renderer)
: process.stdout.write.bind(process.stdout);
const detector = createTerminalPalette(
process.stdin,
process.stdout,
writeFn,
true,
);
try { try {
const tmuxColors = await detector.detect({ size: 16, timeout: 1200 }) const tmuxColors = await detector.detect({ size: 16, timeout: 1200 });
if (tmuxColors?.palette?.[0]) { if (tmuxColors?.palette?.[0]) {
colors = tmuxColors colors = tmuxColors;
} }
} finally { } finally {
detector.cleanup() detector.cleanup();
} }
} }
const hasPalette = Boolean(colors?.palette?.some((value) => Boolean(value))) const hasPalette = Boolean(
const hasDefaultColors = Boolean(colors?.defaultBackground || colors?.defaultForeground) colors?.palette?.some((value) => Boolean(value)),
);
const hasDefaultColors = Boolean(
colors?.defaultBackground || colors?.defaultForeground,
);
if (!hasPalette && !hasDefaultColors) { if (!hasPalette && !hasDefaultColors) {
// No system colors available, fall back to default // No system colors available, fall back to default
@@ -179,89 +209,100 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
if (store.active === "system") { if (store.active === "system") {
setStore( setStore(
produce((draft) => { produce((draft) => {
draft.active = "opencode" draft.active = "catppuccin";
draft.ready = true draft.ready = true;
}) }),
) );
} }
return return;
} }
if (colors) { if (colors) {
setStore( setStore(
produce((draft) => { produce((draft) => {
draft.system = colors draft.system = colors;
if (store.active === "system") { if (store.active === "system") {
draft.ready = true draft.ready = true;
} }
}) }),
) );
} }
} }
onMount(init) onMount(init);
// Setup SIGUSR2 signal handler for dynamic theme reload // Setup SIGUSR2 signal handler for dynamic theme reload
// This allows external tools to trigger a theme refresh by sending: // This allows external tools to trigger a theme refresh by sending:
// `kill -USR2 <pid>` // `kill -USR2 <pid>`
const cleanupSignalHandler = setupThemeSignalHandler(() => { const cleanupSignalHandler = setupThemeSignalHandler(() => {
renderer.clearPaletteCache() renderer.clearPaletteCache();
init() init();
}) });
onCleanup(cleanupSignalHandler) onCleanup(cleanupSignalHandler);
// Sync active theme with app store settings // Sync active theme with app store settings
createEffect(() => { createEffect(() => {
const theme = appStore.state().settings.theme const theme = appStore.state().settings.theme;
if (theme) setStore("active", theme) if (theme) setStore("active", theme);
}) });
// Emit theme change events for observers // Emit theme change events for observers
createEffect(() => { createEffect(() => {
const theme = store.active const theme = store.active;
const mode = store.mode const mode = store.mode;
if (store.ready) { if (store.ready) {
emitThemeChanged(theme, mode) emitThemeChanged(theme, mode);
} }
}) });
const values = createMemo(() => { const values = createMemo(() => {
return resolveTerminalTheme(store.themes, store.active, store.mode, store.system) return resolveTerminalTheme(
}) store.themes,
store.active,
store.mode,
store.system,
);
});
const syntax = createMemo(() => generateSyntax(values() as unknown as Record<string, RGBA>)) const syntax = createMemo(() =>
generateSyntax(values() as unknown as Record<string, RGBA>),
);
const subtleSyntax = createMemo(() => const subtleSyntax = createMemo(() =>
generateSubtleSyntax(values() as unknown as Record<string, RGBA> & { thinkingOpacity?: number }) generateSubtleSyntax(
) values() as unknown as Record<string, RGBA> & {
thinkingOpacity?: number;
},
),
);
return { return {
theme: new Proxy(values(), { theme: new Proxy(values(), {
get(_target, prop) { get(_target, prop) {
// @ts-expect-error - dynamic property access // @ts-expect-error - dynamic property access
return values()[prop] return values()[prop];
}, },
}) as ThemeResolved, }) as ThemeResolved,
get selected() { get selected() {
return store.active return store.active;
}, },
all() { all() {
return store.themes return store.themes;
}, },
syntax, syntax,
subtleSyntax, subtleSyntax,
mode() { mode() {
return store.mode return store.mode;
}, },
setMode(mode: "dark" | "light") { setMode(mode: "dark" | "light") {
setStore("mode", mode) setStore("mode", mode);
emitThemeModeChanged(mode) emitThemeModeChanged(mode);
}, },
set(theme: string) { set(theme: string) {
appStore.setTheme(theme as ThemeName) appStore.setTheme(theme as ThemeName);
}, },
get ready() { get ready() {
return store.ready return store.ready;
}, },
} };
}, },
}) });

View File

@@ -0,0 +1,513 @@
/**
* navigation-store — the yazi-style navigation model, as a plain Solid store.
*
* This module is deliberately free of JSX and of any `.tsx` page imports so it
* can be exercised directly by unit tests (`bun test`) without the OpenTUI JSX
* runtime (which is supplied only by the build-time @opentui/solid bun-plugin).
* The Solid provider wrapper (`useNavigation` / `NavigationProvider`) and the
* simple-context plumbing live in `NavigationContext.tsx`; the app imports the
* provider from there, tests import `createNavigation` directly from here.
*
* ── Model ────────────────────────────────────────────────────────────────
* The app horizontally lays out three columns per tab:
*
* parent | current | preview
*
* Layout ratios (1/7 : 3/7 : 3/7 in the final remake) live in
* `@/utils/navigation` (PANE_RATIO). This module owns only the *focusable*
* nav model — which column is focused and where its list cursor lives. The
* parent/preview columns are always derived, never focused.
*
* The tab list is the app's ROOT and participates in the same pane flow as
* any other pane. View renders at most three panes, `UP | CURRENT | PREVIEW`:
*
* • At launch the tab list is the CURRENT pane, with nothing in UP (`atRootTab`).
* • Opening a tab (j/k to hover, `l`/Enter) slides it into the UP/parent pane;
* that tab's content becomes CURRENT and its hovered item PREVIEW
* (`enterTabContent`).
* • Drilling deeper (`l`/Enter in content) pushes frames; once past the tab's
* own root the UP/CURRENT/PREVIEW columns are all content, and the tab drops
* OUT of the 3-pane view.
* • `popDepth`/`h` walks back up: at content depth 0 `h` returns to the tab
* root (`backToTabRoot`, the tab becomes CURRENT again); `h` at the root
* stays (out of the panes — no-op).
*
* Depth-stack tabs (Feed, MyShows, Discover, Search, Player, Settings):
* ONE focusable content pane — the current column (DEPTH_CENTER_PANE = 1);
* the parent/preview are derived. Search drills query→results; Player is a
* single now-playing pane under the tab list (2-pane, no preview). Every
* tab returns to the root via `h` at depth 0 (`backToTabRoot`).
*
* Tabs switch via the tab list (j/k + l/Enter), digit keys `1`-`6`, and
* `[`/`]`, each re-syncing the tab cursor (`tabCursor`).
*/
import { createSignal, batch } from "solid-js";
import { TABS, TabsCount, DEPTH_TABS, rootFrameFor } from "@/utils/navigation";
export enum NavMode {
NORMAL = "NORMAL",
VISUAL = "VISUAL",
COMMAND = "COMMAND",
INPUT = "INPUT",
}
/** The current content pane of the active tab, i.e. the focusable column
* (index 1) for every depth-tab. Content panes occupy 1..n; the tab list is
* pane 0. A tab switch made while focused on content resets `activePane` to
* this pane (unless already on the tab list). */
export const DEPTH_CENTER_PANE = 1 as PaneId;
/** The tab list — the leading pane (pane 0) of the tab flow, rendered to the
* left of the active tab's content (1..n). It is the app's outermost pane:
* starting focus lives here, tab switches made from it keep focus on it, and
* swiping left past the first content pane returns to it. Swiping left again
* — beyond it — goes out of the panes (no-op). While it is focused, j/k
* moves the tab cursor and `l`/Enter opens the hovered tab's content. */
export type PaneId = number; // 0 = tab list; 1..n = the active tab's content panes
// ── Depth stack ──────────────────────────────────────────────────────────────
/** One frame in a tab's depth stack. `kind` identifies the list (page-defined,
* e.g. "feeds", "episodes:feedId", "settings:sections"); `focus` is the
* focused row index within that list. `ctx` optionally carries an id or
* payload the page needs to derive the list (e.g. a feed id). */
export type DepthFrame = {
kind: string;
ctx?: string;
focus: number;
};
// ── Selection store ───────────────────────────────────────────────────────────
// A Set per (tab, paneKey). `paneKey` is a string each pane uses to namespace
// its selection (e.g. "myshows:episodes"). Visual mode toggles into range
// selection anchored at the focused index.
type SelectionMap = Record<string, Set<string>>;
const HAS_VISUAL = (mode: NavMode) => mode === NavMode.VISUAL;
/**
* Construct a fresh, self-contained navigation state graph.
*
* Exported (not just inlined into the Solid provider) so unit tests can build
* a nav graph inside a `createRoot` without rendering any provider tree.
*/
export function createNavigation() {
const [activeTab, setActiveTab] = createSignal<TABS>(TABS.FEED);
// The root tab panel's cursor — which tab j/k is currently hovering. It is
// independent of `activeTab` until l/Enter activates it (activateTabCursor)
// or a direct tab switch (digits / [ ]) re-syncs it. So the panel behaves
// just like any other yazi list: j/k move the cursor, Enter/l open.
const [tabCursorSignal, setTabCursor] = createSignal<TABS>(TABS.FEED);
// App focus starts on the tab list (the app root). `activePane` is always
// DEPTH_CENTER_PANE for the active depth-tab; the per-tab depth stack plus
// the `atRootTab` flag describe where focus sits (the tab is the CURRENT
// pane when at the root, and slides into the UP/parent pane once content is
// opened).
const [activePane, setActivePane] = createSignal<PaneId>(DEPTH_CENTER_PANE);
// Whether focus is on the tab-list root view — the tab is the CURRENT pane
// with nothing above it. Opening a tab moves it to UP; deeper goes back out.
const [atRootTabSignal, setAtTabRoot] = createSignal(true);
const [mode, setMode] = createSignal<NavMode>(NavMode.NORMAL);
const [count, setCount] = createSignal<number | null>(null);
const [inputFocused, setInputFocused] = createSignal(false);
// per-tab depth stack. Depth-tabs get a root frame on first visit.
const [stacks, setStacks] = createSignal<Partial<Record<TABS, DepthFrame[]>>>(
{ [TABS.FEED]: [rootFrameFor(TABS.FEED)] },
);
// per-pane focused index map (unused by depth-tabs, which read/write the
// top frame's focus for DEPTH_CENTER_PANE; kept for any future fixed-pane
// pages). Keyed by `${tab}:${pane}`.
const [paneIndices, setPaneIndices] = createSignal<Record<string, number>>(
{},
);
const [selections, setSelections] = createSignal<SelectionMap>({});
const [visualAnchor, setVisualAnchor] = createSignal<{
paneKey: string;
index: number;
} | null>(null);
const [commandBuffer, setCommandBuffer] = createSignal("");
const [commandError, setCommandError] = createSignal<string | null>(null);
/** Depth stack for a tab (always non-empty — every tab is a depth-tab). */
const depthStackFor = (tab: TABS = activeTab()) => stacks()[tab] ?? [];
const ensureStack = (tab: TABS) => {
if (DEPTH_TABS.has(tab) && depthStackFor(tab).length === 0) {
setStacks((s) => ({ ...s, [tab]: [rootFrameFor(tab)] }));
}
};
/** Apply all tab-switch side effects synchronously. Done here in the
* imperative `switchTab` path rather than a reactive `createEffect`
* because this module is exercised by unit tests without the OpenTUI
* JSX runtime, and in that environment Solid's `createEffect` is a
* no-op (server build). Routing every tab change through this helper
* keeps the behavior identical under both runtimes.
*
* - a depth-tab switch from the root keeps the root (the tab list stays
* CURRENT); switches made from inside content drop into the new tab's
* current/center pane.
* - clear mode/command/visual/count state */
const applyTabSwitch = (tab: TABS) => {
ensureStack(tab);
batch(() => {
if (atRootTabSignal()) {
// a depth-tab switch from the root keeps the root (focus stays on
// the tab list); only entering content (enterTabContent) leaves it.
} else {
setActivePane(DEPTH_CENTER_PANE);
}
setMode(NavMode.NORMAL);
setCount(null);
setCommandBuffer("");
setCommandError(null);
setVisualAnchor(null);
});
};
// ── depth stack accessors ──────────────────────────────────────────────
// Plain functions (not createMemo) so they recompute on every read.
// On the client build these are read inside reactive JSX contexts so
// their underlying signal reads are still tracked; on the server build
// (used by unit tests) createMemo is a no-op that freezes at creation,
// so a plain function is the only option that stays correct in tests.
const depthStack = (): DepthFrame[] => depthStackFor(activeTab());
const currentDepth = (): number => Math.max(0, depthStack().length - 1);
const topFrame = (): DepthFrame | undefined =>
depthStack()[depthStack().length - 1];
const isDepthTab = () => DEPTH_TABS.has(activeTab());
/** Focus within a given depth's frame (default = current/top). */
const depthFocus = (d: number = currentDepth()) =>
depthStack()[d]?.focus ?? 0;
const setDepthFocus = (i: number, d: number = currentDepth()) =>
setStacks((s) => {
const st = s[activeTab()];
if (!st || d < 0 || d >= st.length) return s;
const next = st.slice();
next[d] = { ...next[d], focus: i };
return { ...s, [activeTab()]: next };
});
/** Push a child frame (drill in). */
const pushDepth = (frame: DepthFrame) =>
setStacks((s) => {
const st = s[activeTab()] ?? [];
return { ...s, [activeTab()]: [...st, frame] };
});
/** Pop the top frame (go back up a depth). No-op at root. Returns
* true if a frame was popped. */
const popDepth = (): boolean => {
let popped = false;
setStacks((s) => {
const st = s[activeTab()] ?? [];
if (st.length <= 1) return s;
popped = true;
return { ...s, [activeTab()]: st.slice(0, -1) };
});
return popped;
};
// ── tab switching ──────────────────────────────────────────────────────
/** Internal: set activeTab + run all side effects (root-frame seed,
* pane/mode/command reset). Called by gotoTab/nextTab/prevTab so every
* tab change — programmatic or key-driven — goes through one path. */
const switchTab = (tab: TABS) => {
setActiveTab(tab);
// a direct tab switch re-syncs the root panel's cursor so the panel
// reflects what is actually active.
setTabCursor(tab);
applyTabSwitch(tab);
};
const gotoTab = (tab: TABS) => {
if (tab < 1 || tab > TabsCount) return;
switchTab(tab);
};
const nextTab = () => {
const t = activeTab() >= TabsCount ? 1 : ((activeTab() + 1) as TABS);
switchTab(t);
};
const prevTab = () => {
const t = activeTab() <= 1 ? TabsCount : ((activeTab() - 1) as TABS);
switchTab(t);
};
// ── pane focus ──────────────────────────────────────────────────────────
const setPane = (pane: PaneId) => setActivePane(pane);
// (no fixed-pane swipe — every tab is a depth-tab; h/l drill/pop instead.)
// ── tab root (the app's outermost pane) ──────────────────────────────────
/** True while focus is on the tab list as the CURRENT pane — the app root,
* with nothing above it. Applies to every tab: a depth-tab switch from
* the root keeps it; entering content (`enterTabContent`) clears it; `h`
* at content depth 0 regains it via `backToTabRoot`. */
const atRootTab = (): boolean => atRootTabSignal();
/** Open the active tab's content: the tab slides from CURRENT into the
* UP/parent pane and focus lands on the content's current pane. */
const enterTabContent = () => {
setAtTabRoot(false);
setActivePane(DEPTH_CENTER_PANE);
};
/** Move focus back to the tab list root (UP -> CURRENT), e.g. `h` popping
* out of content at depth 0. */
const backToTabRoot = () => {
setAtTabRoot(true);
setActivePane(DEPTH_CENTER_PANE);
};
/** The tab the root's cursor is hovering (independent of activeTab). */
const tabCursor = (): TABS => tabCursorSignal();
/** Move the root's cursor to the adjacent tab (clamped, no wrap). */
const moveTabCursor = (dir: -1 | 1) => {
setTabCursor((c) => Math.max(1, Math.min(TabsCount, c + dir)) as TABS);
};
/** Open the hovered tab (switch to it and enter its content) from the root.
* The yazi "open" of a tab row. */
const activateTabCursor = () => {
switchTab(tabCursorSignal());
enterTabContent();
};
// ── per-pane focus index ────────────────────────────────────────────────
const paneKey = (pane: PaneId = activePane()) => `${activeTab()}:${pane}`;
/** For depth-tabs (every tab), pane 1 (DEPTH_CENTER_PANE) reads/writes
* the top frame's focus. Other panes fall back to the per-pane index
* map (unused by current pages). */
const focusedIndex = (pane: PaneId = activePane()): number => {
if (isDepthTab() && pane === DEPTH_CENTER_PANE) {
return topFrame()?.focus ?? 0;
}
return paneIndices()[paneKey(pane)] ?? 0;
};
const setFocusedIndex = (pane: PaneId, index: number) => {
if (isDepthTab() && pane === DEPTH_CENTER_PANE) {
setDepthFocus(index);
return;
}
setPaneIndices((m) => ({
...m,
[`${activeTab()}:${pane}`]: index,
}));
};
/** Apply a clamped relative motion to the active pane's focus. Returns
* the new index so callers can update their own scroll state. */
const move = (
delta: number,
listLen: number,
countOverride?: number,
): number => {
if (listLen <= 0) return 0;
const steps = countOverride ?? count() ?? 1;
const pane = activePane();
const cur = focusedIndex(pane);
let next = cur + delta * steps;
// wrap-around like yazi (arrow wraps top<->bottom)
next = ((next % listLen) + listLen) % listLen;
setFocusedIndex(pane, next);
// visual-mode range selection: add newly-traversed items to selection
if (HAS_VISUAL(mode()) && visualAnchor()) {
growVisualSelection(next);
}
return next;
};
const gotoIndex = (index: number, listLen: number): number => {
if (listLen <= 0) return 0;
const pane = activePane();
const next = Math.max(0, Math.min(listLen - 1, index));
setFocusedIndex(pane, next);
if (HAS_VISUAL(mode()) && visualAnchor()) growVisualSelection(next);
return next;
};
// ── selection ───────────────────────────────────────────────────────────
const selSet = (key: string): Set<string> => selections()[key] ?? new Set();
const toggleSelected = (id: string) => {
const key = paneKey();
setSelections((m) => {
const set = new Set(m[key] ?? []);
if (set.has(id)) set.delete(id);
else set.add(id);
return { ...m, [key]: set };
});
};
const isSelected = (id: string) => selSet(paneKey()).has(id);
const clearSelection = (key?: string) => {
const k = key ?? paneKey();
setSelections((m) => {
if (!(k in m)) return m;
const next = { ...m };
delete next[k];
return next;
});
};
const selectedIds = () => [...selSet(paneKey())];
/** Enter visual mode, anchoring range selection at the current focus. */
const enterVisual = () => {
const pane = activePane();
setVisualAnchor({ paneKey: paneKey(pane), index: focusedIndex(pane) });
setMode(NavMode.VISUAL);
};
/** Grow selection between the visual anchor and `index` for the active
* pane. Callers pass item ids aligned to indices; we store ids via the
* resolve callback registered per-pane (see registerResolver). */
let resolvers: Record<string, (index: number) => string | undefined> = {};
const registerResolver = (
key: string,
fn: (i: number) => string | undefined,
) => {
resolvers[key] = fn;
};
const growVisualSelection = (index: number) => {
const anchor = visualAnchor();
if (!anchor) return;
const resolve = resolvers[anchor.paneKey];
if (!resolve) return;
const lo = Math.min(anchor.index, index);
const hi = Math.max(anchor.index, index);
const ids: string[] = [];
for (let i = lo; i <= hi; i++) {
const id = resolve(i);
if (id) ids.push(id);
}
const key = anchor.paneKey;
setSelections((m) => ({ ...m, [key]: new Set(ids) }));
};
// ── modes ────────────────────────────────────────────────────────────────
const enterCommand = () => {
setMode(NavMode.COMMAND);
setCommandBuffer("");
setCommandError(null);
};
const enterInput = () => setMode(NavMode.INPUT);
const exitCommand = () => {
batch(() => {
setMode(NavMode.NORMAL);
setCommandBuffer("");
setCommandError(null);
});
};
const exitVisual = () => {
batch(() => {
setMode(NavMode.NORMAL);
setVisualAnchor(null);
});
};
const toNormal = () => {
if (mode() === NavMode.VISUAL) {
clearSelection();
exitVisual();
} else {
setMode(NavMode.NORMAL);
}
};
// ── command buffer ───────────────────────────────────────────────────────
const appendCommand = (ch: string) => setCommandBuffer((b) => b + ch);
const backspaceCommand = () => setCommandBuffer((b) => b.slice(0, -1));
const submitCommand = (): string => {
const cmd = commandBuffer().trim();
exitCommand();
return cmd;
};
// ── count register ───────────────────────────────────────────────────────
const pushCountDigit = (d: number) => setCount((c) => (c ?? 0) * 10 + d);
const consumeCount = (): number => {
const c = count();
setCount(null);
return c ?? 1;
};
return {
activeTab,
activePane,
mode,
count,
inputFocused,
commandBuffer,
commandError,
visualAnchor,
selections,
selectedIds,
// depth stack
depthStack,
currentDepth,
topFrame,
depthFocus,
setDepthFocus,
pushDepth,
popDepth,
isDepthTab,
// tab
setActiveTab: gotoTab,
nextTab,
prevTab,
// tab root (app's outermost pane)
atRootTab,
enterTabContent,
backToTabRoot,
tabCursor,
moveTabCursor,
activateTabCursor,
// pane focus
setActivePane: setPane,
// focus index
focusedIndex,
setFocusedIndex,
move,
gotoIndex,
// selection
isSelected,
toggleSelected,
clearSelection,
selectedIdsFor: (key: string) => [...selSet(key)],
registerResolver,
enterVisual,
exitVisual,
// modes
setActiveTabSignal: setActiveTab,
setActiveDepth: setPane, // legacy alias
activeDepth: activePane, // legacy alias
setInputFocused,
nextPane: () => {}, // legacy noop; swipe() replaces this
prevPane: () => {},
setMode,
enterCommand,
enterInput,
exitCommand,
toNormal,
// command buffer
setCommandBuffer,
appendCommand,
backspaceCommand,
submitCommand,
setCommandError,
// count
pushCountDigit,
consumeCount,
};
}
export type NavigationState = ReturnType<typeof createNavigation>;

View File

@@ -1,139 +0,0 @@
/**
* Centralized keyboard shortcuts hook for PodTUI
* Single handler to prevent conflicts
*/
import { useKeyboard, useRenderer } from "@opentui/solid"
import type { TabId } from "../components/Tab"
import type { Accessor } from "solid-js"
const TAB_ORDER: TabId[] = ["feed", "shows", "discover", "search", "player", "settings"]
type ShortcutOptions = {
activeTab: TabId
onTabChange: (tab: TabId) => void
onAction?: (action: string) => void
inputFocused?: boolean
navigationEnabled?: boolean
layerDepth?: Accessor<number>
onLayerChange?: (newDepth: number) => void
}
export function useAppKeyboard(options: ShortcutOptions) {
const renderer = useRenderer()
const getNextTab = (current: TabId): TabId => {
const idx = TAB_ORDER.indexOf(current)
return TAB_ORDER[(idx + 1) % TAB_ORDER.length]
}
const getPrevTab = (current: TabId): TabId => {
const idx = TAB_ORDER.indexOf(current)
return TAB_ORDER[(idx - 1 + TAB_ORDER.length) % TAB_ORDER.length]
}
useKeyboard((key) => {
// Always allow quit
if (key.ctrl && key.name === "q") {
renderer.destroy()
return
}
if (key.name === "escape") {
options.onAction?.("escape")
return
}
// Skip global shortcuts if input is focused (let input handle keys)
if (options.inputFocused) {
return
}
if (options.navigationEnabled === false) {
return
}
if (key.name === "return") {
options.onAction?.("enter")
return
}
// Layer navigation with left/right arrows
if (options.layerDepth !== undefined && options.onLayerChange) {
const currentDepth = options.layerDepth()
const maxLayers = 3
if (key.name === "right") {
if (currentDepth < maxLayers) {
options.onLayerChange(currentDepth + 1)
}
return
}
if (key.name === "left") {
if (currentDepth > 0) {
options.onLayerChange(currentDepth - 1)
}
return
}
}
// Tab navigation with left/right arrows OR [ and ]
if (key.name === "right" || key.name === "]") {
options.onTabChange(getNextTab(options.activeTab))
return
}
if (key.name === "left" || key.name === "[") {
options.onTabChange(getPrevTab(options.activeTab))
return
}
// Number keys for direct tab access (1-6)
if (key.name === "1") {
options.onTabChange("feed")
return
}
if (key.name === "2") {
options.onTabChange("shows")
return
}
if (key.name === "3") {
options.onTabChange("discover")
return
}
if (key.name === "4") {
options.onTabChange("search")
return
}
if (key.name === "5") {
options.onTabChange("player")
return
}
if (key.name === "6") {
options.onTabChange("settings")
return
}
// Tab key cycles tabs (Shift+Tab goes backwards)
if (key.name === "tab") {
if (key.shift) {
options.onTabChange(getPrevTab(options.activeTab))
} else {
options.onTabChange(getNextTab(options.activeTab))
}
return
}
// Forward other actions
if (options.onAction) {
if (key.ctrl && key.name === "s") {
options.onAction("save")
} else if (key.ctrl && key.name === "f") {
options.onAction("find")
} else if (key.name === "?" || (key.shift && key.name === "/")) {
options.onAction("help")
}
}
})
}

View File

@@ -12,282 +12,352 @@
* ``` * ```
*/ */
import { createSignal, onCleanup } from "solid-js" import { createSignal, onCleanup } from "solid-js";
import { import {
createAudioBackend, createAudioBackend,
detectPlayers, detectPlayers,
type AudioBackend, type AudioBackend,
type BackendName, type BackendName,
type DetectedPlayer, type DetectedPlayer,
} from "../utils/audio-player" } from "../utils/audio-player";
import { emit, on } from "../utils/event-bus" import { emit, on } from "../utils/event-bus";
import { useAppStore } from "../stores/app" import { useAppStore } from "../stores/app";
import { useProgressStore } from "../stores/progress" import { useProgressStore } from "../stores/progress";
import type { Episode } from "../types/episode" import { useMediaRegistry } from "../utils/media-registry";
import type { Episode } from "../types/episode";
import type { Feed } from "../types/feed";
import { useAudioNavStore, AudioSource } from "../stores/audio-nav";
import { useFeedStore } from "../stores/feed";
export interface AudioControls { export interface AudioControls {
// Signals (reactive getters) // Signals (reactive getters)
isPlaying: () => boolean isPlaying: () => boolean;
position: () => number position: () => number;
duration: () => number duration: () => number;
volume: () => number volume: () => number;
speed: () => number speed: () => number;
backendName: () => BackendName backendName: () => BackendName;
error: () => string | null error: () => string | null;
currentEpisode: () => Episode | null currentEpisode: () => Episode | null;
availablePlayers: () => DetectedPlayer[] availablePlayers: () => DetectedPlayer[];
// Actions // Actions
play: (episode: Episode) => Promise<void> play: (episode: Episode) => Promise<void>;
pause: () => Promise<void> pause: () => Promise<void>;
resume: () => Promise<void> resume: () => Promise<void>;
togglePlayback: () => Promise<void> togglePlayback: () => Promise<void>;
stop: () => Promise<void> stop: () => Promise<void>;
seek: (seconds: number) => Promise<void> seek: (seconds: number) => Promise<void>;
seekRelative: (delta: number) => Promise<void> seekRelative: (delta: number) => Promise<void>;
setVolume: (volume: number) => Promise<void> setVolume: (volume: number) => Promise<void>;
setSpeed: (speed: number) => Promise<void> setSpeed: (speed: number) => Promise<void>;
switchBackend: (name: BackendName) => Promise<void> switchBackend: (name: BackendName) => Promise<void>;
prev: () => Promise<void>;
next: () => Promise<void>;
} }
// Singleton state — shared across all components that call useAudio() // Singleton state — shared across all components that call useAudio()
let backend: AudioBackend | null = null let backend: AudioBackend | null = null;
let pollTimer: ReturnType<typeof setInterval> | null = null let pollTimer: ReturnType<typeof setInterval> | null = null;
let refCount = 0 let refCount = 0;
let pollCount = 0 // Counts poll ticks for throttling progress saves let pollCount = 0; // Counts poll ticks for throttling progress saves
const [isPlaying, setIsPlaying] = createSignal(false) const [isPlaying, setIsPlaying] = createSignal(false);
const [position, setPosition] = createSignal(0) const [position, setPosition] = createSignal(0);
const [duration, setDuration] = createSignal(0) const [duration, setDuration] = createSignal(0);
const [volume, setVolume] = createSignal(0.7) const [volume, setVolume] = createSignal(0.7);
const [speed, setSpeed] = createSignal(1) const [speed, setSpeed] = createSignal(1);
const [backendName, setBackendName] = createSignal<BackendName>("none") const [backendName, setBackendName] = createSignal<BackendName>("none");
const [error, setError] = createSignal<string | null>(null) const [error, setError] = createSignal<string | null>(null);
const [currentEpisode, setCurrentEpisode] = createSignal<Episode | null>(null) const [currentEpisode, setCurrentEpisode] = createSignal<Episode | null>(null);
const [availablePlayers, setAvailablePlayers] = createSignal<DetectedPlayer[]>([]) const [availablePlayers, setAvailablePlayers] = createSignal<DetectedPlayer[]>(
[],
);
function ensureBackend(): AudioBackend { function ensureBackend(): AudioBackend {
if (!backend) { if (!backend) {
const detected = detectPlayers() const detected = detectPlayers();
setAvailablePlayers(detected) setAvailablePlayers(detected);
backend = createAudioBackend() backend = createAudioBackend();
setBackendName(backend.name) setBackendName(backend.name);
registerExitTeardown();
}
return backend;
}
// ── Process-exit teardown ─────────────────────────────────────────────
// `q` (the quit action) calls `process.exit(0)`, which bypasses Solid's
// onCleanup — where `backend.dispose()` would otherwise kill the spawned
// player (mpv). Without this hook those child processes
// survive the host and keep playing audio after the TUI has quit. The
// `exit` event fires synchronously on `process.exit(N)`; the signal
// handlers cover Ctrl-C / kill, which otherwise terminate without running
// `exit` listeners.
let exitTeardownRegistered = false;
function registerExitTeardown(): void {
if (exitTeardownRegistered) return;
exitTeardownRegistered = true;
const teardown = (): void => {
stopPolling();
try {
backend?.dispose();
} catch {
/* best-effort at exit */
}
try {
useMediaRegistry().clearNowPlaying();
} catch {
/* best-effort at exit */
}
};
process.on("exit", teardown);
for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"] as const) {
process.on(sig, () => {
teardown();
process.exit(0);
});
} }
return backend
} }
function startPolling(): void { function startPolling(): void {
stopPolling() stopPolling();
pollCount = 0 pollCount = 0;
pollTimer = setInterval(async () => { pollTimer = setInterval(async () => {
if (!backend || !isPlaying()) return if (!backend || !isPlaying()) return;
try { try {
const pos = await backend.getPosition() const pos = await backend.getPosition();
const dur = await backend.getDuration() const dur = await backend.getDuration();
setPosition(pos) setPosition(pos);
if (dur > 0) setDuration(dur) if (dur > 0) setDuration(dur);
// Save progress every ~5 seconds (10 ticks * 500ms) // Save progress every ~5 seconds (10 ticks * 500ms)
pollCount++ pollCount++;
if (pollCount % 10 === 0) { if (pollCount % 10 === 0) {
const ep = currentEpisode() const ep = currentEpisode();
if (ep) { if (ep) {
const progressStore = useProgressStore() const progressStore = useProgressStore();
progressStore.update(ep.id, pos, dur > 0 ? dur : duration(), speed()) progressStore.update(ep.id, pos, dur > 0 ? dur : duration(), speed());
// Update platform media position
const media = useMediaRegistry();
media.setPosition(pos);
} }
} }
// Check if backend stopped playing (track ended) // Check if backend stopped playing (track ended)
if (!backend.isPlaying() && isPlaying()) { if (!backend.isPlaying() && isPlaying()) {
setIsPlaying(false) setIsPlaying(false);
stopPolling() stopPolling();
// Save final position on track end // Save final position on track end
const ep = currentEpisode() const ep = currentEpisode();
if (ep) { if (ep) {
const progressStore = useProgressStore() const progressStore = useProgressStore();
progressStore.update(ep.id, pos, dur > 0 ? dur : duration(), speed()) progressStore.update(ep.id, pos, dur > 0 ? dur : duration(), speed());
} }
} }
} catch { } catch {
// Backend may have been disposed // Backend may have been disposed
} }
}, 500) }, 500);
} }
function stopPolling(): void { function stopPolling(): void {
if (pollTimer) { if (pollTimer) {
clearInterval(pollTimer) clearInterval(pollTimer);
pollTimer = null pollTimer = null;
} }
} }
async function play(episode: Episode): Promise<void> { async function play(episode: Episode): Promise<void> {
const b = ensureBackend() const b = ensureBackend();
setError(null) setError(null);
if (!episode.audioUrl) { if (!episode.audioUrl) {
setError("No audio URL for this episode") setError("No audio URL for this episode");
return return;
} }
try { try {
const appStore = useAppStore() const appStore = useAppStore();
const progressStore = useProgressStore() const progressStore = useProgressStore();
const storeSpeed = appStore.state().settings.playbackSpeed const storeSpeed = appStore.state().settings.playbackSpeed;
const vol = volume() const vol = volume();
const spd = storeSpeed || speed() const spd = storeSpeed || speed();
// Resume from saved progress if available and not completed // Resume from saved progress if available and not completed
const savedProgress = progressStore.get(episode.id) const savedProgress = progressStore.get(episode.id);
let startPos = 0 let startPos = 0;
if (savedProgress && !progressStore.isCompleted(episode.id)) { if (savedProgress && !progressStore.isCompleted(episode.id)) {
startPos = savedProgress.position startPos = savedProgress.position;
} }
await b.play(episode.audioUrl, { await b.play(episode.audioUrl, {
volume: vol, volume: vol,
speed: spd, speed: spd,
startPosition: startPos > 0 ? startPos : undefined, startPosition: startPos > 0 ? startPos : undefined,
}) });
setCurrentEpisode(episode) setCurrentEpisode(episode);
setIsPlaying(true) setIsPlaying(true);
setPosition(startPos) setPosition(startPos);
setSpeed(spd) setSpeed(spd);
if (episode.duration) setDuration(episode.duration) if (episode.duration) setDuration(episode.duration);
startPolling() // Register with platform media controls
emit("player.play", { episodeId: episode.id }) const media = useMediaRegistry();
media.setNowPlaying({
title: episode.title,
artist: episode.podcastId,
duration: episode.duration,
});
media.setPlaybackState(true);
if (startPos > 0) media.setPosition(startPos);
startPolling();
emit("player.play", { episodeId: episode.id });
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : "Playback failed") setError(err instanceof Error ? err.message : "Playback failed");
setIsPlaying(false) setIsPlaying(false);
} }
} }
async function pause(): Promise<void> { async function pause(): Promise<void> {
if (!backend) return if (!backend) return;
try { try {
await backend.pause() await backend.pause();
setIsPlaying(false) setIsPlaying(false);
stopPolling() stopPolling();
const ep = currentEpisode() const ep = currentEpisode();
if (ep) { if (ep) {
// Save progress on pause // Save progress on pause
const progressStore = useProgressStore() const progressStore = useProgressStore();
progressStore.update(ep.id, position(), duration(), speed()) progressStore.update(ep.id, position(), duration(), speed());
emit("player.pause", { episodeId: ep.id }) emit("player.pause", { episodeId: ep.id });
// Update platform media controls
const media = useMediaRegistry();
media.setPlaybackState(false);
media.setPosition(position());
} }
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : "Pause failed") setError(err instanceof Error ? err.message : "Pause failed");
} }
} }
async function resume(): Promise<void> { async function resume(): Promise<void> {
if (!backend) return if (!backend) return;
try { try {
await backend.resume() await backend.resume();
setIsPlaying(true) setIsPlaying(true);
startPolling() startPolling();
const ep = currentEpisode() const ep = currentEpisode();
if (ep) emit("player.play", { episodeId: ep.id }) if (ep) {
emit("player.play", { episodeId: ep.id });
const media = useMediaRegistry();
media.setPlaybackState(true);
}
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : "Resume failed") setError(err instanceof Error ? err.message : "Resume failed");
} }
} }
async function togglePlayback(): Promise<void> { async function togglePlayback(): Promise<void> {
if (isPlaying()) { if (isPlaying()) {
await pause() await pause();
} else if (currentEpisode()) { } else if (currentEpisode()) {
await resume() await resume();
} }
} }
async function stop(): Promise<void> { async function stop(): Promise<void> {
if (!backend) return if (!backend) return;
try { try {
// Save progress before stopping // Save progress before stopping
const ep = currentEpisode() const ep = currentEpisode();
if (ep) { if (ep) {
const progressStore = useProgressStore() const progressStore = useProgressStore();
progressStore.update(ep.id, position(), duration(), speed()) progressStore.update(ep.id, position(), duration(), speed());
} }
await backend.stop() await backend.stop();
setIsPlaying(false) setIsPlaying(false);
setPosition(0) setPosition(0);
setCurrentEpisode(null) setCurrentEpisode(null);
stopPolling() stopPolling();
emit("player.stop", {}) emit("player.stop", {});
// Clear platform media controls
const media = useMediaRegistry();
media.clearNowPlaying();
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : "Stop failed") setError(err instanceof Error ? err.message : "Stop failed");
} }
} }
async function seek(seconds: number): Promise<void> { async function seek(seconds: number): Promise<void> {
if (!backend) return if (!backend) return;
const clamped = Math.max(0, Math.min(seconds, duration())) const clamped = Math.max(0, Math.min(seconds, duration()));
try { try {
await backend.seek(clamped) await backend.seek(clamped);
setPosition(clamped) setPosition(clamped);
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : "Seek failed") setError(err instanceof Error ? err.message : "Seek failed");
} }
} }
async function seekRelative(delta: number): Promise<void> { async function seekRelative(delta: number): Promise<void> {
await seek(position() + delta) await seek(position() + delta);
} }
async function doSetVolume(vol: number): Promise<void> { async function doSetVolume(vol: number): Promise<void> {
const clamped = Math.max(0, Math.min(1, vol)) const clamped = Math.max(0, Math.min(1, vol));
if (backend) { if (backend) {
try { try {
await backend.setVolume(clamped) await backend.setVolume(clamped);
} catch { } catch {
// Some backends can't change volume at runtime // Some backends can't change volume at runtime
} }
} }
setVolume(clamped) setVolume(clamped);
} }
async function doSetSpeed(spd: number): Promise<void> { async function doSetSpeed(spd: number): Promise<void> {
const clamped = Math.max(0.25, Math.min(3, spd)) const clamped = Math.max(0.25, Math.min(3, spd));
if (backend) { if (backend) {
try { try {
await backend.setSpeed(clamped) await backend.setSpeed(clamped);
} catch { } catch {
// Some backends can't change speed at runtime // Some backends can't change speed at runtime
} }
} }
setSpeed(clamped) setSpeed(clamped);
// Sync back to app store // Sync back to app store
try { try {
const appStore = useAppStore() const appStore = useAppStore();
appStore.updateSettings({ playbackSpeed: clamped }) appStore.updateSettings({ playbackSpeed: clamped });
} catch { } catch {
// Store may not be available // Store may not be available
} }
} }
async function switchBackend(name: BackendName): Promise<void> { async function switchBackend(name: BackendName): Promise<void> {
const wasPlaying = isPlaying() const wasPlaying = isPlaying();
const ep = currentEpisode() const ep = currentEpisode();
const pos = position() const pos = position();
const vol = volume() const vol = volume();
const spd = speed() const spd = speed();
// Stop current backend // Stop current backend
if (backend) { if (backend) {
stopPolling() stopPolling();
backend.dispose() backend.dispose();
backend = null backend = null;
} }
// Create new backend // Create new backend
backend = createAudioBackend(name) backend = createAudioBackend(name);
setBackendName(backend.name) setBackendName(backend.name);
setAvailablePlayers(detectPlayers()) setAvailablePlayers(detectPlayers());
// Resume playback if we were playing // Resume playback if we were playing
if (wasPlaying && ep && ep.audioUrl) { if (wasPlaying && ep && ep.audioUrl) {
@@ -296,12 +366,12 @@ async function switchBackend(name: BackendName): Promise<void> {
startPosition: pos, startPosition: pos,
volume: vol, volume: vol,
speed: spd, speed: spd,
}) });
setIsPlaying(true) setIsPlaying(true);
startPolling() startPolling();
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : "Backend switch failed") setError(err instanceof Error ? err.message : "Backend switch failed");
setIsPlaying(false) setIsPlaying(false);
} }
} }
} }
@@ -314,53 +384,163 @@ async function switchBackend(name: BackendName): Promise<void> {
*/ */
export function useAudio(): AudioControls { export function useAudio(): AudioControls {
// Initialize backend on first use // Initialize backend on first use
ensureBackend() ensureBackend();
// Sync initial speed from app store // Sync initial speed from app store
if (refCount === 0) { if (refCount === 0) {
try { try {
const appStore = useAppStore() const appStore = useAppStore();
const storeSpeed = appStore.state().settings.playbackSpeed const storeSpeed = appStore.state().settings.playbackSpeed;
if (storeSpeed && storeSpeed !== speed()) { if (storeSpeed && storeSpeed !== speed()) {
setSpeed(storeSpeed) setSpeed(storeSpeed);
} }
} catch { } catch {
// Store may not be available yet // Store may not be available yet
} }
} }
refCount++ refCount++;
// Listen for event bus commands (e.g. from other components) // Listen for event bus commands (e.g. from other components)
const unsubPlay = on("player.play", async (data) => { const unsubPlay = on("player.play", async (data) => {
// External play requests — currently just tracks episodeId. // External play requests — currently just tracks episodeId.
// Episode lookup would require feed store integration. // Episode lookup would require feed store integration.
}) });
const unsubStop = on("player.stop", async () => { const unsubStop = on("player.stop", async () => {
if (backend && isPlaying()) { if (backend && isPlaying()) {
await backend.stop() await backend.stop();
setIsPlaying(false) setIsPlaying(false);
setPosition(0) setPosition(0);
setCurrentEpisode(null) setCurrentEpisode(null);
stopPolling() stopPolling();
}
});
// Listen for global multimedia key events (from useMultimediaKeys)
const unsubMediaToggle = on("media.toggle", async () => {
await togglePlayback();
});
const unsubMediaVolUp = on("media.volumeUp", async () => {
await doSetVolume(Math.min(1, Number((volume() + 0.05).toFixed(2))));
});
const unsubMediaVolDown = on("media.volumeDown", async () => {
await doSetVolume(Math.max(0, Number((volume() - 0.05).toFixed(2))));
});
const unsubMediaSeekFwd = on("media.seekForward", async () => {
await seekRelative(10);
});
const unsubMediaSeekBack = on("media.seekBackward", async () => {
await seekRelative(-10);
});
const unsubMediaSpeed = on("media.speedCycle", async () => {
const next = speed() >= 2 ? 0.5 : Number((speed() + 0.25).toFixed(2));
await doSetSpeed(next);
});
const audioNav = useAudioNavStore();
const feedStore = useFeedStore();
async function prev(): Promise<void> {
const current = currentEpisode();
if (!current) return;
const currentPos = position();
const currentDur = duration();
const NAV_START_THRESHOLD = 30;
if (currentPos > NAV_START_THRESHOLD && currentDur > 0) {
await seek(NAV_START_THRESHOLD);
} else {
const source = audioNav.getSource();
let episodes: Array<{ episode: Episode; feed: Feed }> = [];
if (source === AudioSource.FEED) {
episodes = feedStore.getAllEpisodesChronological();
} else if (source === AudioSource.MY_SHOWS) {
const podcastId = audioNav.getPodcastId();
if (!podcastId) return;
const feed = feedStore
.getFilteredFeeds()
.find((f) => f.podcast.id === podcastId);
if (!feed) return;
episodes = feed.episodes.map((ep) => ({ episode: ep, feed }));
}
const currentIndex = audioNav.getCurrentIndex();
const newIndex = Math.max(0, currentIndex - 1);
if (newIndex < episodes.length && episodes[newIndex]) {
const { episode } = episodes[newIndex];
await play(episode);
audioNav.prev(newIndex);
}
}
}
async function next(): Promise<void> {
const current = currentEpisode();
if (!current) return;
const source = audioNav.getSource();
let episodes: Array<{ episode: Episode; feed: Feed }> = [];
if (source === AudioSource.FEED) {
episodes = feedStore.getAllEpisodesChronological();
} else if (source === AudioSource.MY_SHOWS) {
const podcastId = audioNav.getPodcastId();
if (!podcastId) return;
const feed = feedStore
.getFilteredFeeds()
.find((f) => f.podcast.id === podcastId);
if (!feed) return;
episodes = feed.episodes.map((ep) => ({ episode: ep, feed }));
}
const currentIndex = audioNav.getCurrentIndex();
const newIndex = Math.min(episodes.length - 1, currentIndex + 1);
if (newIndex >= 0 && episodes[newIndex]) {
const { episode } = episodes[newIndex];
await play(episode);
audioNav.next(newIndex);
}
} }
})
onCleanup(() => { onCleanup(() => {
refCount-- refCount--;
unsubPlay() unsubPlay();
unsubStop() unsubStop();
unsubMediaToggle();
unsubMediaVolUp();
unsubMediaVolDown();
unsubMediaSeekFwd();
unsubMediaSeekBack();
unsubMediaSpeed();
if (refCount <= 0) { if (refCount <= 0) {
stopPolling() stopPolling();
if (backend) { if (backend) {
backend.dispose() backend.dispose();
backend = null backend = null;
} }
refCount = 0 // Clear media registry on full teardown
const media = useMediaRegistry();
media.clearNowPlaying();
refCount = 0;
} }
}) });
return { return {
isPlaying, isPlaying,
@@ -383,5 +563,7 @@ export function useAudio(): AudioControls {
setVolume: doSetVolume, setVolume: doSetVolume,
setSpeed: doSetSpeed, setSpeed: doSetSpeed,
switchBackend, switchBackend,
} prev,
next,
};
} }

View File

@@ -1,37 +0,0 @@
import { useKeyboard, useRenderer } from "@opentui/solid"
type ShortcutOptions = {
onSave?: () => void
onQuit?: () => void
onTabNext?: () => void
onTabPrev?: () => void
}
export function useKeyboardShortcuts(options: ShortcutOptions) {
const renderer = useRenderer()
useKeyboard((key) => {
if (key.ctrl && key.name === "q") {
if (options.onQuit) {
options.onQuit()
} else {
renderer.destroy()
}
return
}
if (key.ctrl && key.name === "s") {
options.onSave?.()
return
}
if (key.name === "right") {
options.onTabNext?.()
return
}
if (key.name === "left") {
options.onTabPrev?.()
}
})
}

View File

@@ -0,0 +1,95 @@
/**
* Global multimedia key handler hook.
*
* Captures media-related key events (play/pause, volume, seek, speed)
* regardless of which component is focused. Uses the event bus to
* decouple key detection from audio control logic.
*
* Volume and speed are app-level settings — adjustable with or without
* an episode loaded (they apply to the next playback and persist). Seek
* is playback-dependent, so it still requires a loaded episode.
*/
import { useKeyboard } from "@opentui/solid";
import { emit } from "../utils/event-bus";
export type MediaKeyAction =
| "media.toggle"
| "media.volumeUp"
| "media.volumeDown"
| "media.seekForward"
| "media.seekBackward"
| "media.speedCycle";
/** Key-to-action mappings for multimedia controls */
const MEDIA_KEY_MAP: Record<string, MediaKeyAction> = {
// Common terminal media keys — these overlap with Player.tsx local
// bindings, but Player guards on `props.focused` so the global
// handler fires independently when the player tab is *not* active.
//
// When Player IS focused both handlers fire, but since the audio
// actions are idempotent (toggle = toggle, seek = additive) having
// them called twice for the same keypress is avoided by the event
// bus approach — the audio hook only processes event-bus events, and
// Player.tsx calls audio methods directly. We therefore guard with
// a "playerFocused" flag passed via options.
};
export interface MultimediaKeysOptions {
/** When true, skip handling (Player.tsx handles keys locally) */
playerFocused?: () => boolean;
/** When true, skip handling (text input has focus) */
inputFocused?: () => boolean;
/** Whether an episode is currently loaded */
hasEpisode?: () => boolean;
}
/**
* Registers a global keyboard listener that emits media events on the
* event bus. Call once at the app level (e.g. in App.tsx).
*/
export function useMultimediaKeys(options: MultimediaKeysOptions = {}) {
useKeyboard((key) => {
// Don't intercept when a text input owns the keyboard
if (options.inputFocused?.()) return;
// Don't intercept when Player component handles its own keys
if (options.playerFocused?.()) return;
// Ctrl/Meta combos are app-level shortcuts, not media keys
if (key.ctrl || key.meta) return;
switch (key.name) {
case "space":
// Toggle play/pause — always valid (may start a loaded episode)
emit("media.toggle", {});
break;
case "up":
emit("media.volumeUp", {});
break;
case "down":
emit("media.volumeDown", {});
break;
case "left":
if (!options.hasEpisode?.()) return;
emit("media.seekBackward", {});
break;
case "right":
if (!options.hasEpisode?.()) return;
emit("media.seekForward", {});
break;
case "s":
emit("media.speedCycle", {});
break;
default:
// Not a media key — do nothing
break;
}
});
}

View File

@@ -0,0 +1,115 @@
/**
* useScrollIntoView — keeps the ref'd row visible inside its enclosing
* `<scrollbox>` whenever the focus accessor is true.
*
* OpenTUI's `ScrollBoxRenderable` has built-in *keyboard* scrolling but does
* NOT auto-scroll to follow a programmatically-focused child (the app moves
* its own cursor via the yazi nav store, so the scrollbox never sees a key
* for row movement). Every scrollable panel therefore drifts out of view the
* moment the cursor crosses the viewport edge.
*
* Attach the returned `ref` callback to the element that represents the
* focused row of a scrollable list and call the hook with a `when()` that is
* true for exactly that row (e.g. `() => index() === focus()`). Whenever the
* accessor flips true, the nearest ScrollBoxRenderable is scrolled just enough
* to bring the element back into the viewport — a "nearest-edge" scroll:
* • scroll up only if the row's top is clipped above the viewport,
* • scroll down only if the row's bottom is clipped below the viewport,
* never snapping more than necessary (matches yazi list behaviour).
*
* Timing: for ordinary cursor movement (j/k) the list layout does not change
* — only background colour and the cursor glyph flip — so the focused row's
* Yoga-computed position is already valid when this effect fires, and the
* scroll is applied synchronously. On first mount / content population the
* layout for the new rows has not yet been computed, so the hook polls on a
* short timer until layout resolves (bounded so it can never loop forever).
*/
import { createEffect, onCleanup } from "solid-js";
/** Walk up the renderable parent chain to the nearest ScrollBoxRenderable,
* identified by its `viewport` + `content` + numeric `scrollTop`. */
function findScrollBox(node: any): any | null {
let p: any = node?.parent;
while (p) {
if (p.viewport && p.content && typeof p.scrollTop === "number") return p;
p = p.parent;
}
return null;
}
/** Maximum number of retries while waiting for Yoga layout to populate the
* row/viewport dimensions (handles the first-mount frame). */
const MAX_RETRIES = 12;
const RETRY_MS = 16;
export function useScrollIntoView(when: () => boolean) {
let el: any = null;
let timer: ReturnType<typeof setTimeout> | null = null;
const ref = (node: any) => {
el = node;
};
const clearTimer = () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
};
/** Compute the target scrollTop that brings `el` into the viewport of its
* enclosing scrollbox, or `null` if no scroll is possible / needed yet.
* Returns the decision so the caller knows whether to poll again. */
const compute = (): { scroll: number | null; ready: boolean } => {
const node = el;
if (!node) return { scroll: null, ready: false };
const sb = findScrollBox(node);
if (!sb) return { scroll: null, ready: false };
const vp = sb.viewport;
const top: number = sb.scrollTop ?? 0;
const vpH: number = vp?.height ?? 0;
// The scrollbar's onChange sets `content.translateY = -scrollTop`, so
// the child's cumulative `.y` already includes `-scrollTop`; subtracting
// the viewport's stable `.y` and re-adding `scrollTop` recovers the
// row's layout-space offset within the content (scroll-independent).
const childTop: number = node.y ?? 0;
const childH: number = node.height ?? 0;
if (!vpH || !childH) return { scroll: null, ready: false };
const offset = childTop - (vp.y ?? 0) + top;
let target = top;
if (offset < top) target = offset;
else if (offset + childH > top + vpH) target = offset + childH - vpH;
const max = Math.max(0, (sb.scrollHeight ?? 0) - vpH);
if (target > max) target = max;
if (target < 0) target = 0;
target = Math.round(target);
if (target === Math.round(top)) return { scroll: null, ready: true };
return { scroll: target, ready: true };
};
const tryScroll = (retriesLeft: number) => {
const { scroll, ready } = compute();
if (!ready) {
if (retriesLeft > 0)
timer = setTimeout(() => tryScroll(retriesLeft - 1), RETRY_MS);
return;
}
if (scroll != null) {
const sb = findScrollBox(el);
if (sb) sb.scrollTo(scroll);
}
clearTimer();
};
createEffect(() => {
if (!when()) return;
clearTimer();
tryScroll(MAX_RETRIES);
});
onCleanup(() => {
clearTimer();
});
return ref;
}

View File

@@ -1,36 +1,238 @@
// Hack: Force TERM to tmux-256color when running in tmux to enable const VERSION = "0.2.1";
// correct palette detection in @opentui/core
if (process.env.TMUX && !process.env.TERM?.includes("tmux")) { interface CliArgs {
process.env.TERM = "tmux-256color" version: boolean;
query: string | null;
play: string | null;
} }
import { render, useRenderer } from "@opentui/solid" function parseArgs(): CliArgs {
import { App } from "./App" const args = process.argv.slice(2);
import { ThemeProvider } from "./context/ThemeContext" const result: CliArgs = {
import { ToastProvider, Toast } from "./ui/toast" version: false,
import { KeybindProvider } from "./context/KeybindContext" query: null,
import { DialogProvider } from "./ui/dialog" play: null,
import { CommandProvider } from "./ui/command" };
function RendererSetup(props: { children: unknown }) { for (let i = 0; i < args.length; i++) {
const renderer = useRenderer() const arg = args[i];
renderer.disableStdoutInterception() if (arg === "--version" || arg === "-v") {
return props.children result.version = true;
} else if (arg === "--query" || arg === "-q") {
result.query = args[i + 1] || "";
i++;
} else if (arg === "--play" || arg === "-p") {
result.play = args[i + 1] || "";
i++;
}
}
return result;
} }
render(() => ( const cliArgs = parseArgs();
if (cliArgs.version) {
console.log(`PodTUI version ${VERSION}`);
process.exit(0);
}
if (cliArgs.query !== null || cliArgs.play !== null) {
import("./utils/feeds-persistence")
.then(async ({ loadFeedsFromFile }) => {
const feeds = await loadFeedsFromFile();
if (cliArgs.query !== null) {
const query = cliArgs.query;
const normalizedQuery = query.toLowerCase();
const matches = feeds.filter((feed) => {
const title = feed.podcast.title.toLowerCase();
return title.includes(normalizedQuery);
});
if (matches.length === 0) {
console.log(`No shows found matching: ${query}`);
if (feeds.length > 0) {
console.log("\nAvailable shows:");
feeds.slice(0, 5).forEach((feed) => {
console.log(` - ${feed.podcast.title}`);
});
if (feeds.length > 5) {
console.log(` ... and ${feeds.length - 5} more`);
}
}
process.exit(0);
}
if (matches.length === 1) {
const feed = matches[0];
console.log(`\n${feed.podcast.title}`);
if (feed.podcast.description) {
console.log(
feed.podcast.description.substring(0, 200) +
(feed.podcast.description.length > 200 ? "..." : ""),
);
}
console.log(
`\nRecent episodes (${Math.min(5, feed.episodes.length)}):`,
);
feed.episodes.slice(0, 5).forEach((ep, idx) => {
const date =
ep.pubDate instanceof Date
? ep.pubDate.toLocaleDateString()
: String(ep.pubDate);
console.log(` ${idx + 1}. ${ep.title} (${date})`);
});
process.exit(0);
}
console.log(`\nClosest matches for "${query}":`);
matches.slice(0, 5).forEach((feed, idx) => {
console.log(` ${idx + 1}. ${feed.podcast.title}`);
});
process.exit(0);
}
if (cliArgs.play !== null) {
const playArg = cliArgs.play;
const normalizedArg = playArg.toLowerCase();
let feedResult: (typeof feeds)[0] | null = null;
let episodeResult: (typeof feeds)[0]["episodes"][0] | null = null;
if (normalizedArg === "latest") {
let latestFeed: (typeof feeds)[0] | null = null;
let latestEpisode: (typeof feeds)[0]["episodes"][0] | null = null;
let latestDate = 0;
for (const feed of feeds) {
if (feed.episodes.length > 0) {
const ep = feed.episodes[0];
const epDate =
ep.pubDate instanceof Date
? ep.pubDate.getTime()
: Number(ep.pubDate);
if (epDate > latestDate) {
latestDate = epDate;
latestFeed = feed;
latestEpisode = ep;
}
}
}
feedResult = latestFeed;
episodeResult = latestEpisode;
} else {
const parts = normalizedArg.split("/");
const showQuery = parts[0];
const episodeQuery = parts[1];
const matchingFeeds = feeds.filter((feed) =>
feed.podcast.title.toLowerCase().includes(showQuery),
);
if (matchingFeeds.length === 0) {
console.log(`No show found matching: ${showQuery}`);
process.exit(1);
}
const feed = matchingFeeds[0];
if (!episodeQuery) {
if (feed.episodes.length > 0) {
feedResult = feed;
episodeResult = feed.episodes[0];
} else {
console.log(`No episodes available for: ${feed.podcast.title}`);
process.exit(1);
}
} else if (episodeQuery === "latest") {
feedResult = feed;
episodeResult = feed.episodes[0];
} else {
const matchingEpisode = feed.episodes.find((ep) =>
ep.title.toLowerCase().includes(episodeQuery),
);
if (matchingEpisode) {
feedResult = feed;
episodeResult = matchingEpisode;
} else {
console.log(`Episode not found: ${episodeQuery}`);
console.log(`Available episodes for ${feed.podcast.title}:`);
feed.episodes.slice(0, 5).forEach((ep, idx) => {
console.log(` ${idx + 1}. ${ep.title}`);
});
process.exit(1);
}
}
}
if (!feedResult || !episodeResult) {
console.log("Could not find episode to play");
process.exit(1);
}
console.log(`\nPlaying: ${episodeResult.title}`);
console.log(`Show: ${feedResult.podcast.title}`);
try {
const { createAudioBackend } = await import("./utils/audio-player");
const backend = createAudioBackend();
if (episodeResult.audioUrl) {
await backend.play(episodeResult.audioUrl);
console.log("Playback started (use the UI to control)");
} else {
console.log("No audio URL available for this episode");
process.exit(1);
}
} catch (err) {
console.error("Playback error:", err);
process.exit(1);
}
}
})
.catch((err) => {
console.error("Error:", err);
process.exit(1);
});
} else {
import("@opentui/solid").then(async ({ render, useRenderer }) => {
const { App } = await import("./App");
const { ThemeProvider } = await import("./context/ThemeContext");
const toast = await import("./ui/toast");
const { KeybindProvider } = await import("./context/KeybindContext");
const { NavigationProvider } = await import("./context/NavigationContext");
const { DialogProvider } = await import("./ui/dialog");
const { CommandProvider } = await import("./ui/command");
function RendererSetup(props: { children: unknown }) {
const renderer = useRenderer();
renderer.disableStdoutInterception();
return props.children;
}
render(
() => (
<RendererSetup> <RendererSetup>
<ToastProvider> <toast.ToastProvider>
<ThemeProvider mode="dark"> <ThemeProvider mode="dark">
<KeybindProvider> <KeybindProvider>
<NavigationProvider>
<DialogProvider> <DialogProvider>
<CommandProvider> <CommandProvider>
<App /> <App />
<Toast /> <toast.Toast />
</CommandProvider> </CommandProvider>
</DialogProvider> </DialogProvider>
</NavigationProvider>
</KeybindProvider> </KeybindProvider>
</ThemeProvider> </ThemeProvider>
</ToastProvider> </toast.ToastProvider>
</RendererSetup> </RendererSetup>
), { useThread: false }) ),
{ useThread: false },
);
});
}

BIN
src/native/libcavacore.dylib Executable file

Binary file not shown.

View File

@@ -0,0 +1,384 @@
/**
* DiscoverPage — yazi depth-stack view of discoverable podcasts.
*
* depth 0 (current) — category list. Parent pane shows the muted
* placeholder (1/7 slot kept).
* depth 1 (current) — podcast results for the drilled category. Parent
* pane = the categories list.
* preview — detail of the hovered item (category summary, or
* podcast detail + subscribe action).
*
* Renders entirely through `<PaneRow>`; no bespoke 3-column flexbox JSX
* remains. `l`/Enter drills in (category → results) or subscribes (on a
* podcast); `h` pops a depth (noop at 0). j/k move only within the current
* column. Moving through categories at depth 0 updates the store's selected
* category so the preview follows.
*/
import { createMemo, For, Show, onMount, onCleanup } from "solid-js";
import { useDiscoverStore, DISCOVER_CATEGORIES } from "@/stores/discover";
import { format } from "date-fns";
import { useTheme } from "@/context/ThemeContext";
import {
useNavigation,
NavMode,
DEPTH_CENTER_PANE,
type PaneId,
type DepthFrame,
} from "@/context/NavigationContext";
import { on, off } from "@/utils/event-bus";
import type { KeybindActionName } from "@/context/KeybindContext";
import { PaneRow } from "@/components/PaneRow";
import { TabListPane } from "@/components/TabPanel";
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
export const DiscoverPaneCount = 1;
function DiscoverPage() {
const discoverStore = useDiscoverStore();
const { theme } = useTheme();
const muted = () => theme.muted || theme.text;
const nav = useNavigation();
const depth = nav.currentDepth;
const focus = (d: number = depth()) => nav.depthFocus(d);
const categories = () => DISCOVER_CATEGORIES;
const podcasts = () => discoverStore.filteredPodcasts();
const focusedCatIdx = () =>
categories().length === 0 ? 0 : Math.min(focus(0), categories().length - 1);
const focusedCategory = createMemo(() => categories()[focusedCatIdx()]);
const focusedPodIdx = () =>
podcasts().length === 0 ? 0 : Math.min(focus(1), podcasts().length - 1);
const focusedPodcast = createMemo(() => podcasts()[focusedPodIdx()]);
const curLen = () =>
depth() === 0 ? categories().length : podcasts().length;
const ensureFocus = () => {
if (categories().length > 0 && focus(0) >= categories().length)
nav.setDepthFocus(categories().length - 1, 0);
if (podcasts().length > 0 && focus(1) >= podcasts().length)
nav.setDepthFocus(podcasts().length - 1, 1);
};
onMount(ensureFocus);
// Auto-fetch the featured-shows manifest on first mount (network failure is
// non-fatal — the list stays empty until the user hits refresh).
onMount(() => {
discoverStore.refresh().catch(() => {});
});
onMount(() => {
nav.registerResolver(`${nav.activeTab()}:${DEPTH_CENTER_PANE}`, (i) => {
if (depth() === 0) return categories()[i]?.id;
return podcasts()[i]?.id;
});
});
// ── helpers ────────────────────────────────────────────────────────────────
const formatDate = (d: Date) => format(d, "MMM d, yyyy");
// ── drill / open ───────────────────────────────────────────────────────────
function open() {
if (depth() === 0) {
const c = focusedCategory();
if (!c) return;
discoverStore.setSelectedCategory(c.id);
nav.pushDepth({ kind: "results", ctx: c.id, focus: 0 } as DepthFrame);
nav.setActivePane(DEPTH_CENTER_PANE);
return;
}
if (depth() >= 1) {
const pod = focusedPodcast();
if (pod) discoverStore.toggleSubscription(pod.id);
}
}
// ── nav.action handler ────────────────────────────────────────────────────
const PAGE_ACTIONS: Partial<Record<KeybindActionName, () => void>> = {
"move-down": () => step(1),
"move-up": () => step(-1),
"jump-down": () => step(5),
"jump-up": () => step(-5),
"page-down": () => step(10),
"page-up": () => step(-10),
"goto-top": () => nav.gotoIndex(0, curLen()),
"goto-bottom": () => nav.gotoIndex(curLen() - 1, curLen()),
open: () => open(),
"toggle-select": () => {
if (depth() >= 1) {
const pod = focusedPodcast();
if (pod) nav.toggleSelected(pod.id);
}
},
refresh: () => {
discoverStore.refresh().catch(() => {});
},
};
function step(delta: number) {
nav.move(delta, curLen());
// keep the store's selected category synced with the focused row at depth 0
if (depth() === 0) {
const c = focusedCategory();
if (c) discoverStore.setSelectedCategory(c.id);
}
}
const onAction = (data: {
action: KeybindActionName;
pane: PaneId;
mode: NavMode;
}) => {
if (data.pane !== DEPTH_CENTER_PANE) return;
if (nav.activePane() !== DEPTH_CENTER_PANE) return;
ensureFocus();
PAGE_ACTIONS[data.action]?.();
};
onMount(() => {
on("nav.action", onAction);
onCleanup(() => off("nav.action", onAction));
});
// ── render ──────────────────────────────────────────────────────────────────
const isActive = () => nav.activePane() === DEPTH_CENTER_PANE;
const focusBg = (i: number, lf: number, active: boolean) =>
i === lf && active ? theme.primary : i === lf ? theme.border : undefined;
const focusFg = (i: number, lf: number, active: boolean) =>
i === lf && active ? theme.surface : theme.text;
const currentLabel = () =>
depth() === 0
? "Categories"
: `${focusedCategory()?.name ?? "Discover"} · ${podcasts().length}`;
// ── parent pane: previous-depth list (muted/blank at depth 0) ─────────────
// ── parent pane: previous-depth list (muted/blank at depth 0) ──────────
// Stable <Show> gate (not a ternary root swap) so the parent list
// mounts/unmounts cleanly on depth change.
const parentContent = () => (
<Show when={depth() >= 1} fallback={<TabListPane muted />}>
<For each={categories()}>
{(cat, index) => {
const lf = () => nav.depthFocus(0);
const ref = useScrollIntoView(() => index() === lf());
return (
<box
ref={ref}
flexDirection="row"
gap={1}
paddingLeft={1}
paddingRight={1}
backgroundColor={focusBg(index(), lf(), false)}
>
<text fg={focusFg(index(), nav.depthFocus(0), false)}>
{index() === nav.depthFocus(0) ? "" : " "}
</text>
<text fg={focusFg(index(), nav.depthFocus(0), false)}>
{cat.name}
</text>
</box>
);
}}
</For>
</Show>
);
// ── current pane ───────────────────────────────────────────────────────────
const currentContent = () => (
<>
{/* depth 0: categories */}
<Show when={depth() === 0}>
<For each={categories()}>
{(cat, index) => {
const lf = () => focusedCatIdx();
const ref = useScrollIntoView(() => index() === lf());
return (
<box
ref={ref}
flexDirection="row"
gap={1}
paddingLeft={1}
paddingRight={1}
backgroundColor={focusBg(index(), lf(), isActive())}
onMouseDown={() => {
nav.setActivePane(DEPTH_CENTER_PANE);
nav.setDepthFocus(index(), 0);
discoverStore.setSelectedCategory(cat.id);
}}
>
<text fg={focusFg(index(), lf(), isActive())}>
{index() === lf() ? "" : " "}
</text>
<text fg={focusFg(index(), lf(), isActive())}>{cat.name}</text>
</box>
);
}}
</For>
</Show>
{/* depth ≥1: results */}
<Show when={depth() >= 1}>
<Show
when={podcasts().length > 0}
fallback={
<box padding={1}>
<text fg={muted()}>No podcasts found. :refresh</text>
</box>
}
>
<For each={podcasts()}>
{(podcast, index) => {
const lf = () => focusedPodIdx();
const ref = useScrollIntoView(() => index() === lf());
return (
<box
ref={ref}
flexDirection="column"
gap={0}
paddingLeft={1}
paddingRight={1}
backgroundColor={focusBg(index(), lf(), isActive())}
onMouseDown={() => {
nav.setActivePane(DEPTH_CENTER_PANE);
nav.setDepthFocus(index(), 1);
}}
>
<box flexDirection="row" gap={1}>
<text fg={focusFg(index(), lf(), isActive())}>
{index() === lf() ? "" : " "}
</text>
<text fg={focusFg(index(), lf(), isActive())}>
{podcast.title}
</text>
<Show when={podcast.isSubscribed}>
<text
fg={index() === lf() ? theme.surface : theme.success}
>
[+]
</text>
</Show>
</box>
<Show when={podcast.author}>
<text
fg={index() === lf() ? theme.surface : muted()}
paddingLeft={2}
>
by {podcast.author}
</text>
</Show>
</box>
);
}}
</For>
</Show>
</Show>
</>
);
// ── preview pane ───────────────────────────────────────────────────────────
const previewContent = () =>
depth() === 0 ? (
// depth 0 preview: shows for the hovered category
<Show
when={focusedCategory()}
fallback={
<box padding={1}>
<text fg={muted()}>No category focused</text>
</box>
}
>
{(cat) => (
<box flexDirection="column" gap={0} padding={1}>
<text fg={theme.textPrimary ?? theme.text}>
<strong>{cat().name}</strong>
</text>
<Show when={(cat() as any).description}>
<text fg={theme.textSecondary}>{(cat() as any).description}</text>
</Show>
<box height={1} />
<Show
when={podcasts().length > 0}
fallback={
<text fg={muted()}>
No shows in this category yet. :refresh
</text>
}
>
<For each={podcasts()}>
{(pod) => (
<box flexDirection="column" gap={0}>
<text fg={theme.text}>{pod.title}</text>
<Show when={pod.author}>
<text fg={muted()} paddingLeft={2}>
by {pod.author}
</text>
</Show>
</box>
)}
</For>
</Show>
</box>
)}
</Show>
) : (
// depth ≥1 preview: hovered podcast + subscribe
<Show
when={focusedPodcast()}
fallback={
<box padding={1}>
<text fg={muted()}>No podcast focused</text>
</box>
}
>
{(pod) => (
<box flexDirection="column" gap={1} padding={1}>
<text fg={theme.textPrimary ?? theme.text}>
<strong>{pod().title}</strong>
</text>
<Show when={pod().author}>
<text fg={muted()}>by {pod().author}</text>
</Show>
<Show when={pod().isSubscribed}>
<text fg={theme.success}> Subscribed</text>
</Show>
<Show when={!pod().isSubscribed}>
<text fg={theme.primary}>[+] Subscribe (enter)</text>
</Show>
<box height={1} />
<text fg={theme.textSecondary}>
{pod().description?.slice(0, 400) ?? "No description available."}
{(pod().description?.length ?? 0) > 400 ? "…" : ""}
</text>
<Show when={(pod().categories ?? []).length > 0}>
<box flexDirection="row" gap={1}>
<For each={(pod().categories ?? []).slice(0, 4)}>
{(cat) => <text fg={theme.warning}>[{cat}]</text>}
</For>
</box>
</Show>
<Show when={pod().feedUrl}>
<text fg={muted()}>Feed: {pod().feedUrl}</text>
</Show>
<text fg={muted()}>Updated: {formatDate(pod().lastUpdated)}</text>
<box height={1} />
<text fg={muted()}>enter: subscribe · h: back · r: refresh</text>
</box>
)}
</Show>
);
return (
<PaneRow
parent={parentContent}
current={currentContent}
preview={previewContent}
parentLabel={() => (depth() >= 1 ? "Categories" : "Up")}
currentLabel={currentLabel}
previewLabel="Detail"
focused={isActive}
/>
);
}
export { DiscoverPage };

View File

@@ -0,0 +1,85 @@
/**
* PodcastCard component - Reusable card for displaying podcast info
*/
import { Show, For } from "solid-js";
import type { Podcast } from "@/types/podcast";
import { useTheme } from "@/context/ThemeContext";
import { SelectableBox, SelectableText } from "@/components/Selectable";
type PodcastCardProps = {
podcast: Podcast;
selected: boolean;
compact?: boolean;
onSelect?: () => void;
onSubscribe?: () => void;
};
export function PodcastCard(props: PodcastCardProps) {
const { theme } = useTheme();
const handleSubscribeClick = () => {
props.onSubscribe?.();
};
return (
<SelectableBox
selected={() => props.selected}
flexDirection="column"
padding={1}
onMouseDown={props.onSelect}
>
<box flexDirection="row" gap={2} alignItems="center">
<SelectableText selected={() => props.selected} primary>
<strong>{props.podcast.title}</strong>
</SelectableText>
<Show when={props.podcast.isSubscribed}>
<text fg={theme.success}>[+]</text>
</Show>
</box>
{/* Author */}
<Show when={props.podcast.author && !props.compact}>
<SelectableText
selected={() => props.selected}
tertiary
>
by {props.podcast.author}
</SelectableText>
</Show>
{/* Description */}
<Show when={props.podcast.description && !props.compact}>
<SelectableText
selected={() => props.selected}
tertiary
>
{props.podcast.description!.length > 80
? props.podcast.description!.slice(0, 80) + "..."
: props.podcast.description}
</SelectableText>
</Show>
{/**<box
flexDirection="row"
justifyContent="space-between"
marginTop={props.compact ? 0 : 1}
/>**/}
<box flexDirection="row" gap={1}>
<Show when={(props.podcast.categories ?? []).length > 0}>
<For each={(props.podcast.categories ?? []).slice(0, 2)}>
{(cat) => <text fg={theme.warning}>[{cat}]</text>}
</For>
</Show>
</box>
<Show when={props.selected}>
<box onMouseDown={handleSubscribeClick}>
<text fg={props.podcast.isSubscribed ? theme.error : theme.success}>
{props.podcast.isSubscribed ? "[Unsubscribe]" : "[Subscribe]"}
</text>
</box>
</Show>
</SelectableBox>
);
}

View File

@@ -0,0 +1,194 @@
/**
* Feed detail view component for PodTUI
* Shows podcast info and episode list
*/
import { createSignal, For, Show } from "solid-js";
import { useKeyboard } from "@opentui/solid";
import type { Feed } from "@/types/feed";
import type { Episode } from "@/types/episode";
import { format } from "date-fns";
import { useTheme } from "@/context/ThemeContext";
import { SelectableBox, SelectableText } from "@/components/Selectable";
interface FeedDetailProps {
feed: Feed;
focused?: boolean;
onBack?: () => void;
onPlayEpisode?: (episode: Episode) => void;
}
export function FeedDetail(props: FeedDetailProps) {
const { theme } = useTheme();
const [selectedIndex, setSelectedIndex] = createSignal(0);
const [showInfo, setShowInfo] = createSignal(true);
const episodes = () => {
// Sort episodes by publication date (newest first)
return [...props.feed.episodes].sort(
(a, b) => b.pubDate.getTime() - a.pubDate.getTime(),
);
};
const formatDuration = (seconds: number): string => {
const mins = Math.floor(seconds / 60);
const hrs = Math.floor(mins / 60);
if (hrs > 0) {
return `${hrs}h ${mins % 60}m`;
}
return `${mins}m`;
};
const formatDate = (date: Date): string => {
return format(date, "MMM d, yyyy");
};
const handleKeyPress = (key: { name: string }) => {
const eps = episodes();
if (key.name === "escape" && props.onBack) {
props.onBack();
return;
}
if (key.name === "i") {
setShowInfo((v) => !v);
return;
}
if (key.name === "v") {
props.feed.podcast.onToggleVisibility?.(props.feed.id);
return;
}
if (key.name === "up" || key.name === "k") {
setSelectedIndex((i) => Math.max(0, i - 1));
} else if (key.name === "down" || key.name === "j") {
setSelectedIndex((i) => Math.min(eps.length - 1, i + 1));
} else if (key.name === "return") {
const episode = eps[selectedIndex()];
if (episode && props.onPlayEpisode) {
props.onPlayEpisode(episode);
}
} else if (key.name === "home" || key.name === "g") {
setSelectedIndex(0);
} else if (key.name === "end") {
setSelectedIndex(eps.length - 1);
} else if (key.name === "pageup") {
setSelectedIndex((i) => Math.max(0, i - 10));
} else if (key.name === "pagedown") {
setSelectedIndex((i) => Math.min(eps.length - 1, i + 10));
}
};
useKeyboard((key) => {
if (!props.focused) return;
handleKeyPress(key);
});
return (
<box flexDirection="column" gap={1}>
{/* Header with back button */}
<box flexDirection="row" justifyContent="space-between">
<box border padding={0} onMouseDown={props.onBack} borderColor={theme.border}>
<SelectableText selected={() => false} primary>[Esc] Back</SelectableText>
</box>
<box border padding={0} onMouseDown={() => setShowInfo((v) => !v)} borderColor={theme.border}>
<SelectableText selected={() => false} primary>[i] {showInfo() ? "Hide" : "Show"} Info</SelectableText>
</box>
<box border padding={0} onMouseDown={() => props.feed.podcast.onToggleVisibility?.(props.feed.id)} borderColor={theme.border}>
<SelectableText selected={() => false} primary>[v] Toggle Visibility</SelectableText>
</box>
</box>
{/* Podcast info section */}
<Show when={showInfo()}>
<box border padding={1} flexDirection="column" gap={0} borderColor={theme.border}>
<SelectableText selected={() => false} primary>
<strong>{props.feed.customName || props.feed.podcast.title}</strong>
</SelectableText>
{props.feed.podcast.author && (
<box flexDirection="row" gap={1}>
<SelectableText selected={() => false} tertiary>by</SelectableText>
<SelectableText selected={() => false} primary>{props.feed.podcast.author}</SelectableText>
</box>
)}
<box height={1} />
<SelectableText selected={() => false} tertiary>
{props.feed.podcast.description?.slice(0, 200)}
{(props.feed.podcast.description?.length || 0) > 200 ? "..." : ""}
</SelectableText>
<box height={1} />
<box flexDirection="row" gap={2}>
<box flexDirection="row" gap={1}>
<SelectableText selected={() => false} tertiary>Episodes:</SelectableText>
<SelectableText selected={() => false} tertiary>{props.feed.episodes.length}</SelectableText>
</box>
<box flexDirection="row" gap={1}>
<SelectableText selected={() => false} tertiary>Updated:</SelectableText>
<SelectableText selected={() => false} tertiary>{formatDate(props.feed.lastUpdated)}</SelectableText>
</box>
<SelectableText selected={() => false} tertiary>
{props.feed.visibility === "public" ? "[Public]" : "[Private]"}
</SelectableText>
{props.feed.isPinned && <SelectableText selected={() => false} tertiary>[Pinned]</SelectableText>}
</box>
<box flexDirection="row" gap={1}>
<SelectableText selected={() => false} tertiary>[v] Toggle Visibility</SelectableText>
</box>
</box>
</Show>
{/* Episodes header */}
<box flexDirection="row" justifyContent="space-between">
<SelectableText selected={() => false} primary>
<strong>Episodes</strong>
</SelectableText>
<SelectableText selected={() => false} tertiary>({episodes().length} total)</SelectableText>
</box>
{/* Episode list */}
<scrollbox height={showInfo() ? 10 : 15} focused={props.focused}>
<For each={episodes()}>
{(episode, index) => (
<SelectableBox
selected={() => index() === selectedIndex()}
flexDirection="column"
gap={0}
padding={1}
onMouseDown={() => {
setSelectedIndex(index());
if (props.onPlayEpisode) {
props.onPlayEpisode(episode);
}
}}
>
<SelectableText
selected={() => index() === selectedIndex()}
primary
>
{index() === selectedIndex() ? ">" : " "}
</SelectableText>
<SelectableText
selected={() => index() === selectedIndex()}
primary
>
{episode.episodeNumber ? `#${episode.episodeNumber} - ` : ""}
{episode.title}
</SelectableText>
<box flexDirection="row" gap={2} paddingLeft={2}>
<SelectableText selected={() => index() === selectedIndex()} tertiary>{formatDate(episode.pubDate)}</SelectableText>
<SelectableText selected={() => index() === selectedIndex()} tertiary>{formatDuration(episode.duration)}</SelectableText>
</box>
</SelectableBox>
)}
</For>
</scrollbox>
{/* Help text */}
<text fg={theme.textMuted}>
j/k to navigate, Enter to play, i to toggle info, Esc to go back
</text>
</box>
);
}

View File

@@ -0,0 +1,207 @@
/**
* Feed filter component for PodTUI
* Toggle and filter options for feed list
*/
import { createSignal } from "solid-js";
import { FeedVisibility, FeedSortField } from "@/types/feed";
import type { FeedFilter } from "@/types/feed";
import { useTheme } from "@/context/ThemeContext";
interface FeedFilterProps {
filter: FeedFilter;
focused?: boolean;
onFilterChange: (filter: FeedFilter) => void;
}
type FilterField = "visibility" | "sort" | "pinned" | "private" | "search";
export function FeedFilterComponent(props: FeedFilterProps) {
const { theme } = useTheme();
const [focusField, setFocusField] = createSignal<FilterField>("visibility");
const [searchValue, setSearchValue] = createSignal(
props.filter.searchQuery || "",
);
const fields: FilterField[] = ["visibility", "sort", "pinned", "private", "search"];
const handleKeyPress = (key: { name: string; shift?: boolean }) => {
if (key.name === "tab") {
const currentIndex = fields.indexOf(focusField());
const nextIndex = key.shift
? (currentIndex - 1 + fields.length) % fields.length
: (currentIndex + 1) % fields.length;
setFocusField(fields[nextIndex]);
} else if (key.name === "return") {
if (focusField() === "visibility") {
cycleVisibility();
} else if (focusField() === "sort") {
cycleSort();
} else if (focusField() === "pinned") {
togglePinned();
} else if (focusField() === "private") {
togglePrivate();
}
} else if (key.name === "space") {
if (focusField() === "pinned") {
togglePinned();
} else if (focusField() === "private") {
togglePrivate();
}
}
};
const cycleVisibility = () => {
const current = props.filter.visibility;
let next: FeedVisibility | "all";
if (current === "all") next = FeedVisibility.PUBLIC;
else if (current === FeedVisibility.PUBLIC) next = FeedVisibility.PRIVATE;
else next = "all";
props.onFilterChange({ ...props.filter, visibility: next });
};
const cycleSort = () => {
const sortOptions: FeedSortField[] = [
FeedSortField.UPDATED,
FeedSortField.TITLE,
FeedSortField.EPISODE_COUNT,
FeedSortField.LATEST_EPISODE,
];
const currentIndex = sortOptions.indexOf(
props.filter.sortBy as FeedSortField,
);
const nextIndex = (currentIndex + 1) % sortOptions.length;
props.onFilterChange({ ...props.filter, sortBy: sortOptions[nextIndex] });
};
const togglePinned = () => {
props.onFilterChange({
...props.filter,
pinnedOnly: !props.filter.pinnedOnly,
});
};
const togglePrivate = () => {
props.onFilterChange({
...props.filter,
showPrivate: !props.filter.showPrivate,
});
};
const handleSearchInput = (value: string) => {
setSearchValue(value);
props.onFilterChange({ ...props.filter, searchQuery: value });
};
const visibilityLabel = () => {
const vis = props.filter.visibility;
if (vis === "all") return "All";
if (vis === "public") return "Public";
return "Private";
};
const visibilityColor = () => {
const vis = props.filter.visibility;
if (vis === "public") return theme.success;
if (vis === "private") return theme.warning;
return theme.text;
};
const sortLabel = () => {
const sort = props.filter.sortBy;
switch (sort) {
case "title":
return "Title";
case "episodeCount":
return "Episodes";
case "latestEpisode":
return "Latest";
case "updated":
default:
return "Updated";
}
};
return (
<box flexDirection="column" border padding={1} gap={1} borderColor={theme.border}>
<text fg={theme.text}>
<strong>Filter Feeds</strong>
</text>
<box flexDirection="row" gap={2} flexWrap="wrap">
{/* Visibility filter */}
<box
border
padding={0}
backgroundColor={focusField() === "visibility" ? theme.backgroundElement : undefined}
borderColor={theme.border}
>
<box flexDirection="row" gap={1}>
<text fg={focusField() === "visibility" ? theme.primary : theme.textMuted}>
Show:
</text>
<text fg={visibilityColor()}>{visibilityLabel()}</text>
</box>
</box>
{/* Sort filter */}
<box
border
padding={0}
backgroundColor={focusField() === "sort" ? theme.backgroundElement : undefined}
>
<box flexDirection="row" gap={1}>
<text fg={focusField() === "sort" ? theme.primary : theme.textMuted}>Sort:</text>
<text fg={theme.text}>{sortLabel()}</text>
</box>
</box>
{/* Pinned filter */}
<box
border
padding={0}
backgroundColor={focusField() === "pinned" ? theme.backgroundElement : undefined}
>
<box flexDirection="row" gap={1}>
<text fg={focusField() === "pinned" ? theme.primary : theme.textMuted}>
Pinned:
</text>
<text fg={props.filter.pinnedOnly ? theme.warning : theme.textMuted}>
{props.filter.pinnedOnly ? "Yes" : "No"}
</text>
</box>
</box>
{/* Private filter */}
<box
border
padding={0}
backgroundColor={focusField() === "private" ? theme.backgroundElement : undefined}
>
<box flexDirection="row" gap={1}>
<text fg={focusField() === "private" ? theme.primary : theme.textMuted}>
Private:
</text>
<text fg={props.filter.showPrivate ? theme.warning : theme.textMuted}>
{props.filter.showPrivate ? "Yes" : "No"}
</text>
</box>
</box>
</box>
{/* Search box */}
<box flexDirection="row" gap={1}>
<text fg={focusField() === "search" ? theme.primary : theme.textMuted}>Search:</text>
<input
value={searchValue()}
onInput={handleSearchInput}
placeholder="Filter by name..."
focused={props.focused && focusField() === "search"}
width={25}
/>
</box>
<text fg={theme.textMuted}>Tab to navigate, Enter/Space to toggle</text>
</box>
);
}

154
src/pages/Feed/FeedItem.tsx Normal file
View File

@@ -0,0 +1,154 @@
/**
* Feed item component for PodTUI
* Displays a single feed/podcast in the list
*/
import type { Feed, FeedVisibility } from "@/types/feed";
import { format } from "date-fns";
import { useTheme } from "@/context/ThemeContext";
import { SelectableBox, SelectableText } from "@/components/Selectable";
interface FeedItemProps {
feed: Feed;
isSelected: boolean;
showEpisodeCount?: boolean;
showLastUpdated?: boolean;
compact?: boolean;
}
export function FeedItem(props: FeedItemProps) {
const formatDate = (date: Date): string => {
return format(date, "MMM d");
};
const episodeCount = () => props.feed.episodes.length;
const unplayedCount = () => {
// This would be calculated based on episode status
return props.feed.episodes.length;
};
const visibilityIcon = () => {
return props.feed.visibility === "public" ? "[P]" : "[*]";
};
const visibilityColor = () => {
return props.feed.visibility === "public" ? theme.success : theme.warning;
};
const pinnedIndicator = () => {
return props.feed.isPinned ? "*" : " ";
};
const { theme } = useTheme();
if (props.compact) {
// Compact single-line view
return (
<SelectableBox
selected={() => props.isSelected}
flexDirection="row"
gap={1}
paddingLeft={1}
paddingRight={1}
onMouseDown={() => {}}
>
<SelectableText
selected={() => props.isSelected}
primary
>
{props.isSelected ? ">" : " "}
</SelectableText>
<SelectableText
selected={() => props.isSelected}
tertiary
>
{visibilityIcon()}
</SelectableText>
<SelectableText
selected={() => props.isSelected}
primary
>
{props.feed.customName || props.feed.podcast.title}
</SelectableText>
{props.showEpisodeCount && (
<SelectableText
selected={() => props.isSelected}
tertiary
>
({episodeCount()})
</SelectableText>
)}
</SelectableBox>
);
}
// Full view with details
return (
<SelectableBox
selected={() => props.isSelected}
flexDirection="column"
gap={0}
padding={1}
onMouseDown={() => {}}
>
{/* Title row */}
<box flexDirection="row" gap={1}>
<SelectableText
selected={() => props.isSelected}
primary
>
{props.isSelected ? ">" : " "}
</SelectableText>
<SelectableText
selected={() => props.isSelected}
tertiary
>
{visibilityIcon()}
</SelectableText>
<SelectableText
selected={() => props.isSelected}
secondary
>
{pinnedIndicator()}
</SelectableText>
<SelectableText
selected={() => props.isSelected}
primary
>
<strong>{props.feed.customName || props.feed.podcast.title}</strong>
</SelectableText>
</box>
<box flexDirection="row" gap={2} paddingLeft={4}>
{props.showEpisodeCount && (
<SelectableText
selected={() => props.isSelected}
tertiary
>
{episodeCount()} episodes ({unplayedCount()} new)
</SelectableText>
)}
{props.showLastUpdated && (
<SelectableText
selected={() => props.isSelected}
tertiary
>
Updated: {formatDate(props.feed.lastUpdated)}
</SelectableText>
)}
</box>
{props.feed.podcast.description && (
<SelectableText
selected={() => props.isSelected}
paddingLeft={4}
paddingTop={0}
tertiary
>
{props.feed.podcast.description.slice(0, 60)}
{props.feed.podcast.description.length > 60 ? "..." : ""}
</SelectableText>
)}
</SelectableBox>
);
}

198
src/pages/Feed/FeedList.tsx Normal file
View File

@@ -0,0 +1,198 @@
/**
* Feed list component for PodTUI
* Scrollable list of feeds with keyboard navigation and mouse support
*/
import { createSignal, For, Show } from "solid-js";
import { useKeyboard } from "@opentui/solid";
import { FeedItem } from "./FeedItem";
import { useFeedStore } from "@/stores/feed";
import { FeedVisibility, FeedSortField } from "@/types/feed";
import type { Feed } from "@/types/feed";
import { useTheme } from "@/context/ThemeContext";
interface FeedListProps {
focused?: boolean;
compact?: boolean;
showEpisodeCount?: boolean;
showLastUpdated?: boolean;
onSelectFeed?: (feed: Feed) => void;
onOpenFeed?: (feed: Feed) => void;
onFocusChange?: (focused: boolean) => void;
}
export function FeedList(props: FeedListProps) {
const { theme } = useTheme();
const feedStore = useFeedStore();
const [selectedIndex, setSelectedIndex] = createSignal(0);
const filteredFeeds = () => feedStore.getFilteredFeeds();
const handleKeyPress = (key: { name: string }) => {
if (key.name === "escape") {
props.onFocusChange?.(false);
return;
}
const feeds = filteredFeeds();
if (key.name === "up" || key.name === "k") {
setSelectedIndex((i) => Math.max(0, i - 1));
} else if (key.name === "down" || key.name === "j") {
setSelectedIndex((i) => Math.min(feeds.length - 1, i + 1));
} else if (key.name === "return") {
const feed = feeds[selectedIndex()];
if (feed && props.onOpenFeed) {
props.onOpenFeed(feed);
}
} else if (key.name === "home" || key.name === "g") {
setSelectedIndex(0);
} else if (key.name === "end") {
setSelectedIndex(feeds.length - 1);
} else if (key.name === "pageup") {
setSelectedIndex((i) => Math.max(0, i - 5));
} else if (key.name === "pagedown") {
setSelectedIndex((i) => Math.min(feeds.length - 1, i + 5));
} else if (key.name === "p") {
// Toggle pin on selected feed
const feed = feeds[selectedIndex()];
if (feed) {
feedStore.togglePinned(feed.id);
}
} else if (key.name === "v") {
// Toggle visibility on selected feed
const feed = feeds[selectedIndex()];
if (feed) {
const newVisibility = feed.visibility === FeedVisibility.PUBLIC ? FeedVisibility.PRIVATE : FeedVisibility.PUBLIC;
feedStore.updateFeed(feed.id, { visibility: newVisibility });
}
} else if (key.name === "f") {
// Cycle visibility filter
cycleVisibilityFilter();
} else if (key.name === "s") {
// Cycle sort
cycleSortField();
}
// Notify selection change
const selectedFeed = feeds[selectedIndex()];
if (selectedFeed && props.onSelectFeed) {
props.onSelectFeed(selectedFeed);
}
};
useKeyboard((key) => {
if (!props.focused) return;
handleKeyPress(key);
});
const cycleVisibilityFilter = () => {
const current = feedStore.filter().visibility;
let next: FeedVisibility | "all";
if (current === "all") next = FeedVisibility.PUBLIC;
else if (current === FeedVisibility.PUBLIC) next = FeedVisibility.PRIVATE;
else next = "all";
feedStore.setFilter({ ...feedStore.filter(), visibility: next });
};
const cycleSortField = () => {
const sortOptions: FeedSortField[] = [
FeedSortField.UPDATED,
FeedSortField.TITLE,
FeedSortField.EPISODE_COUNT,
FeedSortField.LATEST_EPISODE,
];
const current = feedStore.filter().sortBy as FeedSortField;
const idx = sortOptions.indexOf(current);
const next = sortOptions[(idx + 1) % sortOptions.length];
feedStore.setFilter({ ...feedStore.filter(), sortBy: next });
};
const visibilityLabel = () => {
const vis = feedStore.filter().visibility;
if (vis === "all") return "All";
if (vis === "public") return "Public";
return "Private";
};
const sortLabel = () => {
const sort = feedStore.filter().sortBy;
switch (sort) {
case "title":
return "Title";
case "episodeCount":
return "Episodes";
case "latestEpisode":
return "Latest";
default:
return "Updated";
}
};
const handleFeedClick = (feed: Feed, index: number) => {
setSelectedIndex(index);
if (props.onSelectFeed) {
props.onSelectFeed(feed);
}
};
const handleFeedDoubleClick = (feed: Feed) => {
if (props.onOpenFeed) {
props.onOpenFeed(feed);
}
};
return (
<box flexDirection="column" gap={1}>
{/* Header with filter controls */}
<box flexDirection="row" justifyContent="space-between" paddingBottom={0}>
<text fg={theme.text}>
<strong>My Feeds</strong>
</text>
<text fg={theme.textMuted}>({filteredFeeds().length} feeds)</text>
<box flexDirection="row" gap={1}>
<box border padding={0} onMouseDown={cycleVisibilityFilter} borderColor={theme.border}>
<text fg={theme.primary}>[f] {visibilityLabel()}</text>
</box>
<box border padding={0} onMouseDown={cycleSortField} borderColor={theme.border}>
<text fg={theme.primary}>[s] {sortLabel()}</text>
</box>
</box>
</box>
{/* Feed list in scrollbox */}
<Show
when={filteredFeeds().length > 0}
fallback={
<box border padding={2} borderColor={theme.border}>
<text fg={theme.textMuted}>
No feeds found. Add podcasts from the Discover or Search tabs.
</text>
</box>
}
>
<scrollbox height={15} focused={props.focused}>
<For each={filteredFeeds()}>
{(feed, index) => (
<box onMouseDown={() => handleFeedClick(feed, index())}>
<FeedItem
feed={feed}
isSelected={index() === selectedIndex()}
compact={props.compact}
showEpisodeCount={props.showEpisodeCount ?? true}
showLastUpdated={props.showLastUpdated ?? true}
/>
</box>
)}
</For>
</scrollbox>
</Show>
{/* Navigation help */}
<box paddingTop={0}>
<text fg={theme.textMuted}>
Enter open | Esc up | j/k navigate | p pin | f filter | s sort
</text>
</box>
</box>
);
}

308
src/pages/Feed/FeedPage.tsx Normal file
View File

@@ -0,0 +1,308 @@
/**
* FeedPage — flat chronological list of episodes across all subscribed feeds.
*
* depth 0 (current) — every episode from every feed, newest-first (the
* combined view the old "All Feeds" virtual row used to
* drill into). Parent pane shows the muted tab list.
* preview — detail of the hovered episode.
*
* This page does NOT drill: the previous depth-1 "episodes of one feed" panel
* duplicated My Shows (shows → episodes). Per design, the Feed tab now just
* shows the full flat episodes list immediately.
*
* Renders entirely through `<PaneRow>` (the shared parent|current|preview
* primitive). `l`/Enter plays the focused episode; `h` pops back to the tab
* root. j/k move only within the current column. The Shell router drives
* everything over `nav.action`; this page only handles list/preview data.
*/
import { createMemo, For, Show, onMount, onCleanup } from "solid-js";
import { useFeedStore } from "@/stores/feed";
import { useDownloadStore } from "@/stores/download";
import { DownloadStatus } from "@/types/episode";
import { format } from "date-fns";
import { useTheme } from "@/context/ThemeContext";
import { useAudioNavStore, AudioSource } from "@/stores/audio-nav";
import {
useNavigation,
NavMode,
DEPTH_CENTER_PANE,
type PaneId,
} from "@/context/NavigationContext";
import { useAudio } from "@/hooks/useAudio";
import { on, off } from "@/utils/event-bus";
import type { KeybindActionName } from "@/context/KeybindContext";
import type { Episode } from "@/types/episode";
import type { Feed } from "@/types/feed";
import { LoadingIndicator } from "@/components/LoadingIndicator";
import { PaneRow } from "@/components/PaneRow";
import { TabListPane } from "@/components/TabPanel";
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
export const FeedPaneCount = 1;
type EpItem = { episode: Episode; feed: Feed };
function FeedPage() {
const feedStore = useFeedStore();
const downloadStore = useDownloadStore();
const audioNav = useAudioNavStore();
const audio = useAudio();
const { theme } = useTheme();
const muted = () => theme.muted || theme.text;
const nav = useNavigation();
// ── flat episode list (depth 0 — the only depth Feed has) ────────────────
const episodes = createMemo<EpItem[]>(
() => feedStore.getAllEpisodesChronological() as EpItem[],
);
const focus = () => nav.depthFocus(0);
const focusedEpIdx = () =>
episodes().length === 0 ? 0 : Math.min(focus(), episodes().length - 1);
const focusedItem = (): EpItem | undefined => episodes()[focusedEpIdx()];
const curLen = () => episodes().length;
const ensureFocus = () => {
if (episodes().length > 0 && focus() >= episodes().length)
nav.setDepthFocus(episodes().length - 1, 0);
};
onMount(ensureFocus);
onMount(() => {
nav.registerResolver(
`${nav.activeTab()}:${DEPTH_CENTER_PANE}`,
(i) => episodes()[i]?.episode.id,
);
});
// ── helpers ────────────────────────────────────────────────────────────────
const formatDate = (d: Date) => format(d, "MMM d, yyyy");
const formatDuration = (s: number) => {
const mins = Math.floor(s / 60);
const hrs = Math.floor(mins / 60);
return hrs > 0 ? `${hrs}h ${mins % 60}m` : `${mins}m`;
};
const downloadLabel = (id: string) => {
switch (downloadStore.getDownloadStatus(id)) {
case DownloadStatus.QUEUED:
return "[Q]";
case DownloadStatus.DOWNLOADING:
return `[${downloadStore.getDownloadProgress(id)}%]`;
case DownloadStatus.COMPLETED:
return "[DL]";
case DownloadStatus.FAILED:
return "[ERR]";
default:
return "";
}
};
const downloadColor = (id: string) => {
switch (downloadStore.getDownloadStatus(id)) {
case DownloadStatus.QUEUED:
return theme.warning;
case DownloadStatus.DOWNLOADING:
return theme.primary;
case DownloadStatus.COMPLETED:
return theme.success;
case DownloadStatus.FAILED:
return theme.error;
default:
return muted();
}
};
const playEpisode = (item: EpItem | undefined) => {
if (!item) return;
audio.play(item.episode).catch(() => {});
audioNav.setSource(AudioSource.FEED);
};
// ── open ───────────────────────────────────────────────────────────────────
function open() {
playEpisode(focusedItem());
}
// ── nav.action handler ────────────────────────────────────────────────────
const PAGE_ACTIONS: Partial<Record<KeybindActionName, () => void>> = {
"move-down": () => step(1),
"move-up": () => step(-1),
"jump-down": () => step(5),
"jump-up": () => step(-5),
"page-down": () => step(10),
"page-up": () => step(-10),
"goto-top": () => nav.gotoIndex(0, curLen()),
"goto-bottom": () => nav.gotoIndex(curLen() - 1, curLen()),
open: () => open(),
"toggle-select": () => {
const item = focusedItem();
if (item) nav.toggleSelected(item.episode.id);
},
refresh: () => {
feedStore.refreshAllFeeds().catch(() => {});
},
};
function step(delta: number) {
nav.move(delta, curLen());
}
const onAction = (data: {
action: KeybindActionName;
pane: PaneId;
mode: NavMode;
}) => {
if (data.pane !== DEPTH_CENTER_PANE) return;
if (nav.activePane() !== DEPTH_CENTER_PANE) return;
ensureFocus();
PAGE_ACTIONS[data.action]?.();
};
onMount(() => {
on("nav.action", onAction);
onCleanup(() => off("nav.action", onAction));
});
// ── render ──────────────────────────────────────────────────────────────────
const isActive = () => nav.activePane() === DEPTH_CENTER_PANE;
// Row highlight within the list. `active=true` only for the current pane.
const focusBg = (i: number, listFocus: number, active: boolean) =>
i === listFocus && active
? theme.primary
: i === listFocus
? theme.border
: undefined;
const focusFg = (i: number, listFocus: number, active: boolean) =>
i === listFocus && active ? theme.surface : theme.text;
const currentLabel = () => `Feed · ${episodes().length}`;
// ── parent pane: muted tab list (no parent list — Feed is one depth) ──────
const parentContent = () => <TabListPane muted />;
// ── current pane: the flat episodes list (the only focusable column) ──────
const currentContent = () => (
<Show
when={episodes().length > 0}
fallback={
<box padding={1}>
<text fg={muted()}>No feeds. Subscribe from Discover/Search.</text>
</box>
}
>
<For each={episodes()}>
{(item, index) => {
const fi = () => focusedEpIdx();
const ref = useScrollIntoView(() => index() === fi());
return (
<box
ref={ref}
flexDirection="column"
gap={0}
paddingLeft={1}
paddingRight={1}
backgroundColor={focusBg(index(), fi(), isActive())}
onMouseDown={() => {
nav.setActivePane(DEPTH_CENTER_PANE);
nav.setDepthFocus(index(), 0);
}}
>
<box flexDirection="row" gap={1}>
<text fg={focusFg(index(), fi(), isActive())}>
{index() === fi() ? "" : " "}
</text>
<text fg={focusFg(index(), fi(), isActive())}>
{item.episode.episodeNumber
? `#${item.episode.episodeNumber} `
: ""}
{item.episode.title}
</text>
</box>
<box flexDirection="row" gap={2} paddingLeft={2}>
<text fg={index() === fi() ? theme.surface : theme.info}>
{formatDate(item.episode.pubDate)}
</text>
<text fg={index() === fi() ? theme.surface : muted()}>
{formatDuration(item.episode.duration)}
</text>
<text fg={index() === fi() ? theme.surface : muted()}>
{item.feed.customName || item.feed.podcast.title}
</text>
<Show when={nav.isSelected(item.episode.id)}>
<text fg={theme.warning}></text>
</Show>
<Show when={downloadLabel(item.episode.id)}>
<text fg={downloadColor(item.episode.id)}>
{downloadLabel(item.episode.id)}
</text>
</Show>
</box>
</box>
);
}}
</For>
<Show when={feedStore.isLoadingFeeds()}>
<box paddingLeft={2} paddingTop={1}>
<LoadingIndicator />
</box>
</Show>
</Show>
);
// ── preview pane: hovered-episode detail ───────────────────────────────────
const previewContent = () => (
<Show
when={focusedItem()}
fallback={
<box padding={1}>
<text fg={muted()}>No episode focused</text>
</box>
}
>
{(item) => (
<box flexDirection="column" gap={1} padding={1}>
<text fg={theme.textPrimary ?? theme.text}>
<strong>
{item().episode.episodeNumber
? `#${item().episode.episodeNumber} `
: ""}
{item().episode.title}
</strong>
</text>
<box flexDirection="row" gap={2}>
<text fg={theme.info}>{formatDate(item().episode.pubDate)}</text>
<text fg={muted()}>{formatDuration(item().episode.duration)}</text>
<Show when={downloadLabel(item().episode.id)}>
<text fg={downloadColor(item().episode.id)}>
{downloadLabel(item().episode.id)}
</text>
</Show>
</box>
<text fg={muted()}>
{item().feed.customName || item().feed.podcast.title}
</text>
<Show when={item().feed.podcast.author}>
<text fg={muted()}>by {item().feed.podcast.author}</text>
</Show>
<box height={1} />
<text fg={theme.textSecondary}>
{item().episode.description?.slice(0, 400) ??
"No description available."}
{(item().episode.description?.length ?? 0) > 400 ? "…" : ""}
</text>
<box height={1} />
<text fg={muted()}>enter: play · space: select · h back</text>
</box>
)}
</Show>
);
return (
<PaneRow
parent={parentContent}
current={currentContent}
preview={previewContent}
parentLabel="Up"
currentLabel={currentLabel}
previewLabel="Detail"
focused={isActive}
/>
);
}
export { FeedPage };

View File

@@ -0,0 +1,438 @@
/**
* MyShowsPage — yazi depth-stack view of subscribed shows.
*
* depth 0 (current) — subscribed shows. Parent pane shows the muted
* placeholder (1/7 slot kept).
* depth 1 (current) — episodes of the drilled show. Parent pane = shows.
* preview — detail of the hovered item in the current column.
*
* Renders entirely through `<PaneRow>`; no bespoke 3-column flexbox JSX
* remains. `l`/Enter drills in (show → episodes); `h` pops a depth (noop at
* 0). j/k move only within the current column.
*/
import { createMemo, For, Show, onMount, onCleanup } from "solid-js";
import { useFeedStore } from "@/stores/feed";
import { useDownloadStore } from "@/stores/download";
import { DownloadStatus } from "@/types/episode";
import { format } from "date-fns";
import { useTheme } from "@/context/ThemeContext";
import { useAudioNavStore, AudioSource } from "@/stores/audio-nav";
import {
useNavigation,
NavMode,
DEPTH_CENTER_PANE,
type PaneId,
type DepthFrame,
} from "@/context/NavigationContext";
import { useAudio } from "@/hooks/useAudio";
import { on, off } from "@/utils/event-bus";
import type { KeybindActionName } from "@/context/KeybindContext";
import type { Episode } from "@/types/episode";
import type { Feed } from "@/types/feed";
import { LoadingIndicator } from "@/components/LoadingIndicator";
import { PaneRow } from "@/components/PaneRow";
import { TabListPane } from "@/components/TabPanel";
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
export const MyShowsPaneCount = 1;
export function MyShowsPage() {
const feedStore = useFeedStore();
const downloadStore = useDownloadStore();
const audioNav = useAudioNavStore();
const audio = useAudio();
const { theme } = useTheme();
const muted = () => theme.muted || theme.text;
const nav = useNavigation();
const stack = nav.depthStack;
const depth = nav.currentDepth;
const focus = (d: number = depth()) => nav.depthFocus(d);
const shows = () => feedStore.getFilteredFeeds();
const focusedShowIdx = () =>
shows().length === 0 ? 0 : Math.min(focus(0), shows().length - 1);
const selectedShow = (): Feed | undefined => shows()[focusedShowIdx()];
// depth-1 frame ctx = the drilled feed id
const drilledShowId = (): string => stack()[1]?.ctx ?? "";
const episodes = createMemo<Episode[]>(() => {
if (depth() < 1) return [];
const id = drilledShowId();
const show = shows().find((s) => s.id === id);
if (!show) return [];
return [...show.episodes].sort(
(a, b) => b.pubDate.getTime() - a.pubDate.getTime(),
);
});
const focusedEpIdx = () =>
episodes().length === 0 ? 0 : Math.min(focus(1), episodes().length - 1);
const focusedEpisode = () => episodes()[focusedEpIdx()];
const curLen = () => (depth() === 0 ? shows().length : episodes().length);
const ensureFocus = () => {
if (shows().length > 0 && focus(0) >= shows().length)
nav.setDepthFocus(shows().length - 1, 0);
if (depth() >= 1 && episodes().length > 0 && focus(1) >= episodes().length)
nav.setDepthFocus(episodes().length - 1, 1);
};
onMount(ensureFocus);
onMount(() => {
nav.registerResolver(`${nav.activeTab()}:${DEPTH_CENTER_PANE}`, (i) => {
if (depth() === 0) return shows()[i]?.id;
return episodes()[i]?.id;
});
});
// ── helpers ─────────────────────────────────────────────────────────────────
const formatDate = (d: Date) => format(d, "MMM d, yyyy");
const formatDuration = (s: number) => {
const mins = Math.floor(s / 60);
const hrs = Math.floor(mins / 60);
return hrs > 0 ? `${hrs}h ${mins % 60}m` : `${mins}m`;
};
const downloadLabel = (id: string) => {
switch (downloadStore.getDownloadStatus(id)) {
case DownloadStatus.QUEUED:
return "[Q]";
case DownloadStatus.DOWNLOADING:
return `[${downloadStore.getDownloadProgress(id)}%]`;
case DownloadStatus.COMPLETED:
return "[DL]";
case DownloadStatus.FAILED:
return "[ERR]";
default:
return "";
}
};
const downloadColor = (id: string) => {
switch (downloadStore.getDownloadStatus(id)) {
case DownloadStatus.QUEUED:
return theme.warning;
case DownloadStatus.DOWNLOADING:
return theme.primary;
case DownloadStatus.COMPLETED:
return theme.success;
case DownloadStatus.FAILED:
return theme.error;
default:
return muted();
}
};
const playEpisode = (ep: Episode) => {
audio.play(ep).catch(() => {});
audioNav.setSource(AudioSource.MY_SHOWS, selectedShow()?.podcast.id);
};
// ── drill / open ───────────────────────────────────────────────────────────
function open() {
if (depth() === 0) {
const show = selectedShow();
if (!show) return;
nav.pushDepth({ kind: "episodes", ctx: show.id, focus: 0 } as DepthFrame);
nav.setActivePane(DEPTH_CENTER_PANE);
audioNav.setSource(AudioSource.MY_SHOWS, show.podcast.id);
return;
}
if (depth() >= 1) {
const ep = focusedEpisode();
if (ep) playEpisode(ep);
}
}
// ── nav.action ──────────────────────────────────────────────────────────────
const PAGE_ACTIONS: Partial<Record<KeybindActionName, () => void>> = {
"move-down": () => step(1),
"move-up": () => step(-1),
"jump-down": () => step(5),
"jump-up": () => step(-5),
"page-down": () => step(10),
"page-up": () => step(-10),
"goto-top": () => nav.gotoIndex(0, curLen()),
"goto-bottom": () => nav.gotoIndex(curLen() - 1, curLen()),
open: () => open(),
"toggle-select": () => {
if (depth() >= 1) {
const ep = focusedEpisode();
if (ep) nav.toggleSelected(ep.id);
}
},
refresh: () => {
const show = selectedShow();
if (show) feedStore.refreshFeed(show.id).catch(() => {});
},
unsubscribe: () => {
if (depth() !== 0) return;
const show = selectedShow();
if (show) {
// unsubscribe = remove feed + purge its downloaded files
feedStore.removeFeed(show.id);
downloadStore.removeDownloadsForFeed(show.id).catch(() => {});
ensureFocus();
}
},
};
function step(delta: number) {
nav.move(delta, curLen());
}
const onAction = (data: {
action: KeybindActionName;
pane: PaneId;
mode: NavMode;
}) => {
if (data.pane !== DEPTH_CENTER_PANE) return;
if (nav.activePane() !== DEPTH_CENTER_PANE) return;
ensureFocus();
PAGE_ACTIONS[data.action]?.();
};
onMount(() => {
on("nav.action", onAction);
onCleanup(() => off("nav.action", onAction));
});
// ── render ──────────────────────────────────────────────────────────────────
const isActive = () => nav.activePane() === DEPTH_CENTER_PANE;
const focusBg = (i: number, lf: number, active: boolean) =>
i === lf && active ? theme.primary : i === lf ? theme.border : undefined;
const focusFg = (i: number, lf: number, active: boolean) =>
i === lf && active ? theme.surface : theme.text;
const showTitle = (f: Feed) => f.customName || f.podcast.title;
const currentLabel = () =>
depth() === 0
? `Shows (${shows().length})`
: `${selectedShow() ? showTitle(selectedShow()!) : "Episodes"} · ${episodes().length}`;
// ── parent pane: previous-depth list (muted/blank at depth 0) ─────────────
// ── parent pane: previous-depth list (muted/blank at depth 0) ──────────
// Stable <Show> gate (not a ternary root swap) so the parent list
// mounts/unmounts cleanly on depth change.
const parentContent = () => (
<Show when={depth() >= 1} fallback={<TabListPane muted />}>
<For each={shows()}>
{(feed, index) => {
const lf = () => nav.depthFocus(0);
const ref = useScrollIntoView(() => index() === lf());
return (
<box
ref={ref}
flexDirection="row"
gap={1}
paddingLeft={1}
paddingRight={1}
backgroundColor={focusBg(index(), lf(), false)}
>
<text fg={focusFg(index(), lf(), false)}>
{index() === lf() ? "" : " "}
</text>
<text fg={focusFg(index(), lf(), false)}>{showTitle(feed)}</text>
<text fg={muted()}>({feed.episodes.length})</text>
</box>
);
}}
</For>
</Show>
);
// ── current pane: the current-depth list ───────────────────────────────────
const currentContent = () => (
<>
{/* depth 0: shows — stable sibling <Show> so the swap disposes cleanly */}
<Show when={depth() === 0}>
<Show
when={shows().length > 0}
fallback={
<box padding={1}>
<text fg={muted()}>
No shows. Subscribe from Discover/Search.
</text>
</box>
}
>
<For each={shows()}>
{(feed, index) => {
const lf = () => focusedShowIdx();
const ref = useScrollIntoView(() => index() === lf());
return (
<box
ref={ref}
flexDirection="row"
gap={1}
paddingLeft={1}
paddingRight={1}
backgroundColor={focusBg(index(), lf(), isActive())}
onMouseDown={() => {
nav.setActivePane(DEPTH_CENTER_PANE);
nav.setDepthFocus(index(), 0);
}}
>
<text fg={focusFg(index(), lf(), isActive())}>
{index() === lf() ? "" : " "}
</text>
<text fg={focusFg(index(), lf(), isActive())}>
{showTitle(feed)}
</text>
<text fg={index() === lf() ? theme.surface : muted()}>
({feed.episodes.length})
</text>
</box>
);
}}
</For>
</Show>
</Show>
{/* depth ≥1: episodes */}
<Show when={depth() >= 1}>
<Show
when={episodes().length > 0}
fallback={
<box padding={1}>
<text fg={muted()}>No episodes. :refresh</text>
</box>
}
>
<For each={episodes()}>
{(ep, index) => {
const lf = () => focusedEpIdx();
const ref = useScrollIntoView(() => index() === lf());
return (
<box
ref={ref}
flexDirection="column"
gap={0}
paddingLeft={1}
paddingRight={1}
backgroundColor={focusBg(index(), lf(), isActive())}
onMouseDown={() => {
nav.setActivePane(DEPTH_CENTER_PANE);
nav.setDepthFocus(index(), 1);
}}
>
<box flexDirection="row" gap={1}>
<text fg={focusFg(index(), lf(), isActive())}>
{index() === lf() ? "" : " "}
</text>
<text fg={focusFg(index(), lf(), isActive())}>
{ep.episodeNumber ? `#${ep.episodeNumber} ` : ""}
{ep.title}
</text>
</box>
<box flexDirection="row" gap={2} paddingLeft={2}>
<text fg={index() === lf() ? theme.surface : theme.info}>
{formatDate(ep.pubDate)}
</text>
<text fg={index() === lf() ? theme.surface : muted()}>
{formatDuration(ep.duration)}
</text>
<Show when={nav.isSelected(ep.id)}>
<text fg={theme.warning}></text>
</Show>
<Show when={downloadLabel(ep.id)}>
<text fg={downloadColor(ep.id)}>
{downloadLabel(ep.id)}
</text>
</Show>
</box>
</box>
);
}}
</For>
<Show when={feedStore.isLoadingMore()}>
<box paddingLeft={2} paddingTop={1}>
<LoadingIndicator />
</box>
</Show>
</Show>
</Show>
</>
);
// ── preview pane ───────────────────────────────────────────────────────────
const previewContent = () =>
depth() === 0 ? (
// depth 0 preview: hovered show
<Show
when={selectedShow()}
fallback={
<box padding={1}>
<text fg={muted()}>No show focused</text>
</box>
}
>
{(show) => (
<box flexDirection="column" gap={1} padding={1}>
<text fg={theme.textPrimary ?? theme.text}>
<strong>{showTitle(show())}</strong>
</text>
<Show when={show().podcast.author}>
<text fg={muted()}>by {show().podcast.author}</text>
</Show>
<text fg={theme.textSecondary}>
{show().episodes.length} episodes
</text>
<text fg={muted()}>
{show().podcast.description?.slice(0, 400) ?? "No description."}
</text>
<box height={1} />
<text fg={muted()}>enter/l: open · h: back · x: unsubscribe</text>
</box>
)}
</Show>
) : (
// depth ≥1 preview: hovered episode
<Show
when={focusedEpisode()}
fallback={
<box padding={1}>
<text fg={muted()}>No episode focused</text>
</box>
}
>
{(ep) => (
<box flexDirection="column" gap={1} padding={1}>
<text fg={theme.textPrimary ?? theme.text}>
<strong>
{ep().episodeNumber ? `#${ep().episodeNumber} ` : ""}
{ep().title}
</strong>
</text>
<box flexDirection="row" gap={2}>
<text fg={theme.info}>{formatDate(ep().pubDate)}</text>
<text fg={muted()}>{formatDuration(ep().duration)}</text>
<Show when={downloadLabel(ep().id)}>
<text fg={downloadColor(ep().id)}>
{downloadLabel(ep().id)}
</text>
</Show>
</box>
<Show when={selectedShow()?.podcast.author}>
<text fg={muted()}>by {selectedShow()!.podcast.author}</text>
</Show>
<box height={1} />
<text fg={theme.textSecondary}>
{ep().description?.slice(0, 400) ?? "No description available."}
{(ep().description?.length ?? 0) > 400 ? "…" : ""}
</text>
<box height={1} />
<text fg={muted()}>enter: play · space: select · h: back</text>
</box>
)}
</Show>
);
return (
<PaneRow
parent={parentContent}
current={currentContent}
preview={previewContent}
parentLabel={() => (depth() >= 1 ? "Shows" : "Up")}
currentLabel={currentLabel}
previewLabel="Detail"
focused={isActive}
/>
);
}

View File

@@ -0,0 +1,85 @@
import type { BackendName } from "@/utils/audio-player";
import { useTheme } from "@/context/ThemeContext";
type PlaybackControlsProps = {
isPlaying: boolean;
volume: number;
speed: number;
backendName?: BackendName;
hasAudioUrl?: boolean;
onToggle: () => void;
onPrev: () => void;
onNext: () => void;
onVolumeChange: (value: number) => void;
onSpeedChange: (value: number) => void;
};
const BACKEND_LABELS: Record<BackendName, string> = {
mpv: "mpv",
none: "none",
};
export function PlaybackControls(props: PlaybackControlsProps) {
const { theme } = useTheme();
return (
<box
flexDirection="row"
gap={1}
alignItems="center"
border
padding={1}
borderColor={theme.border}
>
<box
border
padding={0}
onMouseDown={props.onPrev}
borderColor={theme.border}
>
<text fg={theme.primary}>[Prev]</text>
</box>
<box
border
padding={0}
onMouseDown={props.onToggle}
borderColor={theme.border}
>
<text fg={theme.primary}>{props.isPlaying ? "[Pause]" : "[Play]"}</text>
</box>
<box
border
padding={0}
onMouseDown={props.onNext}
borderColor={theme.border}
>
<text fg={theme.primary}>[Next]</text>
</box>
<box flexDirection="row" gap={1} marginLeft={2}>
<text fg={theme.textMuted}>Vol</text>
<text fg={theme.text}>{Math.round(props.volume * 100)}%</text>
<text fg={theme.textMuted}></text>
</box>
<box flexDirection="row" gap={1} marginLeft={2}>
<text fg={theme.textMuted}>Speed</text>
<text fg={theme.text}>{props.speed}x</text>
<text fg={theme.textMuted}>s</text>
</box>
{props.backendName && props.backendName !== "none" && (
<box flexDirection="row" gap={1} marginLeft={2}>
<text fg={theme.textMuted}>via</text>
<text fg={theme.primary}>{BACKEND_LABELS[props.backendName]}</text>
</box>
)}
{props.backendName === "none" && (
<box marginLeft={2}>
<text fg={theme.warning}>No audio player found</text>
</box>
)}
{props.hasAudioUrl === false && (
<box marginLeft={2}>
<text fg={theme.warning}>No audio URL</text>
</box>
)}
</box>
);
}

View File

@@ -0,0 +1,128 @@
/**
* PlayerPage — 2-pane yazi depth view of the now-playing episode.
*
* depth 0 (parent) — tab list (muted, read-only).
* depth 0 (current) — the single now-playing pane (rich view + controls).
*
* No preview pane (PaneRow `panes={2}`). Audio transport (play/pause,
* next/prev, seek) is handled globally by the Shell router (P/N/B/</>); this
* page only renders the now-playing surface. `h` at depth 0 returns to the
* tab root.
*/
import { Show } from "solid-js";
import { PlaybackControls } from "./PlaybackControls";
import { RealtimeWaveform } from "./RealtimeWaveform";
import { useAudio } from "@/hooks/useAudio";
import { useAppStore } from "@/stores/app";
import { useTheme } from "@/context/ThemeContext";
import { useNavigation, DEPTH_CENTER_PANE } from "@/context/NavigationContext";
import { PaneRow } from "@/components/PaneRow";
import { TabListPane } from "@/components/TabPanel";
export const PlayerPaneCount = 1;
export function PlayerPage() {
const audio = useAudio();
const { theme } = useTheme();
const nav = useNavigation();
const muted = () => theme.muted || theme.text;
const isActive = () => nav.activePane() === DEPTH_CENTER_PANE;
const progressPercent = () => {
const d = audio.duration();
if (d <= 0) return 0;
return Math.min(100, Math.round((audio.position() / d) * 100));
};
const formatTime = (seconds: number) => {
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60);
return `${m}:${String(s).padStart(2, "0")}`;
};
// ── parent pane: the tab list (muted) ──────────────────────────────────────
const parentContent = () => <TabListPane muted />;
// ── current pane: now playing ───────────────────────────────────────────────
const currentContent = () => (
<box flexDirection="column" gap={1} padding={1}>
<box flexDirection="row" justifyContent="space-between">
<text fg={theme.text}>
<strong>Now Playing</strong>
</text>
<text fg={muted()}>
{formatTime(audio.position())} / {formatTime(audio.duration())} (
{progressPercent()}%)
</text>
</box>
<Show when={audio.error()}>
{(err) => <text fg={theme.error}>{err()}</text>}
</Show>
<Show
when={audio.currentEpisode()}
fallback={
<box padding={1}>
<text fg={muted()}>No episode loaded.</text>
</box>
}
>
{(ep) => (
<box flexDirection="column" gap={1}>
<text fg={theme.text}>
<strong>{ep().title}</strong>
</text>
<text fg={muted()}>
{ep().description?.slice(0, 500) ?? "No description available."}
</text>
<RealtimeWaveform
visualizerConfig={(() => {
const viz = useAppStore().state().settings.visualizer;
// bars is width-derived in RealtimeWaveform; pass only the
// audio-processing params here.
return {
noiseReduction: viz.noiseReduction,
lowCutOff: viz.lowCutOff,
highCutOff: viz.highCutOff,
};
})()}
/>
</box>
)}
</Show>
<PlaybackControls
isPlaying={audio.isPlaying()}
volume={audio.volume()}
speed={audio.speed()}
backendName={audio.backendName()}
hasAudioUrl={!!audio.currentEpisode()?.audioUrl}
onToggle={audio.togglePlayback}
onPrev={() => audio.seek(0)}
onNext={() => audio.seek(audio.currentEpisode()?.duration ?? 0)}
onSpeedChange={(s: number) => audio.setSpeed(s)}
onVolumeChange={(v: number) => audio.setVolume(v)}
/>
<box height={1} />
<text fg={muted()}>
{"P play/pause N next B prev ◀▶ seek h back"}
</text>
</box>
);
return (
<PaneRow
parent={parentContent}
current={currentContent}
parentLabel="Up"
currentLabel="Player"
panes={2}
focused={isActive}
/>
);
}

View File

@@ -0,0 +1,277 @@
/**
* RealtimeWaveform — live audio frequency visualization using cavacore.
*
* Spawns an independent ffmpeg
* process to decode the audio stream, feeds PCM samples through cavacore
* for FFT analysis, and renders frequency bars as colored terminal
* characters at ~30fps.
*/
import { createSignal, createEffect, onCleanup, on, untrack } from "solid-js";
import { useTerminalDimensions } from "@opentui/solid";
import {
loadCavaCore,
type CavaCore,
type CavaCoreConfig,
} from "@/utils/cavacore";
import { AudioStreamReader } from "@/utils/audio-stream-reader";
import { useAudio } from "@/hooks/useAudio";
import { useTheme } from "@/context/ThemeContext";
import { PANE_RATIO } from "@/utils/navigation";
// ── Types ────────────────────────────────────────────────────────────
export type RealtimeWaveformProps = {
visualizerConfig?: Partial<CavaCoreConfig>;
};
/** Unicode lower block elements: space (silence) through full block (max) */
const BARS = [
" ",
"\u2581",
"\u2582",
"\u2583",
"\u2584",
"\u2585",
"\u2586",
"\u2587",
"\u2588",
];
/** Target frame interval in ms (~30 fps) */
const FRAME_INTERVAL = 33;
/** Number of PCM samples to read per frame (512 is a good FFT window) */
const SAMPLES_PER_FRAME = 512;
// ── Component ────────────────────────────────────────────────────────
export function RealtimeWaveform(props: RealtimeWaveformProps) {
const { theme } = useTheme();
const audio = useAudio();
// Frequency bar values (0.01.0 per bar)
const [barData, setBarData] = createSignal<number[]>([]);
let cava: CavaCore | null = null;
let reader: AudioStreamReader | null = null;
let frameTimer: ReturnType<typeof setInterval> | null = null;
let sampleBuffer: Float64Array | null = null;
// Bar count scales with terminal width so the waveform fills its pane.
// The player is a 2-pane row: current column = (current+preview) of
// (parent+current+preview) of the terminal width. Subtract ~8 chars of
// chrome (scrollbox border + box padding + waveform border + padding).
// Falls back to 64 before the renderer reports a real size.
const dimensions = useTerminalDimensions();
const numBars = () => {
const total = PANE_RATIO.parent + PANE_RATIO.current + PANE_RATIO.preview;
const current = PANE_RATIO.current + PANE_RATIO.preview; // 2-pane grows current
const width = dimensions().width;
if (!width) return 64;
return Math.max(
8,
Math.min(256, Math.floor((width * current) / total) - 8),
);
};
// ── Lifecycle: init cavacore once ──────────────────────────────────
const initCava = () => {
if (cava) return true;
cava = loadCavaCore();
if (!cava) {
return false;
}
return true;
};
// ── Start/stop the visualization pipeline ──────────────────────────
const startVisualization = (url: string, position: number, speed: number) => {
stopVisualization();
if (!url || !initCava() || !cava) return;
// Initialize cavacore with current resolution + any overrides.
// bars is width-derived (see numBars); visualizerConfig supplies the
// audio-processing params (noise reduction, cutoffs, etc.).
const config: CavaCoreConfig = {
bars: numBars(),
sampleRate: 44100,
channels: 1,
...props.visualizerConfig,
};
cava.init(config);
// Pre-allocate sample read buffer
sampleBuffer = new Float64Array(SAMPLES_PER_FRAME);
// Start ffmpeg decode stream (reuse reader if same URL, else create new)
if (!reader || reader.url !== url) {
if (reader) reader.stop();
reader = new AudioStreamReader({ url });
}
reader.start(position, speed);
// Start render loop
frameTimer = setInterval(renderFrame, FRAME_INTERVAL);
};
const stopVisualization = () => {
if (frameTimer) {
clearInterval(frameTimer);
frameTimer = null;
}
if (reader) {
reader.stop();
// Don't null reader — we reuse it across start/stop cycles
}
if (cava?.isReady) {
cava.destroy();
}
sampleBuffer = null;
};
// ── Render loop (called at ~30fps) ─────────────────────────────────
const renderFrame = () => {
if (!cava?.isReady || !reader?.running || !sampleBuffer) return;
// Read available PCM samples from the stream
const count = reader.read(sampleBuffer);
if (count === 0) return;
// Feed samples to cavacore → get frequency bars
const input =
count < sampleBuffer.length
? sampleBuffer.subarray(0, count)
: sampleBuffer;
const output = cava.execute(input);
// Copy bar values to a new array for the signal
setBarData(Array.from(output as Float64Array));
};
createEffect(
on(
[
audio.isPlaying,
() => audio.currentEpisode()?.audioUrl ?? "",
audio.speed,
numBars,
],
([playing, url, speed]) => {
if (playing && url) {
const pos = untrack(audio.position);
startVisualization(url, pos, speed);
} else {
stopVisualization();
}
},
),
);
// ── Seek detection: lightweight effect for position jumps ──────────
//
// Watches position and restarts the reader (not the whole pipeline)
// only on significant jumps (>2s), which indicate a user seek.
// This is intentionally a separate effect — it should NOT trigger a
// full pipeline restart, just restart the ffmpeg stream at the new pos.
let lastSyncPosition = 0;
createEffect(
on(audio.position, (pos) => {
if (!audio.isPlaying || !reader?.running) {
lastSyncPosition = pos;
return;
}
const delta = Math.abs(pos - lastSyncPosition);
lastSyncPosition = pos;
if (delta > 2) {
reader.restart(pos, audio.speed() ?? 1);
}
}),
);
// Cleanup on unmount
onCleanup(() => {
stopVisualization();
if (reader) {
reader.stop();
reader = null;
}
// Don't null cava itself — it can be reused. But do destroy its plan.
if (cava?.isReady) {
cava.destroy();
}
});
// ── Rendering ──────────────────────────────────────────────────────
const playedRatio = () =>
audio.duration() <= 0
? 0
: Math.min(1, audio.position() / audio.duration());
const renderLine = () => {
const bars = barData();
const count = numBars();
// If no data yet, show empty placeholder
if (bars.length === 0) {
const placeholder = ".".repeat(count);
return (
<box flexDirection="row" gap={0}>
<text fg="#3b4252">{placeholder}</text>
</box>
);
}
const played = Math.floor(count * playedRatio());
const playedColor = audio.isPlaying() ? "#6fa8ff" : "#7d8590";
const futureColor = "#3b4252";
const playedChars = bars
.slice(0, played)
.map((v) => BARS[Math.min(BARS.length - 1, Math.floor(v * BARS.length))])
.join("");
const futureChars = bars
.slice(played)
.map((v) => BARS[Math.min(BARS.length - 1, Math.floor(v * BARS.length))])
.join("");
return (
<box flexDirection="row" gap={0}>
<text fg={playedColor}>{playedChars || " "}</text>
<text fg={futureColor}>{futureChars || " "}</text>
</box>
);
};
const handleClick = (event: { x: number }) => {
const count = numBars();
const ratio = event.x / count;
const next = Math.max(
0,
Math.min(audio.duration(), Math.round(audio.duration() * ratio)),
);
audio.seek(next);
};
return (
<box
border
borderColor={theme.border}
padding={1}
onMouseDown={handleClick}
>
{renderLine()}
</box>
);
}

View File

@@ -0,0 +1,95 @@
import { Show } from "solid-js";
import type { SearchResult } from "@/types/source";
import { SourceBadge } from "./SourceBadge";
import { useTheme } from "@/context/ThemeContext";
import { SelectableBox, SelectableText } from "@/components/Selectable";
type ResultCardProps = {
result: SearchResult;
selected: boolean;
onSelect: () => void;
onSubscribe?: () => void;
};
export function ResultCard(props: ResultCardProps) {
const { theme } = useTheme();
const podcast = () => props.result.podcast;
return (
<SelectableBox
selected={() => props.selected}
flexDirection="column"
padding={1}
onMouseDown={props.onSelect}
>
<box
flexDirection="row"
justifyContent="space-between"
alignItems="center"
>
<box flexDirection="row" gap={2} alignItems="center">
<SelectableText
selected={() => props.selected}
primary
>
<strong>{podcast().title}</strong>
</SelectableText>
<SourceBadge
sourceId={props.result.sourceId}
sourceName={props.result.sourceName}
sourceType={props.result.sourceType}
/>
</box>
<Show when={podcast().isSubscribed}>
<text fg={theme.success}>[Subscribed]</text>
</Show>
</box>
<Show when={podcast().author}>
<SelectableText
selected={() => props.selected}
tertiary
>
by {podcast().author}
</SelectableText>
</Show>
<Show when={podcast().description}>
{(description) => (
<SelectableText
selected={() => props.selected}
tertiary
>
{description().length > 120
? description().slice(0, 120) + "..."
: description()}
</SelectableText>
)}
</Show>
<Show when={(podcast().categories ?? []).length > 0}>
<box flexDirection="row" gap={1}>
{(podcast().categories ?? []).slice(0, 3).map((category) => (
<text fg={theme.warning}>[{category}]</text>
))}
</box>
</Show>
<Show when={!podcast().isSubscribed}>
<box
border
padding={0}
paddingLeft={1}
paddingRight={1}
width={18}
onMouseDown={(event) => {
event.stopPropagation?.();
props.onSubscribe?.();
}}
>
<text fg={theme.primary}>[+] Add to Feeds</text>
</box>
</Show>
</SelectableBox>
);
}

View File

@@ -0,0 +1,75 @@
import { Show } from "solid-js";
import { format } from "date-fns";
import type { SearchResult } from "@/types/source";
import { SourceBadge } from "./SourceBadge";
import { useTheme } from "@/context/ThemeContext";
type ResultDetailProps = {
result?: SearchResult;
onSubscribe?: (result: SearchResult) => void;
};
export function ResultDetail(props: ResultDetailProps) {
const { theme } = useTheme();
return (
<box flexDirection="column" border padding={1} gap={1} height="100%" borderColor={theme.border}>
<Show
when={props.result}
fallback={ <text fg={theme.textMuted}>Select a result to see details.</text>}
>
{(result) => (
<>
<text fg={theme.text}>
<strong>{result().podcast.title}</strong>
</text>
<SourceBadge
sourceId={result().sourceId}
sourceName={result().sourceName}
sourceType={result().sourceType}
/>
<Show when={result().podcast.author}>
<text fg={theme.textMuted}>by {result().podcast.author}</text>
</Show>
<Show when={result().podcast.description}>
<text fg={theme.textMuted}>{result().podcast.description}</text>
</Show>
<Show when={(result().podcast.categories ?? []).length > 0}>
<box flexDirection="row" gap={1}>
{(result().podcast.categories ?? []).map((category) => (
<text fg={theme.warning}>[{category}]</text>
))}
</box>
</Show>
<text fg={theme.textMuted}>Feed: {result().podcast.feedUrl}</text>
<text fg={theme.textMuted}>
Updated: {format(result().podcast.lastUpdated, "MMM d, yyyy")}
</text>
<Show when={!result().podcast.isSubscribed}>
<box
border
padding={0}
paddingLeft={1}
paddingRight={1}
width={18}
onMouseDown={() => props.onSubscribe?.(result())}
>
<text fg={theme.primary}>[+] Add to Feeds</text>
</box>
</Show>
<Show when={result().podcast.isSubscribed}>
<text fg={theme.success}>Already subscribed</text>
</Show>
</>
)}
</Show>
</box>
);
}

View File

@@ -3,6 +3,8 @@
*/ */
import { For, Show } from "solid-js" import { For, Show } from "solid-js"
import { useTheme } from "@/context/ThemeContext"
import { SelectableBox, SelectableText } from "@/components/Selectable"
type SearchHistoryProps = { type SearchHistoryProps = {
history: string[] history: string[]
@@ -15,6 +17,7 @@ type SearchHistoryProps = {
} }
export function SearchHistory(props: SearchHistoryProps) { export function SearchHistory(props: SearchHistoryProps) {
const { theme } = useTheme();
const handleSearchClick = (index: number, query: string) => { const handleSearchClick = (index: number, query: string) => {
props.onChange?.(index) props.onChange?.(index)
props.onSelect?.(query) props.onSelect?.(query)
@@ -27,10 +30,10 @@ export function SearchHistory(props: SearchHistoryProps) {
return ( return (
<box flexDirection="column" gap={1}> <box flexDirection="column" gap={1}>
<box flexDirection="row" justifyContent="space-between"> <box flexDirection="row" justifyContent="space-between">
<text fg="gray">Recent Searches</text> <text fg={theme.textMuted}>Recent Searches</text>
<Show when={props.history.length > 0}> <Show when={props.history.length > 0}>
<box onMouseDown={() => props.onClear?.()} padding={0}> <box onMouseDown={() => props.onClear?.()} padding={0}>
<text fg="red">[Clear All]</text> <text fg={theme.error}>[Clear All]</text>
</box> </box>
</Show> </Show>
</box> </box>
@@ -39,7 +42,7 @@ export function SearchHistory(props: SearchHistoryProps) {
when={props.history.length > 0} when={props.history.length > 0}
fallback={ fallback={
<box padding={1}> <box padding={1}>
<text fg="gray">No recent searches</text> <text fg={theme.textMuted}>No recent searches</text>
</box> </box>
} }
> >
@@ -50,23 +53,31 @@ export function SearchHistory(props: SearchHistoryProps) {
const isSelected = () => index() === props.selectedIndex && props.focused const isSelected = () => index() === props.selectedIndex && props.focused
return ( return (
<box <SelectableBox
selected={isSelected}
flexDirection="row" flexDirection="row"
justifyContent="space-between" justifyContent="space-between"
padding={0} padding={0}
paddingLeft={1} paddingLeft={1}
paddingRight={1} paddingRight={1}
backgroundColor={isSelected() ? "#333" : undefined}
onMouseDown={() => handleSearchClick(index(), query)} onMouseDown={() => handleSearchClick(index(), query)}
> >
<box flexDirection="row" gap={1}> <SelectableText
<text fg="gray">{">"}</text> selected={isSelected}
<text fg={isSelected() ? "cyan" : "white"}>{query}</text> tertiary
</box> >
{">"}
</SelectableText>
<SelectableText
selected={isSelected}
primary
>
{query}
</SelectableText>
<box onMouseDown={() => handleRemoveClick(query)} padding={0}> <box onMouseDown={() => handleRemoveClick(query)} padding={0}>
<text fg="red">[x]</text> <text fg={theme.error}>[x]</text>
</box>
</box> </box>
</SelectableBox>
) )
}} }}
</For> </For>

View File

@@ -0,0 +1,439 @@
/**
* SearchPage — yazi depth-stack view of podcast search.
*
* depth 0 (current) — query input row + recent-searches list (navigable
* with j/k when the input is defocused). Parent pane
* shows the tab list (muted); preview shows a hint.
* depth 1 (current) — search results list. Parent pane shows the submitted
* query (muted, read-only); preview shows the detail of
* the focused result.
*
* Typed input owns its keys while `nav.inputFocused()` is true (the Shell
* router yields). Escape defocuses the input (handled in Shell) so j/k/h
* navigation resumes; `s` (the `search` action) refocuses it. Enter on the
* input (or on a focused recent at depth 0) submits the query and pushes to
* depth 1 (results). `h` pops: results→query, query→tab root.
*/
import {
createSignal,
createMemo,
createEffect,
For,
Show,
onMount,
onCleanup,
} from "solid-js";
import { useSearchStore } from "@/stores/search";
import { useFeedStore } from "@/stores/feed";
import { format } from "date-fns";
import { useTheme } from "@/context/ThemeContext";
import {
useNavigation,
NavMode,
DEPTH_CENTER_PANE,
type PaneId,
type DepthFrame,
} from "@/context/NavigationContext";
import { on, off } from "@/utils/event-bus";
import type { KeybindActionName } from "@/context/KeybindContext";
import type { SearchResult } from "@/types/source";
import { PaneRow } from "@/components/PaneRow";
import { TabListPane } from "@/components/TabPanel";
import { useScrollIntoView } from "@/hooks/useScrollIntoView";
export const SearchPaneCount = 1;
function SearchPage() {
const searchStore = useSearchStore();
const feedStore = useFeedStore();
const [inputValue, setInputValue] = createSignal("");
const { theme } = useTheme();
const muted = () => theme.muted || theme.text;
const nav = useNavigation();
const stack = nav.depthStack;
const depth = nav.currentDepth;
const focus = (d: number = depth()) => nav.depthFocus(d);
// depth 1's ctx carries the submitted query string.
const submittedQuery = (): string => stack()[1]?.ctx ?? searchStore.query();
// ── input focusing ────────────────────────────────────────────────────────
// `inputFocused` is true while the query input is being typed in. The Shell
// router yields keys to the <input> while this is true; Escape (in Shell)
// sets it false so navigation resumes; `s` (search action) sets it true.
//
// Typing is the default only on the query depth (0); the results depth
// (1) is always list-navigation. Drive `inputFocused` straight off
// `depth()` rather than seeding it `true` on mount and patching on change:
// the depth stack persists across tab switches, so re-mounting this page
// at depth 1 (e.g. after searching, leaving, and returning to the tab)
// must NOT leave `inputFocused` stuck on — otherwise the Shell swallows
// j/k (yielding to a non-existent input) and only the scrollbox's native
// scroll responds.
//
// The effect only re-runs on a depth transition, so Escape (defocus) and
// `s` (refocus) at the same depth are not clobbered.
onMount(() => nav.setInputFocused(depth() === 0));
onCleanup(() => nav.setInputFocused(false));
createEffect(() => {
nav.setInputFocused(depth() === 0);
});
// ── results (depth 1) ─────────────────────────────────────────────────────
const results = () => searchStore.results();
const focusedResultIdx = () =>
results().length === 0 ? 0 : Math.min(focus(1), results().length - 1);
const focusedResult = createMemo(() => {
const list = results();
if (list.length === 0) return undefined;
return list[focusedResultIdx()];
});
// ── recents (depth 0) ────────────────────────────────────────────────────
const recents = () => searchStore.history();
const curLen = () => (depth() === 0 ? recents().length : results().length);
const ensureFocus = () => {
if (depth() === 1 && results().length > 0 && focus(1) >= results().length)
nav.setDepthFocus(results().length - 1, 1);
};
onMount(ensureFocus);
// Register a visual-mode resolver for the results list (depth 1).
onMount(() => {
const key = `${nav.activeTab()}:${DEPTH_CENTER_PANE}`;
nav.registerResolver(key, (i) => results()[i]?.podcast.id);
});
// ── helpers ─────────────────────────────────────────────────────────────────
const formatDate = (d: Date) => format(d, "MMM d, yyyy");
const runSearch = (query: string) => {
const q = query.trim();
if (!q) return;
searchStore.search(q).catch(() => {});
nav.pushDepth({
kind: "search:results",
ctx: q,
focus: 0,
} as DepthFrame);
nav.setActivePane(DEPTH_CENTER_PANE);
};
const handleSubmit = () => runSearch(inputValue());
const selectRecent = (query: string) => {
setInputValue(query);
runSearch(query);
};
const handleSubscribe = (result: SearchResult) => {
// Actually add the feed to the feed store, then mark the result subscribed
feedStore.addFeed(result.podcast, result.sourceId).catch(() => {});
searchStore.markSubscribed(result.podcast.id);
};
// ── nav.action handler ──────────────────────────────────────────────────────
const PAGE_ACTIONS: Partial<Record<KeybindActionName, () => void>> = {
"move-down": () => step(1),
"move-up": () => step(-1),
"jump-down": () => step(5),
"jump-up": () => step(-5),
"page-down": () => step(10),
"page-up": () => step(-10),
"goto-top": () => nav.gotoIndex(0, curLen()),
"goto-bottom": () => nav.gotoIndex(curLen() - 1, curLen()),
open: () => open(),
"toggle-select": () => {
if (depth() === 1) {
const r = focusedResult();
if (r) nav.toggleSelected(r.podcast.id);
}
},
search: () => {
// `s` refocuses the query input (typing mode) when on the query depth.
if (depth() === 0) nav.setInputFocused(true);
},
refresh: () => {
const q = submittedQuery() || inputValue().trim();
if (q) searchStore.search(q).catch(() => {});
},
};
function step(delta: number) {
nav.move(delta, curLen());
}
function open() {
if (depth() === 0) {
// Enter/l on a focused recent search → submit it and drill to results.
const list = recents();
const idx = Math.min(focus(0), list.length - 1);
const q = list[idx];
if (q) selectRecent(q);
return;
}
if (depth() === 1) {
const r = focusedResult();
if (r) handleSubscribe(r);
}
}
const onAction = (data: {
action: KeybindActionName;
pane: PaneId;
mode: NavMode;
}) => {
if (data.pane !== DEPTH_CENTER_PANE) return;
if (nav.activePane() !== DEPTH_CENTER_PANE) return;
ensureFocus();
PAGE_ACTIONS[data.action]?.();
};
onMount(() => {
on("nav.action", onAction);
onCleanup(() => off("nav.action", onAction));
});
// ── render ──────────────────────────────────────────────────────────────────
const isActive = () => nav.activePane() === DEPTH_CENTER_PANE;
const inputActive = () => nav.inputFocused() && depth() === 0;
const focusBg = (i: number, listFocus: number, active: boolean) =>
i === listFocus && active
? theme.primary
: i === listFocus
? theme.border
: undefined;
const focusFg = (i: number, listFocus: number, active: boolean) =>
i === listFocus && active ? theme.surface : theme.text;
// ── parent pane: previous-depth content (tab list at depth 0) ──────────────
const parentContent = () => (
<Show when={depth() >= 1} fallback={<TabListPane muted />}>
<box flexDirection="column" gap={1} padding={1}>
<text fg={theme.textSecondary}>Query</text>
<text fg={muted()}>{submittedQuery() || "(empty)"}</text>
<box height={1} />
<text fg={muted()}>h: back to query</text>
</box>
</Show>
);
// ── current pane ────────────────────────────────────────────────────────────
const currentContent = () => (
<>
<Show when={depth() === 0}>
{/* query input row + recent searches */}
<box flexDirection="column" gap={1} padding={1}>
<box flexDirection="row" gap={1} alignItems="center">
<text fg={muted()}>Query:</text>
<input
value={inputValue()}
onInput={setInputValue}
onSubmit={() => handleSubmit()}
placeholder="Enter podcast name..."
focused={inputActive()}
width={28}
/>
</box>
<Show when={searchStore.isSearching()}>
<text fg={theme.warning}>Searching...</text>
</Show>
<Show when={searchStore.error()}>
<text fg={theme.error}>{searchStore.error()}</text>
</Show>
<box height={1} />
<text fg={theme.textSecondary}>Recent</text>
<Show
when={recents().length > 0}
fallback={
<text fg={muted()}>
{inputActive()
? "Enter to search"
: "s to type · Enter to search"}
</text>
}
>
<For each={recents()}>
{(query, index) => {
const lf = () => focus(0);
const ref = useScrollIntoView(() => index() === lf());
return (
<box
ref={ref}
flexDirection="row"
gap={1}
paddingLeft={1}
paddingRight={1}
backgroundColor={focusBg(index(), lf(), isActive())}
onMouseDown={() => {
nav.setActivePane(DEPTH_CENTER_PANE);
nav.setDepthFocus(index(), 0);
}}
>
<text fg={focusFg(index(), lf(), isActive())}>
{index() === lf() ? "" : " "}
</text>
<text fg={focusFg(index(), lf(), isActive())}>{query}</text>
</box>
);
}}
</For>
</Show>
<box height={1} />
<text fg={muted()}>
{inputActive()
? "Enter to search · Esc to defocus"
: "j/k recents · s to type · h back"}
</text>
</box>
</Show>
<Show when={depth() >= 1}>
{/* results list */}
<Show
when={results().length > 0}
fallback={
<box padding={1}>
<text fg={muted()}>
{searchStore.query()
? "No results found"
: "Enter a search term to find podcasts"}
</text>
</box>
}
>
<For each={results()}>
{(result, index) => {
const fi = () => focusedResultIdx();
const ref = useScrollIntoView(() => index() === fi());
return (
<box
ref={ref}
flexDirection="column"
gap={0}
paddingLeft={1}
paddingRight={1}
backgroundColor={focusBg(index(), fi(), isActive())}
onMouseDown={() => {
nav.setActivePane(DEPTH_CENTER_PANE);
nav.setDepthFocus(index(), 1);
}}
>
<box flexDirection="row" gap={1}>
<text fg={focusFg(index(), fi(), isActive())}>
{index() === fi() ? "" : " "}
</text>
<text fg={focusFg(index(), fi(), isActive())}>
{result.podcast.title}
</text>
<Show when={result.podcast.isSubscribed}>
<text
fg={index() === fi() ? theme.surface : theme.success}
>
[+]
</text>
</Show>
</box>
<Show when={result.podcast.author}>
<text
fg={index() === fi() ? theme.surface : muted()}
paddingLeft={2}
>
by {result.podcast.author}
</text>
</Show>
</box>
);
}}
</For>
</Show>
</Show>
</>
);
// ── preview pane ────────────────────────────────────────────────────────────
const previewContent = () =>
depth() === 0 ? (
<box flexDirection="column" gap={1} padding={1}>
<text fg={theme.textPrimary ?? theme.text}>
<strong>Search</strong>
</text>
<text fg={muted()}>Type a query, press Enter to search.</text>
<text fg={muted()}>Esc defocuses the input; h goes back.</text>
<box height={1} />
<text fg={theme.textSecondary}>Recent · {recents().length}</text>
<For each={recents().slice(0, 6)}>
{(q) => <text fg={muted()}> {q}</text>}
</For>
</box>
) : (
<Show
when={focusedResult()}
fallback={
<box padding={1}>
<text fg={muted()}>No result focused</text>
</box>
}
>
{(result) => (
<box flexDirection="column" gap={1} padding={1}>
<text fg={theme.text}>
<strong>{result().podcast.title}</strong>
</text>
<Show when={result().podcast.author}>
<text fg={muted()}>by {result().podcast.author}</text>
</Show>
<Show when={result().podcast.description}>
<text fg={theme.textSecondary}>
{result().podcast.description!.slice(0, 400) ??
"No description available."}
{(result().podcast.description?.length ?? 0) > 400 ? "…" : ""}
</text>
</Show>
<Show when={(result().podcast.categories ?? []).length > 0}>
<box flexDirection="row" gap={1}>
<For each={(result().podcast.categories ?? []).slice(0, 4)}>
{(cat) => <text fg={theme.warning}>[{cat}]</text>}
</For>
</box>
</Show>
<text fg={muted()}>Feed: {result().podcast.feedUrl}</text>
<text fg={muted()}>
Updated: {formatDate(result().podcast.lastUpdated)}
</text>
<Show when={result().sourceName}>
<text fg={muted()}>Source: {result().sourceName}</text>
</Show>
<box height={1} />
<Show when={!result().podcast.isSubscribed}>
<text fg={theme.primary}>[+] Subscribe (enter)</text>
</Show>
<Show when={result().podcast.isSubscribed}>
<text fg={theme.success}>Already subscribed</text>
</Show>
<box height={1} />
<text fg={muted()}>enter: subscribe · h: back to query</text>
</box>
)}
</Show>
);
const currentLabel = () =>
depth() === 0
? `Search · ${recents().length} recent`
: `Results · ${results().length}`;
return (
<PaneRow
parent={parentContent}
current={currentContent}
preview={previewContent}
parentLabel={() => (depth() >= 1 ? "Query" : "Up")}
currentLabel={currentLabel}
previewLabel="Detail"
focused={isActive}
/>
);
}
export { SearchPage };

View File

@@ -2,32 +2,35 @@
* SearchResults component for displaying podcast search results * SearchResults component for displaying podcast search results
*/ */
import { For, Show } from "solid-js" import { For, Show } from "solid-js";
import type { SearchResult } from "../types/source" import type { SearchResult } from "@/types/source";
import { ResultCard } from "./ResultCard" import { ResultCard } from "./ResultCard";
import { ResultDetail } from "./ResultDetail" import { ResultDetail } from "./ResultDetail";
type SearchResultsProps = { type SearchResultsProps = {
results: SearchResult[] results: SearchResult[];
selectedIndex: number selectedIndex: number;
focused: boolean focused: boolean;
onSelect?: (result: SearchResult) => void onSelect?: (result: SearchResult) => void;
onChange?: (index: number) => void onChange?: (index: number) => void;
isSearching?: boolean isSearching?: boolean;
error?: string | null error?: string | null;
} };
export function SearchResults(props: SearchResultsProps) { export function SearchResults(props: SearchResultsProps) {
const handleSelect = (index: number) => { const handleSelect = (index: number) => {
props.onChange?.(index) props.onChange?.(index);
} };
return ( return (
<Show when={!props.isSearching} fallback={ <Show
when={!props.isSearching}
fallback={
<box padding={1}> <box padding={1}>
<text fg="yellow">Searching...</text> <text fg="yellow">Searching...</text>
</box> </box>
}> }
>
<Show <Show
when={!props.error} when={!props.error}
fallback={ fallback={
@@ -40,7 +43,9 @@ export function SearchResults(props: SearchResultsProps) {
when={props.results.length > 0} when={props.results.length > 0}
fallback={ fallback={
<box padding={1}> <box padding={1}>
<text fg="gray">No results found. Try a different search term.</text> <text fg="gray">
No results found. Try a different search term.
</text>
</box> </box>
} }
> >
@@ -71,5 +76,5 @@ export function SearchResults(props: SearchResultsProps) {
</Show> </Show>
</Show> </Show>
</Show> </Show>
) );
} }

View File

@@ -0,0 +1,38 @@
import { SourceType } from "@/types/source";
import { useTheme } from "@/context/ThemeContext";
type SourceBadgeProps = {
sourceId: string;
sourceName?: string;
sourceType?: SourceType;
};
const typeLabel = (sourceType?: SourceType) => {
if (sourceType === SourceType.API) return "API";
if (sourceType === SourceType.RSS) return "RSS";
if (sourceType === SourceType.CUSTOM) return "Custom";
return "Source";
};
// No module-level typeColor here — it needs the theme from the component.
// The correct definition lives inside SourceBadge below.
export function SourceBadge(props: SourceBadgeProps) {
const { theme } = useTheme();
const label = () => props.sourceName || props.sourceId;
const typeColor = (sourceType?: SourceType) => {
if (sourceType === SourceType.API) return theme.primary;
if (sourceType === SourceType.RSS) return theme.success;
if (sourceType === SourceType.CUSTOM) return theme.warning;
return theme.textMuted;
};
return (
<box flexDirection="row" gap={1} padding={0}>
<text fg={typeColor(props.sourceType)}>
[{typeLabel(props.sourceType)}]
</text>
<text fg={theme.textMuted}>{label()}</text>
</box>
);
}

Some files were not shown because too many files have changed in this diff Show More