mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-23 18:41:24 -08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88971f12ae |
No files matched your search
@@ -1,15 +0,0 @@
|
||||
# Copy to .env.local to report to Sentry from local builds.
|
||||
# Read by the gui (vite), electron and server (gradle) builds. Real environment variables win.
|
||||
# Rebuild after changing it, the values are baked in at build time.
|
||||
|
||||
# Forces a Sentry release. Without it only clean tagged builds report.
|
||||
# Source maps are never uploaded for a forced release.
|
||||
SENTRY_RELEASE=v0.0.0-local
|
||||
|
||||
# Keeps local events out of production alerts and release health. Defaults to production.
|
||||
SENTRY_ENVIRONMENT=development
|
||||
|
||||
# Leave a DSN empty to disable that part.
|
||||
SENTRY_GUI_DSN=
|
||||
SENTRY_ELECTRON_DSN=
|
||||
SENTRY_SERVER_DSN=
|
||||
@@ -3,5 +3,3 @@
|
||||
*.png binary
|
||||
*.webp binary
|
||||
*.gif binary
|
||||
|
||||
*.ftl -linguist-detectable
|
||||
@@ -19,6 +19,14 @@
|
||||
# Some server code~
|
||||
/server/ @ButterscotchV @loucass003 @Erimelowo
|
||||
|
||||
/server/src/main/java/dev/slimevr/autobone/ @ButterscotchV
|
||||
/server/src/main/java/dev/slimevr/poserecorder/ @ButterscotchV
|
||||
/server/src/main/java/dev/slimevr/posestreamer/ @ButterscotchV
|
||||
|
||||
/server/src/main/java/dev/slimevr/osc/ @Erimelowo
|
||||
/server/src/main/java/dev/slimevr/tracking/processor/ @Erimelowo
|
||||
/server/src/main/java/dev/slimevr/filtering/ @Erimelowo
|
||||
|
||||
/bindings-provider/ @ImSapphire
|
||||
|
||||
# Linux files
|
||||
|
||||
+31
-35
@@ -77,31 +77,32 @@ jobs:
|
||||
- name: Setup PNPM
|
||||
uses: pnpm/action-setup@v6
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
- name: GUI Lint
|
||||
run: pnpm i && pnpm run lint
|
||||
run: pnpm i && cd gui && pnpm run lint
|
||||
|
||||
server-checks:
|
||||
name: Server Checks
|
||||
java-checks:
|
||||
name: Java Checks
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Set up JDK 25
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
java-version: '17'
|
||||
distribution: 'adopt'
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
- name: Server Spotless Check
|
||||
- name: Java Spotless Check
|
||||
run: ./gradlew spotlessCheck --build-cache
|
||||
|
||||
|
||||
build-server-jar:
|
||||
name: Build Desktop Server
|
||||
runs-on: ubuntu-latest
|
||||
@@ -112,19 +113,17 @@ jobs:
|
||||
submodules: recursive
|
||||
- name: Get tags
|
||||
run: git fetch --tags origin --recurse-submodules=no --force
|
||||
- name: Set up JDK 25
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
java-version: '17'
|
||||
distribution: 'adopt'
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
- name: Build ShadowJar
|
||||
run: ./gradlew :server:desktop:shadowJar --build-cache
|
||||
env:
|
||||
SENTRY_SERVER_DSN: ${{ vars.SENTRY_SERVER_DSN }}
|
||||
- name: Test with Gradle
|
||||
run: ./gradlew :server:core:jvmTest
|
||||
run: ./gradlew :server:desktop:test
|
||||
- name: Upload Server Jar
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -146,19 +145,16 @@ jobs:
|
||||
- name: Setup PNPM
|
||||
uses: pnpm/action-setup@v6
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
- name: Build JS
|
||||
env:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
SENTRY_GUI_DSN: ${{ vars.SENTRY_GUI_DSN }}
|
||||
SENTRY_ELECTRON_DSN: ${{ vars.SENTRY_ELECTRON_DSN }}
|
||||
SENTRY_SERVER_DSN: ${{ vars.SENTRY_SERVER_DSN }}
|
||||
run: pnpm i && pnpm run build
|
||||
run: pnpm i && cd gui && pnpm run build
|
||||
- name: Tar GUI Dist
|
||||
run: tar -czf slimevr-gui-dist.tar.gz -C gui/electron/out .
|
||||
run: tar -czf slimevr-gui-dist.tar.gz -C gui/out .
|
||||
- name: Upload GUI Dist
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -182,7 +178,7 @@ jobs:
|
||||
- name: Setup PNPM
|
||||
uses: pnpm/action-setup@v6
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
@@ -203,19 +199,21 @@ jobs:
|
||||
name: gui-dist
|
||||
- name: Extract GUI for Electron
|
||||
shell: bash
|
||||
run: mkdir -p gui/electron/out && tar -xzf slimevr-gui-dist.tar.gz -C gui/electron/out
|
||||
run: mkdir -p gui/out && tar -xzf slimevr-gui-dist.tar.gz -C gui/out
|
||||
- name: Run Electron Builder
|
||||
shell: bash
|
||||
env:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
run: |
|
||||
mkdir -p gui/electron/dist/artifacts/linux/ \
|
||||
gui/electron/dist/artifacts/win \
|
||||
gui/electron/dist/artifacts/mac
|
||||
mkdir -p gui/dist/artifacts/linux/ \
|
||||
gui/dist/artifacts/win \
|
||||
gui/dist/artifacts/mac
|
||||
VERSION=$(git --no-pager tag --sort -taggerdate --points-at HEAD | head -1)
|
||||
[ -z "$VERSION" ] && VERSION="0.0.0"
|
||||
VERSION="${VERSION#v}"
|
||||
echo "Building version: $VERSION"
|
||||
pnpm i
|
||||
cd gui/electron
|
||||
cd gui
|
||||
pnpm exec electron-builder --${{ matrix.platform }} \
|
||||
${{ matrix.platform == 'macos' && '--universal' || '' }} \
|
||||
--config.extraMetadata.version="$VERSION" \
|
||||
@@ -223,7 +221,7 @@ jobs:
|
||||
- name: Collect and Rename Artifacts
|
||||
shell: bash
|
||||
run: |
|
||||
SRC_DIR="${{ github.workspace }}/gui/electron/dist/artifacts"
|
||||
SRC_DIR="${{ github.workspace }}/gui/dist/artifacts"
|
||||
DEST_DIR="${{ github.workspace }}/release-out"
|
||||
mkdir -p "$DEST_DIR"
|
||||
|
||||
@@ -262,11 +260,11 @@ jobs:
|
||||
submodules: recursive
|
||||
- name: Get tags
|
||||
run: git fetch --tags origin --recurse-submodules=no --force
|
||||
- name: Set up JDK 25
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
java-version: '17'
|
||||
distribution: 'adopt'
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
- name: Download GUI Dist
|
||||
@@ -274,16 +272,16 @@ jobs:
|
||||
with:
|
||||
name: gui-dist
|
||||
- name: Extract GUI for Android
|
||||
run: mkdir -p gui/electron/out && tar -xzf slimevr-gui-dist.tar.gz -C gui/electron/out
|
||||
run: mkdir -p gui/out && tar -xzf slimevr-gui-dist.tar.gz -C gui/out
|
||||
- name: Build APK
|
||||
run: ./gradlew :server:android:build --build-cache
|
||||
env:
|
||||
SENTRY_SERVER_DSN: ${{ vars.SENTRY_SERVER_DSN }}
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
ANDROID_STORE_FILE: ${{ secrets.ANDROID_STORE_FILE }}
|
||||
ANDROID_STORE_PASSWD: ${{ secrets.ANDROID_STORE_PASSWD }}
|
||||
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
ANDROID_KEY_PASSWD: ${{ secrets.ANDROID_KEY_PASSWD }}
|
||||
- name: Test with Gradle
|
||||
run: ./gradlew test
|
||||
- name: Prepare APK
|
||||
run: cp server/android/build/outputs/apk/release/*.apk ./SlimeVR-android.apk
|
||||
- name: Upload APK
|
||||
@@ -296,8 +294,6 @@ jobs:
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
run: ./gradlew :server:android:bundleRelease
|
||||
env:
|
||||
SENTRY_SERVER_DSN: ${{ vars.SENTRY_SERVER_DSN }}
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
ANDROID_STORE_FILE: ${{ secrets.ANDROID_GPLAY_STORE_FILE }}
|
||||
ANDROID_STORE_PASSWD: ${{ secrets.ANDROID_GPLAY_STORE_PASSWD }}
|
||||
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_GPLAY_KEY_ALIAS }}
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
steps:
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '22.x'
|
||||
|
||||
|
||||
+2
-18
@@ -4,12 +4,8 @@
|
||||
# Syncthing ignore file
|
||||
.stignore
|
||||
|
||||
# Ignore .idea, except shared project inspection profiles and run configurations
|
||||
.idea/*
|
||||
!.idea/inspectionProfiles/
|
||||
!.idea/inspectionProfiles/*.xml
|
||||
!.idea/runConfigurations/
|
||||
!.idea/runConfigurations/*.xml
|
||||
# Ignore .idea
|
||||
.idea
|
||||
|
||||
# Ignore .fleet
|
||||
.fleet
|
||||
@@ -38,16 +34,10 @@
|
||||
# ignore gradle build folder
|
||||
build/
|
||||
|
||||
# created by clangd for index cache
|
||||
.cache/
|
||||
|
||||
# direnv has been claimed for Nix usage
|
||||
.direnv/
|
||||
.devenv
|
||||
|
||||
# Git worktrees
|
||||
.worktree/
|
||||
|
||||
# Ignore Android local properties
|
||||
local.properties
|
||||
|
||||
@@ -57,9 +47,3 @@ vrconfig.yml.tmp
|
||||
|
||||
# Nixos
|
||||
.bin/
|
||||
|
||||
.env.local
|
||||
|
||||
|
||||
# Fuck claude
|
||||
.claude
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="ConvertLongToDuration" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
</profile>
|
||||
</component>
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="PROJECT_PROFILE" value="Project Default" />
|
||||
<option name="USE_PROJECT_PROFILE" value="true" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="SlimeVR Desktop" type="JetRunConfigurationType" factoryName="Kotlin">
|
||||
<module name="SlimeVR_Server.server.desktop.main" />
|
||||
<option name="MAIN_CLASS_NAME" value="dev.slimevr.desktop.Main" />
|
||||
<option name="VM_PARAMETERS" value="--enable-native-access=ALL-UNNAMED" />
|
||||
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/server/desktop" />
|
||||
<method v="2">
|
||||
<option name="Make" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
||||
+10
-18
@@ -1,7 +1,5 @@
|
||||
# Contributing to SlimeVR
|
||||
|
||||
Please follow general contribution guidelines: [CONTRIBUTING.md](https://github.com/SlimeVR/.github/blob/main/profile/CONTRIBUTING.md).
|
||||
|
||||
This document describes essential knowledge required to contribute to the SlimeVR Server.
|
||||
|
||||
### Prerequisites
|
||||
@@ -24,26 +22,21 @@ Now you can open the codebase in [IDEA](https://www.jetbrains.com/idea/download/
|
||||
|
||||
### Java (server)
|
||||
|
||||
Before contributing to the server, read [server/README.md](server/README.md) for an overview of its architecture and design guidelines.
|
||||
|
||||
The Java code is built with `gradle`, a CLI tool that manages java projects and their
|
||||
dependencies.
|
||||
- You can run the server by running `./gradlew :server:desktop:run` in your IDE's terminal.
|
||||
- You can run the server by running `./gradlew run` in your IDE's terminal.
|
||||
- To compile the code, run `./gradlew shadowJar`. The result will
|
||||
be at `server/desktop/build/libs/slimevr.jar` (you can ignore `server.jar`).
|
||||
be at `server/build/libs/slimevr.jar` (you can ignore `server.jar`).
|
||||
|
||||
(Note: Your IDE may be able to do all of the above for you.)
|
||||
|
||||
### Electron (gui)
|
||||
|
||||
- Activate corepack (included with Node.js) via `corepack enable`
|
||||
(might require launching Git Bash as administrator on Windows)
|
||||
- Make sure you're at the root of the repository.
|
||||
- Activate corepack (included with Node.JS) via `corepack enable` (might require administrator permissions)
|
||||
- Run `pnpm i` in your IDE's terminal to download and install dependencies.
|
||||
- To launch the GUI in dev mode, run `pnpm gui`.
|
||||
- If you get an "Electron uninstall" error, run `node .\gui\electron\node_modules\electron\install.js`.
|
||||
- Finally, to compile for production, run `pnpm package:build` under `gui/electron`.
|
||||
The result will be in `gui/dist/artifacts/`. Content will change depending on the platform.
|
||||
- Finally, to compile for production, run `pnpm package:build`. The result
|
||||
will be at `dist/artifacts/` content will change depending of the platform.
|
||||
|
||||
## Code style
|
||||
|
||||
@@ -92,7 +85,7 @@ Eclipse will only do a subset of the checks in `spotless`, so you may still want
|
||||
### Electron (gui)
|
||||
|
||||
We use ESLint and Prettier to format GUI code.
|
||||
- Make sure you're at the root of the repository.
|
||||
- First, go into the GUI's directory with your terminal by running `cd gui`.
|
||||
- To check code formatting, run `pnpm run lint`.
|
||||
- To fix code formatting, run `pnpm run lint:fix` and `pnpm run format`
|
||||
|
||||
@@ -122,9 +115,8 @@ licensed under `GPL-v3`.
|
||||
We use discord *a lot* to coordinate and discuss development. Come join us at
|
||||
https://discord.gg/SlimeVR!
|
||||
|
||||
## Use of AI, LLM, and code generation
|
||||
**Submission of any content directly from AI is strictly forbidden in all SlimeVR repositories**, including code, documentation, translation, images, sounds, etc. Including, but not limited to: vibe-coding, snippets generated by LLM, AI-generated icons, copilot auto-complete, commit descriptions, PR notes, issues texts and comments. If your auto-complete system suggest next word, function name or variable name - it's okay to use, if it suggest a whole code snipped - it's not allowed.
|
||||
## Use of AI
|
||||
We DO NOT accept contributions that are generated with AI (for example, "vibe-coding").
|
||||
|
||||
An exception is using translation tools to communicate with us if you're unable to properly express yourself in English. Please leave a comment that your post was translated and from which language. Submissions of machine translations to repositories are forbidden.
|
||||
|
||||
AI is allowed for things such as research, debugging, and questions, if no output of AI is submitted.
|
||||
If you do use AI, and you believe your usage of AI is reasonable, you must clearly disclose
|
||||
how you used AI in your submission.
|
||||
@@ -22,8 +22,6 @@ Latest setup instructions are [in our docs](https://docs.slimevr.dev/server/inde
|
||||
## Building & Contributing
|
||||
For information on building and contributing to the codebase, see [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
For an overview of the server architecture and design guidelines, see [server/README.md](server/README.md).
|
||||
|
||||
## Translating
|
||||
|
||||
Translation is done via Pontoon at [i18n.slimevr.dev](https://i18n.slimevr.dev/). Please join our [Discord translation forum](https://discord.com/channels/817184208525983775/1050413434249949235) to coordinate.
|
||||
|
||||
@@ -68,8 +68,8 @@ AlignConsecutiveTableGenDefinitionColons:
|
||||
AlignEscapedNewlines: Right
|
||||
AlignOperands: DontAlign
|
||||
AlignTrailingComments:
|
||||
Kind: Always
|
||||
OverEmptyLines: 2
|
||||
Kind: Never
|
||||
OverEmptyLines: 0
|
||||
AllowAllArgumentsOnNextLine: true
|
||||
AllowAllParametersOfDeclarationOnNextLine: true
|
||||
AllowBreakBeforeNoexceptSpecifier: Never
|
||||
@@ -140,7 +140,7 @@ EmptyLineAfterAccessModifier: Never
|
||||
EmptyLineBeforeAccessModifier: LogicalBlock
|
||||
EnumTrailingComma: Leave
|
||||
ExperimentalAutoDetectBinPacking: false
|
||||
FixNamespaceComments: true
|
||||
FixNamespaceComments: false
|
||||
ForEachMacros:
|
||||
- foreach
|
||||
- Q_FOREACH
|
||||
@@ -216,13 +216,13 @@ PenaltyBreakTemplateDeclaration: 10
|
||||
PenaltyExcessCharacter: 1000000
|
||||
PenaltyIndentedWhitespace: 0
|
||||
PenaltyReturnTypeOnItsOwnLine: 60
|
||||
PointerAlignment: Left
|
||||
PointerAlignment: Right
|
||||
PPIndentWidth: -1
|
||||
QualifierAlignment: Leave
|
||||
ReferenceAlignment: Pointer
|
||||
ReflowComments: Always
|
||||
RemoveBracesLLVM: false
|
||||
RemoveEmptyLinesInUnwrappedLines: true
|
||||
RemoveEmptyLinesInUnwrappedLines: false
|
||||
RemoveParentheses: Leave
|
||||
RemoveSemicolon: false
|
||||
RequiresClausePosition: OwnLine
|
||||
@@ -293,7 +293,5 @@ WhitespaceSensitiveMacros:
|
||||
- PP_STRINGIZE
|
||||
- STRINGIZE
|
||||
WrapNamespaceBodyWithEmptyLines: Leave
|
||||
---
|
||||
Language: Proto
|
||||
DisableFormat: true
|
||||
...
|
||||
|
||||
@@ -42,17 +42,13 @@ message(STATUS "Found OpenVR library at: ${OPENVR_LIBRARY}")
|
||||
add_executable("${PROJECT_NAME}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/paths.cpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/logger.cpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/bridge/BridgeClient.cpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/bridge/BridgeTransport.cpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/solarxr.cpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/vr_utils.cpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp"
|
||||
)
|
||||
set_target_properties("${PROJECT_NAME}" PROPERTIES CXX_STANDARD 23)
|
||||
target_include_directories("${PROJECT_NAME}" PRIVATE "${SOLARXR_PROTOCOL_ROOT}/lib/flatbuffers/include" "${SOLARXR_PROTOCOL_ROOT}/lib/flatbuffers/" "${FLATBUFFERS_GENERATED_ROOT}/include" "${CMAKE_CURRENT_SOURCE_DIR}/include" "${OPENVR_ROOT}/headers")
|
||||
target_link_libraries("${PROJECT_NAME}" PRIVATE "${OPENVR_LIBRARY}")
|
||||
if(WIN32)
|
||||
target_link_libraries("${PROJECT_NAME}" PRIVATE ws2_32)
|
||||
endif()
|
||||
|
||||
if(LINUX)
|
||||
set_target_properties("${PROJECT_NAME}" PROPERTIES OUTPUT_NAME slimevr-bindings-provider)
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
if ((Get-Command "clang-format" -ErrorAction SilentlyContinue) -eq $null) {
|
||||
$errorObj = New-Object System.IO.FileNotFoundException("clang-format is not installed, please install clang-format via your package manager (e.g. winget/chocolatey/scoop) and re-run the script")
|
||||
throw $errorObj
|
||||
}
|
||||
|
||||
$SourceFiles = Get-ChildItem -Path '.\src\' -Recurse -Include "*.cpp","*.hpp"
|
||||
foreach ($file in $SourceFiles) {
|
||||
Write-Output "Formatting $(Resolve-Path -Relative $file.FullName)"
|
||||
clang-format -i "$($file.FullName)"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
#!/bin/bash
|
||||
if ! command -v clang-format >/dev/null 2>&1; then
|
||||
echo "clang-format is not installed, please install clang-format via your package manager (e.g. pacman/apt/dnf/winget) and re-run the script" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
find src/ \( \
|
||||
-iname '*.cpp' \
|
||||
-or -iname '*.hpp' \
|
||||
\) \
|
||||
-exec echo Formatting {} \; \
|
||||
-exec clang-format -i {} \;
|
||||
@@ -1,52 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
// SPDX-FileCopyrightText: (c) 2026 Eiren Rain and SlimeVR Contributors
|
||||
#include "BridgeClient.hpp"
|
||||
#include "BridgeTransport.hpp"
|
||||
|
||||
#include <system_error>
|
||||
|
||||
using namespace std::literals::chrono_literals;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
void BridgeClient::CreateConnection() {
|
||||
fs::path path = GetSocketPath();
|
||||
|
||||
Socket fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (fd == InvalidSocket) {
|
||||
int err = GetLastSocketError();
|
||||
throw std::system_error(err, std::system_category(), "socket() failed");
|
||||
}
|
||||
|
||||
if (last_path_ != path) {
|
||||
Logger::Get().Info("Trying to connect to socket {}", path.string());
|
||||
last_path_ = path;
|
||||
}
|
||||
|
||||
struct sockaddr_un addr{
|
||||
.sun_family = AF_UNIX,
|
||||
};
|
||||
|
||||
const std::u8string path_str = path.u8string();
|
||||
if (path_str.size() > std::size(addr.sun_path) - 1) {
|
||||
CloseSocket(fd);
|
||||
throw std::runtime_error("Socket path too long to fit in sun_path");
|
||||
}
|
||||
memcpy(addr.sun_path, path_str.data(), path_str.size() + 1);
|
||||
|
||||
int ret = connect(fd, reinterpret_cast<const struct sockaddr*>(&addr), sizeof(addr));
|
||||
if (ret == SocketError) {
|
||||
int err = GetLastSocketError();
|
||||
CloseSocket(fd);
|
||||
throw std::system_error(err, std::system_category(), "connect() failed");
|
||||
}
|
||||
|
||||
Logger::Get().Info("Connected to {}", path.string());
|
||||
|
||||
ret = SetNonBlocking(fd);
|
||||
if (ret == SocketError) {
|
||||
int err = GetLastSocketError();
|
||||
Logger::Get().Warning("Failed to set socket into non-blocking mode: {}", std::error_code(err, std::system_category()).message());
|
||||
}
|
||||
|
||||
fd_ = fd;
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
// SPDX-FileCopyrightText: (c) 2026 Eiren Rain and SlimeVR Contributors
|
||||
#pragma once
|
||||
|
||||
#include "BridgeTransport.hpp"
|
||||
|
||||
/**
|
||||
* @brief Client implementation of @ref BridgeTransport for communication with SlimeVR Server using unix sockets.
|
||||
*
|
||||
* @copydoc BridgeTransport
|
||||
*/
|
||||
class BridgeClient : public BridgeTransport {
|
||||
public:
|
||||
using BridgeTransport::BridgeTransport;
|
||||
|
||||
private:
|
||||
void CreateConnection() override;
|
||||
|
||||
std::filesystem::path last_path_;
|
||||
};
|
||||
@@ -1,234 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
// SPDX-FileCopyrightText: (c) 2026 Eiren Rain and SlimeVR Contributors
|
||||
#include "BridgeTransport.hpp"
|
||||
#include "Endianness.hpp"
|
||||
|
||||
#include <solarxr_protocol/generated/all_generated.h>
|
||||
#include <system_error>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <winerror.h>
|
||||
#endif
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
#define UNIX_XDG_DATA_HOME_DEFAULT ".local/share/"
|
||||
#define SLIMEVR_IDENTIFIER "dev.slimevr.SlimeVR"
|
||||
#define UNIX_DEFAULT_TMP_DIR "/tmp"
|
||||
#define SOCKET_NAME "SlimeVRRpc"
|
||||
|
||||
void BridgeTransport::Stop() {
|
||||
if (!thread_.joinable() && !reconnect_thread_.joinable())
|
||||
return;
|
||||
Logger::Get().Info("Bridge stopping");
|
||||
StopAsync();
|
||||
thread_ = std::jthread();
|
||||
reconnect_thread_ = std::jthread();
|
||||
}
|
||||
|
||||
void BridgeTransport::StopAsync() {
|
||||
thread_.request_stop();
|
||||
reconnect_thread_.request_stop();
|
||||
cv_.notify_all();
|
||||
}
|
||||
|
||||
fs::path BridgeTransport::GetSocketPath() {
|
||||
std::vector<fs::path> paths = {};
|
||||
|
||||
if (const char* dir_override = std::getenv("SLIMEVR_SOCKET_DIR")) {
|
||||
paths.push_back(fs::path(dir_override) / SOCKET_NAME);
|
||||
}
|
||||
|
||||
#ifndef _WIN32
|
||||
if (const char* xdg_runtime = std::getenv("XDG_RUNTIME_DIR")) {
|
||||
paths.push_back(fs::path(xdg_runtime) / SOCKET_NAME);
|
||||
}
|
||||
|
||||
if (const char* xdg_data = std::getenv("XDG_DATA_HOME")) {
|
||||
paths.push_back(fs::path(xdg_data) / SLIMEVR_IDENTIFIER / SOCKET_NAME);
|
||||
}
|
||||
|
||||
if (const char* home = std::getenv("HOME")) {
|
||||
paths.push_back(fs::path(home) / UNIX_XDG_DATA_HOME_DEFAULT / SLIMEVR_IDENTIFIER / SOCKET_NAME);
|
||||
}
|
||||
#endif
|
||||
|
||||
std::error_code ec;
|
||||
for (auto path : paths) {
|
||||
if (fs::exists(path, ec)
|
||||
#ifdef _WIN32
|
||||
|| ec.value() == ERROR_CANT_ACCESS_FILE // Windows moment???
|
||||
#endif
|
||||
) {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
// This should work as long as the user's machine does not have
|
||||
// the java.io.tmpdir system property overriden.
|
||||
WCHAR tmp_dir[MAX_PATH + 1];
|
||||
GetTempPathW(std::size(tmp_dir), tmp_dir);
|
||||
return fs::path(tmp_dir) / SOCKET_NAME;
|
||||
#else
|
||||
if (const char* tmp_dir = std::getenv("TMPDIR")) {
|
||||
return fs::path(tmp_dir) / SOCKET_NAME;
|
||||
} else {
|
||||
return fs::path(UNIX_DEFAULT_TMP_DIR) / SOCKET_NAME;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void BridgeTransport::OnRecv(std::span<uint8_t> event) {
|
||||
if (!message_callback_)
|
||||
return;
|
||||
|
||||
auto bundle = flatbuffers::GetRoot<solarxr_protocol::MessageBundle>(event.data());
|
||||
|
||||
if (auto data_feed_msgs = bundle->data_feed_msgs()) {
|
||||
for (auto msg : *data_feed_msgs) {
|
||||
// Logger::Get().Debug("Got message DataFeedMessage::{}", EnumNameDataFeedMessage(msg->message_type()));
|
||||
message_callback_(msg);
|
||||
}
|
||||
}
|
||||
if (auto rpc_msgs = bundle->rpc_msgs()) {
|
||||
for (auto msg : *rpc_msgs) {
|
||||
Logger::Get().Debug("Got message RpcMessage::{}", EnumNameRpcMessage(msg->message_type()));
|
||||
message_callback_(msg);
|
||||
}
|
||||
}
|
||||
if (auto driver_msgs = bundle->driver_msgs()) {
|
||||
for (auto msg : *driver_msgs) {
|
||||
// Logger::Get().Debug("Got message DriverMessage::{}", EnumNameDriverMessage(msg->message_type()));
|
||||
message_callback_(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BridgeTransport::Start() {
|
||||
thread_ = std::jthread([this](std::stop_token stop) { return RunThread(stop); });
|
||||
}
|
||||
|
||||
void BridgeTransport::RunThread(std::stop_token stop) {
|
||||
std::vector<uint8_t> data;
|
||||
data.reserve(0x10000);
|
||||
|
||||
// Kick off connection.
|
||||
ResetConnection();
|
||||
|
||||
while (!stop.stop_requested()) {
|
||||
std::shared_lock fd_lock(fd_mutex_);
|
||||
|
||||
if (fd_ == InvalidSocket) [[unlikely]] {
|
||||
cv_.wait(fd_lock, stop, [this] { return fd_ != InvalidSocket; });
|
||||
if (stop.stop_requested())
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
ptrdiff_t ret = Poll(fd_, 1ms);
|
||||
if (ret == 0) [[likely]] {
|
||||
// No data on the socket after timeout
|
||||
continue;
|
||||
}
|
||||
|
||||
uint32_t msg_len;
|
||||
ret = ReadFully(fd_, stop, &msg_len, sizeof(msg_len));
|
||||
if (ret == 0) [[unlikely]] {
|
||||
throw std::runtime_error("EOF");
|
||||
}
|
||||
|
||||
msg_len = ConvertEndianness<std::endian::little>(msg_len);
|
||||
// If we get something bigger than this, something's probably up
|
||||
if (msg_len > 0x40000) [[unlikely]] {
|
||||
throw std::runtime_error(std::format("Got too large message ({} bytes)", msg_len));
|
||||
}
|
||||
|
||||
const uint32_t unwrapped_len = msg_len - 4;
|
||||
data.reserve(unwrapped_len);
|
||||
|
||||
ret = ReadFully(fd_, stop, data.data(), unwrapped_len);
|
||||
if (ret == 0) [[unlikely]] {
|
||||
throw std::runtime_error("EOF");
|
||||
}
|
||||
|
||||
OnRecv({ data.data(), unwrapped_len });
|
||||
} catch (Cancelled&) {
|
||||
continue;
|
||||
} catch (std::exception& e) {
|
||||
Logger::Get().Error("Error on socket: {}", e.what());
|
||||
error_callback_(e);
|
||||
fd_lock.unlock();
|
||||
ResetConnection();
|
||||
}
|
||||
}
|
||||
|
||||
CloseConnectionHandles();
|
||||
}
|
||||
|
||||
void BridgeTransport::ResetConnection() {
|
||||
CloseConnectionHandles();
|
||||
|
||||
reconnect_thread_ = std::jthread([this](std::stop_token stop) {
|
||||
while (!stop.stop_requested()) {
|
||||
try {
|
||||
std::unique_lock fd_lock(fd_mutex_);
|
||||
CreateConnection();
|
||||
assert(fd_ != InvalidSocket);
|
||||
|
||||
cv_.notify_all();
|
||||
|
||||
// connect callback may call a function that needs to block on the fd
|
||||
fd_lock.unlock();
|
||||
OnConnect();
|
||||
|
||||
return;
|
||||
} catch (std::system_error& e) {
|
||||
if (last_error_ != e.code()) {
|
||||
Logger::Get().Error("Error when trying to connect: {}", e.what());
|
||||
last_error_ = e.code();
|
||||
}
|
||||
error_callback_(e);
|
||||
} catch (std::exception& e) {
|
||||
Logger::Get().Error("Error when trying to connect: {}", e.what());
|
||||
error_callback_(e);
|
||||
}
|
||||
|
||||
std::this_thread::sleep_for(100ms);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void BridgeTransport::CloseConnectionHandles() {
|
||||
std::unique_lock fd_lock(fd_mutex_);
|
||||
if (fd_ == InvalidSocket)
|
||||
return;
|
||||
|
||||
CloseSocket(fd_);
|
||||
OnDisconnect();
|
||||
fd_ = InvalidSocket;
|
||||
}
|
||||
|
||||
void BridgeTransport::SendMessage(const flatbuffers::FlatBufferBuilder& fbb) {
|
||||
std::shared_lock fd_lock(fd_mutex_);
|
||||
if (fd_ == InvalidSocket) [[unlikely]]
|
||||
return;
|
||||
|
||||
std::lock_guard write_lock(write_mutex_);
|
||||
|
||||
if (fbb.GetSize() + 4 > std::numeric_limits<uint32_t>::max()) [[unlikely]] {
|
||||
Logger::Get().Warning("Skipping send of message (wrapped size larger than 32-bit unsigned integer limit)");
|
||||
return;
|
||||
}
|
||||
|
||||
const uint32_t size = static_cast<uint32_t>(fbb.GetSize());
|
||||
const uint32_t le_wrapped_size = ConvertEndianness<std::endian::little>(size + 4);
|
||||
|
||||
try {
|
||||
WriteFully(fd_, &le_wrapped_size, sizeof(le_wrapped_size));
|
||||
WriteFully(fd_, fbb.GetBufferPointer(), size);
|
||||
} catch (std::exception& e) {
|
||||
Logger::Get().Error("Failed to write message: {}", e.what());
|
||||
}
|
||||
}
|
||||
@@ -1,343 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
// SPDX-FileCopyrightText: (c) 2026 Eiren Rain and SlimeVR Contributors
|
||||
#pragma once
|
||||
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <shared_mutex>
|
||||
#include <span>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
#include <variant>
|
||||
|
||||
// Needs to be before anything that includes Windows.h to avoid macro clashes
|
||||
#include <solarxr_protocol/generated/all_generated.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define NOMINMAX
|
||||
#include <Winsock2.h>
|
||||
#include <afunix.h>
|
||||
// Microsoft why
|
||||
#undef ERROR
|
||||
#undef SendMessage
|
||||
#else
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#endif
|
||||
|
||||
#include "../logger.hpp"
|
||||
|
||||
/**
|
||||
* @brief Passes messages between SlimeVR Server and SteamVR Driver using Unix sockets.
|
||||
*
|
||||
* Client or Server connection handling is implemented by extending this class.
|
||||
*
|
||||
* This class provides a set of methods to start, stop an IO thread, and send messages over a Unix socket.
|
||||
*
|
||||
* When a message is received and parsed from the pipe, the on_message_received function passed in the constructor is called
|
||||
* from the bridge thread with the message as a parameter.
|
||||
*
|
||||
* @param logger A shared pointer to an Logger object to log messages from the transport.
|
||||
* @param on_message_received A function to be called from event loop thread when a message is received and parsed from the pipe.
|
||||
* @param on_connect A function to be called when the socket is connected to.
|
||||
* @param on_disconnect A function to be called when the connection is ended.
|
||||
*/
|
||||
class BridgeTransport {
|
||||
public:
|
||||
using MessageHeader = std::variant<const solarxr_protocol::data_feed::DataFeedMessageHeader*, const solarxr_protocol::rpc::RpcMessageHeader*, const solarxr_protocol::driver_protocol::DriverMessageHeader*>;
|
||||
|
||||
#ifdef _WIN32
|
||||
using Socket = SOCKET;
|
||||
constexpr static Socket InvalidSocket = INVALID_SOCKET;
|
||||
constexpr static int SocketError = SOCKET_ERROR;
|
||||
#else
|
||||
using Socket = int;
|
||||
constexpr static Socket InvalidSocket = -1;
|
||||
constexpr static int SocketError = -1;
|
||||
#endif
|
||||
|
||||
static inline int GetLastSocketError() {
|
||||
#ifdef _WIN32
|
||||
return WSAGetLastError();
|
||||
#else
|
||||
return errno;
|
||||
#endif
|
||||
}
|
||||
|
||||
static inline int CloseSocket(Socket fd) {
|
||||
#ifdef _WIN32
|
||||
return closesocket(fd);
|
||||
#else
|
||||
return close(fd);
|
||||
#endif
|
||||
}
|
||||
|
||||
static inline bool IsBlockingError(int err) {
|
||||
#ifdef _WIN32
|
||||
return err == WSAEWOULDBLOCK;
|
||||
#else
|
||||
return err == EAGAIN || err == EWOULDBLOCK;
|
||||
#endif
|
||||
}
|
||||
|
||||
static inline int SetNonBlocking(Socket fd) {
|
||||
#ifdef _WIN32
|
||||
u_long mode = 1;
|
||||
return ioctlsocket(fd, FIONBIO, &mode);
|
||||
#else
|
||||
return fcntl(fd, F_SETFL, O_NONBLOCK);
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Exception thrown when IO is cancelled by stop token.
|
||||
*/
|
||||
class Cancelled : public std::exception {
|
||||
public:
|
||||
Cancelled() noexcept { };
|
||||
~Cancelled() { };
|
||||
|
||||
const char* what() const noexcept override {
|
||||
return "IO operation cancelled";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Read @a size bytes from @a fd into @a data, retrying until all data is read or an error occurs.
|
||||
*
|
||||
* @throws @ref Cancelled stop was requested on @a stop
|
||||
* @throws std::system_error error returned on socket
|
||||
* @returns @ref SocketError on fail, otherwise number of bytes read
|
||||
*/
|
||||
static ptrdiff_t ReadFully(Socket fd, std::stop_token stop, void* data, size_t size) {
|
||||
ptrdiff_t ret;
|
||||
size_t received = 0;
|
||||
while (!stop.stop_requested() && received < size) {
|
||||
ret = recv(fd, reinterpret_cast<char*>(data) + received, size - received, 0);
|
||||
if (ret == 0) // EOF
|
||||
return ret;
|
||||
|
||||
if (ret == SocketError) [[unlikely]] {
|
||||
int err = GetLastSocketError();
|
||||
if (IsBlockingError(err)) [[likely]] {
|
||||
// we couldn't read because it would block, just try again
|
||||
continue;
|
||||
} else {
|
||||
throw std::system_error(err, std::system_category(), "recv() failed");
|
||||
}
|
||||
}
|
||||
|
||||
received += ret;
|
||||
}
|
||||
|
||||
if (stop.stop_requested())
|
||||
throw Cancelled();
|
||||
return received;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Write @a size bytes from @a data to @a fd, retrying until all data is written or an error occurs.
|
||||
*
|
||||
* @throws std::system_error error returned on socket
|
||||
*
|
||||
* @returns @ref SocketError on fail, otherwise number of bytes written
|
||||
*/
|
||||
static inline ptrdiff_t WriteFully(Socket fd, const void* data, size_t size) {
|
||||
#ifdef __linux__
|
||||
constexpr int flags = MSG_NOSIGNAL;
|
||||
#else
|
||||
constexpr int flags = 0;
|
||||
#endif
|
||||
|
||||
ptrdiff_t ret;
|
||||
size_t sent = 0;
|
||||
while (sent < size) {
|
||||
ret = send(fd, reinterpret_cast<const char*>(data) + sent, size - sent, flags);
|
||||
if (ret == SocketError) [[unlikely]] {
|
||||
int err = GetLastSocketError();
|
||||
if (IsBlockingError(err)) [[likely]] {
|
||||
// we couldn't write because it would block, just try again
|
||||
continue;
|
||||
} else {
|
||||
throw std::system_error(err, std::system_category(), "send() failed");
|
||||
}
|
||||
}
|
||||
|
||||
sent += ret;
|
||||
}
|
||||
|
||||
return sent;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Wait for input to be ready on @a fd, timing out after @a timeout.
|
||||
*
|
||||
* @param fd file descriptor to poll
|
||||
* @param timeout amount of time to wait before giving up
|
||||
*
|
||||
* @throws std::system_error error returned when polling
|
||||
* @throws std::runtime_error error on socket, or hang up was detected
|
||||
*
|
||||
* @returns @ref 0 if there is no data, positive value if there is data
|
||||
*/
|
||||
template <typename Rep, typename Period>
|
||||
static int Poll(Socket fd, std::chrono::duration<Rep, Period> timeout) noexcept(false) {
|
||||
struct pollfd pollfd{
|
||||
.fd = fd,
|
||||
.events = POLLIN,
|
||||
};
|
||||
|
||||
int ret;
|
||||
|
||||
#ifdef _WIN32
|
||||
ret = WSAPoll(&pollfd, 1, std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count());
|
||||
#else
|
||||
{
|
||||
auto s = std::chrono::duration_cast<std::chrono::seconds>(timeout);
|
||||
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(timeout - s);
|
||||
struct timespec ts{
|
||||
.tv_sec = s.count(),
|
||||
.tv_nsec = ns.count(),
|
||||
};
|
||||
ret = ppoll(&pollfd, 1, timeout == timeout.zero() ? nullptr : &ts, nullptr);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
constexpr int InterruptedErrno = WSAEINTR;
|
||||
#else
|
||||
constexpr int InterruptedErrno = EINTR;
|
||||
#endif
|
||||
|
||||
if (ret == SocketError) {
|
||||
int err = GetLastSocketError();
|
||||
throw std::system_error(err, std::system_category(), "Poll() failed");
|
||||
}
|
||||
|
||||
if ((pollfd.revents & (POLLERR | POLLHUP)) != 0) {
|
||||
throw std::runtime_error("Socket connection lost");
|
||||
}
|
||||
|
||||
return pollfd.revents & POLLIN;
|
||||
}
|
||||
|
||||
BridgeTransport(std::function<void(MessageHeader&&)> on_message_received = {},
|
||||
std::function<void()> on_connect = {},
|
||||
std::function<void()> on_disconnect = {},
|
||||
std::function<void(std::exception&)> on_error = {})
|
||||
: connect_callback_(on_connect)
|
||||
, message_callback_(on_message_received)
|
||||
, disconnect_callback_(on_disconnect)
|
||||
, error_callback_(on_error) {
|
||||
#ifdef _WIN32
|
||||
WSADATA _ws_data;
|
||||
if (int ret = WSAStartup(MAKEWORD(2, 2), &_ws_data); ret != 0) {
|
||||
Logger::Get().Error("WSAStartup failed with code {}", ret);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
virtual ~BridgeTransport() {
|
||||
Stop();
|
||||
#ifdef _WIN32
|
||||
WSACleanup();
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Starts the channel by creating a thread.
|
||||
*
|
||||
* Connects and automatic reconnects with a timeout are implemented internally.
|
||||
*/
|
||||
void Start();
|
||||
|
||||
/**
|
||||
* @brief Stops the channel by stopping the thread and closing the connection handles.
|
||||
*
|
||||
* Blocks until the thread is stopped and the connection handles are closed.
|
||||
*/
|
||||
void Stop();
|
||||
|
||||
/**
|
||||
* @brief Stops the channel asynchronously and returns immediately.
|
||||
*/
|
||||
void StopAsync();
|
||||
|
||||
/**
|
||||
* @brief Sends a message over the channel, you must Finish() the builder before calling this.
|
||||
*
|
||||
* @param message The message to send.
|
||||
*/
|
||||
void SendMessage(const flatbuffers::FlatBufferBuilder& fbb);
|
||||
|
||||
/**
|
||||
* @brief Checks if the channel is connected.
|
||||
*
|
||||
* @return true if the channel is connected, false otherwise.
|
||||
*/
|
||||
bool IsConnected() const {
|
||||
std::shared_lock fd_lock(fd_mutex_);
|
||||
return fd_ != InvalidSocket;
|
||||
};
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Try to create a connection.
|
||||
*
|
||||
* Called while an exclusive lock is taken on @ref fd_mutex_.
|
||||
* Make sure this doesn't block as it will hold up shutdown.
|
||||
*
|
||||
* @ref fd_ must be initialised if this returns without throwing.
|
||||
*
|
||||
* @throws std::system_error I/O error when creating connection
|
||||
* @throws std::exception failed to create connection
|
||||
*/
|
||||
virtual void CreateConnection() = 0;
|
||||
/**
|
||||
* @brief Close the current socket if it's connected.
|
||||
*
|
||||
* Locks @ref fd_mutex_, do not call this with the mutex locked.
|
||||
*/
|
||||
void ResetConnection();
|
||||
|
||||
/**
|
||||
* @brief Closes the current connection, must be called while an exclusive lock is taken on the mutex.
|
||||
*/
|
||||
void CloseConnectionHandles();
|
||||
|
||||
void OnConnect() {
|
||||
if (connect_callback_)
|
||||
connect_callback_();
|
||||
}
|
||||
void OnRecv(std::span<uint8_t> event);
|
||||
void OnDisconnect() {
|
||||
if (disconnect_callback_)
|
||||
disconnect_callback_();
|
||||
}
|
||||
|
||||
static std::filesystem::path GetSocketPath();
|
||||
|
||||
/// Guards @ref fd_ and the condition variable @ref cv_.
|
||||
mutable std::shared_mutex fd_mutex_;
|
||||
/// Guards write operations.
|
||||
mutable std::mutex write_mutex_;
|
||||
/// Signaled on connection, or when we're exiting.
|
||||
std::condition_variable_any cv_;
|
||||
Socket fd_ = InvalidSocket;
|
||||
|
||||
private:
|
||||
void RunThread(std::stop_token stop);
|
||||
|
||||
std::function<void()> connect_callback_;
|
||||
std::function<void(MessageHeader&&)> message_callback_;
|
||||
std::function<void()> disconnect_callback_;
|
||||
std::function<void(std::exception&)> error_callback_;
|
||||
|
||||
std::jthread thread_;
|
||||
std::jthread reconnect_thread_;
|
||||
std::optional<std::error_code> last_error_;
|
||||
};
|
||||
@@ -1,17 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
// SPDX-FileCopyrightText: (c) 2026 Eiren Rain and SlimeVR Contributors
|
||||
#pragma once
|
||||
|
||||
#include <bit>
|
||||
#include <type_traits>
|
||||
|
||||
template <std::endian Endianness, typename T>
|
||||
requires(std::is_integral_v<T>)
|
||||
inline T ConvertEndianness(T v) {
|
||||
// I don't really care about mixed endianness..
|
||||
if constexpr (std::endian::native == Endianness) {
|
||||
return v;
|
||||
} else {
|
||||
return std::byteswap(v);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
#endif
|
||||
|
||||
Logger::Logger()
|
||||
: log_stream(Paths::GetLogPath() / "slimevr-bindings-provider.log",
|
||||
: log_stream(Paths::getLogPath() / "slimevr-bindings-provider.log",
|
||||
std::ios::out | std::ios::app)
|
||||
#ifdef _WIN32
|
||||
, should_log_to_std_streams(GetConsoleWindow() != nullptr)
|
||||
@@ -15,7 +15,7 @@ Logger::Logger()
|
||||
{
|
||||
}
|
||||
|
||||
Logger& Logger::Get() {
|
||||
Logger &Logger::get() {
|
||||
static Logger logger;
|
||||
return logger;
|
||||
}
|
||||
@@ -15,8 +15,8 @@ private:
|
||||
#endif
|
||||
|
||||
template <bool important, typename... Args>
|
||||
void Log(std::string_view suffix, std::format_string<Args...> fmt,
|
||||
Args&&... args) {
|
||||
void log(std::string_view suffix, std::format_string<Args...> fmt,
|
||||
Args &&...args) {
|
||||
auto now = std::chrono::system_clock::now();
|
||||
auto time_t = std::chrono::system_clock::to_time_t(now);
|
||||
|
||||
@@ -40,28 +40,28 @@ public:
|
||||
Logger();
|
||||
|
||||
template <typename... Args>
|
||||
void Debug(std::format_string<Args...> fmt, Args&&... args) {
|
||||
void debug(std::format_string<Args...> fmt, Args &&...args) {
|
||||
#ifndef NDEBUG
|
||||
Log<false>("[DEBUG]", fmt, std::forward<Args>(args)...);
|
||||
log<false>("[DEBUG]", fmt, std::forward<Args>(args)...);
|
||||
#endif
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void Info(std::format_string<Args...> fmt, Args&&... args) {
|
||||
Log<false>("[INFO]", fmt, std::forward<Args>(args)...);
|
||||
void info(std::format_string<Args...> fmt, Args &&...args) {
|
||||
log<false>("[INFO]", fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void Warning(std::format_string<Args...> fmt, Args&&... args) {
|
||||
Log<true>("[WARN]", fmt, std::forward<Args>(args)...);
|
||||
void warning(std::format_string<Args...> fmt, Args &&...args) {
|
||||
log<true>("[WARN]", fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void Error(std::format_string<Args...> fmt, Args&&... args) {
|
||||
Log<true>("[ERROR]", fmt, std::forward<Args>(args)...);
|
||||
void error(std::format_string<Args...> fmt, Args &&...args) {
|
||||
log<true>("[ERROR]", fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
void Flush() {
|
||||
void flush() {
|
||||
#ifdef _WIN32
|
||||
if (should_log_to_std_streams) {
|
||||
#endif
|
||||
@@ -73,5 +73,5 @@ public:
|
||||
log_stream.flush();
|
||||
}
|
||||
|
||||
static Logger& Get();
|
||||
static Logger &get();
|
||||
};
|
||||
+122
-105
@@ -1,3 +1,4 @@
|
||||
#include <cassert>
|
||||
#include <csignal>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
@@ -8,15 +9,13 @@
|
||||
#include "flatbuffers/flatbuffers.h"
|
||||
#include "solarxr_protocol/generated/all_generated.h"
|
||||
|
||||
#include "bridge/BridgeClient.hpp"
|
||||
#include "logger.hpp"
|
||||
#include "solarxr.hpp"
|
||||
#include "vr_utils.hpp"
|
||||
|
||||
#include "openvr.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#define WIN32_MEAN_AND_LEAN
|
||||
#define NOMINMAX
|
||||
#include <Windows.h>
|
||||
#else
|
||||
#include <cstdlib>
|
||||
@@ -26,112 +25,102 @@ namespace fs = std::filesystem;
|
||||
using namespace std::chrono_literals;
|
||||
using namespace solarxr_protocol;
|
||||
|
||||
static void ShutdownVR(vr::IVRSystem* _sys) { vr::VR_Shutdown(); }
|
||||
static void shutdown_vr(vr::IVRSystem *_sys) { vr::VR_Shutdown(); }
|
||||
|
||||
static void OnYawReset(BridgeTransport& conn) {
|
||||
static void onYawReset(SolarXRConnection &conn) {
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::YAW, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Yaw, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(
|
||||
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({ msgHeader });
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
|
||||
fbb.Finish(bundle);
|
||||
conn.SendMessage(fbb);
|
||||
conn.sendMsg(fbb);
|
||||
}
|
||||
static void OnFullReset(BridgeTransport& conn) {
|
||||
static void onFullReset(SolarXRConnection &conn) {
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::FULL, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Full, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(
|
||||
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({ msgHeader });
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
|
||||
fbb.Finish(bundle);
|
||||
conn.SendMessage(fbb);
|
||||
conn.sendMsg(fbb);
|
||||
}
|
||||
static void OnMountingCalibration(BridgeTransport& conn) {
|
||||
static void onMountingCalibration(SolarXRConnection &conn) {
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::MOUNTING, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Mounting, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(
|
||||
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({ msgHeader });
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
|
||||
fbb.Finish(bundle);
|
||||
conn.SendMessage(fbb);
|
||||
conn.sendMsg(fbb);
|
||||
}
|
||||
static void OnFeetMountingCalibration(BridgeTransport& conn) {
|
||||
static void onFeetMountingCalibration(SolarXRConnection &conn) {
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
auto bodyParts = fbb.CreateVector(
|
||||
{ datatypes::BodyPart::LEFT_FOOT, datatypes::BodyPart::RIGHT_FOOT });
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::MOUNTING, bodyParts, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Mounting, bodyParts, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(
|
||||
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({ msgHeader });
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
|
||||
fbb.Finish(bundle);
|
||||
conn.SendMessage(fbb);
|
||||
conn.sendMsg(fbb);
|
||||
}
|
||||
static void OnToggleTracking(BridgeTransport& conn) {
|
||||
static void onToggleTracking(SolarXRConnection &conn) {
|
||||
static bool shouldPause = false;
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
shouldPause = !shouldPause;
|
||||
auto toggleReq = rpc::CreateSetPauseTrackingRequest(fbb, shouldPause);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::SetPauseTrackingRequest, toggleReq.Union());
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(
|
||||
fbb, nullptr, rpc::RpcMessage::SetPauseTrackingRequest,
|
||||
toggleReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({ msgHeader });
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
|
||||
fbb.Finish(bundle);
|
||||
conn.SendMessage(fbb);
|
||||
conn.sendMsg(fbb);
|
||||
}
|
||||
|
||||
sig_atomic_t should_exit = 0;
|
||||
|
||||
static void OnSignal(int signal) {
|
||||
Logger::Get().Info("Received signal {}", signal);
|
||||
static void signal_handler(int signal) {
|
||||
Logger::get().info("Received signal {}", signal);
|
||||
should_exit = 1;
|
||||
}
|
||||
|
||||
int main() {
|
||||
auto& logger = Logger::Get();
|
||||
|
||||
// Steam and SteamVR respectively set these environment variables on applications that
|
||||
// they spawn, which the SteamVR client library (vrclient) will then use as the
|
||||
// application key when initiating the connection with vrserver. This may not
|
||||
// be ideal if we are launched by another Steam or OpenVR application, as we will inherit
|
||||
// their app key through the environment, which means SteamVR will load the wrong bindings.
|
||||
// A real-world example of this is if someone uses an application such as OpenVR-Autostarter
|
||||
// to start the SlimeVR Server. OpenVR-Autostarter installs an application manifest with the
|
||||
// app key "dreiekk.openvr-autostarter", so when it starts SlimeVR Server, which then starts us,
|
||||
// the STEAMVR_APPKEY="dreiekk.openvr-autostarter" environment variable will be set.
|
||||
//
|
||||
// We want SteamVR to use the appkey of the Steam version of our application if possible.
|
||||
// Unfortunately, we cannot install an application vrmanifest to force the app key,
|
||||
// as SteamVR requires a binary path in the manifest to consider it valid. We do not want to install
|
||||
// a manifest with a binary path because we want the SlimeVR Server to start us when the
|
||||
// driver initiates a connection, rather than getting auto-started by SteamVR.
|
||||
//
|
||||
// This is not documented anywhere publicly, see CVRClient::SendConnectMessage in vrclient instead.
|
||||
|
||||
constexpr const char* STEAM_APPID = "3245490";
|
||||
constexpr const char* STEAMVR_APPKEY = "steam.overlay.3245490";
|
||||
|
||||
auto &logger = Logger::get();
|
||||
// Steam and SteamVR sets these environment variables on applications that it
|
||||
// spawns, but if an app spawned by Steam then spawns a child that initialises
|
||||
// OpenVR, SteamVR will give the child the appkey of the root application it
|
||||
// is a descendant of, e.g. if SteamVR launches SlimeVR as an overlay,
|
||||
// it will set SteamAppId="3245490" and STEAMVR_APPKEY="steam.overlay.3245490"
|
||||
// which breaks our bindings. We want SteamVR to use a generated appkey if
|
||||
// possible.
|
||||
#ifdef _WIN32
|
||||
SetEnvironmentVariableA("SteamAppId", STEAM_APPID);
|
||||
SetEnvironmentVariableA("STEAMVR_APPKEY", STEAMVR_APPKEY);
|
||||
SetEnvironmentVariableA("SteamAppId", nullptr);
|
||||
SetEnvironmentVariableA("STEAMVR_APPKEY", nullptr);
|
||||
#else
|
||||
setenv("SteamAppId", STEAM_APPID, 1);
|
||||
setenv("STEAMVR_APPKEY", STEAMVR_APPKEY, 1);
|
||||
unsetenv("SteamAppId");
|
||||
unsetenv("STEAMVR_APPKEY");
|
||||
#endif
|
||||
|
||||
try {
|
||||
BridgeClient conn(nullptr, nullptr, [] { should_exit = 1; }, [](std::exception&) { should_exit = 1; });
|
||||
conn.Start();
|
||||
|
||||
std::unique_ptr<vr::IVRSystem, decltype(&ShutdownVR)> sys{ nullptr, ShutdownVR };
|
||||
SolarXRConnection conn;
|
||||
std::unique_ptr<vr::IVRSystem, decltype(&shutdown_vr)> sys{ nullptr,
|
||||
shutdown_vr };
|
||||
|
||||
// On vrlink, VR_Init returns
|
||||
// VRInitError_Driver_WirelessHmdNotConnected while the connection
|
||||
@@ -146,19 +135,22 @@ int main() {
|
||||
}
|
||||
|
||||
if (sys == nullptr or err != vr::VRInitError_None) {
|
||||
logger.Error("Failed to init OpenVR: {} ({})",
|
||||
logger.error("Failed to init OpenVR: {} ({})",
|
||||
vr::VR_GetVRInitErrorAsSymbol(err),
|
||||
vr::VR_GetVRInitErrorAsEnglishDescription(err));
|
||||
return 1;
|
||||
}
|
||||
|
||||
logger.Info("Initialised OpenVR, HMD model '{}'", VRUtils::GetStringProp(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_ModelNumber_String).value_or("<unknown>"));
|
||||
logger.info("Initialised OpenVR, HMD model '{}'",
|
||||
VRUtils::getStringProp(vr::k_unTrackedDeviceIndex_Hmd,
|
||||
vr::Prop_ModelNumber_String)
|
||||
.value_or("<unknown>"));
|
||||
|
||||
vr::IVRApplications* app = vr::VRApplications();
|
||||
vr::IVRInput* input = vr::VRInput();
|
||||
vr::IVRApplications *app = vr::VRApplications();
|
||||
vr::IVRInput *input = vr::VRInput();
|
||||
|
||||
fs::path actionManifestPath;
|
||||
std::tie(std::ignore, actionManifestPath) = VRUtils::InitialiseManifests();
|
||||
std::tie(std::ignore, actionManifestPath) = VRUtils::initialiseManifest();
|
||||
|
||||
// We don't want our app key to randomly change if SteamVR decides to honour
|
||||
// application manifests with no binary path. Instead let it generate an
|
||||
@@ -175,16 +167,21 @@ int main() {
|
||||
// SetActionManifestPath may return IPCError if vrserver is busy and takes
|
||||
// too long to reply, so keep invoking until it succeeds
|
||||
{
|
||||
vr::EVRInputError err;
|
||||
vr::EVRInputError err{};
|
||||
constexpr int max_tries = 5;
|
||||
int tries = 0;
|
||||
while ((err = input->SetActionManifestPath(actionManifestPath.string().data())) == vr::VRInputError_IPCError && tries++ < max_tries) {
|
||||
logger.Debug("IPC error loading action manifest, retrying ({}/{})", tries, max_tries);
|
||||
while ((err = input->SetActionManifestPath(
|
||||
actionManifestPath.string().data()))
|
||||
== vr::VRInputError_IPCError
|
||||
&& tries++ < max_tries) {
|
||||
logger.debug("IPC error loading action manifest, retrying ({}/{})",
|
||||
tries, max_tries);
|
||||
std::this_thread::sleep_for(20ms);
|
||||
}
|
||||
|
||||
if (err != vr::VRInputError_None) {
|
||||
logger.Error("Failed to set action manifest path: {}", std::to_underlying(err));
|
||||
logger.error("Failed to set action manifest path: {}",
|
||||
std::to_underlying(err));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -192,60 +189,74 @@ int main() {
|
||||
vr::VRActionSetHandle_t action_set;
|
||||
if (auto err = input->GetActionSetHandle("/actions/main", &action_set);
|
||||
err != vr::VRInputError_None) {
|
||||
logger.Error("Failed to get main action set handle: {}", std::to_underlying(err));
|
||||
logger.error("Failed to get main action set handle: {}",
|
||||
std::to_underlying(err));
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::map<std::string, std::tuple<vr::VRActionHandle_t, std::function<void(BridgeTransport&)>>>
|
||||
std::map<std::string, std::tuple<vr::VRActionHandle_t, std::function<void(SolarXRConnection &)>>>
|
||||
actions{
|
||||
{ "/actions/main/in/YawReset", std::make_tuple(vr::k_ulInvalidActionHandle, OnYawReset) },
|
||||
{ "/actions/main/in/FullReset", std::make_tuple(vr::k_ulInvalidActionHandle, OnFullReset) },
|
||||
{ "/actions/main/in/MountingCalibration", std::make_tuple(vr::k_ulInvalidActionHandle, OnMountingCalibration) },
|
||||
{ "/actions/main/in/FeetMountingCalibration", std::make_tuple(vr::k_ulInvalidActionHandle, OnFeetMountingCalibration) },
|
||||
{ "/actions/main/in/ToggleTracking", std::make_tuple(vr::k_ulInvalidActionHandle, OnToggleTracking) },
|
||||
{ "/actions/main/in/YawReset",
|
||||
std::make_tuple(vr::k_ulInvalidActionHandle, onYawReset) },
|
||||
{ "/actions/main/in/FullReset",
|
||||
std::make_tuple(vr::k_ulInvalidActionHandle, onFullReset) },
|
||||
{ "/actions/main/in/MountingCalibration",
|
||||
std::make_tuple(vr::k_ulInvalidActionHandle,
|
||||
onMountingCalibration) },
|
||||
{ "/actions/main/in/FeetMountingCalibration",
|
||||
std::make_tuple(vr::k_ulInvalidActionHandle,
|
||||
onFeetMountingCalibration) },
|
||||
{ "/actions/main/in/ToggleTracking",
|
||||
std::make_tuple(vr::k_ulInvalidActionHandle, onToggleTracking) },
|
||||
};
|
||||
|
||||
for (auto& [name, tuple] : actions) {
|
||||
auto& [handle, _] = tuple;
|
||||
for (auto &[name, tuple] : actions) {
|
||||
auto &[handle, _] = tuple;
|
||||
if (auto err = input->GetActionHandle(name.c_str(), &handle);
|
||||
err != vr::VRInputError_None || handle == vr::k_ulInvalidActionHandle) {
|
||||
logger.Warning("Failed to get action handle for action {}: {}", name,
|
||||
logger.warning("Failed to get action handle for action {}: {}", name,
|
||||
std::to_underlying(err));
|
||||
}
|
||||
}
|
||||
|
||||
constexpr auto interval = 1000ms / 30;
|
||||
|
||||
signal(SIGINT, OnSignal);
|
||||
signal(SIGTERM, OnSignal);
|
||||
signal(SIGINT, signal_handler);
|
||||
signal(SIGTERM, signal_handler);
|
||||
while (!should_exit) {
|
||||
vr::VREvent_t event{};
|
||||
while (sys->PollNextEvent(&event, sizeof(event))) {
|
||||
switch (event.eventType) {
|
||||
case vr::VREvent_Quit:
|
||||
logger.Info("OpenVR runtime requested quit");
|
||||
logger.info("OpenVR runtime requested quit");
|
||||
should_exit = 1;
|
||||
break;
|
||||
case vr::VREvent_Input_BindingLoadFailed: {
|
||||
auto& loadData = event.data.inputBinding;
|
||||
logger.Debug("Binding load failed (ulAppContainer={} pathMessage={} pathUrl={} pathControllerType={})",
|
||||
loadData.ulAppContainer, loadData.pathMessage, loadData.pathUrl, loadData.pathControllerType);
|
||||
auto &loadData = event.data.inputBinding;
|
||||
logger.debug("Binding load failed (ulAppContainer={} "
|
||||
"pathMessage={} pathUrl={} pathControllerType={})",
|
||||
loadData.ulAppContainer, loadData.pathMessage,
|
||||
loadData.pathUrl, loadData.pathControllerType);
|
||||
break;
|
||||
}
|
||||
case vr::VREvent_Input_BindingLoadSuccessful: {
|
||||
auto& loadData = event.data.inputBinding;
|
||||
logger.Debug("Binding load successful (ulAppContainer={} pathMessage={} pathUrl={} pathControllerType={})",
|
||||
loadData.ulAppContainer, loadData.pathMessage, loadData.pathUrl, loadData.pathControllerType);
|
||||
auto &loadData = event.data.inputBinding;
|
||||
logger.debug("Binding load successful (ulAppContainer={} "
|
||||
"pathMessage={} pathUrl={} pathControllerType={})",
|
||||
loadData.ulAppContainer, loadData.pathMessage,
|
||||
loadData.pathUrl, loadData.pathControllerType);
|
||||
break;
|
||||
}
|
||||
case vr::VREvent_Input_ActionManifestReloaded:
|
||||
logger.Debug("Action manifest reloaded");
|
||||
logger.debug("Action manifest reloaded");
|
||||
break;
|
||||
case vr::VREvent_Input_ActionManifestLoadFailed: {
|
||||
auto& manifestData = event.data.actionManifest;
|
||||
logger.Debug(
|
||||
"Action manifest load failed (pathAppKey={} pathMessage={} pathMessageParam={} pathManifestPath={})",
|
||||
manifestData.pathAppKey, manifestData.pathMessage, manifestData.pathMessageParam, manifestData.pathManifestPath);
|
||||
auto &manifestData = event.data.actionManifest;
|
||||
logger.debug(
|
||||
"Action manifest load failed (pathAppKey={} pathMessage={} "
|
||||
"pathMessageParam={} pathManifestPath={})",
|
||||
manifestData.pathAppKey, manifestData.pathMessage,
|
||||
manifestData.pathMessageParam, manifestData.pathManifestPath);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
@@ -253,6 +264,11 @@ int main() {
|
||||
}
|
||||
}
|
||||
|
||||
if (!conn.connected()) {
|
||||
logger.warning("Connection to SlimeVR lost, exiting");
|
||||
break;
|
||||
}
|
||||
|
||||
vr::VRActiveActionSet_t set{
|
||||
.ulActionSet = action_set,
|
||||
.ulRestrictedToDevice = vr::k_ulInvalidInputValueHandle,
|
||||
@@ -261,38 +277,39 @@ int main() {
|
||||
};
|
||||
if (auto err = input->UpdateActionState(&set, sizeof(set), 1);
|
||||
err != vr::VRInputError_None) {
|
||||
logger.Warning("Error when updating action states: {}",
|
||||
logger.warning("Error when updating action states: {}",
|
||||
std::to_underlying(err));
|
||||
}
|
||||
|
||||
for (auto& [name, tuple] : actions) {
|
||||
auto& [handle, callback] = tuple;
|
||||
for (auto &[name, tuple] : actions) {
|
||||
auto &[handle, callback] = tuple;
|
||||
vr::InputDigitalActionData_t action_data{};
|
||||
if (auto err = input->GetDigitalActionData(
|
||||
handle, &action_data, sizeof(action_data),
|
||||
vr::k_ulInvalidInputValueHandle);
|
||||
err != vr::VRInputError_None) {
|
||||
logger.Warning("Failed to get action state for {} ({}): {}", name, handle, std::to_underlying(err));
|
||||
logger.warning("Failed to get action state for {} ({}): {}", name,
|
||||
handle, std::to_underlying(err));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (action_data.bActive && action_data.bChanged && action_data.bState) {
|
||||
logger.Debug("Action {} triggered", name);
|
||||
logger.debug("Action {} triggered", name);
|
||||
callback(conn);
|
||||
}
|
||||
}
|
||||
|
||||
logger.Flush();
|
||||
logger.flush();
|
||||
std::this_thread::sleep_for(interval);
|
||||
}
|
||||
|
||||
logger.Info("Main loop done");
|
||||
} catch (std::exception& ex) {
|
||||
logger.Error("Exception in main: {}", ex.what());
|
||||
logger.Flush();
|
||||
logger.info("Main loop done");
|
||||
} catch (std::exception &ex) {
|
||||
logger.error("Exception in main: {}", ex.what());
|
||||
logger.flush();
|
||||
return 1;
|
||||
}
|
||||
|
||||
logger.Flush();
|
||||
logger.flush();
|
||||
return 0;
|
||||
}
|
||||
@@ -1,22 +1,15 @@
|
||||
#include "paths.hpp"
|
||||
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define NOMINMAX
|
||||
#include <Windows.h>
|
||||
#undef GetTempPath
|
||||
#endif
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
fs::path Paths::GetDataPath() {
|
||||
fs::path Paths::getDataPath() {
|
||||
fs::path basePath{};
|
||||
|
||||
#if defined(__linux__)
|
||||
if (const char* dataHomeOverride = getenv("XDG_DATA_HOME")) {
|
||||
if (const char *dataHomeOverride = getenv("XDG_DATA_HOME")) {
|
||||
basePath = dataHomeOverride;
|
||||
} else {
|
||||
const char* homeDir = getenv("HOME");
|
||||
const char *homeDir = getenv("HOME");
|
||||
if (homeDir == nullptr)
|
||||
throw std::runtime_error("HOME is unset");
|
||||
|
||||
@@ -24,7 +17,7 @@ fs::path Paths::GetDataPath() {
|
||||
}
|
||||
#elif defined(_WIN32)
|
||||
{
|
||||
const char* appData = getenv("APPDATA");
|
||||
const char *appData = getenv("APPDATA");
|
||||
if (appData == nullptr)
|
||||
throw std::runtime_error("APPDATA is unset");
|
||||
|
||||
@@ -37,18 +30,4 @@ fs::path Paths::GetDataPath() {
|
||||
return basePath / "dev.slimevr.SlimeVR";
|
||||
}
|
||||
|
||||
fs::path Paths::GetLogPath() { return Paths::GetDataPath() / "logs"; }
|
||||
|
||||
fs::path Paths::GetTempPath() noexcept {
|
||||
#ifdef _WIN32
|
||||
WCHAR tmp_dir[MAX_PATH + 1];
|
||||
GetTempPathW(std::size(tmp_dir), tmp_dir);
|
||||
return tmp_dir;
|
||||
#else
|
||||
if (const char* tmp_dir = getenv("TMPDIR")) {
|
||||
return tmp_dir;
|
||||
}
|
||||
|
||||
return "/tmp";
|
||||
#endif
|
||||
}
|
||||
fs::path Paths::getLogPath() { return Paths::getDataPath() / "logs"; }
|
||||
@@ -4,10 +4,8 @@
|
||||
|
||||
namespace Paths {
|
||||
// Throws when path cannot be found
|
||||
std::filesystem::path GetDataPath() noexcept(false);
|
||||
std::filesystem::path getDataPath() noexcept(false);
|
||||
|
||||
// Throws when path cannot be found
|
||||
std::filesystem::path GetLogPath() noexcept(false);
|
||||
|
||||
std::filesystem::path GetTempPath() noexcept;
|
||||
std::filesystem::path getLogPath() noexcept(false);
|
||||
} // namespace Paths
|
||||
@@ -0,0 +1,163 @@
|
||||
#include "solarxr.hpp"
|
||||
#include "logger.hpp"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
#if defined(__linux__)
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#elif defined(_WIN32)
|
||||
#include <Windows.h>
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
fs::path SolarXRConnection::getSocketPath() {
|
||||
using namespace std::string_view_literals;
|
||||
#if defined(__linux__)
|
||||
#define MAKE_SOCKET_PATH(PATH) \
|
||||
std::make_pair(PATH##sv, static_cast<const char *>(getenv(PATH)))
|
||||
|
||||
constexpr std::string_view socketName = "SlimeVRRpc";
|
||||
std::array<std::pair<std::string_view, const char *>, 4> socketPaths{
|
||||
MAKE_SOCKET_PATH("SLIMEVR_SOCKET_DIR"),
|
||||
MAKE_SOCKET_PATH("XDG_RUNTIME_DIR"),
|
||||
MAKE_SOCKET_PATH("TMPDIR"),
|
||||
{ "/tmp", "/tmp" }
|
||||
};
|
||||
|
||||
#undef MAKE_SOCKET_PATH
|
||||
|
||||
for (auto [name, path] : socketPaths) {
|
||||
if (path == nullptr) {
|
||||
Logger::get().info(
|
||||
"Skipping socket directory {} because it doesn't exist", name);
|
||||
continue;
|
||||
}
|
||||
fs::path socketPath = fs::path(path) / socketName;
|
||||
if (fs::exists(socketPath))
|
||||
return socketPath;
|
||||
|
||||
Logger::get().info(
|
||||
"Skipping socket directory {} because socket does not exist", name);
|
||||
}
|
||||
#elif defined(_WIN32)
|
||||
throw std::logic_error(
|
||||
"SolarXRConnection::getSocketPath should not be called on Windows");
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
|
||||
throw std::runtime_error("Failed to find socket directory");
|
||||
}
|
||||
|
||||
SolarXRConnection::SolarXRConnection() {
|
||||
#if defined(__linux__)
|
||||
sockaddr_un addr{};
|
||||
addr.sun_family = AF_UNIX;
|
||||
strcpy(addr.sun_path, getSocketPath().string().data());
|
||||
|
||||
fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (fd == -1) {
|
||||
throw std::runtime_error(
|
||||
std::format("Failed to create listen socket: {}", strerror(errno)));
|
||||
}
|
||||
|
||||
if (connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
|
||||
int e = errno;
|
||||
close(fd);
|
||||
throw std::runtime_error(std::format("Failed to connect to socket {}: {}",
|
||||
addr.sun_path, strerror(e)));
|
||||
}
|
||||
|
||||
#elif defined(_WIN32)
|
||||
const char *pipeName = R"(\\.\pipe\SlimeVRRpc)";
|
||||
if (!WaitNamedPipe(pipeName, 5000)) {
|
||||
throw std::runtime_error("Timed out waiting for pipe");
|
||||
}
|
||||
|
||||
pipe = CreateFile(pipeName, GENERIC_READ | GENERIC_WRITE, 0, nullptr,
|
||||
OPEN_EXISTING, 0, nullptr);
|
||||
if (pipe == INVALID_HANDLE_VALUE) {
|
||||
throw std::runtime_error(
|
||||
std::format("Unable to open pipe (error={})", GetLastError()));
|
||||
}
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
}
|
||||
|
||||
SolarXRConnection::~SolarXRConnection() {
|
||||
#if defined(__linux__)
|
||||
if (fd != -1)
|
||||
close(fd);
|
||||
#elif defined(_WIN32)
|
||||
if (pipe != INVALID_HANDLE_VALUE)
|
||||
CloseHandle(pipe);
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
}
|
||||
|
||||
bool SolarXRConnection::connected() {
|
||||
#if defined(__linux__)
|
||||
if (read(fd, nullptr, 0) == -1) {
|
||||
return !(errno == EBADF || errno == EINVAL);
|
||||
}
|
||||
|
||||
return true;
|
||||
#elif defined(_WIN32)
|
||||
if (!WriteFile(pipe, nullptr, 0, nullptr, nullptr)) {
|
||||
int err = GetLastError();
|
||||
// The documentation says it should return ERROR_BROKEN_PIPE
|
||||
// when the write-end has been closed, but it seems to actually
|
||||
// return ERROR_NO_DATA...
|
||||
return !(err == ERROR_NO_DATA || err == ERROR_BROKEN_PIPE);
|
||||
}
|
||||
|
||||
return true;
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
}
|
||||
|
||||
void SolarXRConnection::sendMsg(flatbuffers::FlatBufferBuilder &fbb) {
|
||||
// The server expects the total size of the buffer to be written at the
|
||||
// start of the packet, including the first 4 bytes for the size
|
||||
int size = fbb.GetSize() + 4;
|
||||
// This may be wrong on mixed-endianness, but oh well...
|
||||
if constexpr (std::endian::native != std::endian::little)
|
||||
size = std::byteswap(size);
|
||||
|
||||
#if defined(__linux__)
|
||||
if (write(fd, &size, sizeof(size)) == -1) {
|
||||
Logger::get().warning("Failed to write message size to socket: {}",
|
||||
strerror(errno));
|
||||
return;
|
||||
}
|
||||
|
||||
if (write(fd, fbb.GetBufferPointer(), fbb.GetSize()) == -1) {
|
||||
Logger::get().warning("Failed to write message to socket: {}",
|
||||
strerror(errno));
|
||||
return;
|
||||
}
|
||||
#elif defined(_WIN32)
|
||||
uint8_t tempBuf[2048];
|
||||
if (fbb.GetSize() > 2048 - 4) {
|
||||
Logger::get().warning("Message is too big for temporary buffer");
|
||||
return;
|
||||
}
|
||||
|
||||
*reinterpret_cast<int *>(&tempBuf[0]) = size;
|
||||
memcpy(&tempBuf[4], fbb.GetBufferPointer(), fbb.GetSize());
|
||||
if (!WriteFile(pipe, tempBuf, fbb.GetSize() + 4, nullptr, nullptr)) {
|
||||
Logger::get().warning("Failed to write message to pipe (error={})",
|
||||
GetLastError());
|
||||
return;
|
||||
}
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#define WIN32_MEAN_AND_LEAN
|
||||
#include <Windows.h>
|
||||
#endif
|
||||
|
||||
#include "flatbuffers/flatbuffer_builder.h"
|
||||
|
||||
class SolarXRConnection {
|
||||
private:
|
||||
#if defined(__linux__)
|
||||
int fd{ -1 };
|
||||
#elif defined(_WIN32)
|
||||
HANDLE pipe{ INVALID_HANDLE_VALUE };
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
|
||||
static std::filesystem::path getSocketPath();
|
||||
|
||||
public:
|
||||
SolarXRConnection() noexcept(false);
|
||||
|
||||
~SolarXRConnection();
|
||||
|
||||
bool connected();
|
||||
void sendMsg(flatbuffers::FlatBufferBuilder &fbb);
|
||||
};
|
||||
@@ -11,14 +11,14 @@
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
std::optional<std::string>
|
||||
VRUtils::GetStringProp(vr::TrackedDeviceIndex_t deviceIndex,
|
||||
VRUtils::getStringProp(vr::TrackedDeviceIndex_t deviceIndex,
|
||||
vr::ETrackedDeviceProperty prop) {
|
||||
vr::IVRSystem* sys = vr::VRSystem();
|
||||
vr::IVRSystem *sys = vr::VRSystem();
|
||||
vr::ETrackedPropertyError err{ vr::TrackedProp_Success };
|
||||
|
||||
uint32_t required_len = sys->GetStringTrackedDeviceProperty(deviceIndex, prop, nullptr, 0, &err);
|
||||
if (err != vr::TrackedProp_BufferTooSmall) {
|
||||
Logger::Get().Info(
|
||||
Logger::get().info(
|
||||
"Failed to get size of string property {} for device {}: {}",
|
||||
std::to_underlying(prop), deviceIndex,
|
||||
sys->GetPropErrorNameFromEnum(err));
|
||||
@@ -29,7 +29,7 @@ VRUtils::GetStringProp(vr::TrackedDeviceIndex_t deviceIndex,
|
||||
sys->GetStringTrackedDeviceProperty(deviceIndex, prop, s.data(), required_len,
|
||||
&err);
|
||||
if (err != vr::TrackedProp_Success) {
|
||||
Logger::Get().Info("Failed to get string property {} for device {}: {}",
|
||||
Logger::get().info("Failed to get string property {} for device {}: {}",
|
||||
std::to_underlying(prop), deviceIndex,
|
||||
sys->GetPropErrorNameFromEnum(err));
|
||||
return std::nullopt;
|
||||
@@ -38,8 +38,8 @@ VRUtils::GetStringProp(vr::TrackedDeviceIndex_t deviceIndex,
|
||||
return s;
|
||||
}
|
||||
|
||||
std::tuple<fs::path, fs::path> VRUtils::InitialiseManifests() {
|
||||
fs::path manifestDir = Paths::GetDataPath() / "bindings-provider";
|
||||
std::tuple<fs::path, fs::path> VRUtils::initialiseManifest() {
|
||||
fs::path manifestDir = Paths::getDataPath() / "bindings-provider";
|
||||
std::error_code ec;
|
||||
fs::create_directories(manifestDir, ec);
|
||||
if (ec) {
|
||||
@@ -59,7 +59,7 @@ std::tuple<fs::path, fs::path> VRUtils::InitialiseManifests() {
|
||||
std::make_pair("vive_controller.json"sv, SVR_VRAPP_VIVE_BINDS),
|
||||
};
|
||||
|
||||
for (auto& [name, contents] : requiredFiles) {
|
||||
for (auto &[name, contents] : requiredFiles) {
|
||||
fs::path path = manifestDir / name;
|
||||
if (!fs::exists(path)) {
|
||||
std::ofstream stream(path);
|
||||
|
||||
@@ -8,9 +8,9 @@
|
||||
#include "openvr.h"
|
||||
|
||||
namespace VRUtils {
|
||||
std::optional<std::string> GetStringProp(vr::TrackedDeviceIndex_t deviceIndex,
|
||||
std::optional<std::string> getStringProp(vr::TrackedDeviceIndex_t deviceIndex,
|
||||
vr::ETrackedDeviceProperty prop);
|
||||
|
||||
// Returns <app vrmanifest path, action manifest json path>
|
||||
std::tuple<std::filesystem::path, std::filesystem::path> InitialiseManifests();
|
||||
std::tuple<std::filesystem::path, std::filesystem::path> initialiseManifest();
|
||||
} // namespace VRUtils
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
# Crowdin Configuration File
|
||||
# https://developer.crowdin.com/configuration-file/
|
||||
|
||||
files:
|
||||
- source: /gui/app/public/i18n/en/translation.ftl
|
||||
translation: /gui/app/public/i18n/%locale%/%original_file_name%
|
||||
update_option: update_as_unapproved
|
||||
languages_mapping:
|
||||
locale:
|
||||
zh-CN: zh-Hans
|
||||
zh-TW: zh-Hant
|
||||
nb: nb-NO
|
||||
sv: sv-SE
|
||||
fr: fr
|
||||
de: de
|
||||
it: it
|
||||
ja: ja
|
||||
ko: ko
|
||||
ar: ar
|
||||
cs: cs
|
||||
da: da
|
||||
el: el
|
||||
es-419: es-419
|
||||
et: et
|
||||
fi: fi
|
||||
he: he
|
||||
lt: lt
|
||||
nl: nl
|
||||
pl: pl
|
||||
ru: ru
|
||||
th: th
|
||||
tr: tr
|
||||
uk: uk
|
||||
vi: vi
|
||||
# In-context editor pseudo-language
|
||||
ach-UG: ach-UG
|
||||
Generated
+9
-9
@@ -5,11 +5,11 @@
|
||||
"nixpkgs-lib": "nixpkgs-lib"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1790898470,
|
||||
"narHash": "sha256-zTwuwezD0w3hpga6a6P8emidzAZFyWqlNeRBlpWOOl8=",
|
||||
"lastModified": 1778716662,
|
||||
"narHash": "sha256-m1Yf0wZ8j1OHjTc2UwHwyQRSnNeSgLJOd7q5Y45hzi4=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"rev": "024633cd702b10285db5cb19b40ad48d2399ba60",
|
||||
"rev": "f7c1a2d347e4c52d5fb8d10cb4d94b5884e546fb",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -20,11 +20,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1790822859,
|
||||
"narHash": "sha256-69xHQhAeMAD2wDXO7T2pcOZIF9Sga2W+JkmY2a11Ops=",
|
||||
"lastModified": 1781577229,
|
||||
"narHash": "sha256-lrp67w8AulE9Ks53n27I45ADSzbOCn4H+CNW1Ck8B+8=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "c59305bab2065cfecc4944690d9eedbb56f3a9fa",
|
||||
"rev": "567a49d1913ce81ac6e9582e3553dd90a955875f",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -36,11 +36,11 @@
|
||||
},
|
||||
"nixpkgs-lib": {
|
||||
"locked": {
|
||||
"lastModified": 1790477367,
|
||||
"narHash": "sha256-oujbxmVKDhci2E4EM3KyAbRUgp5/IsCoiA/LfEF7OOk=",
|
||||
"lastModified": 1777168982,
|
||||
"narHash": "sha256-GOkGPcboWE9BmGCRMLX3worL4EMnsnG8MyKmXNeYuhQ=",
|
||||
"owner": "nix-community",
|
||||
"repo": "nixpkgs.lib",
|
||||
"rev": "f7cd230690d9fc982d06129f9189b101fddcfa3b",
|
||||
"rev": "f5901329dade4a6ea039af1433fb087bd9c1fe14",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
@@ -20,12 +20,7 @@
|
||||
];
|
||||
|
||||
perSystem =
|
||||
{
|
||||
system,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
{ lib, pkgs, ... }:
|
||||
let
|
||||
runtimeLibs = [
|
||||
pkgs.alsa-lib
|
||||
@@ -64,59 +59,67 @@
|
||||
pkgs.libxcrypt-legacy
|
||||
];
|
||||
|
||||
# we use static runtime
|
||||
# https://github.com/electron-userland/electron-builder/blob/a6117b3011a105204af8cc2eca02a56976d1ef29/packages/app-builder-lib/src/toolsets/linux.ts#L122
|
||||
appImageTools = pkgs.stdenvNoCC.mkDerivation {
|
||||
name = "electron-builder-appimage-runtime";
|
||||
src =
|
||||
let
|
||||
# Keep in sync with "appimage" toolset version in gui/electron/electron-builder.yml
|
||||
appimageToolsVersion = "1.0.3";
|
||||
in
|
||||
pkgs.fetchzip {
|
||||
url = "https://github.com/electron-userland/electron-builder-binaries/releases/download/appimage@${appimageToolsVersion}/appimage-tools-runtime-20251108.tar.gz";
|
||||
hash = "sha256-Iqhvyp6BNpH+tXvVO7MLgYbsJ6va4lXO7El3wtyWBII=";
|
||||
stripRoot = false;
|
||||
};
|
||||
toolDirectoryName =
|
||||
if pkgs.stdenv.hostPlatform.isDarwin then
|
||||
"darwin"
|
||||
else if pkgs.stdenv.hostPlatform.isLinux then
|
||||
{
|
||||
"armv7l-linux" = "linux-arm32";
|
||||
"aarch64-linux" = "linux-arm64";
|
||||
"i686-linux" = "linux-ia32";
|
||||
"x86_64-linux" = "linux-x64";
|
||||
}
|
||||
."${pkgs.stdenv.hostPlatform.system}"
|
||||
else
|
||||
throw "Unsupported platform";
|
||||
|
||||
# we use fuse2
|
||||
# https://github.com/electron-userland/electron-builder/blob/a6117b3011a105204af8cc2eca02a56976d1ef29/packages/app-builder-lib/src/toolsets/linux.ts#L122
|
||||
runtime = pkgs.stdenvNoCC.mkDerivation {
|
||||
name = "electron-builder-appimage-runtime";
|
||||
src = pkgs.fetchurl {
|
||||
url = "https://github.com/electron-userland/electron-builder-binaries/releases/download/appimage-12.0.1/appimage-12.0.1.7z";
|
||||
hash = "sha256-0S/3648dHsRlLKUjen+9yjOswMdYBFY2/spi3G7LjsQ=";
|
||||
};
|
||||
# https://github.com/NixOS/nixpkgs/blob/7890ba0a99c064446fe2178ef2f8e3abdf6ec42a/pkgs/by-name/lo/losslesscut-bin/build-from-windows.nix#L20
|
||||
nativeBuildInputs = [ pkgs.p7zip ];
|
||||
unpackPhase = ''
|
||||
runHook preUnpack
|
||||
7z x "$src"
|
||||
runHook postUnpack
|
||||
'';
|
||||
installPhase = ''
|
||||
mkdir $out
|
||||
cp -r -t $out/ lib/ runtimes/
|
||||
ln -s -t $out \
|
||||
"${pkgs.desktop-file-utils}/bin/desktop-file-validate" \
|
||||
"${pkgs.squashfsTools}/bin/mksquashfs"
|
||||
cp -r -t $out/ \
|
||||
lib/ \
|
||||
runtime-*
|
||||
'';
|
||||
};
|
||||
|
||||
buildToolsVersion = "36.0.0";
|
||||
androidComposition = pkgs.androidenv.composeAndroidPackages {
|
||||
buildToolsVersions = [
|
||||
buildToolsVersion
|
||||
];
|
||||
platformVersions = [
|
||||
"36"
|
||||
];
|
||||
appImageTools = pkgs.stdenvNoCC.mkDerivation {
|
||||
name = "electron-builder-appimage-tools";
|
||||
dontUnpack = true;
|
||||
|
||||
installPhase = ''
|
||||
mkdir -p "$out/${toolDirectoryName}"
|
||||
ln -s -t $out/${toolDirectoryName} \
|
||||
"${pkgs.desktop-file-utils}/bin/desktop-file-validate" \
|
||||
"${pkgs.squashfsTools}/bin/mksquashfs"
|
||||
ln -s ${runtime}/runtime-* $out/
|
||||
ln -s ${runtime}/lib $out/lib
|
||||
'';
|
||||
};
|
||||
in
|
||||
{
|
||||
# For Android SDK
|
||||
_module.args.pkgs = import nixpkgs {
|
||||
inherit system;
|
||||
config.allowUnfree = true;
|
||||
config.android_sdk.accept_license = true;
|
||||
};
|
||||
|
||||
devShells.default = pkgs.mkShell rec {
|
||||
devShells.default = pkgs.mkShell {
|
||||
packages = [
|
||||
# for running the jar
|
||||
pkgs.jdk25
|
||||
|
||||
pkgs.jdk17
|
||||
# for build
|
||||
pkgs.electron
|
||||
pkgs.rpm
|
||||
pkgs.fpm
|
||||
pkgs.p7zip
|
||||
# For Windows GUI cross-build
|
||||
pkgs.wineWow64Packages.stable
|
||||
pkgs.zlib
|
||||
pkgs.squashfsTools
|
||||
@@ -133,10 +136,20 @@
|
||||
pkgs.binutils
|
||||
pkgs.git
|
||||
pkgs.node-gyp-build
|
||||
androidComposition.androidsdk
|
||||
];
|
||||
buildInputs = runtimeLibs;
|
||||
|
||||
JAVA_HOME = "${pkgs.jdk17}/lib/openjdk";
|
||||
USE_SYSTEM_FPM = "true";
|
||||
ELECTRON_BUILDER_7ZIP_PATH = "${pkgs.p7zip}/bin/7za";
|
||||
APPIMAGE_TOOLS_PATH = "${appImageTools}";
|
||||
#ELECTRON_SKIP_BINARY_DOWNLOAD = true;
|
||||
#ELECTRON_DIST = "${pkgs.electron.dist}";
|
||||
#ELECTRON_VERSION = "${pkgs.electron.version}";
|
||||
|
||||
# for electron-vite, so `pnpm gui` works
|
||||
ELECTRON_EXEC_PATH = "${pkgs.electron}/bin/electron";
|
||||
|
||||
shellHook = ''
|
||||
export LD_LIBRARY_PATH="${
|
||||
lib.makeLibraryPath [
|
||||
@@ -144,21 +157,7 @@
|
||||
pkgs.hidapi
|
||||
]
|
||||
}:$LD_LIBRARY_PATH"
|
||||
|
||||
# VSCode's extension host sets ELECTRON_RUN_AS_NODE=1 on itself, and
|
||||
# shells it forks inherit it. It makes electron run as plain node, so
|
||||
# the main process crashes on `import { app } from 'electron'`.
|
||||
unset ELECTRON_RUN_AS_NODE
|
||||
'';
|
||||
|
||||
JAVA_HOME = "${pkgs.jdk25}/lib/openjdk";
|
||||
USE_SYSTEM_FPM = "true";
|
||||
ELECTRON_BUILDER_7ZIP_PATH = "${pkgs.p7zip}/bin/7za";
|
||||
APPIMAGE_TOOLS_PATH = "${appImageTools}";
|
||||
# for electron-vite, so `pnpm gui` works
|
||||
ELECTRON_EXEC_PATH = "${pkgs.electron}/bin/electron";
|
||||
ANDROID_HOME = "${androidComposition.androidsdk}/libexec/android-sdk";
|
||||
GRADLE_OPTS = "-Dorg.gradle.project.android.aapt2FromMavenOverride=${ANDROID_HOME}/build-tools/${buildToolsVersion}/aapt2";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
+6
-13
@@ -1,30 +1,23 @@
|
||||
# Fixes bug with spotless. See https://github.com/diffplug/spotless/issues/834#issuecomment-819118761
|
||||
org.gradle.jvmargs=-Xmx4g -Xms1g \
|
||||
--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED \
|
||||
org.gradle.jvmargs=--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED \
|
||||
--add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED \
|
||||
--add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED \
|
||||
--add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED \
|
||||
--add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED
|
||||
|
||||
org.gradle.parallel=true
|
||||
#org.gradle.caching=true
|
||||
org.gradle.configureondemand=true
|
||||
|
||||
kotlin.code.style=official
|
||||
# https://github.com/Kotlin/kotlinx-atomicfu#atomicfu-compiler-plugin
|
||||
kotlinx.atomicfu.enableJvmIrTransformation=true
|
||||
|
||||
android.useAndroidX=true
|
||||
android.nonTransitiveRClass=true
|
||||
#org.gradle.configuration-cache=true
|
||||
# solarxr-protocol:kotlin-codegen's generateTestSchemas isn't cache-compatible yet (submodule); degrade to a warning there instead of failing the whole build
|
||||
#org.gradle.configuration-cache.problems=warn
|
||||
org.gradle.unsafe.configuration-cache=false
|
||||
|
||||
kotlinVersion=2.3.10
|
||||
spotlessVersion=8.2.1
|
||||
shadowJarVersion=9.3.1
|
||||
buildconfigVersion=6.0.7
|
||||
wireVersion=5.3.1
|
||||
# sentry and sentry-android-core must stay on the same version
|
||||
sentryVersion=8.+
|
||||
sentryAndroidGradleVersion=6.23.0
|
||||
|
||||
# Fix gradle leaving multiple java processes running that accumulate and use multiple GBs of RAM
|
||||
# This mostly seems to affect it when running from console, and then sending a SIGINT (Ctrl + C)
|
||||
org.gradle.daemon.idletimeout=10000
|
||||
Vendored
BIN
Binary file not shown.
+2
-2
@@ -1,7 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionSha256Sum=bbaeb2fef8710818cf0e261201dab964c572f92b942812df0c3620d62a529a01
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.4-bin.zip
|
||||
distributionSha256Sum=f1771298a70f6db5a29daf62378c4e18a17fc33c9ba6b14362e0cdf40610380d
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
||||
@@ -86,7 +86,8 @@ done
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
|
||||
' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
@@ -114,7 +115,7 @@ case "$( uname )" in #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
@@ -205,7 +206,7 @@ fi
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
@@ -213,7 +214,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
|
||||
Vendored
+2
-2
@@ -70,11 +70,11 @@ goto fail
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
|
||||
File renamed without changes.
+7
-7
@@ -1,16 +1,16 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# JS/TS dependencies
|
||||
node_modules/
|
||||
.pnp
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
coverage/
|
||||
/coverage
|
||||
|
||||
# Build artifacts
|
||||
build/
|
||||
target/
|
||||
/build
|
||||
/target
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
@@ -26,8 +26,8 @@ yarn-error.log*
|
||||
*.log
|
||||
|
||||
# vite
|
||||
dist/
|
||||
stats.html
|
||||
/dist
|
||||
/stats.html
|
||||
vite.config.ts.timestamp*
|
||||
electron.vite.config.*.mjs
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export default {
|
||||
'app/**/*.{js,jsx,ts,tsx}':
|
||||
'pnpm --filter @slimevr/gui-app exec eslint --no-warn-ignored --cache --fix',
|
||||
'**/*.{ts,tsx}': () => 'tsc -p tsconfig.json --noEmit',
|
||||
'{electron,src}/**/*.{js,jsx,ts,tsx}': 'eslint --max-warnings=0 --no-warn-ignored --cache --fix',
|
||||
'**/*.{js,jsx,ts,tsx,css,scss,md,json}': 'prettier --write',
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,223 +0,0 @@
|
||||
# Please developers (not translators) don't reuse a key inside another key
|
||||
# or concat text with a translation string in the code, use the appropriate
|
||||
# features like variables and selectors in each appropriate case!
|
||||
# And also comment the string if it's something not easy to translate, so you help
|
||||
# translators on what it means
|
||||
|
||||
|
||||
## Websocket (server) status
|
||||
|
||||
|
||||
## Update notification
|
||||
|
||||
|
||||
## Tips
|
||||
|
||||
|
||||
## Units
|
||||
|
||||
|
||||
## Dropdown
|
||||
|
||||
|
||||
## Text input
|
||||
|
||||
|
||||
## File input
|
||||
|
||||
|
||||
## Window controls
|
||||
|
||||
|
||||
## Body parts
|
||||
|
||||
|
||||
## BoardType
|
||||
|
||||
|
||||
## Proportions
|
||||
|
||||
|
||||
## Tracker reset buttons
|
||||
|
||||
|
||||
## Navigation bar
|
||||
|
||||
|
||||
## Biovision hierarchy recording
|
||||
|
||||
|
||||
## Tracking pause
|
||||
|
||||
|
||||
## Widget: Developer settings
|
||||
|
||||
|
||||
## Widget: IMU Visualizer
|
||||
|
||||
|
||||
## Tracker status
|
||||
|
||||
|
||||
## Tracker status columns
|
||||
|
||||
|
||||
## Tracker rotation
|
||||
|
||||
|
||||
## Tracker information
|
||||
|
||||
|
||||
## Tracker settings
|
||||
|
||||
|
||||
## Dongle settings
|
||||
|
||||
|
||||
## Tracker part card info
|
||||
|
||||
|
||||
## Body assignment menu
|
||||
|
||||
|
||||
## Tracker assignment menu
|
||||
|
||||
|
||||
## Mounting menu
|
||||
|
||||
|
||||
## Sidebar settings
|
||||
|
||||
|
||||
## Bone routing settings
|
||||
|
||||
|
||||
## SteamVR / Monado output settings
|
||||
|
||||
|
||||
## Tracker mechanics
|
||||
|
||||
|
||||
## Keybinds Page
|
||||
|
||||
|
||||
## FK/Tracking settings
|
||||
|
||||
|
||||
## Gesture control settings (tracker tapping)
|
||||
|
||||
|
||||
## Appearance settings
|
||||
|
||||
settings-general-interface-dev_mode-description = This mode can be useful if you need in-depth data or need to interact with connected trackers on a more advanced level.
|
||||
|
||||
## Notification settings
|
||||
|
||||
|
||||
## Behavior settings
|
||||
|
||||
|
||||
## Serial settings
|
||||
|
||||
|
||||
## OSC VRChat settings
|
||||
|
||||
|
||||
## VRChat OSC status
|
||||
|
||||
|
||||
## VMC OSC settings
|
||||
|
||||
|
||||
## Common OSC settings
|
||||
|
||||
|
||||
## Advanced settings
|
||||
|
||||
|
||||
## Home Screen
|
||||
|
||||
|
||||
## Tracking Checklist
|
||||
|
||||
|
||||
## Setup/onboarding menu
|
||||
|
||||
|
||||
## Quiz
|
||||
|
||||
|
||||
## Wi-Fi setup
|
||||
|
||||
|
||||
## Install info
|
||||
|
||||
|
||||
## Setup start
|
||||
|
||||
|
||||
## Tracker connection setup
|
||||
|
||||
|
||||
## Tracker assignment setup
|
||||
|
||||
|
||||
## Tracker assignment warnings
|
||||
|
||||
|
||||
## Tracker mounting method choose
|
||||
|
||||
|
||||
## Tracker manual mounting setup
|
||||
|
||||
|
||||
## Tracker automatic mounting setup
|
||||
|
||||
|
||||
## Tracker manual proportions setupa
|
||||
|
||||
|
||||
## Tracker automatic proportions setup
|
||||
|
||||
|
||||
## User height calibration
|
||||
|
||||
|
||||
## Stay Aligned setup
|
||||
|
||||
|
||||
## Home
|
||||
|
||||
|
||||
## Trackers Still On notification
|
||||
|
||||
|
||||
## Firmware tool globals
|
||||
|
||||
|
||||
## Firmware tool Steps
|
||||
|
||||
|
||||
## firmware tool build status
|
||||
|
||||
|
||||
## Firmware update status
|
||||
|
||||
|
||||
## Dedicated Firmware Update Page
|
||||
|
||||
|
||||
## Tray Menu
|
||||
|
||||
|
||||
## First exit modal
|
||||
|
||||
|
||||
## Unknown device modal
|
||||
|
||||
|
||||
## Error collection consent modal
|
||||
|
||||
|
||||
## Tracking checklist section
|
||||
|
||||
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 22 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 28 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 149 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 92 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 151 KiB |
Binary file not shown.
@@ -1,215 +0,0 @@
|
||||
{
|
||||
"asset":{
|
||||
"generator":"Khronos glTF Blender I/O v3.5.30",
|
||||
"version":"2.0"
|
||||
},
|
||||
"scene":0,
|
||||
"scenes":[
|
||||
{
|
||||
"name":"Scene",
|
||||
"nodes":[
|
||||
3
|
||||
]
|
||||
}
|
||||
],
|
||||
"nodes":[
|
||||
{
|
||||
"mesh":0,
|
||||
"name":"Butterfly_Tracker_Enclosure_simplified_1"
|
||||
},
|
||||
{
|
||||
"mesh":1,
|
||||
"name":"Butterfly_Tracker_Enclosure_simplified_2"
|
||||
},
|
||||
{
|
||||
"children":[
|
||||
0,
|
||||
1
|
||||
],
|
||||
"name":"Butterfly_Tracker_Enclosure_simplified",
|
||||
"rotation":[
|
||||
0,
|
||||
-1,
|
||||
0,
|
||||
4.371138828673793e-08
|
||||
],
|
||||
"scale":[
|
||||
0.007811995688825846,
|
||||
0.007811995688825846,
|
||||
0.007811995688825846
|
||||
]
|
||||
},
|
||||
{
|
||||
"children":[
|
||||
2
|
||||
],
|
||||
"name":"Scene",
|
||||
"rotation":[
|
||||
0.7071066498756409,
|
||||
0,
|
||||
0.70710688829422,
|
||||
5.338508302088485e-08
|
||||
]
|
||||
}
|
||||
],
|
||||
"materials":[
|
||||
{
|
||||
"doubleSided":true,
|
||||
"name":"Material.002",
|
||||
"pbrMetallicRoughness":{
|
||||
"baseColorFactor":[
|
||||
0.6968905329704285,
|
||||
0.00031615045736543834,
|
||||
0.8000156879425049,
|
||||
1
|
||||
],
|
||||
"metallicFactor":0,
|
||||
"roughnessFactor":0.5
|
||||
}
|
||||
},
|
||||
{
|
||||
"doubleSided":true,
|
||||
"name":"Material.003",
|
||||
"pbrMetallicRoughness":{
|
||||
"baseColorFactor":[
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1
|
||||
],
|
||||
"metallicFactor":0,
|
||||
"roughnessFactor":0.5
|
||||
}
|
||||
}
|
||||
],
|
||||
"meshes":[
|
||||
{
|
||||
"name":"Mesh_0",
|
||||
"primitives":[
|
||||
{
|
||||
"attributes":{
|
||||
"POSITION":0,
|
||||
"NORMAL":1
|
||||
},
|
||||
"indices":2,
|
||||
"material":0
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name":"Mesh_1",
|
||||
"primitives":[
|
||||
{
|
||||
"attributes":{
|
||||
"POSITION":3,
|
||||
"NORMAL":4
|
||||
},
|
||||
"indices":5,
|
||||
"material":1
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"accessors":[
|
||||
{
|
||||
"bufferView":0,
|
||||
"componentType":5126,
|
||||
"count":522,
|
||||
"max":[
|
||||
17.571449279785156,
|
||||
2.8736557960510254,
|
||||
10.974367141723633
|
||||
],
|
||||
"min":[
|
||||
-17.571449279785156,
|
||||
-2.86672043800354,
|
||||
-44.02436828613281
|
||||
],
|
||||
"type":"VEC3"
|
||||
},
|
||||
{
|
||||
"bufferView":1,
|
||||
"componentType":5126,
|
||||
"count":522,
|
||||
"type":"VEC3"
|
||||
},
|
||||
{
|
||||
"bufferView":2,
|
||||
"componentType":5123,
|
||||
"count":2316,
|
||||
"type":"SCALAR"
|
||||
},
|
||||
{
|
||||
"bufferView":3,
|
||||
"componentType":5126,
|
||||
"count":198,
|
||||
"max":[
|
||||
14.886968612670898,
|
||||
2.2176363468170166,
|
||||
-8.26647663116455
|
||||
],
|
||||
"min":[
|
||||
-14.77835750579834,
|
||||
-1.4023200273513794,
|
||||
-24.783527374267578
|
||||
],
|
||||
"type":"VEC3"
|
||||
},
|
||||
{
|
||||
"bufferView":4,
|
||||
"componentType":5126,
|
||||
"count":198,
|
||||
"type":"VEC3"
|
||||
},
|
||||
{
|
||||
"bufferView":5,
|
||||
"componentType":5123,
|
||||
"count":1128,
|
||||
"type":"SCALAR"
|
||||
}
|
||||
],
|
||||
"bufferViews":[
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":6264,
|
||||
"byteOffset":0,
|
||||
"target":34962
|
||||
},
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":6264,
|
||||
"byteOffset":6264,
|
||||
"target":34962
|
||||
},
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":4632,
|
||||
"byteOffset":12528,
|
||||
"target":34963
|
||||
},
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":2376,
|
||||
"byteOffset":17160,
|
||||
"target":34962
|
||||
},
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":2376,
|
||||
"byteOffset":19536,
|
||||
"target":34962
|
||||
},
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":2256,
|
||||
"byteOffset":21912,
|
||||
"target":34963
|
||||
}
|
||||
],
|
||||
"buffers":[
|
||||
{
|
||||
"byteLength":24168,
|
||||
"uri":"data:application/octet-stream;base64,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 truncated
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
{
|
||||
"asset":{
|
||||
"generator":"Khronos glTF Blender I/O v3.5.30",
|
||||
"version":"2.0"
|
||||
},
|
||||
"scene":0,
|
||||
"scenes":[
|
||||
{
|
||||
"name":"Scene",
|
||||
"nodes":[
|
||||
0
|
||||
]
|
||||
}
|
||||
],
|
||||
"nodes":[
|
||||
{
|
||||
"mesh":0,
|
||||
"name":"RemeshedExtension",
|
||||
"rotation":[
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
7.549790126404332e-08
|
||||
]
|
||||
}
|
||||
],
|
||||
"materials":[
|
||||
{
|
||||
"doubleSided":true,
|
||||
"name":"Case.001",
|
||||
"pbrMetallicRoughness":{
|
||||
"baseColorFactor":[
|
||||
0.32314273715019226,
|
||||
0.014443378895521164,
|
||||
1,
|
||||
1
|
||||
],
|
||||
"metallicFactor":0,
|
||||
"roughnessFactor":0.5
|
||||
}
|
||||
}
|
||||
],
|
||||
"meshes":[
|
||||
{
|
||||
"name":"RemeshedExtension",
|
||||
"primitives":[
|
||||
{
|
||||
"attributes":{
|
||||
"POSITION":0,
|
||||
"TEXCOORD_0":1,
|
||||
"NORMAL":2
|
||||
},
|
||||
"indices":3,
|
||||
"material":0
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"accessors":[
|
||||
{
|
||||
"bufferView":0,
|
||||
"componentType":5126,
|
||||
"count":478,
|
||||
"max":[
|
||||
0.15670615434646606,
|
||||
0.04510210081934929,
|
||||
0.18132467567920685
|
||||
],
|
||||
"min":[
|
||||
-0.15670615434646606,
|
||||
-0.043286897242069244,
|
||||
-0.17565464973449707
|
||||
],
|
||||
"type":"VEC3"
|
||||
},
|
||||
{
|
||||
"bufferView":1,
|
||||
"componentType":5126,
|
||||
"count":478,
|
||||
"type":"VEC2"
|
||||
},
|
||||
{
|
||||
"bufferView":2,
|
||||
"componentType":5126,
|
||||
"count":478,
|
||||
"type":"VEC3"
|
||||
},
|
||||
{
|
||||
"bufferView":3,
|
||||
"componentType":5123,
|
||||
"count":1968,
|
||||
"type":"SCALAR"
|
||||
}
|
||||
],
|
||||
"bufferViews":[
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":5736,
|
||||
"byteOffset":0,
|
||||
"target":34962
|
||||
},
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":3824,
|
||||
"byteOffset":5736,
|
||||
"target":34962
|
||||
},
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":5736,
|
||||
"byteOffset":9560,
|
||||
"target":34962
|
||||
},
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":3936,
|
||||
"byteOffset":15296,
|
||||
"target":34963
|
||||
}
|
||||
],
|
||||
"buffers":[
|
||||
{
|
||||
"byteLength":19232,
|
||||
"uri":"data:application/octet-stream;base64,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 truncated
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
@@ -1,127 +0,0 @@
|
||||
{
|
||||
"asset":{
|
||||
"generator":"Khronos glTF Blender I/O v3.5.30",
|
||||
"version":"2.0"
|
||||
},
|
||||
"scene":0,
|
||||
"scenes":[
|
||||
{
|
||||
"name":"Scene",
|
||||
"nodes":[
|
||||
0
|
||||
]
|
||||
}
|
||||
],
|
||||
"nodes":[
|
||||
{
|
||||
"mesh":0,
|
||||
"name":"RemeshedCase",
|
||||
"rotation":[
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
7.549790126404332e-08
|
||||
]
|
||||
}
|
||||
],
|
||||
"materials":[
|
||||
{
|
||||
"doubleSided":true,
|
||||
"name":"Case",
|
||||
"pbrMetallicRoughness":{
|
||||
"baseColorFactor":[
|
||||
0.32314273715019226,
|
||||
0.014443378895521164,
|
||||
1,
|
||||
1
|
||||
],
|
||||
"metallicFactor":0,
|
||||
"roughnessFactor":0.5
|
||||
}
|
||||
}
|
||||
],
|
||||
"meshes":[
|
||||
{
|
||||
"name":"RemeshedCase",
|
||||
"primitives":[
|
||||
{
|
||||
"attributes":{
|
||||
"POSITION":0,
|
||||
"TEXCOORD_0":1,
|
||||
"NORMAL":2
|
||||
},
|
||||
"indices":3,
|
||||
"material":0
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"accessors":[
|
||||
{
|
||||
"bufferView":0,
|
||||
"componentType":5126,
|
||||
"count":749,
|
||||
"max":[
|
||||
0.3704195022583008,
|
||||
0.11134736984968185,
|
||||
0.23180294036865234
|
||||
],
|
||||
"min":[
|
||||
-0.3704195022583008,
|
||||
-0.12710295617580414,
|
||||
-0.25865787267684937
|
||||
],
|
||||
"type":"VEC3"
|
||||
},
|
||||
{
|
||||
"bufferView":1,
|
||||
"componentType":5126,
|
||||
"count":749,
|
||||
"type":"VEC2"
|
||||
},
|
||||
{
|
||||
"bufferView":2,
|
||||
"componentType":5126,
|
||||
"count":749,
|
||||
"type":"VEC3"
|
||||
},
|
||||
{
|
||||
"bufferView":3,
|
||||
"componentType":5123,
|
||||
"count":2670,
|
||||
"type":"SCALAR"
|
||||
}
|
||||
],
|
||||
"bufferViews":[
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":8988,
|
||||
"byteOffset":0,
|
||||
"target":34962
|
||||
},
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":5992,
|
||||
"byteOffset":8988,
|
||||
"target":34962
|
||||
},
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":8988,
|
||||
"byteOffset":14980,
|
||||
"target":34962
|
||||
},
|
||||
{
|
||||
"buffer":0,
|
||||
"byteLength":5340,
|
||||
"byteOffset":23968,
|
||||
"target":34963
|
||||
}
|
||||
],
|
||||
"buffers":[
|
||||
{
|
||||
"byteLength":29308,
|
||||
"uri":"data:application/octet-stream;base64,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 truncated
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,66 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { Navigate, Outlet, useLocation } from 'react-router-dom';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { useErrorReporting } from '@/hooks/error-reporting';
|
||||
import { settingsDefaultsAtom } from '@/store/app-store';
|
||||
import { ConnectionLost } from './onboarding/pages/ConnectionLost';
|
||||
import { ErrorReportingConsentPage } from './ErrorReportingConsent';
|
||||
|
||||
export const CONNECTING_PATH = '/connecting';
|
||||
export const ERROR_REPORTING_CONSENT_PATH = '/error-reporting-consent';
|
||||
|
||||
const STATUS_PATHS = [CONNECTING_PATH, ERROR_REPORTING_CONSENT_PATH];
|
||||
|
||||
interface ReturnTo {
|
||||
path: string;
|
||||
state: unknown;
|
||||
}
|
||||
|
||||
function StatusPage({ path }: { path: string }) {
|
||||
return path === ERROR_REPORTING_CONSENT_PATH ? (
|
||||
<ErrorReportingConsentPage />
|
||||
) : (
|
||||
<ConnectionLost />
|
||||
);
|
||||
}
|
||||
|
||||
export function AppStatusGate() {
|
||||
const { isConnected } = useWebsocketAPI();
|
||||
const { needsAnswer } = useErrorReporting();
|
||||
const settingsDefaults = useAtomValue(settingsDefaultsAtom);
|
||||
const location = useLocation();
|
||||
const [appShown, setAppShown] = useState(false);
|
||||
|
||||
const statusPath = needsAnswer
|
||||
? ERROR_REPORTING_CONSENT_PATH
|
||||
: !isConnected || !settingsDefaults
|
||||
? CONNECTING_PATH
|
||||
: null;
|
||||
const onStatusPath = STATUS_PATHS.includes(location.pathname);
|
||||
|
||||
useEffect(() => {
|
||||
if (!statusPath && !onStatusPath) setAppShown(true);
|
||||
}, [statusPath, onStatusPath]);
|
||||
|
||||
const returnTo: ReturnTo = onStatusPath
|
||||
? (location.state?.returnTo ?? { path: '/', state: null })
|
||||
: { path: location.pathname + location.search, state: location.state };
|
||||
|
||||
if (!appShown && statusPath && location.pathname !== statusPath) {
|
||||
return <Navigate to={statusPath} replace state={{ returnTo }} />;
|
||||
}
|
||||
if ((appShown || !statusPath) && onStatusPath) {
|
||||
return <Navigate to={returnTo.path} replace state={returnTo.state} />;
|
||||
}
|
||||
|
||||
const covering = appShown ? statusPath : null;
|
||||
return (
|
||||
<>
|
||||
{covering && <StatusPage path={covering} />}
|
||||
<div className={covering ? 'hidden' : 'contents'}>
|
||||
<Outlet />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { Localized } from '@fluent/react';
|
||||
import { Button } from './commons/Button';
|
||||
import { LoaderIcon, SlimeState } from './commons/icon/LoaderIcon';
|
||||
|
||||
export function CrashScreen({ eventId }: { eventId: string }) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full w-full flex-col gap-4 p-4 bg-background-80 text-background-10">
|
||||
<LoaderIcon slimeState={SlimeState.SAD} size={200} />
|
||||
<div className="max-w-xl flex flex-col gap-3">
|
||||
<Localized id="crash_screen-title">
|
||||
<h1 className="text-main-title" />
|
||||
</Localized>
|
||||
<Localized id="crash_screen-description">
|
||||
<p className="text-standard" />
|
||||
</Localized>
|
||||
{eventId && (
|
||||
<Localized id="crash_screen-event_id" vars={{ id: eventId }}>
|
||||
<p className="text-standard font-mono" />
|
||||
</Localized>
|
||||
)}
|
||||
<div className="flex flex-row gap-2">
|
||||
{eventId && (
|
||||
<Button
|
||||
variant="secondary"
|
||||
id="crash_screen-copy"
|
||||
onClick={() => navigator.clipboard.writeText(eventId)}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
id="crash_screen-reload"
|
||||
onClick={() => window.location.reload()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import { ErrorReportingConsent } from 'solarxr-protocol';
|
||||
import { Typography } from './commons/Typography';
|
||||
import { Button } from './commons/Button';
|
||||
import { EmptyLayout } from './EmptyLayout';
|
||||
import { useErrorReporting } from '@/hooks/error-reporting';
|
||||
import { ErrorReportingDetails } from './ErrorReportingDetails';
|
||||
import { LoaderIcon, SlimeState } from './commons/icon/LoaderIcon';
|
||||
|
||||
export function ErrorReportingConsentPage() {
|
||||
const { answer } = useErrorReporting();
|
||||
|
||||
return (
|
||||
<EmptyLayout>
|
||||
<div className="flex w-full h-full justify-center items-center overflow-y-auto p-4">
|
||||
<div className="flex flex-col items-center gap-4 w-full max-w-2xl">
|
||||
<LoaderIcon slimeState={SlimeState.CURIOUS} size={200} />
|
||||
<div className="flex flex-col items-center text-center">
|
||||
<Typography
|
||||
variant="main-title"
|
||||
id="error_collection_modal-title"
|
||||
/>
|
||||
<Typography id="error_collection_modal-subtitle" />
|
||||
</div>
|
||||
<ErrorReportingDetails />
|
||||
<Typography id="error_collection_modal-change_later" />
|
||||
<div className="flex w-full flex-col-reverse xs:flex-row gap-3 xs:justify-between">
|
||||
<Button
|
||||
variant="tertiary"
|
||||
onClick={() => answer(ErrorReportingConsent.DENIED)}
|
||||
id="error_collection_modal-cancel"
|
||||
/>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => answer(ErrorReportingConsent.ALLOWED)}
|
||||
id="error_collection_modal-confirm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</EmptyLayout>
|
||||
);
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { Localized } from '@fluent/react';
|
||||
import { CheckIcon } from './commons/icon/CheckIcon';
|
||||
import { Typography } from './commons/Typography';
|
||||
|
||||
const COLLECTED_DATA = [
|
||||
'errors',
|
||||
'system',
|
||||
'recordings',
|
||||
'usage',
|
||||
'proportions',
|
||||
] as const;
|
||||
|
||||
export function ErrorReportingDetails({
|
||||
className = 'bg-background-70',
|
||||
}: {
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={classNames('flex flex-col gap-3 rounded-lg p-4', className)}
|
||||
>
|
||||
<Localized
|
||||
id="settings-interface-behavior-error_tracking-no_personal_data"
|
||||
elems={{ b: <b /> }}
|
||||
>
|
||||
<Typography />
|
||||
</Localized>
|
||||
<Typography
|
||||
bold
|
||||
id="settings-interface-behavior-error_tracking-collects"
|
||||
/>
|
||||
<ul className="gap-x-6 gap-y-2">
|
||||
{COLLECTED_DATA.map((item) => (
|
||||
<li key={item} className="flex items-start gap-2">
|
||||
<div className="mt-1 shrink-0 fill-accent-background-10">
|
||||
<CheckIcon size={14} />
|
||||
</div>
|
||||
<Typography
|
||||
id={`settings-interface-behavior-error_tracking-collects-${item}`}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<Typography id="settings-interface-behavior-error_tracking-footer" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode, useEffect, useRef } from 'react';
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import { ProfileKind } from 'solarxr-protocol';
|
||||
import { ArrowDownIcon } from './commons/icon/ArrowIcons';
|
||||
import { CheckIcon } from './commons/icon/CheckIcon';
|
||||
import { HumanIcon } from './commons/icon/HumanIcon';
|
||||
import { TuneIcon } from './commons/icon/TuneIcon';
|
||||
import { PopoverMenu, PopoverMenuItem } from './commons/PopoverMenu';
|
||||
import { Tooltip } from './commons/Tooltip';
|
||||
import { Typography } from './commons/Typography';
|
||||
import { useBreakpoint } from '@/hooks/breakpoint';
|
||||
import {
|
||||
ProfileNames,
|
||||
Profiles,
|
||||
useProfileOperations,
|
||||
useProfiles,
|
||||
} from '@/hooks/profiles';
|
||||
|
||||
function ProfileSection({
|
||||
titleId,
|
||||
icon,
|
||||
profiles,
|
||||
open,
|
||||
onSelect,
|
||||
}: {
|
||||
titleId: string;
|
||||
icon: ReactNode;
|
||||
profiles: ProfileNames;
|
||||
open: boolean;
|
||||
onSelect: (name: string) => void;
|
||||
}) {
|
||||
const listRef = useRef<HTMLUListElement>(null);
|
||||
|
||||
// Long lists open scrolled to the active profile
|
||||
useEffect(() => {
|
||||
const list = listRef.current;
|
||||
if (!open || !list) return;
|
||||
const active = list.querySelector<HTMLElement>('[aria-current]');
|
||||
if (!active) return;
|
||||
list.scrollTop =
|
||||
active.offsetTop - list.clientHeight / 2 + active.offsetHeight / 2;
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col min-w-0 py-1">
|
||||
<div className="flex items-center gap-2 px-4 py-2 fill-background-10">
|
||||
{icon}
|
||||
<Typography bold id={titleId} />
|
||||
</div>
|
||||
<ul
|
||||
ref={listRef}
|
||||
className="relative flex flex-col min-w-0 max-h-[30vh] overflow-y-auto overscroll-contain dropdown-scroll"
|
||||
>
|
||||
{profiles.names.map((name) => {
|
||||
const active = name === profiles.active;
|
||||
return (
|
||||
<li key={name}>
|
||||
<PopoverMenuItem current={active} onClick={() => onSelect(name)}>
|
||||
<span className="w-3 flex justify-center fill-accent-background-10 shrink-0">
|
||||
{active && <CheckIcon size={10} />}
|
||||
</span>
|
||||
<span className="min-w-0 truncate">
|
||||
<Typography
|
||||
tag="span"
|
||||
whitespace="whitespace-nowrap"
|
||||
bold={active}
|
||||
>
|
||||
{name}
|
||||
</Typography>
|
||||
</span>
|
||||
</PopoverMenuItem>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProfileMenu({
|
||||
profiles,
|
||||
open,
|
||||
onClose,
|
||||
}: {
|
||||
profiles: Profiles;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { switchProfile } = useProfileOperations();
|
||||
|
||||
const select = (kind: ProfileKind, active: string, name: string) => {
|
||||
onClose();
|
||||
if (name !== active) switchProfile(kind, name);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full min-w-0 divide-y divide-background-50">
|
||||
<ProfileSection
|
||||
titleId="titlebar-profiles-settings"
|
||||
icon={<TuneIcon size={14} />}
|
||||
profiles={profiles.settings}
|
||||
open={open}
|
||||
onSelect={(name) =>
|
||||
select(ProfileKind.SETTINGS, profiles.settings.active, name)
|
||||
}
|
||||
/>
|
||||
<ProfileSection
|
||||
titleId="titlebar-profiles-user"
|
||||
icon={<HumanIcon width={12} />}
|
||||
profiles={profiles.user}
|
||||
open={open}
|
||||
onSelect={(name) =>
|
||||
select(ProfileKind.USER, profiles.user.active, name)
|
||||
}
|
||||
/>
|
||||
<PopoverMenuItem to="/settings/profiles" onClick={onClose}>
|
||||
<Typography id="titlebar-profiles-manage" />
|
||||
</PopoverMenuItem>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProfileQuickSwitch() {
|
||||
const { l10n } = useLocalization();
|
||||
const { isMobile } = useBreakpoint('mobile');
|
||||
const profiles = useProfiles();
|
||||
|
||||
if (!profiles) return null;
|
||||
|
||||
return (
|
||||
<PopoverMenu
|
||||
anchorClassName="min-w-0"
|
||||
drawerTitle={
|
||||
<Typography variant="section-title" id="titlebar-profiles" />
|
||||
}
|
||||
trigger={(triggerProps, open) => (
|
||||
<Tooltip
|
||||
preferedDirection="bottom"
|
||||
disabled={open}
|
||||
content={<Typography id="titlebar-profiles-tooltip" />}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
{...triggerProps}
|
||||
aria-label={l10n.getString('titlebar-profiles')}
|
||||
className={classNames(
|
||||
'flex items-center gap-2 h-7 pl-2.5 pr-2 rounded-lg min-w-0 shrink',
|
||||
'text-background-10 fill-background-10 hover:bg-background-50',
|
||||
open ? 'bg-background-50' : 'bg-background-60'
|
||||
)}
|
||||
>
|
||||
<TuneIcon size={14} />
|
||||
{!isMobile && (
|
||||
<>
|
||||
<span className="min-w-0 max-w-[140px] truncate">
|
||||
<Typography tag="span" whitespace="whitespace-nowrap">
|
||||
{profiles.settings.active}
|
||||
</Typography>
|
||||
</span>
|
||||
<span className="w-px h-3.5 bg-background-40 shrink-0" />
|
||||
<span className="flex shrink-0">
|
||||
<HumanIcon width={12} />
|
||||
</span>
|
||||
<span className="min-w-0 max-w-[140px] truncate">
|
||||
<Typography tag="span" whitespace="whitespace-nowrap">
|
||||
{profiles.user.active}
|
||||
</Typography>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<span
|
||||
className={classNames(
|
||||
'shrink-0 transition-transform',
|
||||
open && 'rotate-180'
|
||||
)}
|
||||
>
|
||||
<ArrowDownIcon size={12} />
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
>
|
||||
{({ open, close }) => (
|
||||
<ProfileMenu profiles={profiles} open={open} onClose={close} />
|
||||
)}
|
||||
</PopoverMenu>
|
||||
);
|
||||
}
|
||||
@@ -1,281 +0,0 @@
|
||||
import { Typography } from './commons/Typography';
|
||||
import classNames from 'classnames';
|
||||
import { MountingMethod, ResetType } from 'solarxr-protocol';
|
||||
import {
|
||||
BODY_PARTS_GROUPS,
|
||||
MountingResetGroup,
|
||||
ResetBtnStatus,
|
||||
useReset,
|
||||
UseResetOptions,
|
||||
} from '@/hooks/reset';
|
||||
import { Tooltip } from './commons/Tooltip';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { assignedTrackersAtom } from '@/store/app-store';
|
||||
import { useBreakpoint } from '@/hooks/breakpoint';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { ResetButtonIcon } from './home/ResetButton';
|
||||
import { MountingMethodModal } from './mounting/MountingMethodModal';
|
||||
import { useResetsSettings } from '@/hooks/resets-settings';
|
||||
import { IconButton } from './commons/IconButton';
|
||||
import { GearIcon } from './commons/icon/GearIcon';
|
||||
|
||||
const MAINBUTTON_CLASSES = ({ disabled }: { disabled: boolean }) =>
|
||||
classNames(
|
||||
'relative overflow-clip',
|
||||
'flex h-full items-center justify-center gap-2 px-4 bg-background-60 rounded-lg fill-background-10 aspect-square md:aspect-auto',
|
||||
{
|
||||
'cursor-pointer hover:bg-background-50 bg-background-60': !disabled,
|
||||
'cursor-not-allowed bg-background-70 brightness-75': disabled,
|
||||
}
|
||||
);
|
||||
|
||||
function ButtonProgress({
|
||||
progress,
|
||||
status,
|
||||
}: {
|
||||
progress: number;
|
||||
status: ResetBtnStatus;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'absolute top-0 left-0 w-0 h-full bg-accent-background-20 opacity-50'
|
||||
)}
|
||||
style={{
|
||||
width: `${progress * 100}%`,
|
||||
transition:
|
||||
status === 'counting'
|
||||
? 'width 0.3s cubic-bezier(0.68, -0.8, 0.32, 1.8)'
|
||||
: 'width 1s linear',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function BasicResetButton({
|
||||
customName,
|
||||
...options
|
||||
}: UseResetOptions & { customName?: string }) {
|
||||
const { isMd } = useBreakpoint('md');
|
||||
const {
|
||||
triggerReset,
|
||||
status,
|
||||
name: resetName,
|
||||
timer,
|
||||
progress: resetProress,
|
||||
disabled,
|
||||
duration,
|
||||
error,
|
||||
} = useReset(options);
|
||||
const { resetsSettings } = useResetsSettings();
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
|
||||
const progress = status === 'counting' ? resetProress / duration : 0;
|
||||
|
||||
const needsMethod =
|
||||
options.type === ResetType.MOUNTING &&
|
||||
options.group === 'default' &&
|
||||
resetsSettings?.mountingMethod === MountingMethod.UNKNOWN;
|
||||
|
||||
const name = needsMethod
|
||||
? 'toolbar-mounting_calibration-pick_method'
|
||||
: customName || resetName;
|
||||
|
||||
const skiReset =
|
||||
options.type === ResetType.MOUNTING &&
|
||||
options.group === 'default' &&
|
||||
resetsSettings?.mountingMethod === MountingMethod.POSE;
|
||||
|
||||
const onClick = () => {
|
||||
if (disabled) return;
|
||||
if (needsMethod) {
|
||||
setPickerOpen(true);
|
||||
return;
|
||||
}
|
||||
triggerReset(resetsSettings?.mountingMethod);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Tooltip
|
||||
disabled={!error && isMd}
|
||||
content={
|
||||
error ? (
|
||||
<Typography
|
||||
id={error}
|
||||
textAlign="text-center"
|
||||
color="text-status-critical"
|
||||
/>
|
||||
) : (
|
||||
<Typography textAlign="text-center" id={name} />
|
||||
)
|
||||
}
|
||||
spacing={5}
|
||||
preferedDirection={error ? 'bottom' : 'top'}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
className={classNames(
|
||||
MAINBUTTON_CLASSES({ disabled }),
|
||||
'rounded-lg',
|
||||
'absolute'
|
||||
)}
|
||||
style={{
|
||||
animationIterationCount: 1,
|
||||
}}
|
||||
onClick={onClick}
|
||||
>
|
||||
<div
|
||||
className={classNames({
|
||||
'animate-spin-ccw': !skiReset && status === 'finished',
|
||||
'animate-skiing': skiReset && status === 'finished',
|
||||
'opacity-0': status === 'counting',
|
||||
})}
|
||||
style={{
|
||||
animationIterationCount: 1,
|
||||
}}
|
||||
>
|
||||
<ResetButtonIcon {...options} />
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={classNames('hidden md:block relative', {
|
||||
'opacity-0': status === 'counting',
|
||||
})}
|
||||
>
|
||||
<Typography
|
||||
variant="section-title"
|
||||
textAlign="text-center"
|
||||
id={name}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ButtonProgress progress={progress} status={status} />
|
||||
<div
|
||||
className={classNames(
|
||||
{
|
||||
'opacity-0': status !== 'counting',
|
||||
'animate-timer-tick': status === 'counting',
|
||||
},
|
||||
'absolute top-0 h-full flex items-center justify-center'
|
||||
)}
|
||||
>
|
||||
<Typography variant="main-title" textAlign="text-center">
|
||||
{timer}
|
||||
</Typography>
|
||||
</div>
|
||||
</button>
|
||||
</Tooltip>
|
||||
{needsMethod && (
|
||||
<MountingMethodModal
|
||||
isOpen={pickerOpen}
|
||||
onClose={() => setPickerOpen(false)}
|
||||
triggerReset={triggerReset}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function Toolbar() {
|
||||
const assignedTrackers = useAtomValue(assignedTrackersAtom);
|
||||
const { resetsSettings } = useResetsSettings();
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
|
||||
const splitMounting = resetsSettings?.mountingMethod === MountingMethod.POSE;
|
||||
|
||||
const { visibleGroups, groupVisibility } = useMemo(() => {
|
||||
const groupVisibility = Object.keys(BODY_PARTS_GROUPS)
|
||||
.filter((k) => ['fingers', 'toes'].includes(k))
|
||||
.reduce(
|
||||
(curr, key) => {
|
||||
const group = key as MountingResetGroup;
|
||||
curr[group] = assignedTrackers.some(
|
||||
({ tracker }) =>
|
||||
tracker.info?.bodyPart &&
|
||||
BODY_PARTS_GROUPS[group].includes(tracker.info?.bodyPart)
|
||||
);
|
||||
|
||||
return curr;
|
||||
},
|
||||
{} as Record<MountingResetGroup, boolean>
|
||||
);
|
||||
|
||||
return {
|
||||
groupVisibility,
|
||||
visibleGroups: Object.values(groupVisibility).filter((v) => v).length,
|
||||
};
|
||||
}, [assignedTrackers]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex mobile:py-2 flex-col items-center bg-background-70 rounded-t-lg h-[var(--toolbar-h)] mr-2 xs:mt-2 mobile:mr-0">
|
||||
<div className="px-3 py-3 w-full flex gap-4 justify-center md:justify-start">
|
||||
<div className="flex-col flex gap-1 md:w-[60%]">
|
||||
<Typography variant="section-title" id="toolbar-drift_reset" />
|
||||
<div className="gap-2 md:h-[72px] h-[62px] w-full grid-cols-2 grid">
|
||||
<BasicResetButton type={ResetType.FULL} />
|
||||
<BasicResetButton type={ResetType.YAW} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-col flex gap-1 md:flex-grow">
|
||||
<div className="flex justify-between gap-2">
|
||||
<Typography
|
||||
variant="section-title"
|
||||
id="toolbar-mounting_calibration"
|
||||
/>
|
||||
<IconButton
|
||||
labelId="toolbar-mounting_calibration-pick_method"
|
||||
className="fill-background-30 hover:fill-background-20 cursor-pointer"
|
||||
onClick={() => setPickerOpen(true)}
|
||||
>
|
||||
<GearIcon size={18}></GearIcon>
|
||||
</IconButton>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="gap-2 md:h-[72px] h-[62px] w-full md:grid flex"
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${splitMounting ? 2 + visibleGroups : 1}, 1fr)`,
|
||||
}}
|
||||
>
|
||||
<BasicResetButton
|
||||
type={ResetType.MOUNTING}
|
||||
group={'default'}
|
||||
customName="toolbar-mounting_calibration-default"
|
||||
/>
|
||||
{splitMounting && (
|
||||
<>
|
||||
<BasicResetButton
|
||||
type={ResetType.MOUNTING}
|
||||
group={'feet'}
|
||||
customName="toolbar-mounting_calibration-feet"
|
||||
/>
|
||||
{groupVisibility['toes'] && (
|
||||
<BasicResetButton
|
||||
type={ResetType.MOUNTING}
|
||||
group={'toes'}
|
||||
customName="toolbar-mounting_calibration-toes"
|
||||
/>
|
||||
)}
|
||||
{groupVisibility['fingers'] && (
|
||||
<BasicResetButton
|
||||
type={ResetType.MOUNTING}
|
||||
group={'fingers'}
|
||||
customName="toolbar-mounting_calibration-fingers"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<MountingMethodModal
|
||||
isOpen={pickerOpen}
|
||||
onClose={() => setPickerOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode } from 'react';
|
||||
import ReactModal from 'react-modal';
|
||||
import { collectFocusables, isFocusable } from '@/utils/focus-nav';
|
||||
|
||||
/**
|
||||
* `react-modal` parks focus on its own `tabindex="-1"` content node, which is
|
||||
* not something a user can act on. Runs a frame late to land after react-modal's
|
||||
* own focus call, and leaves an explicit `autoFocus` in the content alone.
|
||||
* A `[data-nav-entry]` takes the priority
|
||||
*
|
||||
* FIXME: replace react-modal; its focus handling keeps forcing workarounds.
|
||||
*/
|
||||
function focusFirstControl(contentEl: HTMLDivElement) {
|
||||
requestAnimationFrame(() => {
|
||||
const active = document.activeElement;
|
||||
if (active && active !== contentEl && contentEl.contains(active)) return;
|
||||
|
||||
const entry = contentEl.querySelector<HTMLElement>('[data-nav-entry]');
|
||||
const target =
|
||||
(entry && (isFocusable(entry) ? entry : collectFocusables(entry)[0])) ||
|
||||
collectFocusables(contentEl)[0];
|
||||
target?.focus();
|
||||
});
|
||||
}
|
||||
|
||||
export function BaseModal({
|
||||
children,
|
||||
important = false,
|
||||
closeable = true,
|
||||
...props
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
children: ReactNode;
|
||||
appendClasses?: string;
|
||||
important?: boolean;
|
||||
closeable?: boolean;
|
||||
} & ReactModal.Props) {
|
||||
return (
|
||||
<ReactModal
|
||||
{...props}
|
||||
onAfterOpen={(obj) => {
|
||||
props.onAfterOpen?.(obj);
|
||||
if (obj?.contentEl) focusFirstControl(obj.contentEl);
|
||||
}}
|
||||
shouldCloseOnOverlayClick={closeable}
|
||||
shouldCloseOnEsc={closeable}
|
||||
overlayClassName={
|
||||
props.overlayClassName ||
|
||||
classNames(
|
||||
'fixed top-0 right-0 left-0 bottom-0 flex flex-col justify-center',
|
||||
'items-center w-full h-full bg-background-90 bg-opacity-60',
|
||||
// Above the app chrome (top bar, settings page picker, floating buttons) at z-50
|
||||
important ? 'z-[70]' : 'z-[60]'
|
||||
)
|
||||
}
|
||||
className={
|
||||
props.className ||
|
||||
classNames(
|
||||
'items-center focus:ring-transparent focus:ring-offset-transparent',
|
||||
'focus:outline-transparent outline-none bg-background-60 p-6 rounded-lg m-2',
|
||||
'text-background-10 text-standard',
|
||||
props.appendClasses
|
||||
)
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</ReactModal>
|
||||
);
|
||||
}
|
||||
@@ -1,476 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import {
|
||||
FocusEvent,
|
||||
HTMLAttributes,
|
||||
PointerEvent,
|
||||
ReactNode,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { BodyPart } from 'solarxr-protocol';
|
||||
import { useBreakpoint } from '@/hooks/breakpoint';
|
||||
|
||||
const DOT_HIT_PADDING = 12;
|
||||
|
||||
export interface BodySideNames {
|
||||
left: Set<string>;
|
||||
right: Set<string>;
|
||||
}
|
||||
|
||||
const bodyPartFromName = (name: string): BodyPart | null => {
|
||||
const part = (BodyPart as unknown as Record<string, number | undefined>)[
|
||||
name
|
||||
];
|
||||
return typeof part === 'number' ? part : null;
|
||||
};
|
||||
|
||||
const boxOf = (el: HTMLElement, offset: { left: number; top: number }) => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
return {
|
||||
left: rect.left - offset.left,
|
||||
top: rect.top - offset.top,
|
||||
right: rect.right - offset.left,
|
||||
bottom: rect.bottom - offset.top,
|
||||
};
|
||||
};
|
||||
|
||||
const geometry = (
|
||||
slot: { left: number; top: number; width: number; height: number },
|
||||
control: HTMLElement,
|
||||
group: HTMLElement,
|
||||
offset: { left: number; top: number }
|
||||
) => {
|
||||
const slotX = slot.left + slot.width / 2;
|
||||
const slotY = slot.top + slot.height / 2;
|
||||
const { left, top, right, bottom } = boxOf(group, offset);
|
||||
const row = boxOf(control, offset);
|
||||
const rowY = (row.top + row.bottom) / 2;
|
||||
|
||||
const cap = group.dataset.connectorEdge === 'cap';
|
||||
|
||||
return {
|
||||
x: cap ? (left + right) / 2 : slotX > right ? right : left,
|
||||
y: cap
|
||||
? slotY > bottom
|
||||
? bottom
|
||||
: top
|
||||
: Math.min(Math.max(rowY, top), bottom),
|
||||
dx: cap ? 0 : slotX > right ? 1 : -1,
|
||||
dy: cap ? (slotY > bottom ? 1 : -1) : 0,
|
||||
gap: cap
|
||||
? Math.max(top - slotY, slotY - bottom, 0)
|
||||
: Math.max(left - slotX, slotX - right, 0),
|
||||
};
|
||||
};
|
||||
|
||||
const readCssVarColor = (varName: string, fallback: string) => {
|
||||
if (typeof window === 'undefined') return fallback;
|
||||
const raw = getComputedStyle(document.documentElement)
|
||||
.getPropertyValue(varName)
|
||||
.trim();
|
||||
return raw ? `rgb(${raw})` : fallback;
|
||||
};
|
||||
|
||||
export interface BodyInteractionsProps {
|
||||
leftControls?: ReactNode;
|
||||
rightControls?: ReactNode;
|
||||
topControls?: ReactNode;
|
||||
bottomControls?: ReactNode;
|
||||
dotsSize?: number;
|
||||
assignedRoles: BodyPart[];
|
||||
onSelectRole: (role: BodyPart) => void;
|
||||
highlightedRoles: BodyPart[];
|
||||
dotClass?: (part: BodyPart) => string | undefined;
|
||||
dotContent?: (part: BodyPart) => ReactNode;
|
||||
dotProps?: (part: BodyPart) => HTMLAttributes<HTMLDivElement>;
|
||||
activeParts?: BodyPart[];
|
||||
figure: ReactNode;
|
||||
sideNames: BodySideNames;
|
||||
}
|
||||
|
||||
export function BodyInteractions({
|
||||
leftControls,
|
||||
rightControls,
|
||||
topControls,
|
||||
bottomControls,
|
||||
highlightedRoles,
|
||||
assignedRoles,
|
||||
dotsSize = 15,
|
||||
onSelectRole,
|
||||
dotClass,
|
||||
dotContent,
|
||||
dotProps,
|
||||
activeParts = [],
|
||||
figure,
|
||||
sideNames,
|
||||
}: BodyInteractionsProps) {
|
||||
const { isMobile } = useBreakpoint('mobile');
|
||||
const { left: leftPartNames, right: rightPartNames } = sideNames;
|
||||
|
||||
const [hoveredControl, setHoveredControl] = useState<string | null>(null);
|
||||
|
||||
const personRef = useRef<HTMLDivElement | null>(null);
|
||||
const leftContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
const rightContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
const topContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
const bottomContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
const updateSlotsRef = useRef<() => void>(() => {});
|
||||
const mutationObserverRef = useRef<MutationObserver>(
|
||||
new MutationObserver(() => updateSlotsRef.current())
|
||||
);
|
||||
const resizeObserverRef = useRef<ResizeObserver>(
|
||||
new ResizeObserver(() => updateSlotsRef.current())
|
||||
);
|
||||
const canvasRefRef = useRef<HTMLCanvasElement | null>(null);
|
||||
const [slotsButtonsPos, setSlotsButtonPos] = useState<
|
||||
{
|
||||
id: string;
|
||||
part: BodyPart | null;
|
||||
left: number;
|
||||
top: number;
|
||||
height: number;
|
||||
width: number;
|
||||
hidden: boolean;
|
||||
buttonOffset: {
|
||||
left: number;
|
||||
top: number;
|
||||
};
|
||||
}[]
|
||||
>([]);
|
||||
|
||||
const getSlotsPos = () => {
|
||||
return (
|
||||
(personRef.current && [
|
||||
...(personRef.current.querySelectorAll('.body-part-circle') as any),
|
||||
]) ||
|
||||
[]
|
||||
);
|
||||
};
|
||||
|
||||
const getControlsPos = () => {
|
||||
const pos = (container: HTMLDivElement) =>
|
||||
[...(container.querySelectorAll('.control') as any)].filter(
|
||||
({ id }) => !!id
|
||||
);
|
||||
|
||||
const left =
|
||||
(leftContainerRef.current && pos(leftContainerRef.current)) || [];
|
||||
const right =
|
||||
(rightContainerRef.current && pos(rightContainerRef.current)) || [];
|
||||
const top = (topContainerRef.current && pos(topContainerRef.current)) || [];
|
||||
const bottom =
|
||||
(bottomContainerRef.current && pos(bottomContainerRef.current)) || [];
|
||||
return [...left, ...right, ...top, ...bottom];
|
||||
};
|
||||
|
||||
const getOffset = (el: HTMLDivElement, offset = { left: 0, top: 0 }) => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
return {
|
||||
left: rect.left - (offset.left || 0),
|
||||
top: rect.top - (offset.top || 0),
|
||||
width: rect.width || el.offsetWidth,
|
||||
height: rect.height || el.offsetHeight,
|
||||
};
|
||||
};
|
||||
|
||||
const updateSlots = () => {
|
||||
if (
|
||||
!(
|
||||
personRef.current &&
|
||||
canvasRefRef.current &&
|
||||
rightContainerRef.current &&
|
||||
leftContainerRef.current
|
||||
)
|
||||
)
|
||||
return;
|
||||
const ctx = canvasRefRef.current.getContext('2d');
|
||||
if (!ctx) return;
|
||||
const slotsPos = getSlotsPos();
|
||||
const controlsPos = getControlsPos();
|
||||
|
||||
canvasRefRef.current.width = canvasRefRef.current.clientWidth;
|
||||
canvasRefRef.current.height = canvasRefRef.current.clientHeight;
|
||||
|
||||
ctx.strokeStyle = '#608AAB';
|
||||
ctx.lineWidth = 2;
|
||||
|
||||
const canvasBox = canvasRefRef.current.getBoundingClientRect();
|
||||
const personBox = personRef.current.getBoundingClientRect();
|
||||
|
||||
const controlsPosIds = controlsPos.map(({ id: cid }) => cid);
|
||||
const slots = slotsPos.map((slot: HTMLDivElement) => {
|
||||
const slotPosition = getOffset(slot, canvasBox);
|
||||
return {
|
||||
...slotPosition,
|
||||
id: slot.id,
|
||||
part: bodyPartFromName(slot.id),
|
||||
hidden: !controlsPosIds.includes(slot.id),
|
||||
buttonOffset: {
|
||||
left: canvasBox.left - personBox.left,
|
||||
top: canvasBox.top - personBox.top,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const whiteColor = readCssVarColor('--background-20', '#FFFFFF');
|
||||
const ASSIGN_RIGHT = readCssVarColor('--assign-right', '#FFFFFF');
|
||||
const ASSIGN_LEFT = readCssVarColor('--assign-left', '#FFFFFF');
|
||||
const LINE_BREAK_WIDTH = isMobile ? 20 : 40;
|
||||
|
||||
slots.forEach((slot) => {
|
||||
const controls = controlsPos.filter(
|
||||
({ id, dataset }) => id === slot.id && dataset.connector !== 'off'
|
||||
);
|
||||
const isAssigned = slot.part != null && assignedRoles.includes(slot.part);
|
||||
const isActive = slot.part != null && activeParts.includes(slot.part);
|
||||
|
||||
ctx.lineWidth = slot.id === hoveredControl || isActive ? 4 : 2;
|
||||
ctx.strokeStyle =
|
||||
isAssigned || isActive
|
||||
? leftPartNames.has(slot.id)
|
||||
? ASSIGN_LEFT
|
||||
: rightPartNames.has(slot.id)
|
||||
? ASSIGN_RIGHT
|
||||
: whiteColor
|
||||
: '#204A6B';
|
||||
|
||||
const slotX = slot.left + slot.width / 2;
|
||||
const slotY = slot.top + slot.height / 2;
|
||||
|
||||
controls.forEach((control) => {
|
||||
const group = control.closest('[data-connector-group]');
|
||||
const controlPosition = getOffset(group ?? control, canvasBox);
|
||||
|
||||
if (group) {
|
||||
const { x, y, dx, dy, gap } = geometry(
|
||||
slot,
|
||||
control,
|
||||
group,
|
||||
canvasBox
|
||||
);
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, y);
|
||||
if (gap > LINE_BREAK_WIDTH * 2)
|
||||
ctx.lineTo(x + dx * LINE_BREAK_WIDTH, y + dy * LINE_BREAK_WIDTH);
|
||||
ctx.lineTo(slotX, slotY);
|
||||
ctx.stroke();
|
||||
return;
|
||||
}
|
||||
|
||||
const offsetX =
|
||||
controlPosition.left < slot.left ? controlPosition.width : 0;
|
||||
|
||||
const constolLeft = controlPosition.left + offsetX;
|
||||
const leftOffsetX =
|
||||
LINE_BREAK_WIDTH * (controlPosition.left < slot.left ? -1 : 1);
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(
|
||||
constolLeft,
|
||||
controlPosition.top + controlPosition.height / 2
|
||||
);
|
||||
ctx.lineTo(
|
||||
constolLeft - leftOffsetX,
|
||||
controlPosition.top + controlPosition.height / 2
|
||||
);
|
||||
ctx.lineTo(slotX, slotY);
|
||||
ctx.stroke();
|
||||
});
|
||||
});
|
||||
setSlotsButtonPos(slots);
|
||||
};
|
||||
|
||||
const highlightFrom = (target: EventTarget | null) => {
|
||||
const control = (target as HTMLElement | null)?.closest<HTMLElement>(
|
||||
'.control'
|
||||
);
|
||||
setHoveredControl(control?.id || null);
|
||||
};
|
||||
|
||||
const onControlPointerOver = (event: PointerEvent<HTMLDivElement>) =>
|
||||
highlightFrom(event.target);
|
||||
|
||||
const controlFocusProps = {
|
||||
onPointerOver: onControlPointerOver,
|
||||
onPointerLeave: () => setHoveredControl(null),
|
||||
onFocusCapture: (event: FocusEvent<HTMLDivElement>) =>
|
||||
highlightFrom(event.target),
|
||||
onBlurCapture: () => setHoveredControl(null),
|
||||
};
|
||||
|
||||
updateSlotsRef.current = updateSlots;
|
||||
const assignedKey = useMemo(
|
||||
() => [...assignedRoles].sort((a, b) => a - b).join(','),
|
||||
[assignedRoles]
|
||||
);
|
||||
const activeKey = useMemo(
|
||||
() => [...activeParts].sort((a, b) => a - b).join(','),
|
||||
[activeParts]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
updateSlots();
|
||||
}, [figure, assignedKey, activeKey, hoveredControl]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!rightContainerRef.current ||
|
||||
!leftContainerRef.current ||
|
||||
!personRef.current
|
||||
)
|
||||
return;
|
||||
|
||||
resizeObserverRef.current.observe(personRef.current);
|
||||
|
||||
mutationObserverRef.current.observe(rightContainerRef.current, {
|
||||
attributes: true,
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
mutationObserverRef.current.observe(leftContainerRef.current, {
|
||||
attributes: true,
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
if (topContainerRef.current)
|
||||
mutationObserverRef.current.observe(topContainerRef.current, {
|
||||
attributes: true,
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
if (bottomContainerRef.current)
|
||||
mutationObserverRef.current.observe(bottomContainerRef.current, {
|
||||
attributes: true,
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (
|
||||
!rightContainerRef.current ||
|
||||
!leftContainerRef.current ||
|
||||
!personRef.current
|
||||
)
|
||||
return;
|
||||
mutationObserverRef.current.takeRecords();
|
||||
resizeObserverRef.current.unobserve(personRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="relative w-full h-full">
|
||||
<canvas
|
||||
ref={canvasRefRef}
|
||||
className="absolute w-full h-full top-0 z-10"
|
||||
width="100%"
|
||||
height="100%"
|
||||
/>
|
||||
<div className="flex flex-col w-full h-full">
|
||||
<div ref={topContainerRef} className="z-10" {...controlFocusProps}>
|
||||
{topControls}
|
||||
</div>
|
||||
<div className="flex flex-grow min-h-0 gap-5">
|
||||
<div ref={leftContainerRef} className="z-10" {...controlFocusProps}>
|
||||
{leftControls}
|
||||
</div>
|
||||
<div
|
||||
ref={personRef}
|
||||
className="relative flex h-full min-w-0 flex-grow justify-center"
|
||||
>
|
||||
{figure}
|
||||
{slotsButtonsPos.map(
|
||||
({
|
||||
top,
|
||||
left,
|
||||
height,
|
||||
width,
|
||||
id,
|
||||
part,
|
||||
hidden,
|
||||
buttonOffset,
|
||||
}) => {
|
||||
const hitSize = dotsSize + DOT_HIT_PADDING * 2;
|
||||
const required =
|
||||
part != null && highlightedRoles.includes(part);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={id}
|
||||
{...(part != null ? dotProps?.(part) : undefined)}
|
||||
aria-hidden="true"
|
||||
className={classNames(
|
||||
'absolute z-10',
|
||||
hidden && 'pointer-events-none'
|
||||
)}
|
||||
onClick={() =>
|
||||
!hidden && part != null && onSelectRole(part)
|
||||
}
|
||||
style={{
|
||||
width: hitSize,
|
||||
height: hitSize,
|
||||
top: top + height / 2 - hitSize / 2 + buttonOffset.top,
|
||||
left: left + width / 2 - hitSize / 2 + buttonOffset.left,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="absolute"
|
||||
style={{ top: DOT_HIT_PADDING, left: DOT_HIT_PADDING }}
|
||||
>
|
||||
{!hidden && required && (
|
||||
<div
|
||||
className={classNames(
|
||||
'absolute rounded-full bg-status-warning',
|
||||
'transition-opacity opacity-100 animate-ping'
|
||||
)}
|
||||
style={{
|
||||
width: dotsSize,
|
||||
height: dotsSize,
|
||||
animationDuration: '1.5s',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
className={classNames(
|
||||
'absolute rounded-full outline-background-90 transition duration-150 ease-linear box-border',
|
||||
'hover:bg-accent-background-40',
|
||||
'flex items-center justify-center',
|
||||
part != null && assignedRoles.includes(part)
|
||||
? 'bg-status-success'
|
||||
: required
|
||||
? 'bg-status-warning'
|
||||
: 'bg-background-10',
|
||||
leftPartNames.has(id) &&
|
||||
'border-4 border-assign-left',
|
||||
rightPartNames.has(id) &&
|
||||
'border-4 border-assign-right',
|
||||
part != null && dotClass?.(part),
|
||||
hidden ? 'opacity-0' : 'opacity-100'
|
||||
)}
|
||||
style={{
|
||||
width: dotsSize,
|
||||
height: dotsSize,
|
||||
boxShadow: '0px 0px 4px black',
|
||||
}}
|
||||
>
|
||||
{part != null && dotContent?.(part)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
<div ref={rightContainerRef} className="z-10" {...controlFocusProps}>
|
||||
{rightControls}
|
||||
</div>
|
||||
</div>
|
||||
<div ref={bottomContainerRef} className="z-10" {...controlFocusProps}>
|
||||
{bottomControls}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { ComponentProps } from 'react';
|
||||
import { NavLink, type NavLinkProps } from 'react-router-dom';
|
||||
import { Tooltip, type Direction } from './Tooltip';
|
||||
import { Typography } from './Typography';
|
||||
|
||||
type NativeButtonProps = Omit<
|
||||
ComponentProps<'button'>,
|
||||
'aria-pressed' | 'aria-expanded' | 'aria-current' | 'aria-label'
|
||||
>;
|
||||
|
||||
type CommonProps = {
|
||||
/** Toggle or selection state, e.g. a segmented option. Button mode only. */
|
||||
pressed?: boolean;
|
||||
/** Disclosure state, e.g. an accordion header. Button mode only. */
|
||||
expanded?: boolean;
|
||||
/** Marks the active entry in a stepper or nav. */
|
||||
current?: 'step' | 'page' | true;
|
||||
/** Accessible name, for when the children don't already give one. */
|
||||
label?: string;
|
||||
/** Fluent id. Opts this surface into a tooltip (hover *and* focus). */
|
||||
tooltipId?: string;
|
||||
tooltipVars?: ComponentProps<typeof Typography>['vars'];
|
||||
tooltipDirection?: Direction;
|
||||
};
|
||||
|
||||
type ButtonProps = CommonProps &
|
||||
NativeButtonProps & { [dataAttr: `data-${string}`]: unknown } & {
|
||||
to?: undefined;
|
||||
};
|
||||
|
||||
type LinkProps = CommonProps &
|
||||
Omit<NavLinkProps, 'className' | 'children'> & {
|
||||
[dataAttr: `data-${string}`]: unknown;
|
||||
} & {
|
||||
/** Router path. Renders a `NavLink` instead of a `<button>`. */
|
||||
to: NavLinkProps['to'];
|
||||
className?: string;
|
||||
children?: ComponentProps<'button'>['children'];
|
||||
};
|
||||
|
||||
/**
|
||||
* A clickable surface that keeps whatever styling you give it and only adds
|
||||
* the semantics: tab focus, Enter/Space, and a default `type="button"` so a
|
||||
* `<button>` does not submit a surrounding form unless asked to.
|
||||
*
|
||||
* Pass `to` and it renders a router `NavLink` instead, so the same call site
|
||||
* covers both an action and a navigation.
|
||||
*
|
||||
* Reach for this anywhere you would have put `onClick` on a `<div>`. Use
|
||||
* `Button` for the styled variants and `IconButton` for icon-only controls.
|
||||
*
|
||||
* No tooltip by default, since the children are already the label. Pass
|
||||
* `tooltipId` where the extra explanation earns its place.
|
||||
*
|
||||
* It cannot wrap another button or link. If the surface already contains one,
|
||||
* leave the container inert and make the inner control the real button.
|
||||
*/
|
||||
export function Clickable({
|
||||
className,
|
||||
pressed,
|
||||
expanded,
|
||||
current,
|
||||
label,
|
||||
tooltipId,
|
||||
tooltipVars,
|
||||
tooltipDirection = 'bottom',
|
||||
...props
|
||||
}: ButtonProps | LinkProps) {
|
||||
const surface =
|
||||
props.to !== undefined ? (
|
||||
<NavLink
|
||||
{...(props as LinkProps)}
|
||||
aria-current={current}
|
||||
aria-label={label}
|
||||
className={classNames('text-left', className)}
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
{...(props as ButtonProps)}
|
||||
aria-pressed={pressed}
|
||||
aria-expanded={expanded}
|
||||
aria-current={current}
|
||||
aria-label={label}
|
||||
className={classNames('text-left', className)}
|
||||
/>
|
||||
);
|
||||
|
||||
if (!tooltipId) return surface;
|
||||
|
||||
return (
|
||||
<Tooltip
|
||||
preferedDirection={tooltipDirection}
|
||||
content={<Typography id={tooltipId} vars={tooltipVars} />}
|
||||
spacing={5}
|
||||
>
|
||||
{surface}
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
import { ReactNode, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { CloseIcon } from './icon/CloseIcon';
|
||||
import { IconButton } from './IconButton';
|
||||
|
||||
const SLIDE_MS = 200;
|
||||
|
||||
export function Drawer({
|
||||
isOpen,
|
||||
onClose,
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
title: ReactNode;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement | null>(null);
|
||||
const [shown, setShown] = useState(false);
|
||||
|
||||
const setRef = (node: HTMLDivElement | null) => {
|
||||
node?.setAttribute('popover', 'manual');
|
||||
ref.current = node;
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
if (!isOpen) {
|
||||
setShown(false);
|
||||
const timeout = setTimeout(() => {
|
||||
if (el.matches(':popover-open')) el.hidePopover();
|
||||
}, SLIDE_MS);
|
||||
return () => clearTimeout(timeout);
|
||||
}
|
||||
if (!el.matches(':popover-open')) el.showPopover();
|
||||
el.getBoundingClientRect();
|
||||
setShown(true);
|
||||
}, [isOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
};
|
||||
window.addEventListener('keydown', onKeyDown);
|
||||
return () => window.removeEventListener('keydown', onKeyDown);
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setRef}
|
||||
className="fixed inset-0 top-[44px] m-0 p-0 border-0 bg-transparent w-full h-auto max-w-none max-h-none overflow-hidden"
|
||||
style={{ pointerEvents: shown ? undefined : 'none' }}
|
||||
>
|
||||
<div
|
||||
className="absolute inset-0 rounded-t-lg bg-background-90 transition-opacity duration-200"
|
||||
style={{ opacity: shown ? 0.5 : 0 }}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<div
|
||||
className="absolute left-0 w-full text-background-10 max-h-full transition-[bottom] duration-200 overflow-clip"
|
||||
style={{ bottom: shown ? 0 : '-100%' }}
|
||||
>
|
||||
<div className="bg-background-60 rounded-t-lg border-background-40 border-t-2 pb-[env(safe-area-inset-bottom)]">
|
||||
<div className="h-12 rounded-t-lg relative flex justify-center items-center">
|
||||
{title}
|
||||
<IconButton
|
||||
labelId="titlebar-close"
|
||||
tooltip={false}
|
||||
className="absolute right-4 top-3 h-6 w-6 bg-background-70 rounded-full flex justify-center items-center"
|
||||
onClick={onClose}
|
||||
>
|
||||
<CloseIcon size={20} className="stroke-white" />
|
||||
</IconButton>
|
||||
</div>
|
||||
<div
|
||||
className="overflow-y-auto"
|
||||
style={{ maxHeight: 'calc(100vh - 49px - 44px)' }}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
.dropdown-popover {
|
||||
display: none;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transform: scale(0.98);
|
||||
transition:
|
||||
opacity 120ms ease,
|
||||
transform 120ms ease,
|
||||
display 120ms allow-discrete,
|
||||
overlay 120ms allow-discrete;
|
||||
|
||||
&:popover-open {
|
||||
display: flex;
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
transform: scale(1);
|
||||
}
|
||||
|
||||
@starting-style {
|
||||
&:popover-open {
|
||||
opacity: 0;
|
||||
transform: scale(0.98);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,622 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { Clickable } from './Clickable';
|
||||
import {
|
||||
CSSProperties,
|
||||
forwardRef,
|
||||
ReactNode,
|
||||
useEffect,
|
||||
useId,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import {
|
||||
Control,
|
||||
FieldError,
|
||||
FieldPath,
|
||||
FieldValues,
|
||||
useController,
|
||||
UseControllerProps,
|
||||
} from 'react-hook-form';
|
||||
import { ArrowDownIcon, ArrowUpIcon } from './icon/ArrowIcons';
|
||||
import { CheckIcon } from './icon/CheckIcon';
|
||||
import { ProgressBar } from './ProgressBar';
|
||||
import { a11yClick } from '@/utils/a11y';
|
||||
import './Dropdown.scss';
|
||||
import { Typography } from './Typography';
|
||||
import {
|
||||
FLOATING_LABEL_PADDING,
|
||||
FieldCaption,
|
||||
FloatingLabel,
|
||||
} from './FloatingLabel';
|
||||
|
||||
export type DropdownItem = {
|
||||
value: string;
|
||||
label: ReactNode;
|
||||
};
|
||||
|
||||
export type DropdownDirection = 'up' | 'down';
|
||||
|
||||
function isItemSelected(
|
||||
selection: DropdownSingleSelection | DropdownMultipleSelection,
|
||||
itemValue: string
|
||||
): boolean {
|
||||
return selection.multiple
|
||||
? selection.value.includes(itemValue)
|
||||
: selection.value === itemValue;
|
||||
}
|
||||
|
||||
type DropdownProps = {
|
||||
direction?: DropdownDirection;
|
||||
variant?: 'primary' | 'secondary' | 'tertiary' | 'quaternary';
|
||||
alignment?: 'left' | 'right';
|
||||
display?: 'fit' | 'block';
|
||||
placeholder: ReactNode;
|
||||
// Field label. Rendered as a caption above the box, unless `inside` is 'label'.
|
||||
label?: string;
|
||||
// What fills the box while nothing is selected:
|
||||
// 'placeholder' (default) - the placeholder text (blank if it is empty/null)
|
||||
// 'label' - the label, as a floating label inside the box
|
||||
// 'none' - nothing
|
||||
inside?: 'placeholder' | 'label' | 'none';
|
||||
// Keep the caption once a value is selected (default). Set false to drop it.
|
||||
persistLabel?: boolean;
|
||||
name: string;
|
||||
items: DropdownItem[];
|
||||
maxHeight?: string | number;
|
||||
error?: FieldError;
|
||||
loading?: boolean;
|
||||
renderValue?: () => ReactNode;
|
||||
menuWidth?: string;
|
||||
};
|
||||
|
||||
type DropdownSingleSelection = {
|
||||
multiple?: false;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
};
|
||||
|
||||
type DropdownMultipleSelection = {
|
||||
multiple: true;
|
||||
value: string[];
|
||||
onChange: (value: string[]) => void;
|
||||
};
|
||||
|
||||
function DropdownItem({
|
||||
item,
|
||||
variant,
|
||||
onSelected,
|
||||
isOpen,
|
||||
checked,
|
||||
multiple,
|
||||
innerFocusValue,
|
||||
name,
|
||||
}: {
|
||||
item: DropdownItem;
|
||||
variant: Required<DropdownProps>['variant'];
|
||||
onSelected: () => void;
|
||||
isOpen: boolean;
|
||||
checked: boolean;
|
||||
multiple?: boolean;
|
||||
innerFocusValue: string | null;
|
||||
name: string;
|
||||
}) {
|
||||
const variantStyles = {
|
||||
primary:
|
||||
'text-background-10 checked-hover:text-background-10 checked-hover:bg-background-50 focus:text-background-10 focus:bg-background-50',
|
||||
secondary:
|
||||
'text-background-10 checked-hover:text-background-10 checked-hover:bg-background-40 focus:text-background-10 focus:bg-background-40',
|
||||
tertiary:
|
||||
'bg-accent-background-30 checked-hover:bg-accent-background-20 focus:bg-accent-background-20 text-background-10',
|
||||
quaternary:
|
||||
'text-background-10 checked-hover:text-background-10 checked-hover:bg-background-60 focus:text-background-10 focus:bg-background-60',
|
||||
};
|
||||
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!innerFocusValue) {
|
||||
return;
|
||||
}
|
||||
if (innerFocusValue === item.value) {
|
||||
ref.current?.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
}, [innerFocusValue]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!isOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (innerFocusValue === item.value || (!innerFocusValue && checked)) {
|
||||
ref.current?.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'py-2 px-2 min-w-max cursor-pointer transition-colors select-none',
|
||||
variantStyles[variant],
|
||||
innerFocusValue === item.value &&
|
||||
'ring-inset ring-2 ring-accent-background-10'
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onSelected();
|
||||
}}
|
||||
onKeyDown={(e) => a11yClick(e) && onSelected()}
|
||||
tabIndex={-1}
|
||||
aria-hidden={!isOpen}
|
||||
ref={ref}
|
||||
id={`__dropdownList-${name}-item-${item.value}`}
|
||||
>
|
||||
<div className="flex items-center gap-2.5">
|
||||
{multiple && (
|
||||
<div
|
||||
className={classNames(
|
||||
'w-4 h-4 rounded flex items-center justify-center transition-colors shrink-0',
|
||||
checked
|
||||
? 'bg-accent-background-30 text-background-10'
|
||||
: 'bg-background-50 border border-background-40'
|
||||
)}
|
||||
>
|
||||
{checked && <CheckIcon size={9} className="fill-current" />}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 min-w-0">{item.label}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type DropdownAction = 'all' | 'none';
|
||||
|
||||
type DropdownListProps = {
|
||||
isOpen: boolean;
|
||||
onSelect: (item: DropdownItem) => void;
|
||||
isSelected: (value: string) => boolean;
|
||||
multiple?: boolean;
|
||||
onSelectAll?: () => void;
|
||||
onDeselectAll?: () => void;
|
||||
innerFocusValue: string | null;
|
||||
focusedAction: DropdownAction | null;
|
||||
anchorName: string;
|
||||
menuWidth?: string;
|
||||
} & Pick<
|
||||
Required<DropdownProps>,
|
||||
| 'display'
|
||||
| 'alignment'
|
||||
| 'direction'
|
||||
| 'items'
|
||||
| 'variant'
|
||||
| 'maxHeight'
|
||||
| 'name'
|
||||
>;
|
||||
|
||||
const DropdownList = forwardRef<HTMLDivElement, DropdownListProps>(function (
|
||||
{
|
||||
isOpen,
|
||||
onSelect,
|
||||
isSelected,
|
||||
multiple,
|
||||
onSelectAll,
|
||||
onDeselectAll,
|
||||
innerFocusValue,
|
||||
focusedAction,
|
||||
display,
|
||||
alignment,
|
||||
direction,
|
||||
items,
|
||||
variant,
|
||||
maxHeight,
|
||||
name,
|
||||
anchorName,
|
||||
menuWidth,
|
||||
},
|
||||
ref
|
||||
) {
|
||||
const variantStyles = {
|
||||
primary: 'bg-background-60',
|
||||
secondary: 'bg-background-50',
|
||||
tertiary: 'bg-accent-background-30',
|
||||
quaternary: 'bg-background-70',
|
||||
};
|
||||
|
||||
const columnArea =
|
||||
display === 'block' && !menuWidth
|
||||
? 'center'
|
||||
: alignment === 'left'
|
||||
? 'span-right'
|
||||
: 'span-left';
|
||||
const rowArea = direction === 'up' ? 'top' : 'bottom';
|
||||
|
||||
const ulRef = useRef<HTMLUListElement>(null);
|
||||
|
||||
const setDivRef = (node: HTMLDivElement | null) => {
|
||||
node?.setAttribute('popover', 'manual');
|
||||
if (typeof ref === 'function') {
|
||||
ref(node);
|
||||
} else if (ref) {
|
||||
ref.current = node;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'dropdown-popover fixed inset-auto m-0 border-0 p-0 rounded overflow-hidden flex-col',
|
||||
direction === 'up' ? 'mb-3' : 'mt-3',
|
||||
variantStyles[variant],
|
||||
menuWidth ?? (display === 'block' ? 'w-full' : 'w-fit')
|
||||
)}
|
||||
style={
|
||||
{
|
||||
positionAnchor: anchorName,
|
||||
positionArea: `${rowArea} ${columnArea}`,
|
||||
positionTryFallbacks: 'flip-block',
|
||||
} as CSSProperties
|
||||
}
|
||||
onTransitionEnd={(e) => {
|
||||
if (e.propertyName === 'opacity' && !isOpen) {
|
||||
ulRef.current?.scrollTo({ top: 0 });
|
||||
}
|
||||
}}
|
||||
ref={setDivRef}
|
||||
id={`__dropdownList-${name}`}
|
||||
>
|
||||
{multiple && (onSelectAll || onDeselectAll) && (
|
||||
<div className="flex items-center justify-between px-3 py-2 border-b border-background-10/10 text-xs font-bold bg-background-80/60 select-none">
|
||||
<Clickable
|
||||
id={`__dropdownList-${name}-action-all`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onSelectAll?.();
|
||||
}}
|
||||
className={classNames(
|
||||
'text-background-10 hover:text-background-20 transition-colors rounded',
|
||||
focusedAction === 'all' && 'ring-2 ring-accent-background-10'
|
||||
)}
|
||||
>
|
||||
<Typography id="dropdown_select-all" />
|
||||
</Clickable>
|
||||
<Clickable
|
||||
id={`__dropdownList-${name}-action-none`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onDeselectAll?.();
|
||||
}}
|
||||
className={classNames(
|
||||
'text-background-30 hover:text-background-10 transition-colors rounded',
|
||||
focusedAction === 'none' && 'ring-2 ring-accent-background-10'
|
||||
)}
|
||||
>
|
||||
<Typography id="dropdown_unselect-all" />
|
||||
</Clickable>
|
||||
</div>
|
||||
)}
|
||||
<ul
|
||||
ref={ulRef}
|
||||
className="flex flex-col min-h-0 text-sm overflow-y-scroll dropdown-scroll overscroll-contain"
|
||||
style={{ maxHeight }}
|
||||
>
|
||||
{items.map((item) => (
|
||||
<DropdownItem
|
||||
item={item}
|
||||
variant={variant}
|
||||
onSelected={() => onSelect(item)}
|
||||
isOpen={isOpen}
|
||||
key={item.value}
|
||||
checked={isSelected(item.value)}
|
||||
multiple={multiple}
|
||||
innerFocusValue={innerFocusValue}
|
||||
name={name}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export function DropdownInside(
|
||||
props: DropdownProps & (DropdownSingleSelection | DropdownMultipleSelection)
|
||||
) {
|
||||
const {
|
||||
direction = 'up',
|
||||
variant = 'primary',
|
||||
alignment = 'right',
|
||||
display = 'fit',
|
||||
placeholder,
|
||||
label,
|
||||
inside = 'placeholder',
|
||||
persistLabel = true,
|
||||
name,
|
||||
items,
|
||||
maxHeight = '50vh',
|
||||
error,
|
||||
loading,
|
||||
renderValue,
|
||||
menuWidth,
|
||||
} = props;
|
||||
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
const variantStyles = {
|
||||
primary: 'bg-background-60 hover:bg-background-50',
|
||||
secondary: 'bg-background-50 hover:bg-background-40',
|
||||
tertiary: 'bg-accent-background-30 hover:bg-accent-background-20',
|
||||
quaternary: 'bg-background-70 hover:bg-background-60',
|
||||
};
|
||||
|
||||
const displayStyles = {
|
||||
fit: 'w-fit',
|
||||
block: 'w-full',
|
||||
};
|
||||
|
||||
const hasValue = props.multiple ? props.value.length > 0 : !!props.value;
|
||||
const labelInside = inside === 'label' && !!label;
|
||||
const showCaption = !!label && !labelInside && (persistLabel || !hasValue);
|
||||
const emptyValue = inside === 'placeholder' ? placeholder : '';
|
||||
|
||||
const getShownValue = (): ReactNode => {
|
||||
if (renderValue) return renderValue();
|
||||
if (props.multiple) {
|
||||
return props.value.length > 0
|
||||
? `${props.value.length} selected`
|
||||
: emptyValue;
|
||||
}
|
||||
return props.value
|
||||
? (items.find((item) => item.value === props.value)?.label ?? placeholder)
|
||||
: emptyValue;
|
||||
};
|
||||
|
||||
const selectItem = (item: DropdownItem) => {
|
||||
if (props.multiple) {
|
||||
const exists = props.value.includes(item.value);
|
||||
props.onChange(
|
||||
exists
|
||||
? props.value.filter((v) => v !== item.value)
|
||||
: [...props.value, item.value]
|
||||
);
|
||||
} else {
|
||||
props.onChange(item.value);
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const selectAll = () =>
|
||||
props.multiple && props.onChange(items.map((i) => i.value));
|
||||
const deselectAll = () => props.multiple && props.onChange([]);
|
||||
|
||||
/**
|
||||
* The header select-all / unselect-all buttons sit before the items in the
|
||||
* roving order, so arrows reach them like any option.
|
||||
*/
|
||||
const actionKeys: DropdownAction[] = props.multiple ? ['all', 'none'] : [];
|
||||
const navCount = actionKeys.length + items.length;
|
||||
const resolveNav = (
|
||||
index: number | null
|
||||
): { action: DropdownAction | null; item: DropdownItem | null } => {
|
||||
if (index === null || index < 0) return { action: null, item: null };
|
||||
if (index < actionKeys.length)
|
||||
return { action: actionKeys[index] ?? null, item: null };
|
||||
return { action: null, item: items[index - actionKeys.length] ?? null };
|
||||
};
|
||||
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const anchorName = `--dropdown-anchor-${useId().replace(/:/g, '')}`;
|
||||
|
||||
const [innerFocusIndex, setInnerFocusIndex] = useState<number | null>(null);
|
||||
// Index may point past the range (items changed, empty list) - resolve safely.
|
||||
const { action: focusedAction, item: focusedItem } =
|
||||
resolveNav(innerFocusIndex);
|
||||
const getCurrentActiveIndex = () => {
|
||||
const i = props.multiple
|
||||
? items.findIndex((item) => props.value.includes(item.value))
|
||||
: items.findIndex((item) => item.value === props.value);
|
||||
return i >= 0 ? i + actionKeys.length : actionKeys.length;
|
||||
};
|
||||
const innerFocusPrev = () => {
|
||||
const current = innerFocusIndex ?? getCurrentActiveIndex();
|
||||
setInnerFocusIndex(Math.max(0, current - 1));
|
||||
};
|
||||
const innerFocusNext = () => {
|
||||
const current = innerFocusIndex ?? getCurrentActiveIndex();
|
||||
setInnerFocusIndex(Math.min(navCount - 1, current + 1));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
setInnerFocusIndex(null);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
}, [loading]);
|
||||
|
||||
useEffect(() => {
|
||||
const el = listRef.current;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
if (isOpen && !el.matches(':popover-open')) {
|
||||
el.showPopover();
|
||||
} else if (!isOpen && el.matches(':popover-open')) {
|
||||
el.hidePopover();
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
return (
|
||||
<div className={classNames('flex flex-col gap-1', displayStyles[display])}>
|
||||
{showCaption && <FieldCaption>{label}</FieldCaption>}
|
||||
<div
|
||||
className={classNames(
|
||||
'min-h-[48px] min-w-0 text-background-10 text-left dropdown',
|
||||
displayStyles[display]
|
||||
)}
|
||||
onKeyDown={(e) => {
|
||||
if (loading) {
|
||||
return;
|
||||
}
|
||||
if (!isOpen) {
|
||||
if (a11yClick(e)) {
|
||||
setInnerFocusIndex(getCurrentActiveIndex());
|
||||
setIsOpen(!isOpen);
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
|
||||
// Up/Down opens the list (APG combobox pattern).
|
||||
if (
|
||||
items.length > 0 &&
|
||||
(e.key === 'ArrowDown' || e.key === 'ArrowUp')
|
||||
) {
|
||||
setInnerFocusIndex(
|
||||
e.key === 'ArrowDown' ? actionKeys.length : navCount - 1
|
||||
);
|
||||
setIsOpen(true);
|
||||
e.preventDefault();
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
if (a11yClick(e)) {
|
||||
e.preventDefault();
|
||||
if (focusedAction === 'all') return selectAll();
|
||||
if (focusedAction === 'none') return deselectAll();
|
||||
if (!focusedItem) {
|
||||
setIsOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
selectItem(focusedItem);
|
||||
if (!props.multiple) setIsOpen(false);
|
||||
}
|
||||
switch (e.key) {
|
||||
case 'ArrowUp':
|
||||
case 'ArrowLeft':
|
||||
innerFocusPrev();
|
||||
e.preventDefault();
|
||||
return;
|
||||
case 'ArrowDown':
|
||||
case 'ArrowRight':
|
||||
innerFocusNext();
|
||||
e.preventDefault();
|
||||
return;
|
||||
case 'Escape':
|
||||
setIsOpen(false);
|
||||
return;
|
||||
case 'Home':
|
||||
setInnerFocusIndex(0);
|
||||
return;
|
||||
case 'End':
|
||||
setInnerFocusIndex(navCount - 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}}
|
||||
onBlur={(e) => {
|
||||
if (e.currentTarget.contains(e.relatedTarget)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsOpen(false);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (!loading) setIsOpen((o) => !o);
|
||||
}}
|
||||
className={classNames(
|
||||
'flex flex-row items-center gap-2 pl-3 pr-11 rounded-md relative min-h-[48px] min-w-0 overflow-hidden',
|
||||
labelInside ? FLOATING_LABEL_PADDING : 'py-3',
|
||||
loading ? 'cursor-not-allowed opacity-60' : 'cursor-pointer',
|
||||
variantStyles[variant]
|
||||
)}
|
||||
tabIndex={loading ? -1 : 0}
|
||||
aria-disabled={loading}
|
||||
ref={ref}
|
||||
style={{ anchorName } as CSSProperties}
|
||||
aria-controls={`__dropdownList-${name}`}
|
||||
aria-expanded={isOpen}
|
||||
aria-activedescendant={
|
||||
focusedAction
|
||||
? `__dropdownList-${name}-action-${focusedAction}`
|
||||
: focusedItem
|
||||
? `__dropdownList-${name}-item-${focusedItem.value}`
|
||||
: ''
|
||||
}
|
||||
role="combobox"
|
||||
>
|
||||
{labelInside && <FloatingLabel label={label} floating={hasValue} />}
|
||||
<span
|
||||
className={classNames(
|
||||
'min-w-0 flex-grow truncate',
|
||||
!hasValue && 'text-background-20 italic'
|
||||
)}
|
||||
>
|
||||
{getShownValue()}
|
||||
</span>
|
||||
<div className="fill-background-10 pointer-events-none absolute inset-y-0 right-5 flex items-center">
|
||||
{isOpen ? <ArrowUpIcon size={16} /> : <ArrowDownIcon size={16} />}
|
||||
</div>
|
||||
{loading && (
|
||||
<div className="absolute left-0 right-0 bottom-0">
|
||||
<ProgressBar indeterminate height={3} bottom />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{error?.message && (
|
||||
<div className="text-status-critical">{error.message}</div>
|
||||
)}
|
||||
<DropdownList
|
||||
alignment={alignment}
|
||||
direction={direction}
|
||||
display={display}
|
||||
menuWidth={menuWidth}
|
||||
isOpen={isOpen}
|
||||
items={items}
|
||||
multiple={props.multiple}
|
||||
onSelectAll={selectAll}
|
||||
onDeselectAll={deselectAll}
|
||||
onSelect={(item: DropdownItem) => {
|
||||
ref.current?.focus();
|
||||
selectItem(item);
|
||||
}}
|
||||
variant={variant}
|
||||
maxHeight={maxHeight}
|
||||
isSelected={(value) => isItemSelected(props, value)}
|
||||
ref={listRef}
|
||||
anchorName={anchorName}
|
||||
innerFocusValue={focusedItem?.value ?? null}
|
||||
focusedAction={focusedAction}
|
||||
name={name}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Dropdown<T extends FieldValues = FieldValues>({
|
||||
control,
|
||||
name,
|
||||
rules,
|
||||
...props
|
||||
}: DropdownProps & {
|
||||
control: Control<T>;
|
||||
name: FieldPath<T>;
|
||||
rules?: UseControllerProps<T, FieldPath<T>>['rules'];
|
||||
}) {
|
||||
const {
|
||||
field: { value, onChange },
|
||||
} = useController({ name, control, rules });
|
||||
|
||||
return (
|
||||
<DropdownInside value={value} name={name} {...props} onChange={onChange} />
|
||||
);
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode } from 'react';
|
||||
import { LoaderIcon, SlimeState } from './icon/LoaderIcon';
|
||||
import { Typography } from './Typography';
|
||||
|
||||
/** Slime, a title and a line of guidance for a panel with nothing in it */
|
||||
export function EmptyState({
|
||||
slimeState,
|
||||
iconSize,
|
||||
glow = false,
|
||||
lowPriority = false,
|
||||
titleId,
|
||||
titleColor,
|
||||
descriptionId,
|
||||
descriptionColor,
|
||||
action,
|
||||
className,
|
||||
}: {
|
||||
slimeState: SlimeState;
|
||||
iconSize?: number;
|
||||
/** Accent halo behind the slime */
|
||||
glow?: boolean;
|
||||
lowPriority?: boolean;
|
||||
titleId: string;
|
||||
titleColor?: string;
|
||||
descriptionId: string;
|
||||
descriptionColor?: string;
|
||||
action?: ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
const icon = (
|
||||
<LoaderIcon
|
||||
slimeState={slimeState}
|
||||
size={iconSize}
|
||||
lowPriority={lowPriority}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'flex flex-col items-center justify-center gap-4 text-center p-6',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{glow ? (
|
||||
<div className="relative flex items-center justify-center antialiased">
|
||||
<div
|
||||
className="absolute w-64 h-64 rounded-full pointer-events-none"
|
||||
style={{
|
||||
background:
|
||||
'radial-gradient(circle, rgb(var(--accent-background-30), 0.25) 0%, rgb(var(--accent-background-30), 0) 70%)',
|
||||
}}
|
||||
/>
|
||||
{icon}
|
||||
</div>
|
||||
) : (
|
||||
icon
|
||||
)}
|
||||
<div className="flex flex-col gap-1 max-w-xs">
|
||||
<Typography
|
||||
bold
|
||||
variant="section-title"
|
||||
color={titleColor}
|
||||
id={titleId}
|
||||
/>
|
||||
<Typography
|
||||
variant="standard"
|
||||
color={descriptionColor}
|
||||
id={descriptionId}
|
||||
/>
|
||||
</div>
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import { BodyPart } from 'solarxr-protocol';
|
||||
import {
|
||||
ExtremityFigureSpec,
|
||||
ExtremityParts,
|
||||
ExtremitySide,
|
||||
} from '@/utils/extremities';
|
||||
|
||||
const CIRCLE_RADIUS = 0.0001;
|
||||
|
||||
export function ExtremityFigure({
|
||||
spec,
|
||||
parts,
|
||||
side,
|
||||
height = spec.height,
|
||||
className,
|
||||
}: {
|
||||
spec: ExtremityFigureSpec;
|
||||
parts: ExtremityParts;
|
||||
side: ExtremitySide;
|
||||
height?: number;
|
||||
className?: string;
|
||||
}) {
|
||||
const mirror = side === 'left';
|
||||
const x = (cx: number) => (mirror ? spec.width - cx : cx);
|
||||
|
||||
return (
|
||||
<svg
|
||||
width="100%"
|
||||
className={className}
|
||||
viewBox={`0 0 ${spec.width} ${height}`}
|
||||
>
|
||||
<image
|
||||
width={spec.width}
|
||||
height={spec.height}
|
||||
transform={
|
||||
mirror ? `translate(${spec.width},0) scale(-1,1)` : undefined
|
||||
}
|
||||
href={spec.image}
|
||||
/>
|
||||
{Object.entries(parts.digits).flatMap(([digit, joints]) =>
|
||||
joints.map((part, joint) => {
|
||||
const [cx, cy] = spec.anchors[digit][joint];
|
||||
return (
|
||||
<circle
|
||||
key={part}
|
||||
className="body-part-circle"
|
||||
cx={x(cx)}
|
||||
cy={cy}
|
||||
r={CIRCLE_RADIUS}
|
||||
id={BodyPart[part]}
|
||||
/>
|
||||
);
|
||||
})
|
||||
)}
|
||||
<circle
|
||||
className="body-part-circle"
|
||||
cx={x(spec.rootAnchor[0])}
|
||||
cy={spec.rootAnchor[1]}
|
||||
r={CIRCLE_RADIUS}
|
||||
id={BodyPart[parts.root]}
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode } from 'react';
|
||||
import { Typography } from './Typography';
|
||||
|
||||
export function FloatingLabel({
|
||||
label,
|
||||
floating,
|
||||
className,
|
||||
}: {
|
||||
label: ReactNode;
|
||||
floating: boolean;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<Typography
|
||||
variant="standard"
|
||||
bold={floating}
|
||||
italic={!floating}
|
||||
color={classNames(
|
||||
'text-background-10 pointer-events-none absolute left-3 z-20 leading-none transition-all duration-150 ease-out',
|
||||
floating ? `top-[0.5rem] origin-left` : 'top-1/2 -translate-y-1/2',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
|
||||
export function FieldCaption({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<Typography
|
||||
variant="standard"
|
||||
bold
|
||||
color={classNames('text-background-10 leading-none origin-left')}
|
||||
>
|
||||
{children}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
|
||||
// Vertical padding a control needs so a floating label clears its value.
|
||||
export const FLOATING_LABEL_PADDING = 'pt-[1.15rem] pb-[0.15rem]';
|
||||
@@ -1,68 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { CheckIcon } from './icon/CheckIcon';
|
||||
import { CrossIcon } from './icon/CrossIcon';
|
||||
import { Typography } from './Typography';
|
||||
|
||||
const EXAMPLES = [
|
||||
{
|
||||
id: 'front',
|
||||
src: '/images/reset/FullResetPose.webp',
|
||||
alt: 'Reset position',
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
id: 'side',
|
||||
src: '/images/reset/FullResetPoseSide.webp',
|
||||
alt: 'Reset position side',
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
id: 'wrong',
|
||||
src: '/images/reset/FullResetPoseWrong.webp',
|
||||
alt: 'Reset position wrong',
|
||||
ok: false,
|
||||
},
|
||||
];
|
||||
|
||||
export function FullResetExamples({
|
||||
captions = false,
|
||||
className,
|
||||
tileClassName = 'bg-background-70',
|
||||
}: {
|
||||
captions?: boolean;
|
||||
className?: string;
|
||||
tileClassName?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={classNames('grid grid-cols-3 gap-2', className)}>
|
||||
{EXAMPLES.map(({ id, src, alt, ok }) => (
|
||||
<div
|
||||
key={id}
|
||||
className={classNames(
|
||||
'flex flex-col min-h-0 rounded-md relative',
|
||||
tileClassName
|
||||
)}
|
||||
>
|
||||
{ok ? (
|
||||
<CheckIcon className="md:w-10 sm:w-8 w-6 h-auto absolute top-2 right-2 fill-status-success" />
|
||||
) : (
|
||||
<CrossIcon className="md:w-10 sm:w-8 w-6 h-auto absolute top-2 right-2 fill-status-critical" />
|
||||
)}
|
||||
<img
|
||||
src={src}
|
||||
className="min-h-0 flex-1 w-full object-contain p-2"
|
||||
alt={alt}
|
||||
/>
|
||||
{captions && (
|
||||
<div className="px-3 pb-3">
|
||||
<Typography
|
||||
textAlign="text-center"
|
||||
id={`onboarding-automatic_mounting-preparation-example-${id}`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import { ComponentProps } from 'react';
|
||||
import { Clickable } from './Clickable';
|
||||
|
||||
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
|
||||
? Omit<T, K>
|
||||
: never;
|
||||
|
||||
/**
|
||||
* Icon-only button. `labelId` does double duty: it names the control for screen
|
||||
* readers and renders as the tooltip, so an icon never ships unlabelled.
|
||||
*
|
||||
* The tooltip is on by default here, since unlike `Clickable` there is no
|
||||
* visible text to fall back on. Pass `tooltip={false}` where it would be noise.
|
||||
*
|
||||
* Inherits `Clickable`'s link mode: pass `to` and it renders a `NavLink`.
|
||||
*/
|
||||
export function IconButton({
|
||||
labelId,
|
||||
tooltip = true,
|
||||
...props
|
||||
}: {
|
||||
/** Fluent id, used for both the accessible name and the tooltip text. */
|
||||
labelId: string;
|
||||
tooltip?: boolean;
|
||||
} & DistributiveOmit<ComponentProps<typeof Clickable>, 'label' | 'tooltipId'>) {
|
||||
const { l10n } = useLocalization();
|
||||
|
||||
return (
|
||||
<Clickable
|
||||
{...props}
|
||||
label={l10n.getString(labelId)}
|
||||
tooltipId={tooltip ? labelId : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode } from 'react';
|
||||
import { Typography } from './Typography';
|
||||
|
||||
export type KbdVariant = 'default' | 'active' | 'invalid' | 'empty';
|
||||
|
||||
const KBD_VARIANTS: Record<KbdVariant, string> = {
|
||||
default: 'bg-background-90 border-background-60',
|
||||
active: 'bg-background-90 border-accent-background-30 animate-pulse',
|
||||
invalid: 'bg-status-critical/20 border-status-critical animate-shake',
|
||||
empty: 'bg-background-90 border-dashed border-background-60',
|
||||
};
|
||||
|
||||
// A keycap-styled label
|
||||
export function Kbd({
|
||||
children,
|
||||
id,
|
||||
variant = 'default',
|
||||
className,
|
||||
}: {
|
||||
children?: ReactNode;
|
||||
id?: string;
|
||||
variant?: KbdVariant;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<kbd
|
||||
className={classNames(
|
||||
'inline-flex items-center justify-center rounded-md border transition-all',
|
||||
KBD_VARIANTS[variant],
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Typography variant="standard" bold textAlign="text-center" id={id}>
|
||||
{children}
|
||||
</Typography>
|
||||
</kbd>
|
||||
);
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
import {
|
||||
forwardRef,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
} from 'react';
|
||||
import { Typography } from './Typography';
|
||||
import { Kbd } from './Kbd';
|
||||
import classNames from 'classnames';
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import './KeybindRow.scss';
|
||||
import {
|
||||
MODIFIER_ORDER,
|
||||
keybindLabel,
|
||||
modifierNameForKey,
|
||||
modifiersFromHeld,
|
||||
resolveKey,
|
||||
} from './keybind-keys';
|
||||
|
||||
const maxKeybindLength = 5;
|
||||
|
||||
type RecorderState = {
|
||||
held: Set<string>;
|
||||
best: string[] | null;
|
||||
flash: { slot: number; msgId: string } | null;
|
||||
};
|
||||
|
||||
type RecorderAction =
|
||||
| { type: 'keydown'; code: string; keys: string[] }
|
||||
| { type: 'keyup'; code: string }
|
||||
| { type: 'clear' }
|
||||
| { type: 'flash'; slot: number; msgId: string }
|
||||
| { type: 'clearFlash' };
|
||||
|
||||
function recorderReducer(
|
||||
state: RecorderState,
|
||||
action: RecorderAction
|
||||
): RecorderState {
|
||||
switch (action.type) {
|
||||
case 'keydown': {
|
||||
const held = new Set(state.held);
|
||||
held.add(action.code);
|
||||
const hasMain = action.keys.some((k) => !MODIFIER_ORDER.includes(k));
|
||||
const bestHasMain = (state.best ?? []).some(
|
||||
(k) => !MODIFIER_ORDER.includes(k)
|
||||
);
|
||||
const best =
|
||||
hasMain || !bestHasMain ? action.keys : (state.best ?? action.keys);
|
||||
return { held, best, flash: null };
|
||||
}
|
||||
case 'keyup': {
|
||||
const held = new Set(state.held);
|
||||
held.delete(action.code);
|
||||
return { ...state, held };
|
||||
}
|
||||
case 'clear':
|
||||
return { held: new Set(), best: null, flash: null };
|
||||
case 'flash':
|
||||
return { ...state, flash: { slot: action.slot, msgId: action.msgId } };
|
||||
case 'clearFlash':
|
||||
return { ...state, flash: null };
|
||||
}
|
||||
}
|
||||
|
||||
export const KeybindRecorder = forwardRef<
|
||||
HTMLInputElement,
|
||||
{
|
||||
keys: string[];
|
||||
onKeysChange: (v: string[]) => void;
|
||||
error?: string;
|
||||
onSubmitModal?: () => void;
|
||||
onUnbindModal?: () => void;
|
||||
onCloseModal?: () => void;
|
||||
}
|
||||
>(function KeybindRecorder(
|
||||
{ keys, onKeysChange, error, onSubmitModal, onUnbindModal, onCloseModal },
|
||||
ref
|
||||
) {
|
||||
const { l10n } = useLocalization();
|
||||
const [state, dispatch] = useReducer(recorderReducer, {
|
||||
held: new Set<string>(),
|
||||
best: null,
|
||||
flash: null,
|
||||
});
|
||||
const [focused, setFocused] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
useImperativeHandle(ref, () => inputRef.current!, []);
|
||||
|
||||
const recording = state.held.size > 0;
|
||||
const showing = recording ? (state.best ?? []) : keys;
|
||||
const activeIndex = showing.length;
|
||||
const slotCount = recording
|
||||
? Math.min(showing.length + 1, maxKeybindLength)
|
||||
: Math.max(showing.length, 1);
|
||||
const displayError = state.flash ? l10n.getString(state.flash.msgId) : error;
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => inputRef.current?.focus(), 50);
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!state.flash) return;
|
||||
const timer = setTimeout(() => dispatch({ type: 'clearFlash' }), 350);
|
||||
return () => clearTimeout(timer);
|
||||
}, [state.flash]);
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
const hasModifier = state.held.size > 0;
|
||||
|
||||
if (!hasModifier && e.key === 'Escape') {
|
||||
onCloseModal?.();
|
||||
return;
|
||||
}
|
||||
if (!hasModifier && (e.key === 'Backspace' || e.key === 'Delete')) {
|
||||
onUnbindModal?.();
|
||||
return;
|
||||
}
|
||||
if (!hasModifier && e.key === 'Enter') {
|
||||
onSubmitModal?.();
|
||||
return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (e.repeat) return;
|
||||
|
||||
const modifierName = modifierNameForKey(e.key);
|
||||
if (modifierName) {
|
||||
dispatch({
|
||||
type: 'keydown',
|
||||
code: e.code,
|
||||
keys: modifiersFromHeld(new Set(state.held).add(e.code)),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const key = resolveKey(e);
|
||||
if (!key) {
|
||||
dispatch({
|
||||
type: 'flash',
|
||||
slot: activeIndex,
|
||||
msgId: 'settings-keybinds-error-unsupported-key',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: 'keydown',
|
||||
code: e.code,
|
||||
keys: [...modifiersFromHeld(state.held), key],
|
||||
});
|
||||
};
|
||||
|
||||
const handleKeyUp = (e: React.KeyboardEvent) => {
|
||||
const wasRecording = state.held.size > 0;
|
||||
dispatch({ type: 'keyup', code: e.code });
|
||||
|
||||
if (!wasRecording) return;
|
||||
const stillHeld = new Set(state.held);
|
||||
stillHeld.delete(e.code);
|
||||
if (stillHeld.size === 0 && state.best) {
|
||||
onKeysChange(state.best);
|
||||
dispatch({ type: 'clear' });
|
||||
}
|
||||
};
|
||||
|
||||
const handleBlur = () => {
|
||||
setFocused(false);
|
||||
if (state.held.size > 0) dispatch({ type: 'clear' });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative w-full">
|
||||
<div
|
||||
className={classNames(
|
||||
'flex flex-col gap-4 p-4 rounded-2xl bg-background-70 transition-all relative z-10 shadow-lg border',
|
||||
displayError
|
||||
? 'border-status-critical'
|
||||
: focused
|
||||
? 'border-accent-background-30'
|
||||
: 'border-transparent'
|
||||
)}
|
||||
onClick={() => inputRef.current?.focus()}
|
||||
>
|
||||
<input
|
||||
className="absolute inset-0 opacity-0 cursor-pointer w-full h-full"
|
||||
ref={inputRef}
|
||||
data-nav-raw
|
||||
onFocus={() => setFocused(true)}
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
onKeyUp={handleKeyUp}
|
||||
/>
|
||||
<div className="flex flex-wrap gap-2 justify-center items-center">
|
||||
{Array.from({ length: slotCount }).map((_, i) => {
|
||||
const key = showing[i];
|
||||
const isActive = i === activeIndex && key == null;
|
||||
const isInvalid = state.flash?.slot === i;
|
||||
const variant = isInvalid
|
||||
? 'invalid'
|
||||
: isActive
|
||||
? 'active'
|
||||
: key != null
|
||||
? 'default'
|
||||
: 'empty';
|
||||
return (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<Kbd
|
||||
variant={variant}
|
||||
className="px-4 py-2 min-w-[54px] h-[48px]"
|
||||
>
|
||||
{key != null ? keybindLabel(key) : isActive ? '...' : ''}
|
||||
</Kbd>
|
||||
{i < slotCount - 1 && (
|
||||
<Typography variant="standard" bold textAlign="text-center">
|
||||
+
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="text-center">
|
||||
<Typography id="settings-keybinds-recorder-hint-recording" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{displayError && (
|
||||
<div className="absolute inset-x-0 top-full z-0 -mt-4 pt-6 pb-2 px-4 bg-background-80 rounded-b-2xl text-status-critical text-sm font-medium text-center">
|
||||
{displayError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -1,123 +0,0 @@
|
||||
import { BaseModal } from './BaseModal';
|
||||
import {
|
||||
Controller,
|
||||
Control,
|
||||
useFormContext,
|
||||
FieldValues,
|
||||
FieldPath,
|
||||
} from 'react-hook-form';
|
||||
import { KeybindRecorder } from './KeybindRecorder';
|
||||
import { isValidKeybind, keybindKey } from './keybind-keys';
|
||||
import { Kbd } from './Kbd';
|
||||
import { Typography } from './Typography';
|
||||
import { KeyboardIcon } from './icon/KeyboardIcon';
|
||||
import { useLocalization } from '@fluent/react';
|
||||
|
||||
function KeybindHint({ keyId, labelId }: { keyId: string; labelId: string }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Kbd id={keyId} className="px-2 py-2 leading-none" />
|
||||
<Typography variant="standard" id={labelId} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function KeybindRecorderModal<T extends FieldValues = FieldValues>({
|
||||
id,
|
||||
control,
|
||||
name,
|
||||
isVisisble,
|
||||
onClose,
|
||||
onUnbind,
|
||||
onSubmit,
|
||||
takenBindings,
|
||||
activatedError,
|
||||
}: {
|
||||
id?: string;
|
||||
control: Control<T>;
|
||||
name: FieldPath<T>;
|
||||
isVisisble: boolean;
|
||||
onClose: () => void;
|
||||
onUnbind: () => void;
|
||||
onSubmit: () => void;
|
||||
onReset?: () => void;
|
||||
takenBindings?: { name: string; binding: string[] }[];
|
||||
activatedError?: string | null;
|
||||
}) {
|
||||
const keybindlocalization = 'settings-keybinds_' + id;
|
||||
const { l10n } = useLocalization();
|
||||
const { handleSubmit } = useFormContext();
|
||||
|
||||
const handleModalSubmit = () => {
|
||||
handleSubmit(onSubmit)();
|
||||
};
|
||||
|
||||
const validateBinding = (value: string[]) => {
|
||||
if (!value || value.length === 0) return true;
|
||||
if (!isValidKeybind(value))
|
||||
return l10n.getString('settings-keybinds-error-add-modifier');
|
||||
const clash = (takenBindings ?? []).find(
|
||||
(t) => keybindKey(t.binding) === keybindKey(value)
|
||||
);
|
||||
return clash
|
||||
? l10n.getString('settings-keybinds-already-assigned', {
|
||||
name: clash.name,
|
||||
})
|
||||
: true;
|
||||
};
|
||||
|
||||
return (
|
||||
<BaseModal
|
||||
isOpen={isVisisble}
|
||||
onRequestClose={onClose}
|
||||
appendClasses="w-full max-w-md"
|
||||
>
|
||||
<div className="flex flex-col gap-6 w-full">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 bg-accent-background-40 flex justify-center items-center rounded-full fill-background-10 flex-shrink-0">
|
||||
<KeyboardIcon size={20} className="fill-background-10" />
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<Typography
|
||||
variant="standard"
|
||||
id="settings-keybinds-recorder-modal-title"
|
||||
/>
|
||||
<Typography variant="section-title" id={keybindlocalization} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Controller
|
||||
control={control}
|
||||
name={name}
|
||||
rules={{ validate: validateBinding }}
|
||||
render={({ field, fieldState }) => (
|
||||
<KeybindRecorder
|
||||
keys={field.value ?? []}
|
||||
onKeysChange={field.onChange}
|
||||
ref={field.ref}
|
||||
error={activatedError ?? fieldState.error?.message}
|
||||
onSubmitModal={handleModalSubmit}
|
||||
onUnbindModal={onUnbind}
|
||||
onCloseModal={onClose}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-center gap-x-6 gap-y-2 pt-4 border-t border-background-60">
|
||||
<KeybindHint
|
||||
keyId="settings-keybinds-recorder-modal-key-enter"
|
||||
labelId="settings-keybinds-recorder-modal-done-button"
|
||||
/>
|
||||
<KeybindHint
|
||||
keyId="settings-keybinds-recorder-modal-key-backspace"
|
||||
labelId="settings-keybinds-recorder-modal-unbind-button"
|
||||
/>
|
||||
<KeybindHint
|
||||
keyId="settings-keybinds-recorder-modal-key-escape"
|
||||
labelId="settings-keybinds-recorder-modal-cancel-button"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</BaseModal>
|
||||
);
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
@keyframes shake {
|
||||
0% {
|
||||
transform: translate(1px, 1px) rotate(0deg);
|
||||
}
|
||||
10% {
|
||||
transform: translate(-1px, -2px) rotate(-1deg);
|
||||
}
|
||||
20% {
|
||||
transform: translate(-3px, 0px) rotate(1deg);
|
||||
}
|
||||
30% {
|
||||
transform: translate(3px, 2px) rotate(0deg);
|
||||
}
|
||||
40% {
|
||||
transform: translate(1px, -1px) rotate(1deg);
|
||||
}
|
||||
50% {
|
||||
transform: translate(-1px, 2px) rotate(-1deg);
|
||||
}
|
||||
60% {
|
||||
transform: translate(-3px, 1px) rotate(0deg);
|
||||
}
|
||||
70% {
|
||||
transform: translate(3px, 1px) rotate(-1deg);
|
||||
}
|
||||
80% {
|
||||
transform: translate(-1px, -1px) rotate(1deg);
|
||||
}
|
||||
90% {
|
||||
transform: translate(1px, 2px) rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: translate(1px, -2px) rotate(-1deg);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-shake {
|
||||
animation: shake 0.35s ease-in-out;
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
import { Typography } from './Typography';
|
||||
import { Clickable } from './Clickable';
|
||||
import { Control, useWatch } from 'react-hook-form';
|
||||
import { KeybindForm } from '@/components/settings/pages/KeybindSettings';
|
||||
import { NumberSelector } from './NumberSelector';
|
||||
import { useLocaleConfig } from '@/i18n/config';
|
||||
import { Kbd } from './Kbd';
|
||||
import { keybindLabel } from './keybind-keys';
|
||||
import { RecordIcon } from './icon/RecordIcon';
|
||||
import { ResetIcon } from './icon/ResetIcon';
|
||||
import { Tooltip } from './Tooltip';
|
||||
import classNames from 'classnames';
|
||||
|
||||
function KeyBindKeyList({ keybind }: { keybind: string[] }) {
|
||||
if (keybind.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center gap-2 px-4 py-2 rounded-xl fill-background-10 border border-dashed border-background-50 bg-background-90 group-hover:border-accent-background-40 transition-all">
|
||||
<RecordIcon width={16} />
|
||||
<Typography id="settings-keybinds-click-to-record" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="group flex items-center justify-start md:justify-center gap-1.5 flex-wrap">
|
||||
{keybind.map((key, i) => (
|
||||
<div key={i} className="flex items-center gap-1.5">
|
||||
<Kbd className="px-2 md:px-4 py-2 min-w-[34px] md:min-w-[40px] group-hover:border-accent-background-40">
|
||||
{keybindLabel(key)}
|
||||
</Kbd>
|
||||
{i < keybind.length - 1 && (
|
||||
<Typography variant="standard" bold textAlign="text-center">
|
||||
+
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ResetButton({
|
||||
isModified,
|
||||
onClick,
|
||||
}: {
|
||||
isModified?: boolean;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Tooltip
|
||||
content={<Typography id="settings-keybinds-reset-single" />}
|
||||
preferedDirection="top"
|
||||
>
|
||||
<Clickable
|
||||
disabled={!isModified}
|
||||
className={classNames(
|
||||
'w-7 h-7 rounded-xl flex items-center justify-center transition-all',
|
||||
{
|
||||
'text-accent hover:bg-background-60 cursor-pointer opacity-100':
|
||||
isModified,
|
||||
'text-background-40 opacity-30 cursor-not-allowed': !isModified,
|
||||
}
|
||||
)}
|
||||
onClick={onClick}
|
||||
>
|
||||
<ResetIcon size={16} />
|
||||
</Clickable>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
export function KeybindsRow({
|
||||
id,
|
||||
control,
|
||||
index,
|
||||
openKeybindRecorderModal,
|
||||
onResetSingle,
|
||||
isModified,
|
||||
bindingEditable = true,
|
||||
}: {
|
||||
id?: string;
|
||||
control: Control<KeybindForm>;
|
||||
index: number;
|
||||
openKeybindRecorderModal?: (index: number) => void;
|
||||
onResetSingle: (index: number) => void;
|
||||
isModified?: boolean;
|
||||
bindingEditable?: boolean;
|
||||
}) {
|
||||
const binding =
|
||||
useWatch({
|
||||
control,
|
||||
name: `keybinds.${index}.binding`,
|
||||
}) ?? [];
|
||||
|
||||
const { currentLocales } = useLocaleConfig();
|
||||
const secondsFormat = new Intl.NumberFormat(currentLocales, {
|
||||
style: 'unit',
|
||||
unit: 'second',
|
||||
unitDisplay: 'narrow',
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
|
||||
return (
|
||||
<tr className="bg-background-80 flex flex-col md:table-row p-4 md:p-0 gap-3 md:gap-0 border-b border-background-60 md:border-b-0 relative">
|
||||
<td className="py-2 md:py-4 pl-0 md:pl-6 pr-0 md:pr-4 block md:table-cell align-middle">
|
||||
<div className="flex items-center justify-between md:justify-start gap-2.5">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="w-7 h-7 hidden md:flex items-center justify-center flex-shrink-0">
|
||||
<ResetButton
|
||||
isModified={isModified}
|
||||
onClick={() => onResetSingle(index)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center m-0 p-0 leading-none">
|
||||
<Typography
|
||||
id={`settings-keybinds_${id}`}
|
||||
variant="standard"
|
||||
bold
|
||||
whitespace="whitespace-nowrap"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="md:hidden">
|
||||
<ResetButton
|
||||
isModified={isModified}
|
||||
onClick={() => onResetSingle(index)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td className="py-2 md:py-4 px-0 md:px-4 block md:table-cell align-middle">
|
||||
<div className="flex justify-start md:justify-center items-center">
|
||||
{bindingEditable && openKeybindRecorderModal ? (
|
||||
<Tooltip
|
||||
content={<Typography id="settings-keybinds-change-shortcut" />}
|
||||
preferedDirection="top"
|
||||
>
|
||||
<Clickable
|
||||
className="cursor-pointer rounded-xl transition-all hover:scale-105 active:scale-95"
|
||||
onClick={() => openKeybindRecorderModal(index)}
|
||||
>
|
||||
<KeyBindKeyList keybind={binding} />
|
||||
</Clickable>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Typography
|
||||
variant="standard"
|
||||
textAlign="text-center"
|
||||
italic
|
||||
color="secondary"
|
||||
id="settings-keybinds-system-managed-hint"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td className="py-2 md:py-4 px-0 md:px-6 block md:table-cell align-middle">
|
||||
<div className="flex flex-col items-start md:items-end gap-1 pt-2 md:pt-0 justify-center">
|
||||
<span className="md:hidden">
|
||||
<Typography id="keybind_config-keybind_delay" />
|
||||
</span>
|
||||
<NumberSelector
|
||||
control={control}
|
||||
name={`keybinds.${index}.delay`}
|
||||
valueLabelFormat={(value) => secondsFormat.format(value)}
|
||||
min={0}
|
||||
max={10}
|
||||
step={0.2}
|
||||
/>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
|
||||
import { Clickable } from './Clickable';
|
||||
import { FieldCaption } from './FloatingLabel';
|
||||
import { Typography } from './Typography';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useLocaleConfig } from '@/i18n/config';
|
||||
import { stepKeys } from '@/utils/a11y';
|
||||
|
||||
export function NumberSelector<T extends FieldValues = FieldValues>({
|
||||
label,
|
||||
valueLabelFormat,
|
||||
control,
|
||||
name,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
doubleStep,
|
||||
disabled = false,
|
||||
showButtonWithNumber = false,
|
||||
}: {
|
||||
label?: string;
|
||||
valueLabelFormat?: (value: number) => string;
|
||||
control: Control<T>;
|
||||
name: FieldPath<T>;
|
||||
min: number;
|
||||
max: number;
|
||||
step: number | ((value: number, add: boolean) => number);
|
||||
doubleStep?: number;
|
||||
disabled?: boolean;
|
||||
showButtonWithNumber?: boolean;
|
||||
}) {
|
||||
const { currentLocales } = useLocaleConfig();
|
||||
|
||||
const stepFn =
|
||||
typeof step === 'function'
|
||||
? step
|
||||
: (value: number, add: boolean) =>
|
||||
+(add ? value + step : value - step).toFixed(2);
|
||||
|
||||
const doubleStepFn = useCallback(
|
||||
(value: number, add: boolean) =>
|
||||
doubleStep === undefined
|
||||
? 0
|
||||
: +(add ? value + doubleStep : value - doubleStep).toFixed(2),
|
||||
[doubleStep]
|
||||
);
|
||||
|
||||
const decimalFormat = useMemo(
|
||||
() =>
|
||||
new Intl.NumberFormat(currentLocales, {
|
||||
style: 'decimal',
|
||||
maximumFractionDigits: 2,
|
||||
signDisplay: 'exceptZero',
|
||||
}),
|
||||
[currentLocales]
|
||||
);
|
||||
|
||||
return (
|
||||
<Controller
|
||||
control={control}
|
||||
name={name}
|
||||
render={({ field: { onChange, value } }) => {
|
||||
const num = Number(value);
|
||||
const hasLabel = label !== undefined && label.length !== 0;
|
||||
const shown = valueLabelFormat ? valueLabelFormat(num) : num;
|
||||
|
||||
const clamp = (v: number) => Math.min(max, Math.max(min, v));
|
||||
const bump = (add: boolean, big = false) =>
|
||||
!disabled &&
|
||||
onChange(clamp(big ? doubleStepFn(num, add) : stepFn(num, add)));
|
||||
|
||||
const onKeyDown = stepKeys({
|
||||
value: num,
|
||||
min,
|
||||
max,
|
||||
step: stepFn,
|
||||
bigStep: doubleStep !== undefined ? doubleStepFn : undefined,
|
||||
onChange,
|
||||
disabled,
|
||||
});
|
||||
|
||||
// Flat full-height stepper segments hugging the box edges.
|
||||
const segment =
|
||||
'flex min-w-[3rem] shrink-0 items-center justify-center px-3 text-lg font-bold leading-none text-background-10 fill-background-10 transition-colors enabled:hover:bg-background-50 disabled:opacity-30';
|
||||
return (
|
||||
<div className="flex flex-col gap-1 w-full">
|
||||
{hasLabel && <FieldCaption>{label}</FieldCaption>}
|
||||
<div
|
||||
role="spinbutton"
|
||||
data-nav-edit
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
aria-label={label}
|
||||
aria-disabled={disabled || undefined}
|
||||
aria-valuenow={num}
|
||||
aria-valuemin={min}
|
||||
aria-valuemax={max}
|
||||
aria-valuetext={typeof shown === 'string' ? shown : undefined}
|
||||
onKeyDown={onKeyDown}
|
||||
className="relative flex items-stretch min-h-[48px] overflow-hidden rounded-md bg-background-60"
|
||||
>
|
||||
{doubleStep !== undefined && (
|
||||
<Clickable
|
||||
tabIndex={-1}
|
||||
className={segment}
|
||||
onClick={() => bump(false, true)}
|
||||
disabled={doubleStepFn(num, false) < min || disabled}
|
||||
>
|
||||
{showButtonWithNumber
|
||||
? decimalFormat.format(-doubleStep)
|
||||
: '--'}
|
||||
</Clickable>
|
||||
)}
|
||||
<Clickable
|
||||
tabIndex={-1}
|
||||
className={segment}
|
||||
onClick={() => bump(false)}
|
||||
disabled={stepFn(num, false) < min || disabled}
|
||||
>
|
||||
−
|
||||
</Clickable>
|
||||
<div className="flex flex-grow items-center justify-center px-2 select-none">
|
||||
<Typography variant="standard">{shown}</Typography>
|
||||
</div>
|
||||
<Clickable
|
||||
tabIndex={-1}
|
||||
className={segment}
|
||||
onClick={() => bump(true)}
|
||||
disabled={stepFn(num, true) > max || disabled}
|
||||
>
|
||||
+
|
||||
</Clickable>
|
||||
{doubleStep !== undefined && (
|
||||
<Clickable
|
||||
tabIndex={-1}
|
||||
className={segment}
|
||||
onClick={() => bump(true, true)}
|
||||
disabled={doubleStepFn(num, true) > max || disabled}
|
||||
>
|
||||
{showButtonWithNumber
|
||||
? decimalFormat.format(doubleStep)
|
||||
: '++'}
|
||||
</Clickable>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import {
|
||||
CSSProperties,
|
||||
ReactNode,
|
||||
useEffect,
|
||||
useId,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { useBreakpoint } from '@/hooks/breakpoint';
|
||||
import { Clickable } from './Clickable';
|
||||
import { Drawer } from './Drawer';
|
||||
import './Dropdown.scss';
|
||||
|
||||
export interface PopoverTriggerProps {
|
||||
'aria-expanded': boolean;
|
||||
'aria-controls': string;
|
||||
popovertarget?: string;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
export interface PopoverMenuState {
|
||||
open: boolean;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A button that opens a menu anchored below it. On phones it opens as a
|
||||
* bottom drawer instead when `drawerTitle` is set.
|
||||
*/
|
||||
export function PopoverMenu({
|
||||
trigger,
|
||||
children,
|
||||
drawerTitle,
|
||||
width = 'w-[260px]',
|
||||
anchorClassName,
|
||||
}: {
|
||||
trigger: (props: PopoverTriggerProps, open: boolean) => ReactNode;
|
||||
children: ReactNode | ((state: PopoverMenuState) => ReactNode);
|
||||
drawerTitle?: ReactNode;
|
||||
width?: string;
|
||||
anchorClassName?: string;
|
||||
}) {
|
||||
const { isMobile } = useBreakpoint('mobile');
|
||||
const useDrawer = isMobile && drawerTitle !== undefined;
|
||||
const [open, setOpen] = useState(false);
|
||||
const popoverRef = useRef<HTMLDivElement>(null);
|
||||
const id = `popover-menu-${useId().replace(/:/g, '')}`;
|
||||
const anchorName = `--${id}`;
|
||||
|
||||
useEffect(() => {
|
||||
const el = popoverRef.current;
|
||||
if (!el) return;
|
||||
el.setAttribute('popover', 'auto');
|
||||
const onToggle = (e: Event) =>
|
||||
setOpen((e as ToggleEvent).newState === 'open');
|
||||
el.addEventListener('toggle', onToggle);
|
||||
return () => el.removeEventListener('toggle', onToggle);
|
||||
}, [useDrawer]);
|
||||
|
||||
const close = () => {
|
||||
popoverRef.current?.hidePopover();
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const content =
|
||||
typeof children === 'function' ? children({ open, close }) : children;
|
||||
|
||||
const triggerProps: PopoverTriggerProps = useDrawer
|
||||
? {
|
||||
'aria-expanded': open,
|
||||
'aria-controls': id,
|
||||
onClick: () => setOpen(true),
|
||||
}
|
||||
: { 'aria-expanded': open, 'aria-controls': id, popovertarget: id };
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={classNames('flex', anchorClassName)}
|
||||
style={{ anchorName } as CSSProperties}
|
||||
>
|
||||
{trigger(triggerProps, open)}
|
||||
</div>
|
||||
{useDrawer ? (
|
||||
<Drawer isOpen={open} onClose={close} title={drawerTitle}>
|
||||
<div id={id}>{content}</div>
|
||||
</Drawer>
|
||||
) : (
|
||||
<div
|
||||
ref={popoverRef}
|
||||
id={id}
|
||||
className={classNames(
|
||||
'dropdown-popover flex-col fixed inset-auto m-0 mt-1 p-0 overflow-hidden rounded-lg border border-background-50 bg-background-60 shadow-lg',
|
||||
width
|
||||
)}
|
||||
style={
|
||||
{
|
||||
positionAnchor: anchorName,
|
||||
positionArea: 'bottom span-left',
|
||||
positionTryFallbacks: 'flip-inline',
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function PopoverMenuItem({
|
||||
onClick,
|
||||
to,
|
||||
current,
|
||||
description,
|
||||
className,
|
||||
children,
|
||||
}: {
|
||||
onClick?: () => void;
|
||||
to?: string;
|
||||
current?: boolean;
|
||||
description?: ReactNode;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const classes = classNames(
|
||||
'flex w-full px-4 py-2 mobile:py-3 hover:bg-background-50',
|
||||
description ? 'flex-col items-start' : 'items-center gap-2',
|
||||
current && 'bg-background-50/50',
|
||||
className
|
||||
);
|
||||
|
||||
if (to !== undefined) {
|
||||
return (
|
||||
<Clickable to={to} onClick={onClick} className={classes}>
|
||||
{children}
|
||||
{description}
|
||||
</Clickable>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Clickable
|
||||
current={current || undefined}
|
||||
onClick={onClick}
|
||||
className={classes}
|
||||
>
|
||||
{children}
|
||||
{description}
|
||||
</Clickable>
|
||||
);
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
|
||||
import { stepKeys } from '@/utils/a11y';
|
||||
|
||||
export function Range<T extends FieldValues = FieldValues>({
|
||||
control,
|
||||
name,
|
||||
values,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
// input props
|
||||
...props
|
||||
}: {
|
||||
control: Control<T>;
|
||||
name: FieldPath<T>;
|
||||
max: number;
|
||||
min: number;
|
||||
step: number;
|
||||
values: { value: number; label: string; defaultValue?: boolean }[];
|
||||
} & React.HTMLProps<HTMLInputElement>) {
|
||||
return (
|
||||
<Controller
|
||||
control={control}
|
||||
name={name}
|
||||
render={({ field: { onChange, ref, name, value } }) => {
|
||||
const emit = (v: number) =>
|
||||
onChange(
|
||||
Math.min(
|
||||
max,
|
||||
Math.max(min, min + Math.round((v - min) / step) * step)
|
||||
)
|
||||
);
|
||||
|
||||
const onKeyDown = stepKeys({
|
||||
value: Number(value),
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
onChange: emit,
|
||||
});
|
||||
return (
|
||||
<label className="text-standard w-full text-center flex items-center flex-col">
|
||||
<input
|
||||
type="range"
|
||||
className="text-background-10 border-accent-background-30"
|
||||
style={{
|
||||
width: 'calc(88% - 0.5vw)',
|
||||
}}
|
||||
{...props}
|
||||
data-nav-edit
|
||||
name={name}
|
||||
ref={ref}
|
||||
value={value}
|
||||
onChange={(e) => emit(e.target.valueAsNumber)}
|
||||
onKeyDown={onKeyDown}
|
||||
list={`${name}-datalist`}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
/>
|
||||
<datalist id={`${name}-datalist`} className="">
|
||||
{values.map(({ value }, i) => (
|
||||
<option key={i}>{value}</option>
|
||||
))}
|
||||
</datalist>
|
||||
<div className="w-full flex flex-nowrap overflow-clip">
|
||||
{Array((max - min) / step + 1)
|
||||
.fill(0)
|
||||
.map((_v, i) => {
|
||||
const value = values.find(
|
||||
({ value }) => i * step + min === value
|
||||
);
|
||||
return (
|
||||
<span
|
||||
key={i}
|
||||
className={classNames(
|
||||
'flex-1',
|
||||
value?.defaultValue && 'text-status-success'
|
||||
)}
|
||||
>
|
||||
{value?.label}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode } from 'react';
|
||||
import { Clickable } from './Clickable';
|
||||
import { Typography } from './Typography';
|
||||
|
||||
export interface SegmentedOption<T> {
|
||||
value: T;
|
||||
labelId?: string;
|
||||
vars?: Record<string, string | number>;
|
||||
label?: ReactNode;
|
||||
dotClass?: string;
|
||||
}
|
||||
|
||||
const variantClasses = {
|
||||
primary: { track: 'bg-background-80', active: 'bg-accent-background-30' },
|
||||
secondary: { track: 'bg-background-80', active: 'bg-background-60' },
|
||||
tertiary: { track: 'bg-background-70', active: 'bg-accent-background-30' },
|
||||
};
|
||||
|
||||
export function SegmentedControl<T extends string | number>({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
variant = 'primary',
|
||||
className,
|
||||
}: {
|
||||
value: T;
|
||||
onChange: (value: T) => void;
|
||||
options: SegmentedOption<T>[];
|
||||
variant?: keyof typeof variantClasses;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'flex flex-wrap items-stretch gap-0.5 p-1 rounded-md min-h-[48px] min-w-0',
|
||||
variantClasses[variant].track,
|
||||
className
|
||||
)}
|
||||
>
|
||||
{options.map((option) => {
|
||||
const active = option.value === value;
|
||||
return (
|
||||
<Clickable
|
||||
key={String(option.value)}
|
||||
pressed={active}
|
||||
onClick={() => onChange(option.value)}
|
||||
className={classNames(
|
||||
'flex items-center gap-1.5 px-3.5 py-1.5 rounded min-w-0 transition-colors',
|
||||
active
|
||||
? classNames(
|
||||
variantClasses[variant].active,
|
||||
'text-background-10'
|
||||
)
|
||||
: 'text-background-20 hover:text-background-10'
|
||||
)}
|
||||
>
|
||||
{option.dotClass && (
|
||||
<span
|
||||
className={classNames(
|
||||
'w-2 h-2 rounded-full shrink-0',
|
||||
option.dotClass
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{option.labelId ? (
|
||||
<Typography
|
||||
tag="span"
|
||||
bold
|
||||
color="text-inherit"
|
||||
id={option.labelId}
|
||||
vars={option.vars}
|
||||
/>
|
||||
) : (
|
||||
<span className="text-standard-bold min-w-0">{option.label}</span>
|
||||
)}
|
||||
</Clickable>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode } from 'react';
|
||||
import { Typography } from './Typography';
|
||||
|
||||
export type StatusVariant =
|
||||
| 'neutral'
|
||||
| 'success'
|
||||
| 'special'
|
||||
| 'warning'
|
||||
| 'critical';
|
||||
|
||||
const VARIANT_CLASSES: Record<StatusVariant, string> = {
|
||||
neutral: 'bg-background-50',
|
||||
success: 'bg-status-success',
|
||||
special: 'bg-status-special',
|
||||
warning: 'bg-status-warning',
|
||||
critical: 'bg-status-critical',
|
||||
};
|
||||
|
||||
export function StatusBadge({
|
||||
variant,
|
||||
id,
|
||||
}: {
|
||||
variant: StatusVariant;
|
||||
id: string;
|
||||
}) {
|
||||
return (
|
||||
<span className="rounded-md px-2 py-1 bg-background-70 flex gap-2 items-center">
|
||||
<div
|
||||
className={classNames('h-2 w-2 rounded-full', VARIANT_CLASSES[variant])}
|
||||
/>
|
||||
<Typography id={id} bold whitespace="whitespace-nowrap" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatusRow({
|
||||
label,
|
||||
badge,
|
||||
children,
|
||||
}: {
|
||||
label: ReactNode;
|
||||
badge: ReactNode;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1 py-2">
|
||||
<div className="flex items-center justify-between gap-2 min-w-0">
|
||||
<div className="min-w-0">{label}</div>
|
||||
{badge}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode, Ref } from 'react';
|
||||
import { Clickable } from './Clickable';
|
||||
import { Typography } from './Typography';
|
||||
import { CheckIcon } from './icon/CheckIcon';
|
||||
import { ArrowDownIcon } from './icon/ArrowIcons';
|
||||
|
||||
export type TimelineState = 'done' | 'skipped' | 'current' | 'todo';
|
||||
|
||||
const BADGE_SIZE = { md: 'h-8 w-8', sm: 'h-[25px] w-[25px]' };
|
||||
|
||||
function TimelineBadge({
|
||||
state,
|
||||
number,
|
||||
size,
|
||||
dotClassName,
|
||||
}: {
|
||||
state: TimelineState;
|
||||
number?: number;
|
||||
size: keyof typeof BADGE_SIZE;
|
||||
dotClassName?: string;
|
||||
}) {
|
||||
const numbered = number !== undefined;
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'flex shrink-0 items-center justify-center rounded-full fill-background-10',
|
||||
BADGE_SIZE[size],
|
||||
state === 'done' && 'bg-accent-background-20',
|
||||
state === 'skipped' && 'bg-background-50 fill-background-30',
|
||||
state === 'current' &&
|
||||
(numbered ? 'bg-accent-background-40' : 'bg-background-50'),
|
||||
state === 'todo' &&
|
||||
(numbered ? 'border-2 border-background-50' : 'bg-background-50')
|
||||
)}
|
||||
>
|
||||
{state === 'done' || state === 'skipped' ? (
|
||||
<CheckIcon size={size === 'md' ? 12 : 10} />
|
||||
) : numbered ? (
|
||||
<Typography
|
||||
variant="section-title"
|
||||
bold
|
||||
color={state === 'todo' ? 'secondary' : 'primary'}
|
||||
>
|
||||
{number}
|
||||
</Typography>
|
||||
) : (
|
||||
<div
|
||||
className={classNames(
|
||||
'h-[12px] w-[12px] rounded-full',
|
||||
dotClassName ??
|
||||
(state === 'current'
|
||||
? 'bg-accent-background-10 animate-pulse animate-low-priority brightness-75'
|
||||
: 'bg-background-40')
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Timeline({ children }: { children: ReactNode }) {
|
||||
return <ol className="flex w-full flex-col">{children}</ol>;
|
||||
}
|
||||
|
||||
export function TimelineItem({
|
||||
state,
|
||||
number,
|
||||
title,
|
||||
size = 'md',
|
||||
last = false,
|
||||
dotClassName,
|
||||
expanded,
|
||||
expandableArrow = true,
|
||||
onToggle,
|
||||
disabled,
|
||||
className,
|
||||
itemRef,
|
||||
children,
|
||||
}: {
|
||||
state: TimelineState;
|
||||
number?: number;
|
||||
title: ReactNode;
|
||||
size?: keyof typeof BADGE_SIZE;
|
||||
last?: boolean;
|
||||
dotClassName?: string;
|
||||
expanded?: boolean;
|
||||
expandableArrow?: boolean;
|
||||
onToggle?: () => void;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
itemRef?: Ref<HTMLLIElement>;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
const titleClasses = classNames(
|
||||
'flex w-full items-center justify-between gap-2 text-left text-section-title',
|
||||
// Only numbered steps dim the ones still to come
|
||||
state === 'todo' && number !== undefined && 'text-background-30'
|
||||
);
|
||||
|
||||
return (
|
||||
<li
|
||||
ref={itemRef}
|
||||
aria-current={state === 'current' ? 'step' : undefined}
|
||||
className={classNames('flex gap-3', className)}
|
||||
>
|
||||
<div className="flex flex-col items-center">
|
||||
<TimelineBadge
|
||||
state={state}
|
||||
number={number}
|
||||
size={size}
|
||||
dotClassName={dotClassName}
|
||||
/>
|
||||
{!last && (
|
||||
<div
|
||||
className={classNames(
|
||||
'w-0.5 flex-1 rounded-full',
|
||||
size === 'md' ? 'my-1' : 'my-0.5',
|
||||
state === 'done' ? 'bg-accent-background-20' : 'bg-background-50'
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
'flex min-w-0 flex-1 flex-col',
|
||||
size === 'md' ? 'pt-1' : 'pt-px',
|
||||
!last && (size === 'md' ? 'pb-6' : 'pb-3')
|
||||
)}
|
||||
>
|
||||
{onToggle ? (
|
||||
<Clickable
|
||||
disabled={disabled}
|
||||
expanded={disabled ? undefined : expanded}
|
||||
className={classNames(
|
||||
titleClasses,
|
||||
!disabled && 'group cursor-pointer hover:text-background-20'
|
||||
)}
|
||||
onClick={onToggle}
|
||||
>
|
||||
{title}
|
||||
{expandableArrow && !disabled && (
|
||||
<div className="fill-background-30 group-hover:scale-125 group-hover:fill-background-20 transition-transform">
|
||||
<ArrowDownIcon size={20} />
|
||||
</div>
|
||||
)}
|
||||
</Clickable>
|
||||
) : (
|
||||
<div className={titleClasses}>{title}</div>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import { Clickable } from './Clickable';
|
||||
import { ReactNode } from 'react';
|
||||
import { Typography } from './Typography';
|
||||
|
||||
export function TogglePill({
|
||||
compact,
|
||||
onClick,
|
||||
pressed,
|
||||
label,
|
||||
value,
|
||||
children,
|
||||
}: {
|
||||
compact?: boolean;
|
||||
onClick?: () => void;
|
||||
pressed?: boolean;
|
||||
label?: string;
|
||||
value?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const className = classNames(
|
||||
'flex items-center gap-1 bg-background-80 rounded-full w-fit',
|
||||
onClick && 'cursor-pointer',
|
||||
compact ? 'p-0.5' : 'p-1'
|
||||
);
|
||||
|
||||
if (!onClick) return <div className={className}>{children}</div>;
|
||||
|
||||
const name = label && value ? `${label}: ${value}` : label;
|
||||
|
||||
return (
|
||||
<Clickable
|
||||
onClick={onClick}
|
||||
pressed={pressed}
|
||||
label={name}
|
||||
className={className}
|
||||
>
|
||||
{children}
|
||||
</Clickable>
|
||||
);
|
||||
}
|
||||
|
||||
export function TogglePillOption({
|
||||
compact,
|
||||
dotClass,
|
||||
labelId,
|
||||
active,
|
||||
onClick,
|
||||
}: {
|
||||
compact?: boolean;
|
||||
dotClass: string;
|
||||
labelId: string;
|
||||
active?: boolean;
|
||||
onClick?: () => void;
|
||||
}) {
|
||||
const className = classNames(
|
||||
'flex items-center rounded-full',
|
||||
compact ? 'gap-1.5 px-2 py-0.5' : 'gap-2 px-3 py-1',
|
||||
onClick && 'cursor-pointer',
|
||||
active === true && 'bg-background-60',
|
||||
active === false && 'opacity-50'
|
||||
);
|
||||
|
||||
const content = (
|
||||
<>
|
||||
<span
|
||||
className={classNames(
|
||||
'w-2.5 h-2.5 rounded-full bg-background-10 outline outline-4',
|
||||
dotClass
|
||||
)}
|
||||
/>
|
||||
<Typography bold id={labelId} />
|
||||
</>
|
||||
);
|
||||
|
||||
if (!onClick) return <div className={className}>{content}</div>;
|
||||
|
||||
return (
|
||||
<Clickable onClick={onClick} pressed={active} className={className}>
|
||||
{content}
|
||||
</Clickable>
|
||||
);
|
||||
}
|
||||
@@ -1,372 +0,0 @@
|
||||
import classNames from 'classnames';
|
||||
import {
|
||||
CSSProperties,
|
||||
ReactNode,
|
||||
useRef,
|
||||
useState,
|
||||
ReactElement,
|
||||
useLayoutEffect,
|
||||
MutableRefObject,
|
||||
createElement,
|
||||
useEffect,
|
||||
useId,
|
||||
} from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Typography } from './Typography';
|
||||
import { Drawer } from './Drawer';
|
||||
import { focusVisible } from '@/utils/focus-nav';
|
||||
|
||||
export type Direction = 'top' | 'left' | 'right' | 'bottom';
|
||||
interface TooltipProps {
|
||||
content: ReactNode;
|
||||
children: ReactElement;
|
||||
preferedDirection: Direction;
|
||||
blockedDirections?: Direction[];
|
||||
mode?: 'corner' | 'center';
|
||||
variant?: 'auto' | 'drawer' | 'floating';
|
||||
disabled?: boolean;
|
||||
tag?: string;
|
||||
spacing?: number;
|
||||
bindTo?: string;
|
||||
}
|
||||
|
||||
type PopoverElement = HTMLDivElement & {
|
||||
showPopover?: () => void;
|
||||
hidePopover?: () => void;
|
||||
};
|
||||
|
||||
const getPositionArea = (
|
||||
preferedDirection: TooltipProps['preferedDirection'],
|
||||
mode: TooltipProps['mode']
|
||||
) => {
|
||||
if (mode === 'corner') {
|
||||
switch (preferedDirection) {
|
||||
case 'top':
|
||||
return 'top span-right';
|
||||
case 'bottom':
|
||||
return 'bottom span-right';
|
||||
case 'left':
|
||||
return 'span-bottom left';
|
||||
case 'right':
|
||||
return 'span-bottom right';
|
||||
}
|
||||
}
|
||||
|
||||
switch (preferedDirection) {
|
||||
case 'top':
|
||||
return 'top center';
|
||||
case 'bottom':
|
||||
return 'bottom center';
|
||||
case 'left':
|
||||
return 'center left';
|
||||
case 'right':
|
||||
return 'center right';
|
||||
}
|
||||
};
|
||||
|
||||
const getPositionTryFallbacks = (
|
||||
preferedDirection: TooltipProps['preferedDirection'],
|
||||
blockedDirections: Direction[]
|
||||
) => {
|
||||
const oppositeDirection: Record<Direction, Direction> = {
|
||||
top: 'bottom',
|
||||
bottom: 'top',
|
||||
left: 'right',
|
||||
right: 'left',
|
||||
};
|
||||
|
||||
if (blockedDirections.includes(oppositeDirection[preferedDirection])) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return preferedDirection === 'top' || preferedDirection === 'bottom'
|
||||
? 'flip-block'
|
||||
: 'flip-inline';
|
||||
};
|
||||
|
||||
const getSpacingStyle = (
|
||||
preferedDirection: TooltipProps['preferedDirection'],
|
||||
spacing: number
|
||||
): CSSProperties => {
|
||||
switch (preferedDirection) {
|
||||
case 'top':
|
||||
return { marginBottom: spacing };
|
||||
case 'bottom':
|
||||
return { marginTop: spacing };
|
||||
case 'left':
|
||||
return { marginRight: spacing };
|
||||
case 'right':
|
||||
return { marginLeft: spacing };
|
||||
}
|
||||
};
|
||||
|
||||
export function FloatingTooltip({
|
||||
childRef,
|
||||
preferedDirection,
|
||||
blockedDirections = [],
|
||||
mode,
|
||||
children,
|
||||
spacing,
|
||||
}: {
|
||||
childRef: MutableRefObject<HTMLElement | null>;
|
||||
children: ReactNode;
|
||||
} & Pick<
|
||||
TooltipProps,
|
||||
'mode' | 'preferedDirection' | 'blockedDirections' | 'spacing'
|
||||
>) {
|
||||
const anchorName = `--tooltip-anchor-${useId().replace(/:/g, '')}`;
|
||||
const tooltipRef = useRef<PopoverElement | null>(null);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (childRef.current && childRef.current.children[0]) {
|
||||
const elem = childRef.current.children[0] as HTMLElement;
|
||||
elem.style.setProperty('anchor-name', anchorName);
|
||||
|
||||
const open = () => setIsOpen(true);
|
||||
const close = () => setIsOpen(false);
|
||||
// Focus only shows the tooltip when the focus is one a user should see
|
||||
// marked. A click focuses the control too, and so does a closing modal
|
||||
// handing focus back to the control that opened it.
|
||||
const focused = () => {
|
||||
if (focusVisible(elem)) setIsOpen(true);
|
||||
};
|
||||
|
||||
elem.addEventListener('mouseenter', open);
|
||||
elem.addEventListener('mouseleave', close);
|
||||
elem.addEventListener('focus', focused);
|
||||
elem.addEventListener('blur', close);
|
||||
|
||||
return () => {
|
||||
elem.style.removeProperty('anchor-name');
|
||||
elem.removeEventListener('mouseenter', open);
|
||||
elem.removeEventListener('mouseleave', close);
|
||||
elem.removeEventListener('focus', focused);
|
||||
elem.removeEventListener('blur', close);
|
||||
};
|
||||
}
|
||||
}, [anchorName, childRef]);
|
||||
|
||||
useEffect(() => {
|
||||
const close = () => setIsOpen(false);
|
||||
window.addEventListener('resize', close);
|
||||
window.addEventListener('scroll', close, true);
|
||||
return () => {
|
||||
window.removeEventListener('resize', close);
|
||||
window.removeEventListener('scroll', close, true);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = tooltipRef.current;
|
||||
if (!el?.showPopover) return;
|
||||
|
||||
try {
|
||||
const isOpenNow = el.matches(':popover-open');
|
||||
|
||||
if (isOpen && !isOpenNow) {
|
||||
el.showPopover();
|
||||
} else if (!isOpen && isOpenNow) {
|
||||
el.hidePopover?.();
|
||||
}
|
||||
} catch {
|
||||
setIsOpen(false);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-auto m-0 border-0 bg-transparent p-0 outline-none backdrop:bg-transparent pointer-events-none"
|
||||
ref={tooltipRef}
|
||||
{...({ popover: 'manual' } as any)}
|
||||
style={
|
||||
{
|
||||
positionAnchor: anchorName,
|
||||
positionArea: getPositionArea(preferedDirection, mode),
|
||||
positionTryFallbacks: getPositionTryFallbacks(
|
||||
preferedDirection,
|
||||
blockedDirections
|
||||
),
|
||||
width: 'max-content',
|
||||
maxWidth: 'calc(100vw - 20px)',
|
||||
...getSpacingStyle(preferedDirection, spacing ?? 20),
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
<div className="bg-background-90 rounded-md p-2 text-background-10 overflow-auto">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const TOOLTIP_DELAY = 500;
|
||||
|
||||
export function DrawerTooltip({
|
||||
children,
|
||||
childRef,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
childRef: MutableRefObject<HTMLElement | null>;
|
||||
}) {
|
||||
const touchTimestamp = useRef<number>(0);
|
||||
const touchTimeout = useRef<number>(0);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
const touchStart = () => {
|
||||
if (childRef.current && childRef.current.children[0]) {
|
||||
touchTimestamp.current = Date.now();
|
||||
const elem = childRef.current.children[0] as HTMLElement;
|
||||
elem.classList.add(classNames('transition-all'));
|
||||
elem.classList.add(classNames('animate-pulse'));
|
||||
elem.classList.add(classNames('scale-[110%]'));
|
||||
elem.classList.add(classNames('duration-500'));
|
||||
if (elem.hasAttribute('disabled')) {
|
||||
open();
|
||||
} else {
|
||||
touchTimeout.current = setTimeout(() => {
|
||||
open();
|
||||
}, TOOLTIP_DELAY) as unknown as number;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const clearEffect = () => {
|
||||
if (childRef.current && childRef.current.children[0]) {
|
||||
const elem = childRef.current.children[0] as HTMLElement;
|
||||
elem.classList.remove(classNames('animate-pulse'));
|
||||
elem.classList.remove(classNames('scale-[110%]'));
|
||||
elem.classList.remove(classNames('duration-500'));
|
||||
}
|
||||
};
|
||||
|
||||
const touchEnd = (e: MouseEvent | TouchEvent) => {
|
||||
if (
|
||||
e.currentTarget instanceof HTMLButtonElement &&
|
||||
e.currentTarget.hasAttribute('disabled')
|
||||
) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (Date.now() - touchTimestamp.current < TOOLTIP_DELAY) {
|
||||
clearTimeout(touchTimeout.current);
|
||||
close();
|
||||
}
|
||||
};
|
||||
|
||||
const scroll = () => {
|
||||
close();
|
||||
};
|
||||
|
||||
const open = () => {
|
||||
if (isOpen) return;
|
||||
clearEffect();
|
||||
setIsOpen(true);
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (childRef.current && childRef.current.children[0]) {
|
||||
const elem = childRef.current.children[0] as HTMLElement;
|
||||
|
||||
elem.addEventListener('scroll', scroll);
|
||||
|
||||
elem.addEventListener('touchstart', touchStart);
|
||||
elem.addEventListener('touchend', touchEnd);
|
||||
elem.addEventListener('touchcancel', touchEnd);
|
||||
|
||||
return () => {
|
||||
elem.removeEventListener('scroll', scroll);
|
||||
|
||||
elem.removeEventListener('touchstart', touchStart);
|
||||
elem.removeEventListener('touchend', touchEnd);
|
||||
elem.removeEventListener('touchcancel', touchEnd);
|
||||
clearTimeout(touchTimeout.current);
|
||||
};
|
||||
}
|
||||
}, []);
|
||||
// FIXME: Completely broken not sure why. Will be solved when tooltips on mobile actually work
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
isOpen={isOpen}
|
||||
onClose={close}
|
||||
title={
|
||||
<Typography variant="section-title" textAlign="text-center">
|
||||
Pro tip
|
||||
</Typography>
|
||||
}
|
||||
>
|
||||
<div className="p-4">{children}</div>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
export function Tooltip({
|
||||
content,
|
||||
children,
|
||||
preferedDirection,
|
||||
blockedDirections = [],
|
||||
mode = 'center',
|
||||
variant = 'auto',
|
||||
disabled = false,
|
||||
tag = 'div',
|
||||
bindTo,
|
||||
spacing = 10,
|
||||
}: TooltipProps) {
|
||||
const childRef = useRef<HTMLElement | null>(null);
|
||||
const isAndroid = window.__ANDROID__?.isThere();
|
||||
|
||||
if (bindTo) {
|
||||
childRef.current = document.querySelector(bindTo);
|
||||
}
|
||||
|
||||
let portal = null;
|
||||
if (variant === 'auto') {
|
||||
portal = isAndroid ? (
|
||||
<DrawerTooltip childRef={childRef}>{content}</DrawerTooltip>
|
||||
) : (
|
||||
<FloatingTooltip
|
||||
preferedDirection={preferedDirection}
|
||||
blockedDirections={blockedDirections}
|
||||
mode={mode}
|
||||
childRef={childRef}
|
||||
spacing={spacing}
|
||||
>
|
||||
{content}
|
||||
</FloatingTooltip>
|
||||
);
|
||||
}
|
||||
|
||||
if (variant === 'drawer')
|
||||
portal = <DrawerTooltip childRef={childRef}>{content}</DrawerTooltip>;
|
||||
|
||||
if (variant === 'floating')
|
||||
portal = (
|
||||
<FloatingTooltip
|
||||
blockedDirections={blockedDirections}
|
||||
preferedDirection={preferedDirection}
|
||||
mode={mode}
|
||||
childRef={childRef}
|
||||
spacing={spacing}
|
||||
>
|
||||
{content}
|
||||
</FloatingTooltip>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{bindTo
|
||||
? children
|
||||
: createElement(
|
||||
tag,
|
||||
{ className: 'contents', ref: childRef },
|
||||
children
|
||||
)}
|
||||
{!disabled && createPortal(portal, document.body)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
import { ReactNode, useEffect, useRef } from 'react';
|
||||
|
||||
export const TOOLTIP_OFFSET = 10;
|
||||
const MAX_TOOLTIP_HEIGHT = 360;
|
||||
|
||||
export function ChartPopover({
|
||||
clientPos,
|
||||
width,
|
||||
estimatedHeight,
|
||||
children,
|
||||
}: {
|
||||
clientPos: { x: number; y: number } | null;
|
||||
width: number;
|
||||
estimatedHeight: number;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const popoverRef = useRef<HTMLDivElement | null>(null);
|
||||
const active = clientPos != null;
|
||||
|
||||
useEffect(() => {
|
||||
const el = popoverRef.current as
|
||||
| (HTMLDivElement & {
|
||||
showPopover?: () => void;
|
||||
hidePopover?: () => void;
|
||||
})
|
||||
| null;
|
||||
if (!el?.showPopover) return;
|
||||
|
||||
try {
|
||||
const isOpenNow = el.matches(':popover-open');
|
||||
|
||||
if (active && !isOpenNow) {
|
||||
el.showPopover();
|
||||
} else if (!active && isOpenNow) {
|
||||
el.hidePopover?.();
|
||||
}
|
||||
} catch {
|
||||
// Safe fallback if popover API fails or is unsupported
|
||||
}
|
||||
}, [active]);
|
||||
|
||||
const height = Math.min(MAX_TOOLTIP_HEIGHT, estimatedHeight);
|
||||
|
||||
const clampedX = clientPos
|
||||
? Math.max(10, Math.min(clientPos.x, window.innerWidth - width - 10))
|
||||
: -9999;
|
||||
const clampedY = clientPos
|
||||
? Math.max(10, Math.min(clientPos.y, window.innerHeight - height - 10))
|
||||
: -9999;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={popoverRef}
|
||||
{...({ popover: 'manual' } as any)}
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: `${clampedX}px`,
|
||||
top: `${clampedY}px`,
|
||||
margin: 0,
|
||||
inset: 'unset',
|
||||
}}
|
||||
className="border-0 bg-transparent p-0 outline-none backdrop:bg-transparent pointer-events-none"
|
||||
>
|
||||
{active && (
|
||||
<div
|
||||
className="bg-background-90/95 border border-background-10/10 rounded-lg px-3 py-2 shadow-2xl max-h-[360px] overflow-y-auto text-background-10"
|
||||
style={{ width }}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,359 +0,0 @@
|
||||
import { memo, ReactNode, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
drawBand,
|
||||
drawDashedPath,
|
||||
drawLine,
|
||||
drawSeries,
|
||||
} from '@/hooks/chart-drawing';
|
||||
import { ChartPopover, TOOLTIP_OFFSET } from './ChartPopover';
|
||||
import {
|
||||
flipTooltipLeft,
|
||||
niceTicks,
|
||||
relativeTimeTick,
|
||||
screenXToTimeSec,
|
||||
timeSecToScreenX,
|
||||
} from '@/hooks/time-axis';
|
||||
import { ChartSource } from '@/hooks/time-series';
|
||||
|
||||
const DEFAULT_LEFT_AXIS_WIDTH = 48;
|
||||
const RIGHT_AXIS_WIDTH = 40;
|
||||
const NO_RIGHT_AXIS_WIDTH = 12;
|
||||
const XAXIS_HEIGHT = 20;
|
||||
const TOP_PADDING = 12;
|
||||
const NO_BANDS: ChartBand[] = [];
|
||||
|
||||
export type ChartAxis =
|
||||
| {
|
||||
min: number;
|
||||
max: number;
|
||||
ticks: number[];
|
||||
format: (v: number) => string;
|
||||
}
|
||||
| {
|
||||
auto: true;
|
||||
symmetric?: boolean;
|
||||
minSpan: number;
|
||||
format: (v: number) => string;
|
||||
};
|
||||
|
||||
export type AxisSide = 'left' | 'right';
|
||||
|
||||
export interface ChartSeries {
|
||||
key: string;
|
||||
color: string;
|
||||
axis?: AxisSide;
|
||||
width?: number;
|
||||
dashed?: boolean;
|
||||
}
|
||||
|
||||
export interface ChartBand {
|
||||
minKey: string;
|
||||
maxKey: string;
|
||||
color: string;
|
||||
axis?: AxisSide;
|
||||
}
|
||||
|
||||
interface ResolvedAxis {
|
||||
min: number;
|
||||
max: number;
|
||||
ticks: number[];
|
||||
}
|
||||
|
||||
function resolveAxis(
|
||||
axis: ChartAxis,
|
||||
side: AxisSide,
|
||||
source: ChartSource,
|
||||
series: ChartSeries[],
|
||||
startSec: number,
|
||||
endSec: number
|
||||
): ResolvedAxis {
|
||||
if (!('auto' in axis)) return axis;
|
||||
|
||||
let lo = Infinity;
|
||||
let hi = -Infinity;
|
||||
const keys = series
|
||||
.filter((s) => (s.axis ?? 'left') === side)
|
||||
.map((s) => s.key);
|
||||
for (let i = 0; i < source.length; i++) {
|
||||
const t = source.time(i);
|
||||
if (t < startSec || t > endSec) continue;
|
||||
for (const key of keys) {
|
||||
const v = source.value(key, i);
|
||||
if (v == null) continue;
|
||||
if (v < lo) lo = v;
|
||||
if (v > hi) hi = v;
|
||||
}
|
||||
}
|
||||
if (lo > hi) {
|
||||
lo = 0;
|
||||
hi = 0;
|
||||
}
|
||||
|
||||
if (axis.symmetric) {
|
||||
const m = Math.max(Math.abs(lo), Math.abs(hi), axis.minSpan / 2);
|
||||
return niceTicks(-m, m);
|
||||
}
|
||||
|
||||
const missing = axis.minSpan - (hi - lo);
|
||||
if (missing > 0) {
|
||||
lo -= missing / 2;
|
||||
hi += missing / 2;
|
||||
}
|
||||
return niceTicks(lo, hi);
|
||||
}
|
||||
|
||||
function TimeSeriesChartComponent({
|
||||
source,
|
||||
startSec,
|
||||
endSec,
|
||||
xAxisTicks,
|
||||
leftAxis,
|
||||
rightAxis,
|
||||
series,
|
||||
bands = NO_BANDS,
|
||||
hoveredTime,
|
||||
onHoveredTimeChange,
|
||||
renderTooltip,
|
||||
tooltipWidth = 240,
|
||||
tooltipHeight = 120,
|
||||
leftAxisWidth = DEFAULT_LEFT_AXIS_WIDTH,
|
||||
}: {
|
||||
source: ChartSource;
|
||||
startSec: number;
|
||||
endSec: number;
|
||||
xAxisTicks: number[];
|
||||
leftAxis: ChartAxis;
|
||||
rightAxis?: ChartAxis;
|
||||
series: ChartSeries[];
|
||||
bands?: ChartBand[];
|
||||
hoveredTime: number | null;
|
||||
onHoveredTimeChange: (t: number | null) => void;
|
||||
renderTooltip?: (hoveredTime: number) => ReactNode;
|
||||
tooltipWidth?: number;
|
||||
tooltipHeight?: number;
|
||||
leftAxisWidth?: number;
|
||||
}) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const rightAxisWidth = rightAxis ? RIGHT_AXIS_WIDTH : NO_RIGHT_AXIS_WIDTH;
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const width = rect.width;
|
||||
const height = rect.height;
|
||||
|
||||
if (canvas.width !== width * dpr || canvas.height !== height * dpr) {
|
||||
canvas.width = width * dpr;
|
||||
canvas.height = height * dpr;
|
||||
}
|
||||
|
||||
ctx.save();
|
||||
ctx.scale(dpr, dpr);
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
|
||||
const plotLeft = leftAxisWidth;
|
||||
const plotRight = width - rightAxisWidth;
|
||||
const plotWidth = plotRight - plotLeft;
|
||||
const plotTop = TOP_PADDING;
|
||||
const plotBottom = height - XAXIS_HEIGHT;
|
||||
const plotHeight = plotBottom - plotTop;
|
||||
|
||||
const timeToPx = (t: number) => {
|
||||
const ratio = (t - startSec) / (endSec - startSec);
|
||||
return plotLeft + ratio * plotWidth;
|
||||
};
|
||||
|
||||
const toPy = (axis: ResolvedAxis) => (v: number) => {
|
||||
const clamped = Math.max(axis.min, Math.min(axis.max, v));
|
||||
const ratio = (clamped - axis.min) / (axis.max - axis.min || 1);
|
||||
return plotBottom - ratio * plotHeight;
|
||||
};
|
||||
|
||||
const left = resolveAxis(
|
||||
leftAxis,
|
||||
'left',
|
||||
source,
|
||||
series,
|
||||
startSec,
|
||||
endSec
|
||||
);
|
||||
const right = rightAxis
|
||||
? resolveAxis(rightAxis, 'right', source, series, startSec, endSec)
|
||||
: null;
|
||||
const leftToPy = toPy(left);
|
||||
const rightToPy = right ? toPy(right) : leftToPy;
|
||||
const sideToPy = (side: AxisSide = 'left') =>
|
||||
side === 'right' ? rightToPy : leftToPy;
|
||||
|
||||
// horizontal grid lines
|
||||
ctx.strokeStyle = 'rgba(255, 255, 255, 0.08)';
|
||||
ctx.lineWidth = 1;
|
||||
left.ticks.forEach((val) => {
|
||||
const y = leftToPy(val);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(plotLeft, y);
|
||||
ctx.lineTo(plotRight, y);
|
||||
ctx.stroke();
|
||||
});
|
||||
|
||||
// Y-axis tick labels
|
||||
ctx.font = '11px Poppins, sans-serif';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillStyle = '#ffffff';
|
||||
|
||||
ctx.textAlign = 'right';
|
||||
left.ticks.forEach((val) => {
|
||||
ctx.fillText(leftAxis.format(val), plotLeft - 6, leftToPy(val));
|
||||
});
|
||||
|
||||
if (right && rightAxis) {
|
||||
ctx.textAlign = 'left';
|
||||
right.ticks.forEach((val) => {
|
||||
ctx.fillText(rightAxis.format(val), plotRight + 6, rightToPy(val));
|
||||
});
|
||||
}
|
||||
|
||||
// X-axis tick labels
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'top';
|
||||
xAxisTicks.forEach((tSec) => {
|
||||
const x = timeToPx(tSec);
|
||||
if (x >= plotLeft && x <= plotRight) {
|
||||
ctx.fillText(relativeTimeTick(tSec, endSec), x, plotBottom + 4);
|
||||
}
|
||||
});
|
||||
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
ctx.rect(plotLeft, plotTop, plotWidth, plotHeight);
|
||||
ctx.clip();
|
||||
|
||||
bands.forEach((band) => {
|
||||
const valToPy = sideToPy(band.axis);
|
||||
ctx.fillStyle = band.color;
|
||||
ctx.globalAlpha = 0.15;
|
||||
drawBand(ctx, source, band.minKey, band.maxKey, timeToPx, valToPy);
|
||||
|
||||
ctx.strokeStyle = band.color;
|
||||
ctx.lineWidth = 1;
|
||||
ctx.globalAlpha = 0.35;
|
||||
drawSeries(source, band.minKey, timeToPx, valToPy, (pts) =>
|
||||
drawLine(ctx, pts)
|
||||
);
|
||||
drawSeries(source, band.maxKey, timeToPx, valToPy, (pts) =>
|
||||
drawLine(ctx, pts)
|
||||
);
|
||||
});
|
||||
ctx.globalAlpha = 1.0;
|
||||
|
||||
const t0Px = timeToPx(0);
|
||||
series.forEach((s) => {
|
||||
ctx.strokeStyle = s.color;
|
||||
ctx.lineWidth = s.width ?? 1.5;
|
||||
drawSeries(source, s.key, timeToPx, sideToPy(s.axis), (pts) =>
|
||||
s.dashed ? drawDashedPath(ctx, pts, t0Px, 5, 4) : drawLine(ctx, pts)
|
||||
);
|
||||
});
|
||||
|
||||
ctx.restore();
|
||||
|
||||
// vertical hover line
|
||||
if (hoveredTime != null) {
|
||||
const hoverX = timeToPx(hoveredTime);
|
||||
if (hoverX >= plotLeft && hoverX <= plotRight) {
|
||||
ctx.strokeStyle = 'rgba(255, 255, 255, 0.4)';
|
||||
ctx.lineWidth = 1.5;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(hoverX, plotTop);
|
||||
ctx.lineTo(hoverX, plotBottom);
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
ctx.restore();
|
||||
}, [
|
||||
source,
|
||||
startSec,
|
||||
endSec,
|
||||
xAxisTicks,
|
||||
leftAxis,
|
||||
rightAxis,
|
||||
series,
|
||||
bands,
|
||||
hoveredTime,
|
||||
leftAxisWidth,
|
||||
rightAxisWidth,
|
||||
]);
|
||||
|
||||
const [hoveredY, setHoveredY] = useState<number | null>(null);
|
||||
|
||||
const plotScreenSpan = (canvas: HTMLCanvasElement) => {
|
||||
const canvasRect = canvas.getBoundingClientRect();
|
||||
return {
|
||||
canvasRect,
|
||||
plotLeftScreen: canvasRect.left + leftAxisWidth,
|
||||
plotWidth: canvasRect.width - leftAxisWidth - rightAxisWidth,
|
||||
};
|
||||
};
|
||||
|
||||
const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
const { plotLeftScreen, plotWidth } = plotScreenSpan(canvas);
|
||||
onHoveredTimeChange(
|
||||
screenXToTimeSec(e.clientX, plotLeftScreen, plotWidth, startSec, endSec)
|
||||
);
|
||||
setHoveredY(e.clientY);
|
||||
};
|
||||
|
||||
let clientPos: { x: number; y: number } | null = null;
|
||||
if (hoveredTime != null && hoveredY != null && canvasRef.current) {
|
||||
const { plotLeftScreen, plotWidth } = plotScreenSpan(canvasRef.current);
|
||||
const screenX = timeSecToScreenX(
|
||||
hoveredTime,
|
||||
plotLeftScreen,
|
||||
plotWidth,
|
||||
startSec,
|
||||
endSec
|
||||
);
|
||||
clientPos = {
|
||||
x: flipTooltipLeft(
|
||||
screenX,
|
||||
window.innerWidth,
|
||||
tooltipWidth,
|
||||
TOOLTIP_OFFSET
|
||||
),
|
||||
y: hoveredY + TOOLTIP_OFFSET,
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="relative w-full h-full"
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseLeave={() => {
|
||||
onHoveredTimeChange(null);
|
||||
setHoveredY(null);
|
||||
}}
|
||||
>
|
||||
<canvas ref={canvasRef} className="w-full h-full block" />
|
||||
|
||||
{renderTooltip && (
|
||||
<ChartPopover
|
||||
clientPos={clientPos}
|
||||
width={tooltipWidth}
|
||||
estimatedHeight={tooltipHeight}
|
||||
>
|
||||
{hoveredTime != null && renderTooltip(hoveredTime)}
|
||||
</ChartPopover>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const TimeSeriesChart = memo(TimeSeriesChartComponent);
|
||||
@@ -1,12 +0,0 @@
|
||||
export const SERIES_COLORS = [
|
||||
'#9085e9',
|
||||
'#c98500',
|
||||
'#00a3e0',
|
||||
'#199e70',
|
||||
'#3987e5',
|
||||
'#d95926',
|
||||
'#d55181',
|
||||
'#008300',
|
||||
'#e66767',
|
||||
'#e59400',
|
||||
];
|
||||
@@ -1,20 +0,0 @@
|
||||
export function ButterflyIcon({ width = 16 }: { width?: number }) {
|
||||
return (
|
||||
<svg width={width} height={width} viewBox="0 0 2480 2480">
|
||||
<g id="Layer1" transform="matrix(1,0,0,1,-0.15748,-513.937008)">
|
||||
<g transform="matrix(1.228651,0,0,1.228651,-283.584475,-321.658225)">
|
||||
<path d="M1240.157,1715.941C1240.157,1715.941 1308.466,1480.841 1554.76,1244.143C1801.055,1007.444 2013.764,977.057 2095.329,1013.841C2176.894,1050.626 2188.089,1167.376 2133.713,1303.317C2079.336,1439.259 2048.949,1432.862 2018.562,1498.434C1988.175,1564.006 2000.969,1619.982 1957.788,1679.157C1914.606,1738.331 1796.257,1738.331 1796.257,1738.331L1606.825,1744.941C1606.825,1744.941 1869.551,1785.216 1962.9,1930.972C2056.248,2076.727 1976.82,2206.105 1921.957,2271.613C1867.094,2337.121 1754.093,2399.354 1657.469,2370.694C1560.844,2342.034 1412.633,2221.663 1349.581,2110.3C1286.53,1998.936 1240.157,1871.196 1240.157,1871.196L1240.157,1715.941Z" />
|
||||
</g>
|
||||
<g transform="matrix(-1.228651,0,0,1.228651,2763.901095,-321.658225)">
|
||||
<path d="M1240.157,1715.941C1240.157,1715.941 1308.466,1480.841 1554.76,1244.143C1801.055,1007.444 2013.764,977.057 2095.329,1013.841C2176.894,1050.626 2188.089,1167.376 2133.713,1303.317C2079.336,1439.259 2048.949,1432.862 2018.562,1498.434C1988.175,1564.006 2000.969,1619.982 1957.788,1679.157C1914.606,1738.331 1796.257,1738.331 1796.257,1738.331L1606.825,1744.941C1606.825,1744.941 1869.551,1785.216 1962.9,1930.972C2056.248,2076.727 1976.82,2206.105 1921.957,2271.613C1867.094,2337.121 1754.093,2399.354 1657.469,2370.694C1560.844,2342.034 1412.633,2221.663 1349.581,2110.3C1286.53,1998.936 1240.157,1871.196 1240.157,1871.196L1240.157,1715.941Z" />
|
||||
</g>
|
||||
<g transform="matrix(1.228651,0,0,1.228651,-300.892813,-306.516335)">
|
||||
<path d="M1312.922,1230.359C1312.922,1230.359 1332.003,1038.626 1419.522,1000.797C1507.04,962.967 1532.669,1024.301 1532.669,1024.301C1532.669,1024.301 1554.478,1075.246 1469.308,1131.715C1386.988,1186.295 1349.786,1318.447 1321.522,1352.346C1313.249,1362.268 1295.908,1377.383 1303.533,1305.121C1305.233,1289.015 1312.922,1230.359 1312.922,1230.359Z" />
|
||||
</g>
|
||||
<g transform="matrix(-1.228651,0,0,1.228651,2781.207774,-306.516335)">
|
||||
<path d="M1312.922,1230.359C1312.922,1230.359 1332.003,1038.626 1419.522,1000.797C1507.04,962.967 1532.669,1024.301 1532.669,1024.301C1532.669,1024.301 1554.478,1075.246 1469.308,1131.715C1386.988,1186.295 1349.786,1318.447 1321.522,1352.346C1313.249,1362.268 1295.908,1377.383 1303.533,1305.121C1305.233,1289.015 1312.922,1230.359 1312.922,1230.359Z" />
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { useId } from 'react';
|
||||
|
||||
export function CameraLockIcon({
|
||||
size = 18,
|
||||
locked = true,
|
||||
}: {
|
||||
size?: number;
|
||||
locked?: boolean;
|
||||
}) {
|
||||
const maskId = `camera-lock-mask-${useId().replace(/:/g, '')}`;
|
||||
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="currentColor"
|
||||
>
|
||||
<defs>
|
||||
<mask
|
||||
id={maskId}
|
||||
maskUnits="userSpaceOnUse"
|
||||
x="0"
|
||||
y="0"
|
||||
width="24"
|
||||
height="24"
|
||||
>
|
||||
<rect x="0" y="0" width="24" height="24" fill="white" />
|
||||
<rect
|
||||
x="13.2"
|
||||
y="10.2"
|
||||
width="12.5"
|
||||
height="15.3"
|
||||
rx="2.6"
|
||||
fill="black"
|
||||
/>
|
||||
</mask>
|
||||
</defs>
|
||||
<g transform="translate(3 1.28) scale(0.82)" mask={`url(#${maskId})`}>
|
||||
<circle cx="12" cy="12" r="3.2" />
|
||||
<path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z" />
|
||||
</g>
|
||||
<g transform="translate(12.08 10.91) scale(0.6)">
|
||||
{locked ? (
|
||||
<path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z" />
|
||||
) : (
|
||||
<path d="M12 17c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6-9h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6h1.9c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm0 12H6V10h12v10z" />
|
||||
)}
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
export function CompareIcon({ width = 20 }: { width?: number }) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
height={width}
|
||||
viewBox="0 -960 960 960"
|
||||
width={width}
|
||||
fill="#ffffff"
|
||||
>
|
||||
<path d="m320-160-56-57 103-103H80v-80h287L264-503l56-57 200 200-200 200Zm320-240L440-600l200-200 56 57-103 103h287v80H593l103 103-56 57Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 1322 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user