12 Commits
Author SHA1 Message Date
Lucas 191148f9b9 fix: sign android apk
CI / Frontend (push) Successful in 41s
CI / Rust (Tauri backend) (push) Successful in 1m57s
Release / Create release (push) Successful in 1s
Release / Build Linux bundles (push) Successful in 3m44s
Release / Build Android APK (push) Successful in 9m38s
2026-11-04 14:19:22 +01:00
Lucas 2f40c60520 fix: android setup action
CI / Frontend (push) Successful in 31s
CI / Rust (Tauri backend) (push) Successful in 1m51s
Release / Create release (push) Successful in 1s
Release / Build Linux bundles (push) Successful in 2m52s
Release / Build Android APK (push) Failing after 9m15s
2026-11-04 13:47:53 +01:00
Lucas 74501fba5c fix: release ci
CI / Frontend (push) Successful in 40s
CI / Rust (Tauri backend) (push) Successful in 1m42s
Release / Create release (push) Successful in 1s
Release / Build Linux bundles (push) Successful in 4m32s
Release / Build Android APK (push) Failing after 17s
2026-11-04 12:42:40 +01:00
Lucas 710caeb0fb chore: add release ci
CI / Frontend (push) Successful in 40s
CI / Rust (Tauri backend) (push) Successful in 1m57s
Release / Create release (push) Successful in 1s
Release / Build Linux bundles (push) Failing after 3m20s
Release / Build Android APK (push) Failing after 1m34s
2026-11-04 12:02:40 +01:00
Lucas 8fe56667c6 chore: use git path for dsp lib dependency
CI / Frontend (push) Successful in 41s
CI / Rust (Tauri backend) (push) Successful in 4m13s
2026-11-04 11:52:38 +01:00
Lucas b0625eafc2 chore: clippy
CI / Frontend (push) Successful in 31s
CI / Rust (Tauri backend) (push) Failing after 1m15s
2026-11-04 11:45:26 +01:00
Lucas 4b5606dd15 chore; add lint
CI / Frontend (push) Successful in 1m19s
CI / Rust (Tauri backend) (push) Failing after 1m13s
2026-11-04 11:36:41 +01:00
Lucas e640ae17e5 chore: add ci
CI / Frontend (push) Failing after 13s
CI / Rust (Tauri backend) (push) Failing after 1m36s
2026-11-04 11:16:36 +01:00
Lucas ddb7a907a1 feat: disconnect devices on app background mobile 2026-11-04 11:08:22 +01:00
Lucas be713620ef feat: better style for notifications 2026-11-03 16:00:26 +01:00
Lucas 8c766c3bc2 feat: settings page 2026-11-03 15:38:51 +01:00
Lucas 87244e5ba3 feat: allow volume button t control sliders on mobile 2026-11-03 14:51:51 +01:00
74 changed files with 2400 additions and 855 deletions
+82
View File
@@ -0,0 +1,82 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
frontend:
name: Frontend
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Install dependencies
run: npm ci
- name: Lint
run: npm run lint
- name: Type check
run: npx tsc --noEmit
- name: Prettier check
run: npm run format # make sure this is `prettier --check .`
- name: Build frontend
run: npm run build
rust:
name: Rust (Tauri backend)
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential curl wget file pkg-config \
libwebkit2gtk-4.1-dev libxdo-dev libssl-dev \
libayatana-appindicator3-dev librsvg2-dev
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Install dependencies
run: npm ci
# Tauri's build script checks that frontendDist exists
- name: Build frontend
run: npm run build
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Rust cache
uses: Swatinem/rust-cache@v2
with:
workspaces: src-tauri
- name: Format check
run: cargo fmt --manifest-path src-tauri/Cargo.toml --all -- --check
- name: Clippy
run: cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
- name: Test
run: cargo test --manifest-path src-tauri/Cargo.toml
+151
View File
@@ -0,0 +1,151 @@
name: Release
on:
push:
tags:
- 'v*'
permissions:
contents: write
env:
API: https://gitea.iceberg.black/api/v1/repos/${{ github.repository }}
jobs:
create-release:
name: Create release
runs-on: ubuntu-latest
outputs:
RELEASE_ID: ${{ steps.create.outputs.RELEASE_ID }}
steps:
- name: Create Gitea release
id: create
run: |
TAG=${GITHUB_REF#refs/tags/}
RELEASE_ID=$(curl -s -X POST "$API/releases" \
-H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
-H "Content-Type: application/json" \
-d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\"}" | jq -r '.id')
echo "RELEASE_ID=$RELEASE_ID" >> $GITHUB_OUTPUT
build-linux:
name: Build Linux bundles
needs: create-release
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential curl wget file pkg-config \
libwebkit2gtk-4.1-dev libxdo-dev libssl-dev \
libayatana-appindicator3-dev librsvg2-dev \
xdg-utils
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Rust cache
uses: Swatinem/rust-cache@v2
with:
workspaces: src-tauri
- name: Install dependencies
run: npm ci
- name: Build Tauri app
run: npm run tauri build
- name: Upload assets
run: |
for f in src-tauri/target/release/bundle/deb/*.deb \
src-tauri/target/release/bundle/rpm/*.rpm \
src-tauri/target/release/bundle/appimage/*.AppImage; do
[ -f "$f" ] || continue
echo "Uploading $f"
curl -s -X POST "$API/releases/${{ needs.create-release.outputs.RELEASE_ID }}/assets?name=$(basename "$f")" \
-H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
-F "attachment=@$f"
done
build-android:
name: Build Android APK
needs: create-release
runs-on: ubuntu-latest
env:
NDK_VERSION: 27.0.12077973
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 17
- name: Setup Android SDK
uses: https://github.com/android-actions/setup-android@v4
with:
packages: 'platform-tools'
- name: Install NDK and platform
run: |
sdkmanager "platforms;android-36" "build-tools;36.0.0" "ndk;${NDK_VERSION}"
echo "NDK_HOME=$ANDROID_HOME/ndk/${NDK_VERSION}" >> $GITHUB_ENV
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-linux-android,armv7-linux-androideabi,i686-linux-android,x86_64-linux-android
- name: Rust cache
uses: Swatinem/rust-cache@v2
with:
workspaces: src-tauri
- name: Install dependencies
run: npm ci
- name: Setup signing
env:
KEYSTORE_B64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
STORE_PASS: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
KEY_PASS: ${{ secrets.ANDROID_KEY_PASSWORD }}
run: |
echo "$KEYSTORE_B64" | base64 -d > src-tauri/gen/android/upload-keystore.jks
{
echo "storeFile=upload-keystore.jks"
echo "storePassword=$STORE_PASS"
echo "keyAlias=$KEY_ALIAS"
echo "keyPassword=$KEY_PASS"
} > src-tauri/gen/android/keystore.properties
- name: Build APK
run: npm run tauri android build -- --apk
- name: Upload APK
run: |
for f in src-tauri/gen/android/app/build/outputs/apk/universal/release/*.apk; do
[ -f "$f" ] || continue
echo "Uploading $f"
curl -s -X POST "$API/releases/${{ needs.create-release.outputs.RELEASE_ID }}/assets?name=$(basename "$f")" \
-H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
-F "attachment=@$f"
done
+1
View File
@@ -23,3 +23,4 @@ dist-ssr
*.sln *.sln
*.sw? *.sw?
*.jks *.jks
keystore.base64
+7
View File
@@ -15,4 +15,11 @@ This template should help get you started developing with Tauri, React and Types
- Check end to end behavioour - Check end to end behavioour
# TAG
git tag -a v1.0.0 -m "Release v1.0.0"
git push origin v1.0.0
git tag -d v1.0.0
git push origin --delete v1.0.0
git tag -d v1.0.0;git push origin --delete v1.0.0;git tag -a v1.0.0 -m "Release v1.0.0";git push origin v1.0.0;
+22
View File
@@ -0,0 +1,22 @@
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import reactHooks from "eslint-plugin-react-hooks";
export default tseslint.config(
js.configs.recommended,
...tseslint.configs.recommended,
{
ignores: ["node_modules/**", "dist/**", "src-tauri/target/**"],
},
{
files: ["**/*.{js,jsx,ts,tsx}"],
plugins: {
"react-hooks": reactHooks,
},
rules: {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
},
}
);
+523 -124
View File
File diff suppressed because it is too large Load Diff
+9 -1
View File
@@ -9,24 +9,32 @@
"preview": "vite preview", "preview": "vite preview",
"tauri": "tauri", "tauri": "tauri",
"format": "prettier --write \"src/**/*.{ts,tsx,js,jsx,css}\"", "format": "prettier --write \"src/**/*.{ts,tsx,js,jsx,css}\"",
"format:check": "prettier --check \"src/**/*.{ts,tsx,js,jsx,css}\"" "format:check": "prettier --check \"src/**/*.{ts,tsx,js,jsx,css}\"",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@tauri-apps/api": "^2", "@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2.7.2", "@tauri-apps/plugin-opener": "^2.7.2",
"@tauri-apps/plugin-os": "^2.4.0",
"@tauri-apps/plugin-store": "^2.5.0", "@tauri-apps/plugin-store": "^2.5.0",
"react": "^19.2.8", "react": "^19.2.8",
"react-dom": "^19.2.8" "react-dom": "^19.2.8"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^10.0.1",
"@tauri-apps/cli": "^2", "@tauri-apps/cli": "^2",
"@types/react": "^19.1.8", "@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6", "@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^4.6.0", "@vitejs/plugin-react": "^4.6.0",
"eslint": "^10.14.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.6", "eslint-plugin-prettier": "^5.5.6",
"eslint-plugin-react-hooks": "^7.1.1",
"prettier": "^3.9.6", "prettier": "^3.9.6",
"typescript": "~5.8.3", "typescript": "~5.8.3",
"typescript-eslint": "^8.72.1",
"vite": "^7.0.4" "vite": "^7.0.4"
} }
} }
+441 -446
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -18,9 +18,10 @@ crate-type = ["staticlib", "cdylib", "rlib"]
tauri-build = { version = "2", features = [] } tauri-build = { version = "2", features = [] }
[dependencies] [dependencies]
tauri = { version = "2.12.4", features = [] } tauri = { version = "2.12.5", features = [] }
tauri-plugin-opener = "2.7.2" tauri-plugin-opener = "2.7.2"
tauri-plugin-os = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1.0.154" serde_json = "1.0.154"
dsp_thomann = { path = "../../dsp-thomann", features = ["serialization"] } dsp_thomann = { git = "https://gitea.iceberg.black/LucasDLTG/dsp-thomann", features = ["serialization"] }
tauri-plugin-store = "2" tauri-plugin-store = "2"
+13 -5
View File
@@ -1,4 +1,3 @@
import java.util.Properties import java.util.Properties
plugins { plugins {
@@ -14,14 +13,19 @@ val tauriProperties = Properties().apply {
} }
} }
// Load signing credentials // Load signing credentials.
// Locally: optional (debug builds and `tauri android dev` work without it).
// In CI: mandatory, so a broken secrets setup fails loudly instead of
// producing an unsigned APK.
val keystoreProperties = Properties().apply { val keystoreProperties = Properties().apply {
val keystoreFile = rootProject.file("keystore.properties") val keystoreFile = rootProject.file("keystore.properties")
require(keystoreFile.exists()) { if (keystoreFile.exists()) {
"Missing keystore.properties"
}
keystoreFile.inputStream().use { load(it) } keystoreFile.inputStream().use { load(it) }
} else if (System.getenv("CI") != null) {
error("Missing keystore.properties in CI")
} }
}
val hasKeystore = keystoreProperties.containsKey("storeFile")
android { android {
compileSdk = 36 compileSdk = 36
@@ -39,6 +43,7 @@ android {
} }
signingConfigs { signingConfigs {
if (hasKeystore) {
create("release") { create("release") {
val keystorePath = keystoreProperties.getProperty("storeFile") val keystorePath = keystoreProperties.getProperty("storeFile")
?: error("Missing storeFile") ?: error("Missing storeFile")
@@ -55,6 +60,7 @@ android {
?: error("Missing keyPassword") ?: error("Missing keyPassword")
} }
} }
}
buildTypes { buildTypes {
getByName("debug") { getByName("debug") {
@@ -73,7 +79,9 @@ android {
getByName("release") { getByName("release") {
isMinifyEnabled = false isMinifyEnabled = false
if (hasKeystore) {
signingConfig = signingConfigs.getByName("release") signingConfig = signingConfigs.getByName("release")
}
proguardFiles( proguardFiles(
*fileTree(".") { include("**/*.pro") } *fileTree(".") { include("**/*.pro") }
@@ -1,11 +1,47 @@
package com.lucas.thomann_dsp_app package com.lucas.thomann_dsp_app
import android.os.Bundle import android.os.Bundle
import android.view.KeyEvent
import android.webkit.JavascriptInterface
import android.webkit.WebView
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
class MainActivity : TauriActivity() { class MainActivity : TauriActivity() {
private var webView: WebView? = null
@Volatile private var interceptVolume = false
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge() enableEdgeToEdge()
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
} }
override fun onWebViewCreate(webView: WebView) {
super.onWebViewCreate(webView)
this.webView = webView
webView.addJavascriptInterface(object {
@JavascriptInterface
fun setIntercept(enabled: Boolean) {
interceptVolume = enabled
}
}, "VolumeBridge")
}
private fun isVolumeKey(keyCode: Int) =
keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (interceptVolume && isVolumeKey(keyCode)) {
val name = if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) "volumeupbutton" else "volumedownbutton"
webView?.post {
webView?.evaluateJavascript("document.dispatchEvent(new Event('$name'))", null)
}
return true // consumed, so the system volume doesn't change
}
return super.onKeyDown(keyCode, event)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
if (interceptVolume && isVolumeKey(keyCode)) return true
return super.onKeyUp(keyCode, event)
}
} }
@@ -1 +1 @@
C:/Users/Lucas/Desktop/Projects/thomann-dsp-app/src-tauri/target/aarch64-linux-android/release/libthomann_dsp_app_lib.so C:/Users/lsdg/OneDrive - ETS ROBERT SAS 49/Bureau/Projects/dsp-thomann-interface/src-tauri/target/aarch64-linux-android/release/libthomann_dsp_app_lib.so
File diff suppressed because one or more lines are too long
@@ -1,4 +0,0 @@
storeFile=../../../thomann-release.jks
storePassword=gitgit
keyAlias=thomann
keyPassword=gitgit
+2 -2
View File
@@ -1,5 +1,5 @@
// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. // THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
include ':tauri-android' include ':tauri-android'
project(':tauri-android').projectDir = new File("C:\\Users\\Lucas\\.cargo\\registry\\src\\index.crates.io-1949cf8c6b5b557f\\tauri-2.12.4\\mobile\\android") project(':tauri-android').projectDir = new File("C:\\Users\\lsdg\\.cargo\\registry\\src\\index.crates.io-1949cf8c6b5b557f\\tauri-2.12.5\\mobile\\android")
include ':tauri-plugin-opener' include ':tauri-plugin-opener'
project(':tauri-plugin-opener').projectDir = new File("C:\\Users\\Lucas\\.cargo\\registry\\src\\index.crates.io-1949cf8c6b5b557f\\tauri-plugin-opener-2.7.2\\android") project(':tauri-plugin-opener').projectDir = new File("C:\\Users\\lsdg\\.cargo\\registry\\src\\index.crates.io-1949cf8c6b5b557f\\tauri-plugin-opener-2.7.2\\android")
+9
View File
@@ -69,8 +69,15 @@ pub fn create_dsp408(
let id = *next_id; let id = *next_id;
*next_id += 1; *next_id += 1;
#[cfg(mobile)]
let mut device = DSPDevice { dsp };
#[cfg(not(mobile))]
let device = DSPDevice { dsp }; let device = DSPDevice { dsp };
#[cfg(mobile)]
device.dsp.set_auto_reconnect(false);
let mut devices = state.devices.lock().map_err(|e| e.to_string())?; let mut devices = state.devices.lock().map_err(|e| e.to_string())?;
devices.insert(id, Arc::new(Mutex::new(device))); devices.insert(id, Arc::new(Mutex::new(device)));
@@ -249,6 +256,7 @@ pub async fn lock_device(
} }
// Command `0x30` // Command `0x30`
#[allow(clippy::too_many_arguments)]
#[tauri::command] #[tauri::command]
pub async fn set_compressor( pub async fn set_compressor(
state: State<'_, AppState>, state: State<'_, AppState>,
@@ -303,6 +311,7 @@ pub async fn set_high_pass(
} }
// Command `0x33` // Command `0x33`
#[allow(clippy::too_many_arguments)]
#[tauri::command] #[tauri::command]
pub async fn set_peq_band( pub async fn set_peq_band(
state: State<'_, AppState>, state: State<'_, AppState>,
+20 -3
View File
@@ -4,11 +4,26 @@ mod state;
use state::AppState; use state::AppState;
use tauri::Manager; use tauri::Manager;
#[cfg(mobile)]
fn handle_run_event(app: &tauri::AppHandle, event: &tauri::RunEvent) {
if let tauri::RunEvent::WindowEvent {
event: tauri::WindowEvent::Focused(false),
..
} = event
{
app.state::<AppState>().disconnect_all();
}
}
#[cfg(not(mobile))]
fn handle_run_event(_app: &tauri::AppHandle, _event: &tauri::RunEvent) {}
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
tauri::Builder::default() let app = tauri::Builder::default()
.plugin(tauri_plugin_store::Builder::new().build()) .plugin(tauri_plugin_store::Builder::new().build())
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_os::init()) // added by `tauri add os`
.manage(AppState::new()) .manage(AppState::new())
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
commands::create_dsp408, commands::create_dsp408,
@@ -51,6 +66,8 @@ pub fn run() {
state.shutdown(); state.shutdown();
} }
}) })
.run(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while building tauri application");
app.run(|app, event| handle_run_event(app, &event));
} }
+19
View File
@@ -30,4 +30,23 @@ impl AppState {
} }
} }
} }
#[cfg(mobile)]
pub fn disconnect_all(&self) {
// clone the Arcs so the map lock isn't held while waiting on devices
let devices: Vec<Arc<Mutex<DSPDevice>>> = {
let map = self.devices.lock().unwrap_or_else(|e| e.into_inner());
map.values().cloned().collect()
};
// one thread per device so a stuck device doesn't delay the others
for device in devices {
std::thread::spawn(move || {
let mut d = device.lock().unwrap_or_else(|e| e.into_inner());
if d.dsp.connected() {
let _ = d.dsp.disconnect();
}
});
}
}
} }
+10 -4
View File
@@ -6,7 +6,7 @@ import DSPPage from './pages/DspPage/DspPage';
import AddDSPForm from './pages/AddDspPage/AddDspPage'; import AddDSPForm from './pages/AddDspPage/AddDspPage';
import { useNotifications } from './hooks/useNotifications'; import { useNotifications } from './hooks/useNotifications';
import Notifications from './components/Notifications/Notifications'; import Notifications from './components/Notifications/Notifications';
import CreditsPage from './pages/CreditsPage/CreditsPage'; import SettingsPage from './pages/SettingsPage/SettingsPage';
import HomePage from './pages/HomePage/HomePage'; import HomePage from './pages/HomePage/HomePage';
import { addDSP, createDSPInstance, restoreDSPs } from './dsp/dspApi'; import { addDSP, createDSPInstance, restoreDSPs } from './dsp/dspApi';
import { removeDSP } from './dsp/dspShared'; import { removeDSP } from './dsp/dspShared';
@@ -14,13 +14,14 @@ import { stopAllPolling } from './dsp/pollRegistry';
import { loadSavedDSPs, saveDSPs, toSaved } from './dsp/dspStorage'; import { loadSavedDSPs, saveDSPs, toSaved } from './dsp/dspStorage';
import { DSPMode } from './features/dsp408/types'; import { DSPMode } from './features/dsp408/types';
import { useIsMobile } from './hooks/useIsMobile'; import { useIsMobile } from './hooks/useIsMobile';
import { useMobileBackgroundDisconnect } from './dsp/useMobileBackgroundDisconnect';
function App() { function App() {
const [dsps, setDsps] = useState<DSP[]>([]); const [dsps, setDsps] = useState<DSP[]>([]);
const [selected, setSelected] = useState<number | null>(null); const [selected, setSelected] = useState<number | null>(null);
const [page, setPage] = useState<AppPage>('home'); const [page, setPage] = useState<AppPage>('home');
const [loaded, setLoaded] = useState(false); const [loaded, setLoaded] = useState(false);
const { notifications, notify, removeNotification, hoverNotification } = useNotifications(); const { notifications, notify, removeNotification, hoverNotification, setNotificationsDisabled } = useNotifications();
const connectedDspCount = dsps.filter((dsp) => isConnected(dsp)).length; const connectedDspCount = dsps.filter((dsp) => isConnected(dsp)).length;
const restoreStarted = useRef(false); const restoreStarted = useRef(false);
const isMobile = useIsMobile(); const isMobile = useIsMobile();
@@ -30,6 +31,9 @@ function App() {
const dspsRef = useRef(dsps); const dspsRef = useRef(dsps);
dspsRef.current = dsps; dspsRef.current = dsps;
useMobileBackgroundDisconnect(dsps, setDsps, notify); // NEW
useEffect(() => { useEffect(() => {
return () => stopAllPolling(dspsRef.current); return () => stopAllPolling(dspsRef.current);
}, []); }, []);
@@ -96,8 +100,10 @@ function App() {
/> />
<main className="stage"> <main className="stage">
{page === 'credits' ? ( {page === 'settings' ? (
<CreditsPage /> <SettingsPage
onNotificationsDisabledChange={setNotificationsDisabled}
/>
) : page === 'add-dsp' ? ( ) : page === 'add-dsp' ? (
<AddDSPForm <AddDSPForm
onCancel={() => setPage('home')} onCancel={() => setPage('home')}
+17
View File
@@ -0,0 +1,17 @@
export function SettingsIcon(props: React.SVGProps<SVGSVGElement>) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
{...props}
>
<path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915" />
<circle cx="12" cy="12" r="3" />
</svg>
);
}
@@ -17,6 +17,12 @@
background: transparent; background: transparent;
} }
.choice-select.is-selected {
outline: 2px solid var(--accent-brand);
outline-offset: -2px;
border-radius: 1.6cqh;
}
.choice-select[data-disabled] { .choice-select[data-disabled] {
opacity: 0.5; opacity: 0.5;
} }
+18 -5
View File
@@ -2,6 +2,7 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom'; import { createPortal } from 'react-dom';
import { TriangleDownIcon } from '../../assets/icons/Triangle'; import { TriangleDownIcon } from '../../assets/icons/Triangle';
import { useVolumeKeys } from '../../hooks/useVolumeKeys';
import './ChoiceSelect.css'; import './ChoiceSelect.css';
type CommitResult = Promise<boolean | void> | boolean | void; type CommitResult = Promise<boolean | void> | boolean | void;
@@ -212,7 +213,6 @@ function ChoiceSelect<T extends string>({
latest.current = value; latest.current = value;
lastCommitted.current = value; lastCommitted.current = value;
setDisplayValue(value); setDisplayValue(value);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]); }, [value]);
// When disabled, drop any in-progress interaction, close the list and show the real value. // When disabled, drop any in-progress interaction, close the list and show the real value.
@@ -231,7 +231,6 @@ function ChoiceSelect<T extends string>({
latest.current = v; latest.current = v;
lastCommitted.current = v; lastCommitted.current = v;
setDisplayValue(v); setDisplayValue(v);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [disabled]); }, [disabled]);
useEffect(() => { useEffect(() => {
@@ -285,7 +284,6 @@ function ChoiceSelect<T extends string>({
window.removeEventListener('scroll', recalc, true); window.removeEventListener('scroll', recalc, true);
window.removeEventListener('resize', recalc); window.removeEventListener('resize', recalc);
}; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]); }, [open]);
// --- wheel on the trigger ---------------------------------------------- // --- wheel on the trigger ----------------------------------------------
@@ -299,6 +297,20 @@ function ChoiceSelect<T extends string>({
return true; return true;
}; };
const { isSelected, select } = useVolumeKeys({
rootRef,
disabled,
onStep: (volumeDirection) => {
// Same mapping as the wheel: up = previous item, down = next item.
const direction = volumeDirection === 1 ? -1 : 1;
if (open) {
setHighlight((h) => Math.min(options.length - 1, Math.max(0, h + direction)));
} else if (step(direction)) {
scheduleWheelCommit();
}
},
});
useNonPassiveWheel(triggerRef, (e) => { useNonPassiveWheel(triggerRef, (e) => {
e.preventDefault(); e.preventDefault();
if (disabled) return; if (disabled) return;
@@ -347,10 +359,10 @@ function ChoiceSelect<T extends string>({
preview(opt); preview(opt);
commitLatest(); commitLatest();
} else { } else {
// Picking the already-shown value still flushes any wheel change that is waiting on its debounce.
commitLatest(); commitLatest();
} }
setOpen(false); setOpen(false);
select();
triggerRef.current?.focus(); triggerRef.current?.focus();
} }
@@ -383,10 +395,11 @@ function ChoiceSelect<T extends string>({
return ( return (
<div <div
className={`choice-select ${className}`} className={`choice-select ${isSelected ? 'is-selected' : ''} ${className}`}
data-disabled={disabled || undefined} data-disabled={disabled || undefined}
ref={rootRef} ref={rootRef}
style={style} style={style}
onPointerDown={select}
> >
<button <button
id={id} id={id}
@@ -11,6 +11,20 @@
background: transparent; background: transparent;
} }
.choice-stepper.is-selected {
outline: 2px solid var(--accent-brand);
outline-offset: -2px;
border-radius: 1.6cqh;
}
.choice-stepper.is-touch .choice-stepper__input {
pointer-events: none; /* taps go to the root, so the whole stepper gets selected */
caret-color: transparent;
user-select: none;
-webkit-user-select: none;
outline: none;
}
.choice-stepper__input { .choice-stepper__input {
flex: 1 1 auto; flex: 1 1 auto;
min-width: 0; min-width: 0;
+21 -3
View File
@@ -1,6 +1,8 @@
import { JSX, useEffect, useRef, useState } from 'react'; import { JSX, useEffect, useRef, useState } from 'react';
import Button from '../Button/Button'; import Button from '../Button/Button';
import { TriangleUpIcon, TriangleDownIcon } from '../../assets/icons/Triangle'; import { TriangleUpIcon, TriangleDownIcon } from '../../assets/icons/Triangle';
import { useVolumeKeys } from '../../hooks/useVolumeKeys';
import { useIsTouch } from '../../hooks/useIsTouch';
import './ChoiceStepper.css'; import './ChoiceStepper.css';
const WHEEL_COMMIT_DELAY = 250; const WHEEL_COMMIT_DELAY = 250;
@@ -115,6 +117,8 @@ function StepperCore<T>({
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const isMobile = useIsTouch();
// Latest-value refs, safe to read from async code and timers. // Latest-value refs, safe to read from async code and timers.
const valueRef = useRef(value); const valueRef = useRef(value);
valueRef.current = value; valueRef.current = value;
@@ -245,6 +249,15 @@ function StepperCore<T>({
}, WHEEL_COMMIT_DELAY); }, WHEEL_COMMIT_DELAY);
} }
const rootRef = useRef<HTMLDivElement>(null);
const { isSelected, select, deselect } = useVolumeKeys({
rootRef,
disabled,
onStep: (direction) => {
if (step(direction) !== null) scheduleWheelCommit();
},
});
useNonPassiveWheel(inputRef, (e) => { useNonPassiveWheel(inputRef, (e) => {
if (disabled) return; if (disabled) return;
e.preventDefault(); e.preventDefault();
@@ -275,7 +288,6 @@ function StepperCore<T>({
lastCommitted.current = value; lastCommitted.current = value;
setLocalValue(value); setLocalValue(value);
setText(formatLabel(value)); setText(formatLabel(value));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value, formatLabel]); }, [value, formatLabel]);
// When disabled, drop any in-progress interaction and show the real value. // When disabled, drop any in-progress interaction and show the real value.
@@ -296,7 +308,6 @@ function StepperCore<T>({
lastCommitted.current = v; lastCommitted.current = v;
setLocalValue(v); setLocalValue(v);
setText(formatLabelRef.current(v)); setText(formatLabelRef.current(v));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [disabled]); }, [disabled]);
useEffect(() => { useEffect(() => {
@@ -330,13 +341,20 @@ function StepperCore<T>({
}; };
return ( return (
<div className={`choice-stepper ${className ?? ''}`} data-disabled={disabled || undefined}> <div
ref={rootRef}
className={`choice-stepper ${isMobile ? 'is-touch' : ''} ${isSelected ? 'is-selected' : ''} ${className ?? ''}`}
data-disabled={disabled || undefined}
onPointerDown={select}
>
<input <input
ref={inputRef} ref={inputRef}
id={id} id={id}
className="choice-stepper__input" className="choice-stepper__input"
value={text} value={text}
disabled={disabled} disabled={disabled}
readOnly={isMobile}
onFocus={deselect}
onChange={(e) => { onChange={(e) => {
typing.current = true; typing.current = true;
setText(e.target.value); setText(e.target.value);
@@ -431,6 +431,7 @@ export const LinearGraph = forwardRef<LinearGraphHandle, LinearGraphProps>(funct
formatX, formatX,
formatY, formatY,
draw, draw,
cq.w
]); ]);
useEffect(() => { useEffect(() => {
+50 -19
View File
@@ -1,23 +1,20 @@
.notifications { .notifications {
position: fixed; position: fixed;
right: var(--space-5); right: var(--space-5);
top: var(--space-5); top: calc(var(--topbar-h) + var(--space-3));
z-index: 9999; z-index: 9999;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: var(--space-3); gap: var(--space-3);
width: 320px; width: min(320px, calc(100vw - 2 * var(--space-5)));
pointer-events: none; pointer-events: none;
animation: notification-in var(--dur-slow) var(--ease-out); /* no "forwards" */
touch-action: pan-y;
} }
.notification { .notification {
display: flex; display: flex;
align-items: center; align-items: flex-start;
justify-content: space-between; justify-content: space-between;
gap: var(--space-3); gap: var(--space-3);
@@ -25,14 +22,34 @@
border-radius: var(--radius-md); border-radius: var(--radius-md);
font-size: 14px; font-size: 14px;
line-height: 1.45;
box-shadow: var(--shadow-md); box-shadow: var(--shadow-md);
animation: notification-in var(--dur-slow) var(--ease-out) forwards; /* no "forwards": it would keep overriding the inline drag transform */
animation: notification-in var(--dur-slow) var(--ease-out);
pointer-events: auto; pointer-events: auto;
min-width: 0;
/* swipe behavior */
touch-action: pan-y; /* browser keeps vertical scroll, we handle horizontal */
user-select: none;
-webkit-user-select: none;
cursor: grab;
will-change: transform, opacity;
} }
.notification--dragging {
cursor: grabbing;
}
/* once the user touches it, the inline style fully controls transform/opacity */
.notification--touched:not(.notification-out) {
animation: none;
}
/* must stay "forwards" so it holds its end state until removal */
.notification-out { .notification-out {
animation: notification-out var(--dur-slow) var(--ease-in) forwards; animation: notification-out var(--dur-slow) var(--ease-in) forwards;
} }
@@ -76,9 +93,10 @@
.notification-message { .notification-message {
flex: 1; flex: 1;
overflow: hidden; min-width: 0;
text-overflow: ellipsis; white-space: normal;
white-space: nowrap; overflow-wrap: anywhere;
word-break: normal;
} }
@keyframes notification-in { @keyframes notification-in {
@@ -105,13 +123,7 @@
} }
} }
/* After a swipe-dismiss, the inline transition takes over (no restart from translateX(0)) */
.notification--swiped {
animation: none;
}
@media (pointer: coarse) { @media (pointer: coarse) {
/* Undo the global 44px min-height on the small × button */
.notification-close { .notification-close {
min-height: 0; min-height: 0;
} }
@@ -119,11 +131,30 @@
@media (max-width: 768px) { @media (max-width: 768px) {
.notifications { .notifications {
top: calc(var(--topbar-h, 0px) + var(--space-2)); top: calc(var(--topbar-h) + var(--space-2));
left: max(var(--space-3), var(--safe-left, 0px)); left: max(var(--space-3), var(--safe-left));
right: max(var(--space-3), var(--safe-right, 0px)); right: max(var(--space-3), var(--safe-right));
width: auto; width: auto;
max-width: 420px; max-width: 420px;
margin-inline: auto; margin-inline: auto;
} }
.notification {
padding: var(--space-3);
font-size: 14px;
align-items: flex-start;
}
.notification-message {
white-space: normal;
overflow: visible;
text-overflow: unset;
overflow-wrap: anywhere;
}
}
@media (prefers-reduced-motion: reduce) {
.notification {
animation-duration: 1ms;
}
} }
+50 -18
View File
@@ -8,9 +8,11 @@ type Props = {
onHover: (id: number, hovering: boolean) => void; onHover: (id: number, hovering: boolean) => void;
}; };
const DRAG_START_PX = 8; // movement before it counts as a swipe const DRAG_START_PX = 6; // movement before it counts as a swipe
const DISMISS_RATIO = 0.35; // fraction of the width to drag before it dismisses const DISMISS_RATIO = 0.35; // fraction of width to drag before it dismisses
const DISMISS_MS = 160; const FLICK_VELOCITY = 0.5; // px/ms, a fast flick dismisses even below the threshold
const DISMISS_MS = 180;
const SNAP_MS = 220;
function NotificationItem({ function NotificationItem({
n, n,
@@ -23,25 +25,34 @@ function NotificationItem({
}) { }) {
const ref = useRef<HTMLDivElement>(null); const ref = useRef<HTMLDivElement>(null);
const startX = useRef<number | null>(null); const startX = useRef<number | null>(null);
const dxRef = useRef(0);
const locked = useRef(false); const locked = useRef(false);
const last = useRef({ x: 0, t: 0, v: 0 }); // for velocity
const [dx, setDx] = useState(0); const [dx, setDx] = useState(0);
const [dragging, setDragging] = useState(false); const [dragging, setDragging] = useState(false);
const [swiped, setSwiped] = useState(false); const [swiped, setSwiped] = useState(false);
const [interacted, setInteracted] = useState(false); // disables the entry animation after first touch
function updateDx(v: number) {
dxRef.current = v;
setDx(v);
}
function reset() { function reset() {
const wasLocked = locked.current; const wasLocked = locked.current;
startX.current = null; startX.current = null;
locked.current = false; locked.current = false;
setDragging(false); setDragging(false);
setDx(0); updateDx(0); // transition handles the snap-back
if (wasLocked) onHover(n.id, false); if (wasLocked) onHover(n.id, false);
} }
function onPointerDown(e: React.PointerEvent<HTMLDivElement>) { function onPointerDown(e: React.PointerEvent<HTMLDivElement>) {
if (swiped || n.removing) return; if (swiped || n.removing) return;
if ((e.target as HTMLElement).closest('button')) return; // let the × button work if ((e.target as HTMLElement).closest('button')) return;
startX.current = e.clientX; startX.current = e.clientX;
last.current = { x: e.clientX, t: performance.now(), v: 0 };
locked.current = false; locked.current = false;
} }
@@ -53,13 +64,25 @@ function NotificationItem({
if (Math.abs(delta) < DRAG_START_PX) return; if (Math.abs(delta) < DRAG_START_PX) return;
locked.current = true; locked.current = true;
e.currentTarget.setPointerCapture(e.pointerId); e.currentTarget.setPointerCapture(e.pointerId);
setInteracted(true);
setDragging(true); setDragging(true);
onHover(n.id, true); // pause the auto-dismiss timer onHover(n.id, true); // pause auto-dismiss timer
}
setDx(delta);
} }
function onPointerUp(e: React.PointerEvent<HTMLDivElement>) { // velocity (smoothed)
const now = performance.now();
const dt = now - last.current.t;
if (dt > 0) {
const instant = (e.clientX - last.current.x) / dt;
last.current.v = last.current.v * 0.6 + instant * 0.4;
}
last.current.x = e.clientX;
last.current.t = now;
updateDx(delta);
}
function finish(e: React.PointerEvent<HTMLDivElement>) {
if (startX.current === null) return; if (startX.current === null) return;
if (!locked.current) { if (!locked.current) {
@@ -68,13 +91,18 @@ function NotificationItem({
} }
const width = ref.current?.offsetWidth ?? 300; const width = ref.current?.offsetWidth ?? 300;
if (Math.abs(dx) > width * DISMISS_RATIO) { const dist = dxRef.current;
const dir = dx > 0 ? 1 : -1; const v = last.current.v;
const flicked = Math.abs(v) > FLICK_VELOCITY && Math.sign(v) === Math.sign(dist);
const farEnough = Math.abs(dist) > width * DISMISS_RATIO;
if (flicked || farEnough) {
const dir = dist > 0 ? 1 : -1;
startX.current = null; startX.current = null;
locked.current = false; locked.current = false;
setSwiped(true); setSwiped(true);
setDragging(false); setDragging(false);
setDx(dir * width * 1.2); updateDx(dir * width * 1.1);
window.setTimeout(() => onRemove(n.id), DISMISS_MS); window.setTimeout(() => onRemove(n.id), DISMISS_MS);
} else { } else {
reset(); reset();
@@ -85,14 +113,17 @@ function NotificationItem({
} }
} }
const touched = dx !== 0 || swiped; const width = ref.current?.offsetWidth ?? 300;
const style: React.CSSProperties | undefined = touched const progress = Math.min(1, Math.abs(dx) / (width * 0.8));
const style: React.CSSProperties | undefined = interacted
? { ? {
transform: `translateX(${dx}px)`, transform: `translateX(${dx}px)`,
opacity: swiped ? 0 : Math.max(0.3, 1 - Math.abs(dx) / 300), opacity: swiped ? 0 : 1 - progress * 0.9,
transition: dragging transition: dragging
? 'none' ? 'none'
: `transform ${DISMISS_MS}ms ease-out, opacity ${DISMISS_MS}ms ease-out`, : `transform ${swiped ? DISMISS_MS : SNAP_MS}ms cubic-bezier(0.22, 1, 0.36, 1),
opacity ${swiped ? DISMISS_MS : SNAP_MS}ms ease-out`,
} }
: undefined; : undefined;
@@ -103,7 +134,8 @@ function NotificationItem({
'notification', 'notification',
n.type, n.type,
n.removing && !swiped ? 'notification-out' : '', n.removing && !swiped ? 'notification-out' : '',
swiped ? 'notification--swiped' : '', interacted ? 'notification--touched' : '',
dragging ? 'notification--dragging' : '',
] ]
.filter(Boolean) .filter(Boolean)
.join(' ')} .join(' ')}
@@ -112,7 +144,7 @@ function NotificationItem({
onMouseLeave={() => onHover(n.id, false)} onMouseLeave={() => onHover(n.id, false)}
onPointerDown={onPointerDown} onPointerDown={onPointerDown}
onPointerMove={onPointerMove} onPointerMove={onPointerMove}
onPointerUp={onPointerUp} onPointerUp={finish}
onPointerCancel={reset} onPointerCancel={reset}
> >
<span className="notification-message" title={n.message}> <span className="notification-message" title={n.message}>
@@ -163,9 +163,16 @@ function SignalFlowMatrix({
const commitTimers = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map()); const commitTimers = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
useEffect(() => { useEffect(() => {
const timers = commitTimers.current;
const tooltipTimer = hideTooltipTimer.current;
return () => { return () => {
if (hideTooltipTimer.current) clearTimeout(hideTooltipTimer.current); if (tooltipTimer) {
commitTimers.current.forEach(clearTimeout); clearTimeout(tooltipTimer);
}
timers.forEach((timer) => clearTimeout(timer));
timers.clear();
}; };
}, []); }, []);
+11 -14
View File
@@ -88,25 +88,22 @@
aspect-ratio: 1; aspect-ratio: 1;
} }
.crown-action { .icon-settings,
height: 70%;
aspect-ratio: 1;
border-radius: 50%;
color: #facc15;
width: auto;
}
.crown-action:hover {
color: #fde047;
}
.icon-crown,
.icon-tab-add, .icon-tab-add,
.icon-tab-add-empty { .icon-tab-add-empty {
aspect-ratio: 1/1; aspect-ratio: 1/1;
height: 80%; height: 80%;
} }
.settings-action {
height: 70%;
width: auto;
aspect-ratio: 1 / 1;
border-radius: 50%;
color: var(--text-muted);
flex: 0 0 auto;
}
.tab-add-empty { .tab-add-empty {
height: 70%; height: 70%;
border-radius: var(--radius-pill); border-radius: var(--radius-pill);
@@ -364,7 +361,7 @@
/* Buttons at least ~40px wide */ /* Buttons at least ~40px wide */
.tab-add, .tab-add,
.crown-action { .settings-action {
height: 40px; height: 40px;
width: 40px; width: 40px;
} }
+6 -6
View File
@@ -2,11 +2,11 @@ import { useEffect, useRef } from 'react';
import { DSP, AppPage, isConnected } from '../../types'; import { DSP, AppPage, isConnected } from '../../types';
import AnimatedLogo from '../../assets/icons/AnimatedLogo'; import AnimatedLogo from '../../assets/icons/AnimatedLogo';
import { PlusIcon } from '../../assets/icons/PlusIcon'; import { PlusIcon } from '../../assets/icons/PlusIcon';
import { CrownIcon } from '../../assets/icons/CrownIcon';
import Led from '../Led/Led'; import Led from '../Led/Led';
import { CloseIcon } from '../../assets/icons/CloseIcon'; import { CloseIcon } from '../../assets/icons/CloseIcon';
import './Topbar.css'; import './Topbar.css';
import { SettingsIcon } from '../../assets/icons/SettingsIcon';
function getStep(count: number) { function getStep(count: number) {
if (count <= 4) return 4; if (count <= 4) return 4;
@@ -224,15 +224,15 @@ function TopBar({
)} )}
<button <button
className="crown-action tab-action" className="settings-action tab-action"
title="Credits & Support" title="Settings"
aria-label="Credits & Support" aria-label="Settings"
onClick={() => { onClick={() => {
setPage('credits'); setPage('settings');
setSelect(null); setSelect(null);
}} }}
> >
<CrownIcon className="icon-crown" /> <SettingsIcon className="icon-settings" />
</button> </button>
</div> </div>
</header> </header>
@@ -14,6 +14,12 @@
-webkit-user-select: none; -webkit-user-select: none;
} }
.gauge-viewport.is-selected {
outline: 0.4cqh solid var(--accent-brand);
outline-offset: -0.4cqh;
border-radius: 1.6cqh;
}
.gauge-track { .gauge-track {
position: relative; position: relative;
flex: 1 1 auto; flex: 1 1 auto;
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react'; import { useEffect, useMemo, useRef, useState } from 'react';
import { useVolumeKeys } from '../../hooks/useVolumeKeys';
import './VerticalSlider.css'; import './VerticalSlider.css';
type StepFn = (value: number) => number; type StepFn = (value: number) => number;
@@ -192,8 +193,9 @@ export default function VerticalSlider({
const sliderRef = useRef<HTMLDivElement>(null); const sliderRef = useRef<HTMLDivElement>(null);
const trackRef = useRef<HTMLDivElement>(null); const trackRef = useRef<HTMLDivElement>(null);
const thumbRef = useRef<HTMLDivElement>(null); const thumbRef = useRef<HTMLDivElement>(null);
const rootRef = useRef<HTMLDivElement>(null);
// --- shared interaction state (all three input methods use these) ------ // --- shared interaction state (all input methods use these) ------------
/** Latest value shown locally. Source of truth for "where is the thumb right now". */ /** Latest value shown locally. Source of truth for "where is the thumb right now". */
const latestValue = useRef(value); const latestValue = useRef(value);
@@ -220,7 +222,6 @@ export default function VerticalSlider({
const wheelTimeout = useRef<ReturnType<typeof setTimeout> | null>(null); const wheelTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
if (scale === 'log' && !values && (min <= 0 || max <= 0)) { if (scale === 'log' && !values && (min <= 0 || max <= 0)) {
// eslint-disable-next-line no-console
console.warn( console.warn(
'VerticalSlider: scale="log" requires min > 0 and max > 0. Falling back to linear behavior for out-of-range bounds.' 'VerticalSlider: scale="log" requires min > 0 and max > 0. Falling back to linear behavior for out-of-range bounds.'
); );
@@ -259,7 +260,8 @@ export default function VerticalSlider({
} }
/** /**
* Single serialized commit pipeline shared by drag, keyboard, wheel and text entry. * Single serialized commit pipeline shared by drag, keyboard, wheel,
* volume buttons and text entry.
* *
* - Only one onChange is ever in flight. * - Only one onChange is ever in flight.
* - While one is in flight, newer values just overwrite `pendingCommit` * - While one is in flight, newer values just overwrite `pendingCommit`
@@ -409,6 +411,7 @@ export default function VerticalSlider({
onInputRef.current?.(next); onInputRef.current?.(next);
} }
/** Returns the value one step up (+1) or down (-1) from `base`. */
/** Returns the value one step up (+1) or down (-1) from `base`. */ /** Returns the value one step up (+1) or down (-1) from `base`. */
function nudge(base: number, direction: 1 | -1) { function nudge(base: number, direction: 1 | -1) {
if (listValues) { if (listValues) {
@@ -416,9 +419,35 @@ export default function VerticalSlider({
const nextIdx = Math.min(listValues.length - 1, Math.max(0, idx + direction)); const nextIdx = Math.min(listValues.length - 1, Math.max(0, idx + direction));
return listValues[nextIdx]; return listValues[nextIdx];
} }
return normalizeValue(base + direction * step(base));
// Use the step size of the region we're moving INTO. Without this, moving
// down from a threshold (e.g. -20) uses the fine step, then gets snapped
// back by the coarse grid of the lower region and never leaves.
const probe = direction === 1 ? base : base - 1e-9;
const s = step(Math.min(max, Math.max(min, probe)));
return normalizeValue(base + direction * s);
} }
/** Moves one step and commits after a short idle delay (shared by wheel and volume buttons). */
function nudgeAndCommitDebounced(direction: 1 | -1) {
updateValue(nudge(latestValue.current, direction));
if (wheelTimeout.current) clearTimeout(wheelTimeout.current);
wheelTimeout.current = setTimeout(() => {
wheelTimeout.current = null;
commitLatestIfChanged();
}, WHEEL_COMMIT_DELAY_MS);
}
// --- hardware volume buttons (mobile only, via the shared hook) --------
const { isSelected, select, deselect } = useVolumeKeys({
rootRef,
disabled,
onStep: nudgeAndCommitDebounced, // volume up = increase, down = decrease
});
// --- keyboard ---------------------------------------------------------- // --- keyboard ----------------------------------------------------------
function handleKeyDown(e: React.KeyboardEvent<HTMLDivElement>) { function handleKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {
@@ -462,14 +491,7 @@ export default function VerticalSlider({
// deltaY < 0 means scrolling up/away from the user — treat that as // deltaY < 0 means scrolling up/away from the user — treat that as
// increasing the value, matching the vertical slider's "up = more". // increasing the value, matching the vertical slider's "up = more".
const direction: 1 | -1 = e.deltaY < 0 ? 1 : -1; nudgeAndCommitDebounced(e.deltaY < 0 ? 1 : -1);
updateValue(nudge(latestValue.current, direction));
if (wheelTimeout.current) clearTimeout(wheelTimeout.current);
wheelTimeout.current = setTimeout(() => {
wheelTimeout.current = null;
commitLatestIfChanged();
}, WHEEL_COMMIT_DELAY_MS);
} }
useEffect(() => { useEffect(() => {
@@ -579,7 +601,10 @@ export default function VerticalSlider({
return ( return (
<div <div
className={['gauge-viewport', disabled && 'is-disabled', className].filter(Boolean).join(' ')} ref={rootRef}
className={['gauge-viewport', disabled && 'is-disabled', isSelected && 'is-selected', className]
.filter(Boolean)
.join(' ')}
style={style} style={style}
> >
<div <div
@@ -603,10 +628,14 @@ export default function VerticalSlider({
aria-valuemax={max} aria-valuemax={max}
aria-valuenow={displayValue} aria-valuenow={displayValue}
tabIndex={disabled ? -1 : 0} tabIndex={disabled ? -1 : 0}
onFocus={select}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp} onKeyUp={handleKeyUp}
onBlur={handleSliderBlur} onBlur={handleSliderBlur}
onPointerDown={startDrag} onPointerDown={(e) => {
select();
startDrag(e);
}}
onPointerMove={handlePointerMove} onPointerMove={handlePointerMove}
onPointerUp={endDrag} onPointerUp={endDrag}
onPointerCancel={endDrag} onPointerCancel={endDrag}
@@ -632,7 +661,10 @@ export default function VerticalSlider({
disabled={disabled} disabled={disabled}
value={editingText ?? formattedValue} value={editingText ?? formattedValue}
style={{ width: '100%' }} style={{ width: '100%' }}
onFocus={() => setEditingText(displayValue.toFixed(decimals))} // plain number while editing onFocus={() => {
deselect(); // volume keys shouldn't move the slider while typing
setEditingText(displayValue.toFixed(decimals)); // plain number while editing
}}
onChange={(e) => setEditingText(e.target.value)} onChange={(e) => setEditingText(e.target.value)}
onBlur={commitEditing} onBlur={commitEditing}
onKeyDown={(e) => { onKeyDown={(e) => {
+10
View File
@@ -0,0 +1,10 @@
import { platform } from '@tauri-apps/plugin-os';
export const isMobileOS: boolean = (() => {
try {
const p = platform();
return p === 'android' || p === 'ios';
} catch {
return false; // not running inside Tauri (tests, browser dev)
}
})();
+54
View File
@@ -0,0 +1,54 @@
import { useEffect, useRef } from 'react';
import { isMobileOS } from './platform';
import { forDSP408, setAppBackgrounded, isPolling } from '../features/dsp408/dsp408';
import { DSP, isConnected } from '../types';
import { SetDsps, NotifyFn } from './dspShared';
export function useMobileBackgroundDisconnect(
dsps: DSP[],
setDsps: SetDsps,
notify: NotifyFn
) {
const dspsRef = useRef(dsps);
dspsRef.current = dsps;
useEffect(() => {
if (!isMobileOS) return; // desktop: nothing is registered
const goBackground = () => {
setAppBackgrounded(true);
for (const d of dspsRef.current) {
if (d.type !== 'DSP408') continue;
// Rust disconnect is idempotent, so no connection-state filter is needed.
// ADJUST: skip demo-mode DSPs here if you don't want them disconnected.
void forDSP408(d, setDsps, notify).disconnectForBackground();
}
};
const onResume = () => {
setAppBackgrounded(false); // allows a MANUAL connect again; never reconnects
for (const d of dspsRef.current) {
if (d.type !== 'DSP408' || !isPolling(d.id)) continue;
const api = forDSP408(d, setDsps, notify);
api
.updateDSPState()
.then((s) => {
if (!isConnected({ ...d, state: s } as DSP)) return api.disconnectForBackground();
})
.catch(() => {});
}
};
const onVisibility = () => {
if (document.visibilityState === 'hidden') goBackground();
else onResume();
};
document.addEventListener('visibilitychange', onVisibility);
window.addEventListener('pagehide', goBackground);
return () => {
document.removeEventListener('visibilitychange', onVisibility);
window.removeEventListener('pagehide', goBackground);
};
}, [setDsps, notify]);
}
@@ -6,7 +6,9 @@ import { sumCurvePoints, sumPhaseCurvePoints } from '../../utils/graph/curve';
import { getPeqCurvePoints, getPeqPhasePoints } from '../../utils/graph/peq'; import { getPeqCurvePoints, getPeqPhasePoints } from '../../utils/graph/peq';
import { getCrossoverCurvePoints, getCrossoverPhasePoints } from '../../utils/graph/crossover'; import { getCrossoverCurvePoints, getCrossoverPhasePoints } from '../../utils/graph/crossover';
import { drawCurves } from '../../utils/graph/draw'; import { drawCurves } from '../../utils/graph/draw';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph'; import LinearGraph, {
type LinearGraphHelpers,
} from '../../../../components/LinearGraph/LinearGraph';
// Constant, so compute once instead of every render. // Constant, so compute once instead of every render.
const GRAPH_FREQS = logSpace(GRAPH_X_MIN, GRAPH_X_MAX, 1000); const GRAPH_FREQS = logSpace(GRAPH_X_MIN, GRAPH_X_MAX, 1000);
@@ -38,7 +40,7 @@ export const MagnitudeGraph = memo(function MagnitudeGraph({
); );
const draw = useCallback( const draw = useCallback(
({ ctx, toPx }: any) => { ({ ctx, toPx }: LinearGraphHelpers) => {
drawCurves({ drawCurves({
ctx, ctx,
toPx, toPx,
@@ -87,7 +89,7 @@ export const PhaseGraph = memo(function PhaseGraph({
); );
const draw = useCallback( const draw = useCallback(
({ ctx, toPx }: any) => { ({ ctx, toPx }: LinearGraphHelpers) => {
drawCurves({ drawCurves({
ctx, ctx,
toPx, toPx,
@@ -1,7 +1,9 @@
import { memo, useCallback, useMemo } from 'react'; import { memo, useCallback, useMemo } from 'react';
import { Ratio } from '../../types'; import { Ratio } from '../../types';
import { RATIO_NUMERIC } from '../../constants'; import { RATIO_NUMERIC } from '../../constants';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph'; import LinearGraph, {
type LinearGraphHelpers,
} from '../../../../components/LinearGraph/LinearGraph';
const formatTick = (v: number) => Math.round(v).toString(); const formatTick = (v: number) => Math.round(v).toString();
@@ -66,7 +68,7 @@ export const CompressorGraph = memo(function CompressorGraph({
}, [threshold, ratio, knee]); }, [threshold, ratio, knee]);
const draw = useCallback( const draw = useCallback(
({ ctx, toPx }: any) => { ({ ctx, toPx }: LinearGraphHelpers) => {
// Unity reference line // Unity reference line
ctx.strokeStyle = '#6b7280'; ctx.strokeStyle = '#6b7280';
ctx.lineWidth = 1; ctx.lineWidth = 1;
@@ -1,8 +1,10 @@
import { memo, useCallback, useMemo } from 'react'; import { memo, useCallback, useMemo } from 'react';
import { DelayUnit } from '../../types'; import { DelayUnit } from '../../types';
import { DELAY_RANGES } from '../../constants'; import { DELAY_RANGES } from '../../constants';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph';
import { DELAY_UNIT_LABEL } from '../../constants'; import { DELAY_UNIT_LABEL } from '../../constants';
import LinearGraph, {
type LinearGraphHelpers,
} from '../../../../components/LinearGraph/LinearGraph';
const formatY = (v: number) => v.toFixed(0); const formatY = (v: number) => v.toFixed(0);
@@ -34,7 +36,7 @@ export const DelayGraph = memo(
const formatX = useCallback((v: number) => labelByX.get(Math.round(v)) ?? '', [labelByX]); const formatX = useCallback((v: number) => labelByX.get(Math.round(v)) ?? '', [labelByX]);
const draw = useCallback( const draw = useCallback(
({ ctx, toPx, plot }: any) => { ({ ctx, toPx, plot }: LinearGraphHelpers) => {
const barWidth = (plot.width / rows.length) * 0.55; const barWidth = (plot.width / rows.length) * 0.55;
rows.forEach((row, i) => { rows.forEach((row, i) => {
@@ -2,7 +2,9 @@ import { memo, useCallback, useMemo } from 'react';
import { GRAPH_FREQS, GRAPH_X_MAX, GRAPH_X_MIN, GRAPH_Y_MIN, Y_AXIS_STEP } from '../../constants'; import { GRAPH_FREQS, GRAPH_X_MAX, GRAPH_X_MIN, GRAPH_Y_MIN, Y_AXIS_STEP } from '../../constants';
import { Curve, CurvePoint } from '../../utils/graph/curve'; import { Curve, CurvePoint } from '../../utils/graph/curve';
import { drawCurves } from '../../utils/graph/draw'; import { drawCurves } from '../../utils/graph/draw';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph'; import LinearGraph, {
type LinearGraphHelpers,
} from '../../../../components/LinearGraph/LinearGraph';
// Expands [baseMin, baseMax] outward to fit whatever the curves actually // Expands [baseMin, baseMax] outward to fit whatever the curves actually
// contain (e.g. gain + geq + peq stacking past the nominal graph range), // contain (e.g. gain + geq + peq stacking past the nominal graph range),
@@ -115,7 +117,7 @@ function ResponseGraphInner<T extends string, S>({
); );
const draw = useCallback( const draw = useCallback(
({ ctx, toPx }: any) => { ({ ctx, toPx }: LinearGraphHelpers) => {
drawCurves({ ctx, toPx, xMin: GRAPH_X_MIN, xMax: GRAPH_X_MAX, yMin, yMax, curves }); drawCurves({ ctx, toPx, xMin: GRAPH_X_MIN, xMax: GRAPH_X_MAX, yMin, yMax, curves });
}, },
[curves, yMin, yMax] [curves, yMin, yMax]
@@ -1,5 +1,7 @@
import { memo, useCallback, useMemo } from 'react'; import { memo, useCallback, useMemo } from 'react';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph'; import LinearGraph, {
type LinearGraphHelpers,
} from '../../../../components/LinearGraph/LinearGraph';
const formatTick = (v: number) => Math.round(v).toString(); const formatTick = (v: number) => Math.round(v).toString();
@@ -25,7 +27,7 @@ export const GateGraph = memo(function GateGraph({
}, [attack, hold, release]); }, [attack, hold, release]);
const draw = useCallback( const draw = useCallback(
({ toPx, ctx }: any) => { ({ ctx, toPx }: LinearGraphHelpers) => {
const { t0, t1, t2, t3, t4, t5 } = envelope; const { t0, t1, t2, t3, t4, t5 } = envelope;
ctx.strokeStyle = '#fbbf24'; ctx.strokeStyle = '#fbbf24';
@@ -4,9 +4,11 @@ import { drawCurves } from '../../utils/graph/draw';
import { GRAPH_X_MIN, GRAPH_X_MAX, GRAPH_Y_MIN, GRAPH_Y_MAX, GEQ_CURVE_Q } from '../../constants'; import { GRAPH_X_MIN, GRAPH_X_MAX, GRAPH_Y_MIN, GRAPH_Y_MAX, GEQ_CURVE_Q } from '../../constants';
import { DiscreteFrequency } from '../../types'; import { DiscreteFrequency } from '../../types';
import { GEQ_BANDS_LABEL } from '../../constants'; import { GEQ_BANDS_LABEL } from '../../constants';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph';
import { getGeqCurvePoints } from '../../utils/graph/geq'; import { getGeqCurvePoints } from '../../utils/graph/geq';
import { LiveBands } from './GeqSection'; import { LiveBands } from './GeqSection';
import LinearGraph, {
type LinearGraphHelpers,
} from '../../../../components/LinearGraph/LinearGraph';
const GEQ_FREQS = logSpace(GRAPH_X_MIN, GRAPH_X_MAX, 1000); const GEQ_FREQS = logSpace(GRAPH_X_MIN, GRAPH_X_MAX, 1000);
@@ -29,7 +31,7 @@ export const GeqGraph = memo(function GeqGraph({
}, [gains, liveBands]); }, [gains, liveBands]);
const draw = useCallback( const draw = useCallback(
({ ctx, toPx }: any) => { ({ ctx, toPx }: LinearGraphHelpers) => {
drawCurves({ drawCurves({
ctx, ctx,
toPx, toPx,
@@ -1,5 +1,7 @@
import { memo, useCallback, useMemo } from 'react'; import { memo, useCallback, useMemo } from 'react';
import LinearGraph from '../../../../components/LinearGraph/LinearGraph'; import LinearGraph, {
type LinearGraphHelpers,
} from '../../../../components/LinearGraph/LinearGraph';
const formatTick = (v: number) => Math.round(v).toString(); const formatTick = (v: number) => Math.round(v).toString();
@@ -20,7 +22,7 @@ export const LimiterGraph = memo(function LimiterGraph({ threshold }: { threshol
}, [threshold]); }, [threshold]);
const draw = useCallback( const draw = useCallback(
({ ctx, toPx }: any) => { ({ ctx, toPx }: LinearGraphHelpers) => {
// Unity reference line // Unity reference line
ctx.strokeStyle = '#6b7280'; ctx.strokeStyle = '#6b7280';
ctx.lineWidth = 1; ctx.lineWidth = 1;
@@ -93,8 +93,9 @@ function MatrixSection({
setLiveGains((prev) => { setLiveGains((prev) => {
if (value === null) { if (value === null) {
if (!(key in prev)) return prev; if (!(key in prev)) return prev;
const { [key]: _removed, ...rest } = prev; return Object.fromEntries(
return rest; Object.entries(prev).filter(([k]) => k !== key)
);
} }
return { ...prev, [key]: value }; return { ...prev, [key]: value };
}); });
@@ -235,7 +235,6 @@ function LinkChannelsModal({
]; ];
for (const group of groups) { for (const group of groups) {
// eslint-disable-next-line no-await-in-loop
await linkChannels(group.source, group.destinations); await linkChannels(group.source, group.destinations);
} }
+46
View File
@@ -78,6 +78,16 @@ export function stopPolling(id: number) {
registerPollStopper('DSP408', stopPolling); registerPollStopper('DSP408', stopPolling);
// --- background state, private to this module --------------------------
let appBackgrounded = false;
export function setAppBackgrounded(v: boolean) {
appBackgrounded = v;
}
export function isPolling(id: number): boolean {
return pollIntervals.has(id);
}
// --- pause helper ---------------------------------------------------------- // --- pause helper ----------------------------------------------------------
async function withPollingPaused<T>( async function withPollingPaused<T>(
@@ -141,6 +151,30 @@ export function forDSP408(dsp: DSP408, setDsps: SetDsps, notify: NotifyFn) {
} }
} }
async function disconnectForBackground() {
// synchronous part first: the webview may be frozen right after this
stopPolling(dsp.id);
updateDSP(setDsps, dsp.id, (d) => ({
...d,
isConnecting: false,
pollingPaused: true,
}));
try {
await invoke('disconnect_dsp408', { id: dsp.id });
} catch {
// socket may already be gone; Rust-side fallback covers the rest
}
// quiet state refresh (no error toast while backgrounded)
try {
const state = await invoke<DSP408['state']>('get_dsp_state', { id: dsp.id });
updateDSP(setDsps, dsp.id, (d) => ({ ...d, state }) as DSP408);
} catch {
/* ignore */
}
}
const isLocked = (s: DSP408['state']) => s.flags.is_locked; const isLocked = (s: DSP408['state']) => s.flags.is_locked;
async function abortLocked() { async function abortLocked() {
@@ -155,6 +189,11 @@ export function forDSP408(dsp: DSP408, setDsps: SetDsps, notify: NotifyFn) {
try { try {
await invoke('connect_dsp408', { id: dsp.id }); await invoke('connect_dsp408', { id: dsp.id });
if (appBackgrounded) { // NEW: backgrounded mid-connect
await disconnectForBackground();
return;
}
let state = await updateDSPState(); let state = await updateDSPState();
if (isLocked(state)) { if (isLocked(state)) {
@@ -174,6 +213,11 @@ export function forDSP408(dsp: DSP408, setDsps: SetDsps, notify: NotifyFn) {
} }
} }
if (appBackgrounded) {
await disconnectForBackground();
return;
}
updateDSP(setDsps, dsp.id, (d) => ({ ...d, isConnecting: false, pollingPaused: false })); updateDSP(setDsps, dsp.id, (d) => ({ ...d, isConnecting: false, pollingPaused: false }));
notify('Connected', 'success', dsp.name); notify('Connected', 'success', dsp.name);
startPolling(dsp, setDsps); startPolling(dsp, setDsps);
@@ -939,5 +983,7 @@ export function forDSP408(dsp: DSP408, setDsps: SetDsps, notify: NotifyFn) {
} }
}); });
}, },
disconnectForBackground,
}; };
} }
+17
View File
@@ -0,0 +1,17 @@
import { useEffect, useState } from 'react';
const QUERY = '(pointer: coarse)';
/** True when the primary input is a finger, regardless of screen width or orientation. */
export function useIsTouch() {
const [isTouch, setIsTouch] = useState(() => window.matchMedia(QUERY).matches);
useEffect(() => {
const mq = window.matchMedia(QUERY);
const handler = (e: MediaQueryListEvent) => setIsTouch(e.matches);
mq.addEventListener('change', handler);
return () => mq.removeEventListener('change', handler);
}, []);
return isTouch;
}
+109 -11
View File
@@ -1,53 +1,151 @@
import { useState, useCallback, useRef } from 'react';
import { useState, useCallback, useRef, useEffect } from 'react';
import { NotificationType, Notification } from '../types'; import { NotificationType, Notification } from '../types';
import { loadSettings } from '../pages/SettingsPage/settingsStore';
type PendingNotification = {
message: string;
type: NotificationType;
dspName?: string;
};
export function useNotifications() { export function useNotifications() {
const [notifications, setNotifications] = useState<Notification[]>([]); const [notifications, setNotifications] = useState<Notification[]>([]);
const hovered = useRef<Set<number>>(new Set());
const nextId = useRef(0); // monotonically increasing counter
const notify = useCallback( const hovered = useRef<Set<number>>(new Set());
(message: string, type: NotificationType = 'error', dspName?: string) => { const nextId = useRef(0);
// null means settings haven't loaded yet
const disabled = useRef<boolean | null>(null);
const overridden = useRef(false);
const pending = useRef<PendingNotification[]>([]);
const addNotification = useCallback(
({ message, type, dspName }: PendingNotification) => {
const id = nextId.current++; const id = nextId.current++;
const fullMessage = dspName ? `${dspName}: ${message}` : message; const fullMessage = dspName ? `${dspName}: ${message}` : message;
setNotifications((prev) => [...prev, { id, message: fullMessage, type }]); setNotifications((prev) => [
...prev,
{ id, message: fullMessage, type },
]);
const removeLater = () => { const removeLater = () => {
if (hovered.current.has(id)) { if (hovered.current.has(id)) {
setTimeout(removeLater, 1000); setTimeout(removeLater, 1000);
return; return;
} }
setNotifications((prev) => prev.filter((n) => n.id !== id)); setNotifications((prev) => prev.filter((n) => n.id !== id));
}; };
setTimeout(removeLater, 5000); setTimeout(removeLater, 5000);
}, },
[] [],
);
// Load notification preference on startup
useEffect(() => {
let cancelled = false;
async function initialize() {
try {
const settings = await loadSettings();
if (cancelled) return;
// Don't overwrite a setting changed while loading
if (!overridden.current) {
disabled.current = settings.disableNotifications;
}
} catch (error) {
console.error('Failed to load notification settings:', error);
if (!cancelled && !overridden.current) {
disabled.current = false;
}
}
if (cancelled) return;
// Process notifications queued during initialization
const queued = pending.current.splice(0);
if (!disabled.current) {
queued.forEach(addNotification);
}
}
initialize();
return () => {
cancelled = true;
};
}, [addNotification]);
// Called by SettingsPage when the checkbox changes
const setNotificationsDisabled = useCallback((value: boolean) => {
overridden.current = true;
disabled.current = value;
if (value) {
setNotifications([]);
hovered.current.clear();
pending.current = [];
}
}, []);
const notify = useCallback(
(
message: string,
type: NotificationType = 'error',
dspName?: string,
) => {
const notification = { message, type, dspName };
// Wait until the preference has loaded
if (disabled.current === null) {
pending.current.push(notification);
return;
}
if (disabled.current) return;
addNotification(notification);
},
[addNotification],
); );
const removeNotification = useCallback((id: number) => { const removeNotification = useCallback((id: number) => {
hovered.current.delete(id); // prevent leaking stale hover state hovered.current.delete(id);
setNotifications((prev) => prev.map((n) => (n.id === id ? { ...n, removing: true } : n)));
setNotifications((prev) =>
prev.map((n) => (n.id === id ? { ...n, removing: true } : n)),
);
setTimeout(() => { setTimeout(() => {
setNotifications((prev) => prev.filter((n) => n.id !== id)); setNotifications((prev) => prev.filter((n) => n.id !== id));
}, 250); }, 250);
}, []); }, []);
const hoverNotification = useCallback((id: number, hovering: boolean) => { const hoverNotification = useCallback(
(id: number, hovering: boolean) => {
if (hovering) { if (hovering) {
hovered.current.add(id); hovered.current.add(id);
} else { } else {
hovered.current.delete(id); hovered.current.delete(id);
} }
}, []); },
[],
);
return { return {
notifications, notifications,
notify, notify,
removeNotification, removeNotification,
hoverNotification, hoverNotification,
setNotificationsDisabled,
}; };
} }
+116
View File
@@ -0,0 +1,116 @@
import { useEffect, useId, useRef, useState } from 'react';
import { useIsTouch } from './useIsTouch';
declare global {
interface Window {
VolumeBridge?: {
setIntercept: (on: boolean) => void;
};
}
}
/** The control that currently owns the hardware volume buttons. */
let activeId: string | null = null;
function setNativeIntercept(on: boolean) {
window.VolumeBridge?.setIntercept(on);
}
type Options = {
rootRef: React.RefObject<HTMLElement | null>;
/** +1 = volume up, -1 = volume down. Always sees fresh state. */
onStep: (direction: 1 | -1) => void;
disabled?: boolean;
};
export function useVolumeKeys({ rootRef, onStep, disabled }: Options) {
const isMobile = useIsTouch();
const id = useId();
const [selected, setSelected] = useState(false);
const onStepRef = useRef(onStep);
onStepRef.current = onStep;
function select() {
if (!isMobile || disabled) return;
activeId = id;
setNativeIntercept(true);
setSelected(true);
}
function deselect() {
setSelected(false);
if (activeId === id) {
activeId = null;
setNativeIntercept(false);
}
}
// Release on unmount
useEffect(() => {
return () => {
if (activeId === id) {
activeId = null;
setNativeIntercept(false);
}
};
}, [id]);
// Release when disabled
useEffect(() => {
if (disabled) deselect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [disabled]);
// Release when tapping outside
useEffect(() => {
if (!isMobile) return;
const onDown = (e: PointerEvent) => {
if (rootRef.current?.contains(e.target as Node)) return;
setSelected(false);
if (activeId === id) {
activeId = null;
setNativeIntercept(false);
}
};
document.addEventListener('pointerdown', onDown, true);
return () => {
document.removeEventListener('pointerdown', onDown, true);
};
}, [isMobile, id, rootRef]);
// Volume events from the native bridge
useEffect(() => {
if (!isMobile || disabled) return;
const onUp = () => {
if (activeId === id) onStepRef.current(1);
};
const onDown = () => {
if (activeId === id) onStepRef.current(-1);
};
document.addEventListener('volumeupbutton', onUp);
document.addEventListener('volumedownbutton', onDown);
return () => {
document.removeEventListener('volumeupbutton', onUp);
document.removeEventListener('volumedownbutton', onDown);
};
}, [isMobile, disabled, id]);
return {
isSelected: isMobile && selected,
select,
deselect,
};
}
-87
View File
@@ -1,87 +0,0 @@
.credits-page {
width: 100%;
max-width: 520px;
margin: auto;
user-select: none;
-webkit-user-select: none;
}
.credits-page__header {
margin-bottom: var(--space-5);
}
.credits-page__title {
margin: 0;
font-size: var(--font-2xl);
font-weight: var(--font-weight-semibold);
color: var(--text-primary);
}
.credits-page__subtitle {
margin: var(--space-2) 0 0;
font-size: var(--font-sm);
color: var(--text-muted);
}
.credits-page__actions {
display: flex;
justify-content: flex-end;
margin-top: var(--space-2);
}
.credits-page input,
.credits-page select,
.credits-page textarea {
user-select: text;
-webkit-user-select: text;
}
/* ---------- Phone ---------- */
@media (max-width: 768px) {
.credits-page {
max-width: 480px;
}
}
/* ---------- Landscape phone: compact card ---------- */
@media (max-height: 500px) and (orientation: landscape) {
.credits-page {
max-width: 440px;
}
.credits-page__header {
margin-bottom: 8px;
}
.credits-page__title {
font-size: var(--font-lg);
}
.credits-page__subtitle {
margin-top: 4px;
font-size: 12px;
}
.credits-page .specs {
gap: 6px;
margin-bottom: 8px;
padding: 8px 12px;
}
.credits-page .spec {
gap: 12px;
}
.credits-page .spec dt,
.credits-page .spec dd {
font-size: 12px;
}
.credits-page__actions {
margin-top: 4px;
}
}
-45
View File
@@ -1,45 +0,0 @@
import Card from '../../components/Card/Card';
import Button from '../../components/Button/Button';
import './CreditsPage.css';
function CreditsPage() {
return (
<Card className="credits-page">
<div className="credits-page__header">
<h1 className="credits-page__title">Credits</h1>
<p className="credits-page__subtitle">
Thanks to the people, projects, and communities that made this application possible.
</p>
</div>
<dl className="specs">
<div className="spec">
<dt>Developer</dt>
<dd>Lucas</dd>
</div>
<div className="spec">
<dt>Framework</dt>
<dd>React + TypeScript</dd>
</div>
<div className="spec">
<dt>Desktop Runtime</dt>
<dd>Tauri</dd>
</div>
<div className="spec">
<dt>Special Thanks</dt>
<dd></dd>
</div>
</dl>
<div className="credits-page__actions">
<Button variant="primary">Support the Project</Button>
</div>
</Card>
);
}
export default CreditsPage;
+218
View File
@@ -0,0 +1,218 @@
.settings-page {
width: 100%;
max-width: 520px;
margin: auto;
user-select: none;
-webkit-user-select: none;
}
/* ---------- Header ---------- */
.settings-page__header {
margin-bottom: var(--space-5);
}
.settings-page__title {
margin: 0;
font-size: var(--font-2xl);
font-weight: var(--font-weight-semibold);
color: var(--text-primary);
}
.settings-page__hint {
margin: var(--space-2) 0 0;
font-size: var(--font-sm);
color: var(--text-muted);
}
/* ---------- Sections ---------- */
.settings-page__section {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.settings-page__section-title {
margin: 0;
font-size: var(--font-sm);
font-weight: var(--font-weight-semibold);
color: var(--text-primary);
}
.settings-page__divider {
height: 1px;
background: var(--border-hairline);
margin: var(--space-5) 0;
}
/* ---------- Checkbox ---------- */
.settings-page__checkbox-label {
display: flex;
align-items: center;
gap: var(--space-3);
min-height: 36px;
cursor: pointer;
}
.settings-page__checkbox-content {
display: flex;
flex-direction: column;
gap: 3px;
min-width: 0;
font-size: var(--font-sm);
color: var(--text-primary);
}
.settings-page__description {
font-size: var(--font-xs);
color: var(--text-muted);
}
.settings-page__checkbox-label input[type='checkbox'] {
appearance: none;
-webkit-appearance: none;
box-sizing: border-box;
flex: 0 0 auto;
display: block;
width: 18px;
height: 18px;
aspect-ratio: 1 / 1;
padding: 0;
margin: 0;
background: var(--bg-panel);
border: var(--border-width) solid var(--border-hairline);
border-radius: var(--radius-sm);
position: relative;
cursor: pointer;
transition:
border-color var(--dur-base) var(--ease-standard),
background var(--dur-base) var(--ease-standard);
}
.settings-page__checkbox-label input[type='checkbox']:checked {
background: var(--accent-brand);
border-color: var(--accent-brand);
}
.settings-page__checkbox-label input[type='checkbox']:checked::after {
content: '';
position: absolute;
left: 50%;
top: 50%;
width: 5px;
height: 9px;
border: solid var(--bg-panel);
border-width: 0 2px 2px 0;
transform: translate(-50%, -60%) rotate(45deg);
}
.settings-page__checkbox-label input[type='checkbox']:focus-visible {
outline: 2px solid var(--accent-brand);
outline-offset: 2px;
}
/* ---------- Credits ---------- */
.settings-page__credits {
display: flex;
flex-direction: column;
gap: var(--space-3);
margin: 0;
}
.settings-page__credit {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
font-size: var(--font-sm);
}
.settings-page__credit dt {
color: var(--text-muted);
}
.settings-page__credit dd {
margin: 0;
color: var(--text-primary);
text-align: right;
}
/* ---------- Text selection ---------- */
.settings-page input {
user-select: text;
-webkit-user-select: text;
}
/* ---------- Phone / touch ---------- */
@media (pointer: coarse) {
.settings-page__checkbox-label {
min-height: 44px;
}
.settings-page__checkbox-label input[type='checkbox'] {
min-height: 0;
}
}
@media (max-width: 768px) {
.settings-page {
width: 100%;
max-width: 520px;
}
}
/* ---------- Landscape phone ---------- */
@media (max-height: 500px) and (orientation: landscape) {
.settings-page {
max-width: 440px;
}
.settings-page__header {
margin-bottom: 8px;
}
.settings-page__title {
font-size: var(--font-lg);
}
.settings-page__hint {
margin-top: 4px;
font-size: 12px;
}
.settings-page__section {
gap: 6px;
}
.settings-page__divider {
margin: 10px 0;
}
.settings-page__credits {
gap: 6px;
}
.settings-page__credit,
.settings-page__checkbox-content {
font-size: 12px;
}
}
+137
View File
@@ -0,0 +1,137 @@
import { useEffect, useState } from 'react';
import Card from '../../components/Card/Card';
import {
AppSettings,
DEFAULT_SETTINGS,
loadSettings,
saveSettings,
} from './settingsStore';
import './SettingsPage.css';
function SettingsPage({
onNotificationsDisabledChange,
}: {
onNotificationsDisabledChange: (disabled: boolean) => void;
}) {
const [settings, setSettings] = useState<AppSettings>(DEFAULT_SETTINGS);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
let cancelled = false;
async function initialize() {
try {
const saved = await loadSettings();
if (!cancelled) {
setSettings(saved);
onNotificationsDisabledChange(saved.disableNotifications);
}
} catch (error) {
console.error('Failed to load settings:', error);
} finally {
if (!cancelled) {
setLoaded(true);
}
}
}
initialize();
return () => {
cancelled = true;
};
}, [onNotificationsDisabledChange]);
async function updateSetting<K extends keyof AppSettings>(
key: K,
value: AppSettings[K],
) {
const updated = {
...settings,
[key]: value,
};
setSettings(updated);
try {
await saveSettings(updated);
} catch (error) {
console.error('Failed to save settings:', error);
}
}
return (
<Card className="settings-page">
<div className="settings-page__header">
<h1 className="settings-page__title">Settings</h1>
<p className="settings-page__hint">
Customize how the application behaves.
</p>
</div>
{/* General */}
<div className="settings-page__section">
<h2 className="settings-page__section-title">General</h2>
<label
htmlFor="disable-notifications"
className="settings-page__checkbox-label"
>
<input
id="disable-notifications"
type="checkbox"
checked={settings.disableNotifications}
disabled={!loaded}
onChange={(e) => {
const value = e.target.checked;
onNotificationsDisabledChange(value);
updateSetting('disableNotifications', value);
}}
/>
<div className="settings-page__checkbox-content">
<span>Disable notifications</span>
<span className="settings-page__description">
Prevent the application from displaying notifications.
</span>
</div>
</label>
</div>
<div className="settings-page__divider" />
{/* About */}
<div className="settings-page__section">
<h2 className="settings-page__section-title">About</h2>
<dl className="settings-page__credits">
<div className="settings-page__credit">
<dt>Developer</dt>
<dd>Lucas</dd>
</div>
<div className="settings-page__credit">
<dt>Framework</dt>
<dd>React + TypeScript</dd>
</div>
<div className="settings-page__credit">
<dt>Desktop Runtime</dt>
<dd>Tauri</dd>
</div>
<div className="settings-page__credit">
<dt>Special Thanks</dt>
<dd>Open-source community</dd>
</div>
</dl>
</div>
</Card>
);
}
export default SettingsPage;
+36
View File
@@ -0,0 +1,36 @@
import { load, Store } from '@tauri-apps/plugin-store';
export type AppSettings = {
disableNotifications: boolean;
};
export const DEFAULT_SETTINGS: AppSettings = {
disableNotifications: false,
};
const STORE_FILE = 'settings.json';
const STORE_KEY = 'settings';
let storePromise: Promise<Store> | null = null;
const getStore = () =>
(storePromise ??= load(STORE_FILE, { autoSave: false }));
export async function loadSettings(): Promise<AppSettings> {
const store = await getStore();
return {
...DEFAULT_SETTINGS,
...(await store.get<Partial<AppSettings>>(STORE_KEY)),
};
}
export async function saveSettings(
settings: AppSettings,
): Promise<void> {
const store = await getStore();
await store.set(STORE_KEY, settings);
await store.save();
}
+1 -1
View File
@@ -14,7 +14,7 @@ export type Notification = {
removing?: boolean; removing?: boolean;
}; };
export type AppPage = 'home' | 'add-dsp' | 'view-dsp' | 'credits'; export type AppPage = 'home' | 'add-dsp' | 'view-dsp' | 'settings';
type DSPDefaultParameters = { type DSPDefaultParameters = {
ip: string; ip: string;