1
1
mirror of https://github.com/ellie/atuin.git synced 2024-09-11 21:18:22 +03:00

feat(gui): add base structure (#1935)

* initial

* ui things

* cargo

* update, add history refresh button

* history page a bit better, add initial dotfiles page

* re-org layout

* bye squigglies

* add dotfiles ui, show aliases

* add default shell detection

* put stats in a little drawer, alias import changes

* use new table for aliases, add alias deleting

* support adding aliases

* close drawer when added, no alias autocomplete

* clippy, format

* attempt to ensure gdk is installed ok

* sudo

* no linux things on mac ffs

* I forgot we build for windows too... end of day

* remove tauri backend from workspace
This commit is contained in:
Ellie Huxtable 2024-04-11 16:59:01 +01:00 committed by GitHub
parent 0da8d34425
commit 6cd4319fcf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
68 changed files with 11186 additions and 362 deletions

View File

@ -2,9 +2,9 @@ name: Rust
on:
push:
branches: [ main ]
branches: [main]
pull_request:
branches: [ main ]
branches: [main]
env:
CARGO_TERM_COLOR: always
@ -17,32 +17,45 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v3
- name: Install rust
uses: dtolnay/rust-toolchain@master
with:
- name: Install rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-release-${{ hashFiles('**/Cargo.lock') }}
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-release-${{ hashFiles('**/Cargo.lock') }}
- name: Run cargo build common
run: cargo build -p atuin-common --locked --release
- name: Install dependencies
if: matrix.os != 'macos-14' && matrix.os != 'windows-latest'
run: |
sudo apt update
sudo apt install libwebkit2gtk-4.1-dev \
build-essential \
curl \
wget \
file \
libssl-dev \
libayatana-appindicator3-dev \
librsvg2-dev
- name: Run cargo build client
run: cargo build -p atuin-client --locked --release
- name: Run cargo build common
run: cargo build -p atuin-common --locked --release
- name: Run cargo build server
run: cargo build -p atuin-server --locked --release
- name: Run cargo build client
run: cargo build -p atuin-client --locked --release
- name: Run cargo build main
run: cargo build --all --locked --release
- name: Run cargo build server
run: cargo build -p atuin-server --locked --release
- name: Run cargo build main
run: cargo build --all --locked --release
cross-compile:
strategy:
@ -54,32 +67,32 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v3
- name: Install cross
uses: taiki-e/install-action@v1
with:
tool: cross
- name: Install cross
uses: taiki-e/install-action@v1
with:
tool: cross
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ matrix.target }}-cross-compile-${{ hashFiles('**/Cargo.lock') }}
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ matrix.target }}-cross-compile-${{ hashFiles('**/Cargo.lock') }}
- name: Run cross build common
run: cross build -p atuin-common --locked --target ${{ matrix.target }}
- name: Run cross build common
run: cross build -p atuin-common --locked --target ${{ matrix.target }}
- name: Run cross build client
run: cross build -p atuin-client --locked --target ${{ matrix.target }}
- name: Run cross build client
run: cross build -p atuin-client --locked --target ${{ matrix.target }}
- name: Run cross build server
run: cross build -p atuin-server --locked --target ${{ matrix.target }}
- name: Run cross build server
run: cross build -p atuin-server --locked --target ${{ matrix.target }}
- name: Run cross build main
run: cross build --all --locked --target ${{ matrix.target }}
- name: Run cross build main
run: cross build --all --locked --target ${{ matrix.target }}
unit-test:
strategy:
@ -88,29 +101,41 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v3
- name: Install rust
uses: dtolnay/rust-toolchain@master
with:
- name: Install rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
- uses: taiki-e/install-action@v2
name: Install nextest
with:
tool: cargo-nextest
- name: Install dependencies
if: matrix.os != 'macos-14' && matrix.os != 'windows-latest'
run: |
sudo apt update
sudo apt install libwebkit2gtk-4.1-dev \
build-essential \
curl \
wget \
file \
libssl-dev \
libayatana-appindicator3-dev \
librsvg2-dev
- uses: taiki-e/install-action@v2
name: Install nextest
with:
tool: cargo-nextest
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${ runner.os }-cargo-debug-${{ hashFiles('**/Cargo.lock') }}
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${ runner.os }-cargo-debug-${{ hashFiles('**/Cargo.lock') }}
- name: Run cargo test
run: cargo nextest run --lib --bins
- name: Run cargo test
run: cargo nextest run --lib --bins
check:
strategy:
@ -119,35 +144,48 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v3
- name: Install rust
uses: dtolnay/rust-toolchain@master
with:
- name: Install rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${ runner.os }-cargo-debug-${{ hashFiles('**/Cargo.lock') }}
- name: Install dependencies
if: matrix.os != 'macos-14' && matrix.os != 'windows-latest'
run: |
sudo apt update
sudo apt install libwebkit2gtk-4.1-dev \
build-essential \
curl \
wget \
file \
libssl-dev \
libayatana-appindicator3-dev \
librsvg2-dev
- name: Run cargo check (all features)
run: cargo check --all-features --workspace
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${ runner.os }-cargo-debug-${{ hashFiles('**/Cargo.lock') }}
- name: Run cargo check (no features)
run: cargo check --no-default-features --workspace
- name: Run cargo check (all features)
run: cargo check --all-features --workspace
- name: Run cargo check (sync)
run: cargo check --no-default-features --features sync --workspace
- name: Run cargo check (no features)
run: cargo check --no-default-features --workspace
- name: Run cargo check (server)
run: cargo check --no-default-features --features server --workspace
- name: Run cargo check (sync)
run: cargo check --no-default-features --features sync --workspace
- name: Run cargo check (client only)
run: cargo check --no-default-features --features client --workspace
- name: Run cargo check (server)
run: cargo check --no-default-features --features server --workspace
- name: Run cargo check (client only)
run: cargo check --no-default-features --features client --workspace
integration-test:
runs-on: ubuntu-latest
@ -163,66 +201,78 @@ jobs:
- 5432:5432
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v3
- name: Install rust
uses: dtolnay/rust-toolchain@master
with:
- name: Install rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
- uses: taiki-e/install-action@v2
name: Install nextest
with:
tool: cargo-nextest
- uses: taiki-e/install-action@v2
name: Install nextest
with:
tool: cargo-nextest
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${ runner.os }-cargo-debug-${{ hashFiles('**/Cargo.lock') }}
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${ runner.os }-cargo-debug-${{ hashFiles('**/Cargo.lock') }}
- name: Run cargo test
run: cargo nextest run --test '*'
env:
ATUIN_DB_URI: postgres://atuin:pass@localhost:5432/atuin
- name: Run cargo test
run: cargo nextest run --test '*'
env:
ATUIN_DB_URI: postgres://atuin:pass@localhost:5432/atuin
clippy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v3
- name: Install latest rust
uses: dtolnay/rust-toolchain@master
with:
- name: Install latest rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
components: clippy
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-debug-${{ hashFiles('**/Cargo.lock') }}
- name: Install dependencies
if: matrix.os != 'macos-14' && matrix.os != 'windows-latest'
run: |
sudo apt update
sudo apt install libwebkit2gtk-4.1-dev \
build-essential \
curl \
wget \
file \
libssl-dev \
libayatana-appindicator3-dev \
librsvg2-dev
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-debug-${{ hashFiles('**/Cargo.lock') }}
- name: Run clippy
run: cargo clippy -- -D warnings
- name: Run clippy
run: cargo clippy -- -D warnings
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v3
- name: Install latest rust
uses: dtolnay/rust-toolchain@master
with:
- name: Install latest rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
components: rustfmt
- name: Format
run: cargo fmt -- --check
- name: Format
run: cargo fmt -- --check

384
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,12 @@
[workspace]
members = [
"atuin",
"atuin-client",
"atuin-server",
"atuin-server-postgres",
"atuin-server-database",
"atuin-common",
"atuin-dotfiles",
"atuin",
"atuin-client",
"atuin-server",
"atuin-server-postgres",
"atuin-server-database",
"atuin-common",
"atuin-dotfiles",
]
resolver = "2"
@ -24,10 +24,10 @@ readme = "README.md"
async-trait = "0.1.58"
base64 = "0.21"
log = "0.4"
time = { version = "0.3", features = [
"serde-human-readable",
"macros",
"local-offset",
time = { version = "=0.3.34", features = [
"serde-human-readable",
"macros",
"local-offset",
] }
clap = { version = "4.5.1", features = ["derive"] }
config = { version = "0.13", default-features = false, features = ["toml"] }
@ -46,7 +46,7 @@ whoami = "1.5.1"
typed-builder = "0.18.0"
pretty_assertions = "1.3.0"
thiserror = "1.0"
rustix = {version = "0.38.30", features=["process", "fs"]}
rustix = { version = "0.38.30", features = ["process", "fs"] }
[workspace.dependencies.reqwest]
version = "0.11"
@ -54,5 +54,5 @@ features = ["json", "rustls-tls-native-roots"]
default-features = false
[workspace.dependencies.sqlx]
version = "0.7.3"
version = "=0.7.3"
features = ["runtime-tokio-rustls", "time", "postgres", "uuid"]

View File

@ -121,7 +121,7 @@ pub trait Database: Send + Sync + 'static {
// Intended for use on a developer machine and not a sync server.
// TODO: implement IntoIterator
pub struct Sqlite {
pool: SqlitePool,
pub pool: SqlitePool,
}
impl Sqlite {

View File

@ -1,3 +1,6 @@
use std::{ffi::OsStr, path::Path, process::Command};
use serde::Serialize;
use sysinfo::{get_current_pid, Process, System};
use thiserror::Error;
@ -12,7 +15,24 @@ pub enum Shell {
Unknown,
}
#[derive(Debug, Error)]
impl std::fmt::Display for Shell {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let shell = match self {
Shell::Bash => "bash",
Shell::Fish => "fish",
Shell::Zsh => "zsh",
Shell::Nu => "nu",
Shell::Xonsh => "xonsh",
Shell::Sh => "sh",
Shell::Unknown => "unknown",
};
write!(f, "{}", shell)
}
}
#[derive(Debug, Error, Serialize)]
pub enum ShellError {
#[error("shell not supported")]
NotSupported,
@ -21,28 +41,89 @@ pub enum ShellError {
ExecError(String),
}
pub fn shell() -> Shell {
let name = shell_name(None);
match name.as_str() {
"bash" => Shell::Bash,
"fish" => Shell::Fish,
"zsh" => Shell::Zsh,
"xonsh" => Shell::Xonsh,
"nu" => Shell::Nu,
"sh" => Shell::Sh,
_ => Shell::Unknown,
}
}
impl Shell {
pub fn current() -> Shell {
let sys = System::new_all();
let process = sys
.process(get_current_pid().expect("Failed to get current PID"))
.expect("Process with current pid does not exist");
let parent = sys
.process(process.parent().expect("Atuin running with no parent!"))
.expect("Process with parent pid does not exist");
let shell = parent.name().trim().to_lowercase();
let shell = shell.strip_prefix('-').unwrap_or(&shell);
Shell::from_string(shell.to_string())
}
/// Best-effort attempt to determine the default shell
/// This implementation will be different across different platforms
/// Caller should ensure to handle Shell::Unknown correctly
pub fn default_shell() -> Result<Shell, ShellError> {
let sys = System::name().unwrap_or("".to_string()).to_lowercase();
// TODO: Support Linux
// I'm pretty sure we can use /etc/passwd there, though there will probably be some issues
if sys.contains("darwin") {
// This works in my testing so far
let path = Shell::Sh.run_interactive([
"dscl localhost -read \"/Local/Default/Users/$USER\" shell | awk '{print $2}'",
])?;
let path = Path::new(path.trim());
let shell = path.file_name();
if shell.is_none() {
return Err(ShellError::NotSupported);
}
Ok(Shell::from_string(
shell.unwrap().to_string_lossy().to_string(),
))
} else {
Err(ShellError::NotSupported)
}
}
pub fn from_string(name: String) -> Shell {
match name.as_str() {
"bash" => Shell::Bash,
"fish" => Shell::Fish,
"zsh" => Shell::Zsh,
"xonsh" => Shell::Xonsh,
"nu" => Shell::Nu,
"sh" => Shell::Sh,
_ => Shell::Unknown,
}
}
/// Returns true if the shell is posix-like
/// Note that while fish is not posix compliant, it behaves well enough for our current
/// featureset that this does not matter.
pub fn is_posixish(&self) -> bool {
matches!(self, Shell::Bash | Shell::Fish | Shell::Zsh)
}
pub fn run_interactive<I, S>(&self, args: I) -> Result<String, ShellError>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let shell = self.to_string();
let output = Command::new(shell)
.arg("-ic")
.args(args)
.output()
.map_err(|e| ShellError::ExecError(e.to_string()))?;
Ok(String::from_utf8(output.stdout).unwrap())
}
}
pub fn shell_name(parent: Option<&Process>) -> String {

View File

@ -2,7 +2,7 @@
name = "atuin-dotfiles"
description = "The dotfiles crate for Atuin"
edition = "2021"
version = "0.1.0" # intentionally not the same as the rest
version = "0.1.0" # intentionally not the same as the rest
authors.workspace = true
rust-version.workspace = true
@ -21,4 +21,5 @@ eyre = { workspace = true }
tokio = { workspace = true }
rmp = { version = "0.8.11" }
rand = { workspace = true }
serde = { workspace = true }
crypto_secretbox = "0.1.1"

View File

@ -1,7 +1,7 @@
use std::{ffi::OsStr, process::Command};
use atuin_common::shell::{shell, shell_name, ShellError};
use eyre::Result;
use serde::Serialize;
use atuin_common::shell::{Shell, ShellError};
use crate::store::AliasStore;
@ -10,28 +10,12 @@ pub mod fish;
pub mod xonsh;
pub mod zsh;
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Alias {
pub name: String,
pub value: String,
}
pub fn run_interactive<I, S>(args: I) -> Result<String, ShellError>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let shell = shell_name(None);
let output = Command::new(shell)
.arg("-ic")
.args(args)
.output()
.map_err(|e| ShellError::ExecError(e.to_string()))?;
Ok(String::from_utf8(output.stdout).unwrap())
}
pub fn parse_alias(line: &str) -> Alias {
let mut parts = line.split('=');
@ -44,15 +28,21 @@ pub fn parse_alias(line: &str) -> Alias {
}
}
pub fn existing_aliases() -> Result<Vec<Alias>, ShellError> {
pub fn existing_aliases(shell: Option<Shell>) -> Result<Vec<Alias>, ShellError> {
let shell = if let Some(shell) = shell {
shell
} else {
Shell::current()
};
// this only supports posix-y shells atm
if !shell().is_posixish() {
if !shell.is_posixish() {
return Err(ShellError::NotSupported);
}
// This will return a list of aliases, each on its own line
// They will be in the form foo=bar
let aliases = run_interactive(["alias"])?;
let aliases = shell.run_interactive(["alias"])?;
let aliases: Vec<Alias> = aliases.lines().map(parse_alias).collect();
Ok(aliases)
@ -62,7 +52,7 @@ pub fn existing_aliases() -> Result<Vec<Alias>, ShellError> {
/// This will not import aliases already in the store
/// Returns aliases that were set
pub async fn import_aliases(store: AliasStore) -> Result<Vec<Alias>> {
let shell_aliases = existing_aliases()?;
let shell_aliases = existing_aliases(None)?;
let store_aliases = store.aliases().await?;
let mut res = Vec::new();

View File

@ -2,7 +2,7 @@ use std::process::Command;
use std::{env, path::PathBuf, str::FromStr};
use atuin_client::settings::Settings;
use atuin_common::shell::shell_name;
use atuin_common::shell::{shell_name, Shell};
use colored::Colorize;
use eyre::Result;
use serde::{Deserialize, Serialize};
@ -13,6 +13,9 @@ use sysinfo::{get_current_pid, Disks, System};
struct ShellInfo {
pub name: String,
// best-effort, not supported on all OSes
pub default: String,
// Detect some shell plugins that the user has installed.
// I'm just going to start with preexec/blesh
pub plugins: Vec<String>,
@ -135,6 +138,8 @@ impl ShellInfo {
}
pub fn new() -> Self {
// TODO: rework to use atuin_common::Shell
let sys = System::new_all();
let process = sys
@ -149,7 +154,13 @@ impl ShellInfo {
let plugins = ShellInfo::plugins(name.as_str(), parent);
Self { name, plugins }
let default = Shell::default_shell().unwrap_or(Shell::Unknown).to_string();
Self {
name,
default,
plugins,
}
}
}

26
ui/.gitignore vendored Normal file
View File

@ -0,0 +1,26 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
gen

7
ui/README.md Normal file
View File

@ -0,0 +1,7 @@
# Tauri + React + Typescript
This template should help get you started developing with Tauri, React and Typescript in Vite.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)

4
ui/backend/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
# Generated by Cargo
# will have compiled files and executables
/target/

5801
ui/backend/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

38
ui/backend/Cargo.toml Normal file
View File

@ -0,0 +1,38 @@
[package]
name = "ui"
version = "0.0.0"
description = "A Tauri App"
publish = false
authors = ["you"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "2.0.0-beta", features = [] }
[dependencies]
atuin-client = { path = "../../atuin-client", version = "18.1.0" }
atuin-common = { path = "../../atuin-common", version = "18.1.0" }
atuin-dotfiles = { path = "../../atuin-dotfiles", version = "0.1.0" }
eyre = "0.6"
tauri = { version = "2.0.0-beta", features = ["tray-icon"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
time = "0.3.34"
uuid = "1.7.0"
syntect = "5.2.0"
[workspace.dependencies.sqlx]
version = "=0.7.3"
features = ["runtime-tokio-rustls", "time", "postgres", "uuid"]
[features]
# this feature is used for production builds or when `devPath` points to the filesystem
# DO NOT REMOVE!!
custom-protocol = ["tauri/custom-protocol"]
#[lib]
#crate-type = ["staticlib", "cdylib", "rlib"]

3
ui/backend/build.rs Normal file
View File

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View File

@ -0,0 +1,24 @@
{
"identifier": "migrated",
"description": "permissions that were migrated from v1",
"context": "local",
"windows": [
"main"
],
"permissions": [
"path:default",
"event:default",
"window:default",
"app:default",
"resources:default",
"menu:default",
"tray:default"
],
"platforms": [
"linux",
"macOS",
"windows",
"android",
"iOS"
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

BIN
ui/backend/icons/32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

BIN
ui/backend/icons/icon.icns Normal file

Binary file not shown.

BIN
ui/backend/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

BIN
ui/backend/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

245
ui/backend/src/db.rs Normal file
View File

@ -0,0 +1,245 @@
// Some wrappers around the Atuin history DB
// I'll probably use this to inform changes to the "upstream" client crate
// We also use Strings a bunch for errors. They're passed to the Tauri frontend,
// which requires that they be serializable.
// Can rework that in the future too, but my main concern is avoiding tauri limitations/reqs
// ending up in the main crate.
use serde::Serialize;
use sqlx::{sqlite::SqliteRow, Row};
use std::collections::HashMap;
use std::path::PathBuf;
use atuin_client::settings::{FilterMode, SearchMode};
use atuin_client::{
database::{Context, Database, OptFilters, Sqlite},
history::History,
};
// useful for preprocessing data for the frontend
#[derive(Serialize, Debug)]
pub struct NameValue<T> {
pub name: String,
pub value: T,
}
#[derive(Serialize, Debug)]
pub struct GlobalStats {
pub total_history: u64,
pub daily: Vec<NameValue<u64>>,
pub last_1d: u64,
pub last_7d: u64,
pub last_30d: u64,
}
#[derive(Serialize)]
pub struct UIHistory {
pub id: String,
/// When the command was run.
pub timestamp: i128,
/// How long the command took to run.
pub duration: i64,
/// The exit code of the command.
pub exit: i64,
/// The command that was run.
pub command: String,
/// The current working directory when the command was run.
pub cwd: String,
/// The session ID, associated with a terminal session.
pub session: String,
/// The hostname of the machine the command was run on.
pub user: String,
pub host: String,
}
pub fn to_ui_history(history: History) -> UIHistory {
let parts: Vec<String> = history.hostname.split(':').map(str::to_string).collect();
let (host, user) = if parts.len() == 2 {
(parts[0].clone(), parts[1].clone())
} else {
("no-host".to_string(), "no-user".to_string())
};
let mac = format!("/Users/{}", user);
let linux = format!("/home/{}", user);
let cwd = history.cwd.replace(mac.as_str(), "~");
let cwd = cwd.replace(linux.as_str(), "~");
UIHistory {
id: history.id.0,
timestamp: history.timestamp.unix_timestamp_nanos(),
duration: history.duration,
exit: history.exit,
command: history.command,
session: history.session,
host,
user,
cwd,
}
}
pub struct HistoryDB(Sqlite);
impl HistoryDB {
pub async fn new(path: PathBuf, timeout: f64) -> Result<Self, String> {
let sqlite = Sqlite::new(path, timeout)
.await
.map_err(|e| e.to_string())?;
Ok(Self(sqlite))
}
pub async fn list(&self, limit: Option<usize>, unique: bool) -> Result<Vec<UIHistory>, String> {
let filters = vec![];
// bit of a hack but provide an empty context
// shell context makes _no sense_ in a GUI
let context = Context {
session: "".to_string(),
cwd: "".to_string(),
host_id: "".to_string(),
hostname: "".to_string(),
git_root: None,
};
let history = self
.0
.list(&filters, &context, limit, unique, false)
.await
.map_err(|e| e.to_string())?;
let history = history
.into_iter()
.filter(|h| h.duration > 0)
.map(to_ui_history)
.collect();
Ok(history)
}
pub async fn search(&self, query: &str) -> Result<Vec<UIHistory>, String> {
let context = Context {
session: "".to_string(),
cwd: "".to_string(),
host_id: "".to_string(),
hostname: "".to_string(),
git_root: None,
};
let filters = OptFilters {
limit: Some(200),
..OptFilters::default()
};
let history = self
.0
.search(
SearchMode::Fuzzy,
FilterMode::Global,
&context,
query,
filters,
)
.await
.map_err(|e| e.to_string())?;
let history = history
.into_iter()
.filter(|h| h.duration > 0)
.map(to_ui_history)
.collect();
Ok(history)
}
pub async fn global_stats(&self) -> Result<GlobalStats, String> {
let day_ago = time::OffsetDateTime::now_utc() - time::Duration::days(1);
let day_ago = day_ago.unix_timestamp_nanos();
let week_ago = time::OffsetDateTime::now_utc() - time::Duration::days(7);
let week_ago = week_ago.unix_timestamp_nanos();
let month_ago = time::OffsetDateTime::now_utc() - time::Duration::days(30);
let month_ago = month_ago.unix_timestamp_nanos();
// get the last 30 days of shell history
let history: Vec<UIHistory> = sqlx::query("SELECT * FROM history WHERE timestamp > ?")
.bind(month_ago as i64)
.map(|row: SqliteRow| {
History::from_db()
.id(row.get("id"))
.timestamp(
time::OffsetDateTime::from_unix_timestamp_nanos(
row.get::<i64, _>("timestamp") as i128,
)
.unwrap(),
)
.duration(row.get("duration"))
.exit(row.get("exit"))
.command(row.get("command"))
.cwd(row.get("cwd"))
.session(row.get("session"))
.hostname(row.get("hostname"))
.deleted_at(None)
.build()
.into()
})
.map(to_ui_history)
.fetch_all(&self.0.pool)
.await
.map_err(|e| e.to_string())?;
let total: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM history")
.fetch_one(&self.0.pool)
.await
.map_err(|e| e.to_string())?;
let mut day = 0;
let mut week = 0;
let mut month = 0;
let mut daily = HashMap::new();
let ymd = time::format_description::parse("[year]-[month]-[day]").unwrap();
for i in history {
if i.timestamp > day_ago {
day += 1;
}
if i.timestamp > week_ago {
week += 1;
}
if i.timestamp > month_ago {
month += 1;
// get the start of the day, as a unix timestamp
let date = time::OffsetDateTime::from_unix_timestamp_nanos(i.timestamp)
.unwrap()
.format(&ymd)
.unwrap();
daily.entry(date).and_modify(|v| *v += 1).or_insert(1);
}
}
let mut daily: Vec<NameValue<u64>> = daily
.into_iter()
.map(|(k, v)| NameValue { name: k, value: v })
.collect();
daily.sort_by(|a, b| a.name.cmp(&b.name));
Ok(GlobalStats {
total_history: total.0 as u64,
last_30d: month,
last_7d: week,
last_1d: day,
daily,
})
}
}

View File

@ -0,0 +1,91 @@
use std::path::PathBuf;
use atuin_client::{encryption, record::sqlite_store::SqliteStore, settings::Settings};
use atuin_common::shell::Shell;
use atuin_dotfiles::{
shell::{existing_aliases, Alias},
store::AliasStore,
};
async fn alias_store() -> eyre::Result<AliasStore> {
let settings = Settings::new()?;
let record_store_path = PathBuf::from(settings.record_store_path.as_str());
let sqlite_store = SqliteStore::new(record_store_path, settings.local_timeout).await?;
let encryption_key: [u8; 32] = encryption::load_key(&settings)?.into();
let host_id = Settings::host_id().expect("failed to get host_id");
Ok(AliasStore::new(sqlite_store, host_id, encryption_key))
}
#[tauri::command]
pub async fn aliases() -> Result<Vec<Alias>, String> {
let alias_store = alias_store().await.map_err(|e| e.to_string())?;
let aliases = alias_store
.aliases()
.await
.map_err(|e| format!("failed to load aliases: {}", e))?;
Ok(aliases)
}
#[tauri::command]
pub async fn delete_alias(name: String) -> Result<(), String> {
let alias_store = alias_store().await.map_err(|e| e.to_string())?;
alias_store
.delete(name.as_str())
.await
.map_err(|e| e.to_string())?;
Ok(())
}
#[tauri::command]
pub async fn set_alias(name: String, value: String) -> Result<(), String> {
let alias_store = alias_store().await.map_err(|e| e.to_string())?;
alias_store
.set(name.as_str(), value.as_str())
.await
.map_err(|e| e.to_string())?;
Ok(())
}
#[tauri::command]
pub async fn import_aliases() -> Result<Vec<Alias>, String> {
let store = alias_store().await.map_err(|e| e.to_string())?;
let shell = Shell::default_shell().map_err(|e| e.to_string())?;
let shell_name = shell.to_string();
if !shell.is_posixish() {
return Err(format!(
"Default shell {shell_name} not supported for import"
));
}
let existing_aliases = existing_aliases(Some(shell)).map_err(|e| e.to_string())?;
let store_aliases = store.aliases().await.map_err(|e| e.to_string())?;
let mut res = Vec::new();
for alias in existing_aliases {
// O(n), but n is small, and imports infrequent
// can always make a map
if store_aliases.contains(&alias) {
continue;
}
res.push(alias.clone());
store
.set(&alias.name, &alias.value)
.await
.map_err(|e| e.to_string())?;
}
Ok(res)
}

View File

@ -0,0 +1 @@
pub mod aliases;

63
ui/backend/src/main.rs Normal file
View File

@ -0,0 +1,63 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::path::PathBuf;
use atuin_client::settings::Settings;
mod db;
mod dotfiles;
mod store;
use db::{GlobalStats, HistoryDB, UIHistory};
use dotfiles::aliases::aliases;
#[tauri::command]
async fn list() -> Result<Vec<UIHistory>, String> {
let settings = Settings::new().map_err(|e| e.to_string())?;
let db_path = PathBuf::from(settings.db_path.as_str());
let db = HistoryDB::new(db_path, settings.local_timeout).await?;
let history = db.list(Some(100), false).await?;
Ok(history)
}
#[tauri::command]
async fn search(query: String) -> Result<Vec<UIHistory>, String> {
let settings = Settings::new().map_err(|e| e.to_string())?;
let db_path = PathBuf::from(settings.db_path.as_str());
let db = HistoryDB::new(db_path, settings.local_timeout).await?;
let history = db.search(query.as_str()).await?;
Ok(history)
}
#[tauri::command]
async fn global_stats() -> Result<GlobalStats, String> {
let settings = Settings::new().map_err(|e| e.to_string())?;
let db_path = PathBuf::from(settings.db_path.as_str());
let db = HistoryDB::new(db_path, settings.local_timeout).await?;
let stats = db.global_stats().await?;
Ok(stats)
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
list,
search,
global_stats,
aliases,
dotfiles::aliases::import_aliases,
dotfiles::aliases::delete_alias,
dotfiles::aliases::set_alias,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

1
ui/backend/src/store.rs Normal file
View File

@ -0,0 +1 @@

View File

@ -0,0 +1,47 @@
{
"app": {
"security": {
"csp": null
},
"trayIcon": {
"iconAsTemplate": false,
"iconPath": "icons/icon.png"
},
"windows": [
{
"fullscreen": false,
"resizable": true,
"title": "Atuin",
"width": 1200,
"height": 800,
"minWidth": 1000,
"minHeight": 500
}
]
},
"build": {
"beforeBuildCommand": "pnpm build",
"beforeDevCommand": "pnpm dev",
"devUrl": "http://localhost:1420",
"frontendDist": "../dist"
},
"bundle": {
"active": true,
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"targets": "all"
},
"identifier": "sh.atuin.app",
"plugins": {
"shell": {
"open": true
}
},
"productName": "Atuin",
"version": "0.0.0"
}

17
ui/components.json Normal file
View File

@ -0,0 +1,17 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/styles.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils"
}
}

BIN
ui/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

14
ui/index.html Normal file
View File

@ -0,0 +1,14 @@
<!doctype html>
<html lang="en" class="h-full bg-white">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tauri + React + TS</title>
</head>
<body class="h-full">
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

46
ui/package.json Normal file
View File

@ -0,0 +1,46 @@
{
"name": "ui",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri"
},
"dependencies": {
"@headlessui/react": "^1.7.18",
"@heroicons/react": "^2.1.3",
"@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-slot": "^1.0.2",
"@tailwindcss/forms": "^0.5.7",
"@tanstack/react-table": "^8.15.3",
"@tauri-apps/api": "2.0.0-beta.7",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"core": "link:@tauri-apps/api/core",
"highlight.js": "^11.9.0",
"lucide-react": "^0.367.0",
"luxon": "^3.4.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-spinners": "^0.13.8",
"recharts": "^2.12.4",
"tailwind-merge": "^2.2.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.0"
},
"devDependencies": {
"@tauri-apps/cli": "2.0.0-beta.2",
"@types/react": "^18.2.74",
"@types/react-dom": "^18.2.24",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.19",
"postcss": "^8.4.38",
"tailwindcss": "^3.4.3",
"typescript": "^5.4.3",
"vite": "^5.2.8",
"vite-tsconfig-paths": "^4.3.2"
}
}

2800
ui/pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

6
ui/postcss.config.js Normal file
View File

@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

6
ui/public/tauri.svg Normal file
View File

@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

1
ui/public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

7
ui/src/App.css Normal file
View File

@ -0,0 +1,7 @@
.logo.vite:hover {
filter: drop-shadow(0 0 2em #747bff);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafb);
}

116
ui/src/App.tsx Normal file
View File

@ -0,0 +1,116 @@
import "./App.css";
import { Fragment, useState, useEffect, ReactElement } from "react";
import { Dialog, Transition } from "@headlessui/react";
import {
Bars3Icon,
ChartPieIcon,
Cog6ToothIcon,
HomeIcon,
XMarkIcon,
MagnifyingGlassIcon,
ClockIcon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import Logo from "./assets/logo-light.svg";
function classNames(...classes: any) {
return classes.filter(Boolean).join(" ");
}
import History from "./pages/History.tsx";
import Dotfiles from "./pages/Dotfiles.tsx";
enum Section {
History,
Dotfiles,
}
function renderMain(section: Section): ReactElement {
switch (section) {
case Section.History:
return <History />;
case Section.Dotfiles:
return <Dotfiles />;
}
}
function App() {
// routers don't really work in Tauri. It's not a browser!
// I think hashrouter may work, but I'd rather avoiding thinking of them as
// pages
const [section, setSection] = useState(Section.History);
const navigation = [
{
name: "History",
icon: ClockIcon,
section: Section.History,
},
{
name: "Dotfiles",
icon: WrenchScrewdriverIcon,
section: Section.Dotfiles,
},
];
return (
<div>
<div className="fixed inset-y-0 z-50 flex w-60 flex-col">
<div className="flex grow flex-col gap-y-5 overflow-y-auto border-r border-gray-200 bg-white px-6 pb-4">
<div className="flex h-16 shrink-0 items-center">
<img className="h-8 w-auto" src={Logo} alt="Atuin" />
</div>
<nav className="flex flex-1 flex-col">
<ul role="list" className="flex flex-1 flex-col gap-y-7">
<li>
<ul role="list" className="-mx-2 space-y-1 w-full">
{navigation.map((item) => (
<li key={item.name}>
<button
onClick={() => setSection(item.section)}
className={classNames(
section == item.section
? "bg-gray-50 text-green-600"
: "text-gray-700 hover:text-green-600 hover:bg-gray-50",
"group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold w-full",
)}
>
<item.icon
className={classNames(
section == item.section
? "text-green-600"
: "text-gray-400 group-hover:text-green-600",
"h-6 w-6 shrink-0",
)}
aria-hidden="true"
/>
{item.name}
</button>
</li>
))}
</ul>
</li>
<li className="mt-auto">
<a
href="#"
className="group -mx-2 flex gap-x-3 rounded-md p-2 text-sm font-semibold leading-6 text-gray-700 hover:bg-gray-50 hover:text-green-600"
>
<Cog6ToothIcon
className="h-6 w-6 shrink-0 text-gray-400 group-hover:text-green-600"
aria-hidden="true"
/>
Settings
</a>
</li>
</ul>
</nav>
</div>
</div>
{renderMain(section)}
</div>
);
}
export default App;

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 14 KiB

1
ui/src/assets/react.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -0,0 +1,26 @@
import * as React from "react";
import { Drawer as VDrawer } from "vaul";
export default function Drawer({
trigger,
children,
width,
open,
onOpenChange,
}: any) {
return (
<VDrawer.Root direction="right" open={open} onOpenChange={onOpenChange}>
<VDrawer.Trigger asChild>{trigger}</VDrawer.Trigger>
<VDrawer.Portal>
<VDrawer.Overlay className="fixed inset-0 bg-black/40 z-50" />
<VDrawer.Content
style={{ width: width || "400px" }}
className={`bg-white flex flex-col z-50 h-full mt-24 fixed bottom-0 right-0`}
>
{children}
</VDrawer.Content>
</VDrawer.Portal>
</VDrawer.Root>
);
}

View File

@ -0,0 +1,75 @@
import { DateTime } from 'luxon';
import { ChevronRightIcon } from '@heroicons/react/20/solid'
function msToTime(ms) {
let milliseconds = (ms).toFixed(1);
let seconds = (ms / 1000).toFixed(1);
let minutes = (ms / (1000 * 60)).toFixed(1);
let hours = (ms / (1000 * 60 * 60)).toFixed(1);
let days = (ms / (1000 * 60 * 60 * 24)).toFixed(1);
if (milliseconds < 1000) return milliseconds + "ms";
else if (seconds < 60) return seconds + "s";
else if (minutes < 60) return minutes + "m";
else if (hours < 24) return hours + "hr";
else return days + " Days"
}
export default function HistoryList(props){
return (
<ul
role="list"
className="divide-y divide-gray-100 overflow-hidden bg-white shadow-sm ring-1 ring-gray-900/5"
>
{props.history.map((h) => (
<li key={h.id} className="relative flex justify-between gap-x-6 px-4 py-5 hover:bg-gray-50 sm:px-6">
<div className="flex min-w-0 gap-x-4">
<div className="flex flex-col justify-center">
<p className="flex text-xs text-gray-500 justify-center">{ DateTime.fromMillis(h.timestamp / 1000000).toLocaleString(DateTime.TIME_WITH_SECONDS)}</p>
<p className="flex text-xs mt-1 text-gray-400 justify-center">{ DateTime.fromMillis(h.timestamp / 1000000).toLocaleString(DateTime.DATE_SHORT)}</p>
</div>
<div className="min-w-0 flex-col justify-center">
<pre className="whitespace-pre-wrap"><code className="text-sm">{h.command}</code></pre>
<p className="mt-1 flex text-xs leading-5 text-gray-500">
<span className="relative truncate ">
{h.user}
</span>
<span>&nbsp;on&nbsp;</span>
<span className="relative truncate ">
{h.host}
</span>
<span>&nbsp;in&nbsp;</span>
<span className="relative truncate ">
{h.cwd}
</span>
</p>
</div>
</div>
<div className="flex shrink-0 items-center gap-x-4">
<div className="hidden sm:flex sm:flex-col sm:items-end">
<p className="text-sm leading-6 text-gray-900">{h.exit}</p>
{h.duration ? (
<p className="mt-1 text-xs leading-5 text-gray-500">
<time dateTime={h.duration}>{msToTime(h.duration / 1000000)}</time>
</p>
) : (
<div className="mt-1 flex items-center gap-x-1.5">
<div className="flex-none rounded-full bg-emerald-500/20 p-1">
<div className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
</div>
<p className="text-xs leading-5 text-gray-500">Online</p>
</div>
)}
</div>
<ChevronRightIcon className="h-5 w-5 flex-none text-gray-400" aria-hidden="true" />
</div>
</li>
))}
</ul>
);
}

View File

@ -0,0 +1,56 @@
import { useState } from "react";
import { ArrowPathIcon } from "@heroicons/react/24/outline";
import { MagnifyingGlassIcon } from "@heroicons/react/20/solid";
interface HistorySearchProps {
refresh: (query: string) => void;
}
export default function HistorySearch(props: HistorySearchProps) {
let [searchQuery, setSearchQuery] = useState("");
return (
<div className="flex flex-1 gap-x-4 self-stretch lg:gap-x-6">
<form
className="relative flex flex-1"
onSubmit={(e) => {
e.preventDefault();
}}
>
<label htmlFor="search-field" className="sr-only">
Search
</label>
<MagnifyingGlassIcon
className="pointer-events-none absolute inset-y-0 left-0 h-full w-5 text-gray-400"
aria-hidden="true"
/>
<input
id="search-field"
className="block h-full w-full border-0 py-0 pl-8 pr-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm"
placeholder="Search..."
autoComplete="off"
autoCapitalize="off"
autoCorrect="off"
spellCheck="false"
type="search"
name="search"
onChange={(query) => {
setSearchQuery(query.target.value);
props.refresh(query.target.value);
}}
/>
</form>
<div className="flex items-center gap-x-4 lg:gap-x-6">
<button
type="button"
className="-m-2.5 p-2.5 text-gray-400 hover:text-gray-500"
onClick={() => {
props.refresh(searchQuery);
}}
>
<ArrowPathIcon className="h-6 w-6" aria-hidden="true" />
</button>
</div>
</div>
);
}

View File

@ -0,0 +1,191 @@
import React, { useEffect, useState } from "react";
import DataTable from "@/components/ui/data-table";
import { Button } from "@/components/ui/button";
import { MoreHorizontal } from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { invoke } from "@tauri-apps/api/core";
import Drawer from "@/components/Drawer";
function loadAliases(
setAliases: React.Dispatch<React.SetStateAction<never[]>>,
) {
invoke("aliases").then((aliases: any) => {
setAliases(aliases);
});
}
type Alias = {
name: string;
value: string;
};
function deleteAlias(
name: string,
setAliases: React.Dispatch<React.SetStateAction<never[]>>,
) {
invoke("delete_alias", { name: name })
.then(() => {
console.log("Deleted alias");
loadAliases(setAliases);
})
.catch(() => {
console.error("Failed to delete alias");
});
}
function AddAlias({ onAdd: onAdd }: { onAdd?: () => void }) {
let [name, setName] = useState("");
let [value, setValue] = useState("");
// simple form to add aliases
return (
<div className="p-4">
<h2 className="text-xl font-semibold leading-6 text-gray-900">
Add alias
</h2>
<p className="mt-2">Add a new alias to your shell</p>
<form
className="mt-4"
onSubmit={(e) => {
e.preventDefault();
invoke("set_alias", { name: name, value: value })
.then(() => {
console.log("Added alias");
if (onAdd) onAdd();
})
.catch(() => {
console.error("Failed to add alias");
});
}}
>
<input
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Alias name"
/>
<input
className="mt-4 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
autoComplete="off"
autoCapitalize="off"
autoCorrect="off"
spellCheck="false"
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Alias value"
/>
<input
type="submit"
className="block mt-4 rounded-md bg-green-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-green-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-green-600"
value="Add alias"
/>
</form>
</div>
);
}
export default function Aliases() {
let [aliases, setAliases] = useState([]);
let [aliasDrawerOpen, setAliasDrawerOpen] = useState(false);
const columns: ColumnDef<Alias>[] = [
{
accessorKey: "name",
header: "Name",
},
{
accessorKey: "value",
header: "Value",
},
{
id: "actions",
cell: ({ row }: any) => {
const alias = row.original;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0 float-right">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4 text-right" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem
onClick={() => deleteAlias(alias.name, setAliases)}
>
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
},
},
];
useEffect(() => {
loadAliases(setAliases);
}, []);
return (
<div className="pt-10">
<div className="sm:flex sm:items-center">
<div className="sm:flex-auto">
<h1 className="text-base font-semibold leading-6 text-gray-900">
Aliases
</h1>
<p className="mt-2 text-sm text-gray-700">
Aliases allow you to condense long commands into short,
easy-to-remember commands.
</p>
</div>
<div className="mt-4 sm:ml-16 sm:mt-0 flex-row">
<Drawer
open={aliasDrawerOpen}
onOpenChange={setAliasDrawerOpen}
width="30%"
trigger={
<button
type="button"
className="block rounded-md bg-green-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-green-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-green-600"
>
Add
</button>
}
>
<AddAlias
onAdd={() => {
loadAliases(setAliases);
setAliasDrawerOpen(false);
}}
/>
</Drawer>
</div>
</div>
<div className="mt-8 flow-root">
<div className="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div className="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8">
<DataTable columns={columns} data={aliases} />
</div>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,143 @@
import { useState, useEffect } from "react";
import { invoke } from "@tauri-apps/api/core";
import PacmanLoader from "react-spinners/PacmanLoader";
import {
BarChart,
Bar,
Rectangle,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
} from "recharts";
const tabs = [
{ name: "Daily", href: "#", current: true },
{ name: "Weekly", href: "#", current: false },
{ name: "Monthly", href: "#", current: false },
];
function classNames(...classes) {
return classes.filter(Boolean).join(" ");
}
function renderLoading() {
<div className="flex items-center justify-center h-full">
<PacmanLoader color="#26bd65" />
</div>;
}
export default function Stats() {
const [stats, setStats]: any = useState([]);
const [chart, setChart]: any = useState([]);
console.log("Stats mounted");
useEffect(() => {
if (stats.length != 0) return;
invoke("global_stats")
.then((s: any) => {
console.log(s.daily);
setStats([
{
name: "Total history",
stat: s.total_history.toLocaleString(),
},
{
name: "Last 1d",
stat: s.last_1d.toLocaleString(),
},
{
name: "Last 7d",
stat: s.last_7d.toLocaleString(),
},
{
name: "Last 30d",
stat: s.last_30d.toLocaleString(),
},
]);
setChart(s.daily);
})
.catch((e) => {
console.log(e);
});
}, []);
if (stats.length == 0) {
return renderLoading();
}
return (
<div className="flex flex-col">
<div className="flexfull">
<dl className="grid grid-cols-1 sm:grid-cols-4 w-full">
{stats.map((item) => (
<div
key={item.name}
className="overflow-hidden bg-white px-4 py-5 shadow sm:p-6"
>
<dt className="truncate text-sm font-medium text-gray-500">
{item.name}
</dt>
<dd className="mt-1 text-3xl font-semibold tracking-tight text-gray-900">
{item.stat}
</dd>
</div>
))}
</dl>
</div>
<div className="flex flex-col h-54 py-4 pl-5">
<div className="sm:hidden">
{/* Use an "onChange" listener to redirect the user to the selected tab URL. */}
<select
id="tabs"
name="tabs"
className="block w-full rounded-md border-gray-300 focus:border-green-500 focus:ring-green-500"
defaultValue={tabs.find((tab) => tab.current).name}
>
{tabs.map((tab) => (
<option key={tab.name}>{tab.name}</option>
))}
</select>
</div>
<div className="hidden sm:block">
<nav className="flex space-x-4" aria-label="Tabs">
{tabs.map((tab) => (
<a
key={tab.name}
href={tab.href}
className={classNames(
tab.current
? "bg-gray-100 text-gray-700"
: "text-gray-500 hover:text-gray-700",
"rounded-md px-3 py-2 text-sm font-medium",
)}
aria-current={tab.current ? "page" : undefined}
>
{tab.name}
</a>
))}
</nav>
</div>
<div className="flex flex-col h-48 pt-5 pr-5">
<ResponsiveContainer width="100%" height="100%">
<BarChart width={500} height={300} data={chart}>
<XAxis dataKey="name" hide={true} />
<YAxis />
<Tooltip />
<Bar dataKey="value" fill="#26bd65" />
</BarChart>
</ResponsiveContainer>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,56 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

View File

@ -0,0 +1,80 @@
"use client";
import {
ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
}
export default function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
);
}

View File

@ -0,0 +1,198 @@
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
))
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}

View File

@ -0,0 +1,117 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
))
Table.displayName = "Table"
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
{...props}
/>
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
))
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

6
ui/src/lib/utils.ts Normal file
View File

@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

10
ui/src/main.tsx Normal file
View File

@ -0,0 +1,10 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./styles.css";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);

32
ui/src/pages/Dotfiles.tsx Normal file
View File

@ -0,0 +1,32 @@
import { useState } from "react";
import { Cog6ToothIcon } from "@heroicons/react/24/outline";
import Aliases from "@/components/dotfiles/Aliases";
import { Drawer } from "@/components/drawer";
import { invoke } from "@tauri-apps/api/core";
function Header() {
return (
<div className="md:flex md:items-center md:justify-between">
<div className="min-w-0 flex-1">
<h2 className="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
Dotfiles
</h2>
</div>
</div>
);
}
export default function Dotfiles() {
return (
<div className="pl-60">
<div className="p-10">
<Header />
Manage your shell aliases, variables and paths
<Aliases />
</div>
</div>
);
}

108
ui/src/pages/History.tsx Normal file
View File

@ -0,0 +1,108 @@
import { Fragment, useState, useEffect } from "react";
import { Dialog, Transition } from "@headlessui/react";
import {
Bars3Icon,
ChartPieIcon,
Cog6ToothIcon,
HomeIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import Logo from "../assets/logo-light.svg";
import { invoke } from "@tauri-apps/api/core";
import HistoryList from "@/components/HistoryList.tsx";
import HistorySearch from "@/components/HistorySearch.tsx";
import Stats from "@/components/history/Stats.tsx";
import Drawer from "@/components/Drawer.tsx";
function refreshHistory(
setHistory: React.Dispatch<React.SetStateAction<never[]>>,
query: String | null,
) {
if (query) {
invoke("search", { query: query })
.then((res: any[]) => {
setHistory(res);
})
.catch((e) => {
console.log(e);
});
} else {
invoke("list").then((h: any[]) => {
setHistory(h);
});
}
}
function Header() {
return (
<div className="md:flex md:items-center md:justify-between">
<div className="min-w-0 flex-1">
<h2 className="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
Shell History
</h2>
</div>
<div className="mt-4 flex md:ml-4 md:mt-0">
<Drawer
width="70%"
trigger={
<button
type="button"
className="inline-flex border-2 items-center hover:shadow-xl rounded-md px-2 py-2 text-sm font-semibold shadow-sm"
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className="w-6 h-6"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 0 1 3 19.875v-6.75ZM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V8.625ZM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V4.125Z"
/>
</svg>
</button>
}
>
<Stats />
</Drawer>
</div>
</div>
);
}
export default function Search() {
let [history, setHistory] = useState([]);
useEffect(() => {
refreshHistory(setHistory, null);
}, []);
return (
<>
<div className="pl-60">
<div className="p-10">
<Header />
<p>A history of all the commands you run in your shell.</p>
</div>
<div className="flex h-16 shrink-0 items-center gap-x-4 border-b border-t border-gray-200 bg-white px-4 shadow-sm sm:gap-x-6 sm:px-6 lg:px-8">
<HistorySearch
refresh={(query: String | null) => {
refreshHistory(setHistory, query);
}}
/>
</div>
<main>
<HistoryList history={history} />
</main>
</div>
</>
);
}

76
ui/src/styles.css Normal file
View File

@ -0,0 +1,76 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 222.2 47.4% 11.2%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 210 40% 98%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 212.7 26.8% 83.9%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

1
ui/src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="vite/client" />

77
ui/tailwind.config.js Normal file
View File

@ -0,0 +1,77 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: ["class"],
content: [
'./pages/**/*.{ts,tsx}',
'./components/**/*.{ts,tsx}',
'./app/**/*.{ts,tsx}',
'./src/**/*.{ts,tsx}',
],
prefix: "",
theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
keyframes: {
"accordion-down": {
from: { height: "0" },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: "0" },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
},
},
plugins: [require("tailwindcss-animate")],
}

29
ui/tsconfig.json Normal file
View File

@ -0,0 +1,29 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

10
ui/tsconfig.node.json Normal file
View File

@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}

22
ui/vite.config.ts Normal file
View File

@ -0,0 +1,22 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";
// https://vitejs.dev/config/
export default defineConfig(async () => ({
plugins: [react(), tsconfigPaths()],
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true,
watch: {
// 3. tell vite to ignore watching `src-tauri`
ignored: ["**/src-tauri/**"],
},
},
}));