Compare commits

...

4 Commits

Author SHA1 Message Date
Jeevitha Kannan K S
e1df2bee62
Merge 0b4f33c761 into 76f8e6438b 2024-11-10 16:18:17 +00:00
Jeevitha Kannan K S
0b4f33c761
Implement case insensitive, fix word disappearing bug
Use regex for case insesitive finding, implement String instead of char<Vec>, fix word disappearing by recalculating the render x for preview text
2024-11-10 21:48:05 +05:30
Jeevitha Kannan K S
190c26cd76
Fix scroll beyond list, color bleeding and refact in confirmation.rs
Remove unnecessary usage of pub in ConfirmPropmt struct fields, simplify numbering, prevent scrolling beyond list, fix color bleeding
2024-11-10 21:47:55 +05:30
Real-MullaC
76f8e6438b
docs: new repo (#888)
* Removes docs and mentions on readme

* Update README.md

* Update README.md

Co-authored-by: Adam Perkowski <adas1per@protonmail.com>

* Update linutil.yml

* Delete xtask.yml

* Update preview.yml

* Update README.md

---------

Co-authored-by: Chris Titus <contact@christitus.com>
Co-authored-by: Adam Perkowski <adas1per@protonmail.com>
2024-11-08 17:09:25 -06:00
20 changed files with 103 additions and 551 deletions

89
.github/mkdocs.yml vendored
View File

@ -1,89 +0,0 @@
site_name: Chris Titus LinUtil Official Documentation
repo_url: https://github.com/ChrisTitusTech/linutil
docs_dir: '../docs'
nav:
- Introduction: 'index.md'
- User Guide: 'userguide.md'
- Contributing:
- Contributing Guide: 'contributing.md'
- Roadmap: 'roadmap.md'
- Documentation:
- Known Issues: 'KnownIssues.md'
- FAQ: 'faq.md'
theme:
name: material
custom_dir: '../overrides'
features:
- navigation.tabs
- navigation.sections
- toc.integrate
- navigation.top
- search.suggest
- search.highlight
- content.tabs.link
- content.code.annotation
- content.code.copy
language: en
logo: assets/favicon.png
favicon: assets/favicon.png
palette:
# Palette toggle for automatic mode
- media: "(prefers-color-scheme)"
toggle:
icon: material/brightness-auto
name: Switch to light mode
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
scheme: default
accent: blue
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: black
accent: blue
toggle:
icon: material/weather-night
name: Switch to light mode
markdown_extensions:
- admonition
- pymdownx.details
- pymdownx.superfences
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
- abbr
- attr_list
- pymdownx.snippets
- md_in_html
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true
- pymdownx.highlight:
anchor_linenums: true
line_spans: __span
pygments_lang_class: true
- pymdownx.inlinehilite
- def_list
- pymdownx.tasklist:
custom_checkbox: true
- toc:
permalink: true
plugins:
- search
- awesome-pages
- git-revision-date-localized
- minify:
minify_html: true
htmlmin_opts:
remove_comments: true
cache_safe: true

View File

Before

Width:  |  Height:  |  Size: 1.3 MiB

After

Width:  |  Height:  |  Size: 1.3 MiB

View File

@ -1,56 +0,0 @@
name: GitHub Pages Deploy
on:
push:
paths:
- '.github/mkdocs.yml'
- '.github/requirements.txt'
- 'docs/**'
- 'overrides/**'
- '.github/CONTRIBUTING.md'
workflow_dispatch:
jobs:
build-and-deploy:
runs-on: ubuntu-latest
environment: linutil_env
permissions:
contents: write
pull-requests: write
steps:
- name: Checkout Repository
uses: actions/checkout@v4
with:
fetch-depth: '0' # Fetch all commit history for all branches as well as tags.
- name: Copy Contributing Guidelines
run: |
echo -e "<!-- THIS FILE IS GENERATED AUTOMATICALLY. EDIT .github/CONTRIBUTING.md -->\n\n$(cat .github/CONTRIBUTING.md)" > 'docs/contributing.md'
- name: Create Pull Request
uses: peter-evans/create-pull-request@v6
with:
commit-message: Update Contributing Guidelines
title: 'docs: Update Contributing Guidelines'
body: 'Automated update of Contributing Guidelines from .github/CONTRIBUTING.md'
branch: update-contributing-guidelines
delete-branch: true
base: main
labels: documentation
token: ${{ secrets.PAT_TOKEN }}
if: success()
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: 3.x # Install latest Stable release of Python 3
cache: 'pip' # Caching pip dependencies
- name: Install Necessary Dependencies
run: pip install -r .github/requirements.txt
- name: Build & Deploy using mkdocs
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: mkdocs gh-deploy --force -f .github/mkdocs.yml

View File

@ -59,16 +59,16 @@ jobs:
- name: Generate preview
uses: charmbracelet/vhs-action@v2.1.0
with:
path: "docs/assets/preview.tape"
path: ".github/preview.tape"
- name: Move preview
run: mv preview.gif docs/assets/preview.gif
run: mv preview.gif .github/preview.gif
- name: Create PR
uses: peter-evans/create-pull-request@v7.0.5
with:
commit-message: Preview for ${{ env.tag_name }}
file-pattern: "docs/assets/preview.gif"
file-pattern: ".github/preview.gif"
add-options: "--force"
token: ${{ secrets.PAT_TOKEN }}
branch: feature/preview-${{ env.tag_name }}

View File

@ -1,58 +0,0 @@
name: XTasks
on:
pull_request:
paths:
- "xtask"
- "Cargo.toml"
- "Cargo.lock"
- ".cargo"
- "core/tabs"
- "docs"
push:
paths:
- "xtask"
- "Cargo.toml"
- "Cargo.lock"
- ".cargo"
- "core/tabs"
- "docs"
env:
CARGO_TERM_COLOR: always
jobs:
docgen:
name: DocGen
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Cache Cargo registry
uses: actions/cache@v4
with:
path: ~/.cargo/registry
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.os }}-cargo-registry-
- name: Cache Cargo index
uses: actions/cache@v4
with:
path: ~/.cargo/git
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.os }}-cargo-index-
- name: Run cargo xtask docgen
run: cargo xtask docgen
- name: Check uncommitted documentation changes
run: |
git diff
git diff-files --quiet \
|| (echo "Run 'cargo xtask docgen' and push the changes" \
&& exit 1)

2
Cargo.lock generated
View File

@ -449,13 +449,13 @@ dependencies = [
"portable-pty",
"rand",
"ratatui",
"regex",
"temp-dir",
"textwrap",
"time",
"tree-sitter-bash",
"tree-sitter-highlight",
"tui-term",
"unicode-width 0.2.0",
"zips",
]

View File

@ -7,7 +7,7 @@
<!-- TODO: crates.io package here + <br> -->
[![Crates.io Version](https://img.shields.io/crates/v/linutil_tui?style=for-the-badge&color=%23af3a03)](https://crates.io/crates/linutil_tui) [![linutil AUR Version](https://img.shields.io/aur/version/linutil?style=for-the-badge&label=%5BAUR%5D%20linutil&color=%23230567ff)](https://aur.archlinux.org/packages/linutil) [![linutil-bin AUR Version](https://img.shields.io/aur/version/linutil-bin?style=for-the-badge&label=%5BAUR%5D%20linutil-bin&color=%23230567ff)](https://aur.archlinux.org/packages/linutil-bin)
![Preview](docs/assets/preview.gif)
![Preview](/.github/preview.gif)
**Linutil** is a distro-agnostic toolbox designed to simplify everyday Linux tasks. It helps you set up applications and optimize your system for specific use cases. The utility is actively developed in Rust 🦀, providing performance and reliability.
@ -128,13 +128,15 @@ If you find Linutil helpful, please consider giving it a ⭐️ to show your sup
## 🎓 Documentation
For comprehensive information on how to use Linutil, visit the [Linutil Official Documentation](https://christitustech.github.io/linutil/).
For comprehensive information on how to use Linutil, visit the [Linutil Official Documentation](https://chris-titus-docs.github.io/linutil-docs/).
## 🛠 Contributing
We welcome contributions from the community! Before you start, please review our [Contributing Guidelines](.github/CONTRIBUTING.md) to understand how to make the most effective and efficient contributions.
[Official LinUtil Roadmap](https://christitustech.github.io/linutil/roadmap)
[Official LinUtil Roadmap](https://chris-titus-docs.github.io/linutil-docs/roadmap/)
Docs are now [here](https://github.com/Chris-Titus-Docs/linutil-docs)
## 🏅 Thanks to All Contributors

View File

@ -1,4 +0,0 @@
# Known Issues
---
- [Known Issues](https://github.com/ChrisTitusTech/linutil/issues)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

View File

@ -1,89 +0,0 @@
# VHS documentation
#
# Output:
# Output <path>.gif Create a GIF output at the given <path>
# Output <path>.mp4 Create an MP4 output at the given <path>
# Output <path>.webm Create a WebM output at the given <path>
#
# Require:
# Require <string> Ensure a program is on the $PATH to proceed
#
# Settings:
# Set FontSize <number> Set the font size of the terminal
# Set FontFamily <string> Set the font family of the terminal
# Set Height <number> Set the height of the terminal
# Set Width <number> Set the width of the terminal
# Set LetterSpacing <float> Set the font letter spacing (tracking)
# Set LineHeight <float> Set the font line height
# Set LoopOffset <float>% Set the starting frame offset for the GIF loop
# Set Theme <json|string> Set the theme of the terminal
# Set Padding <number> Set the padding of the terminal
# Set Framerate <number> Set the framerate of the recording
# Set PlaybackSpeed <float> Set the playback speed of the recording
# Set MarginFill <file|#000000> Set the file or color the margin will be filled with.
# Set Margin <number> Set the size of the margin. Has no effect if MarginFill isn't set.
# Set BorderRadius <number> Set terminal border radius, in pixels.
# Set WindowBar <string> Set window bar type. (one of: Rings, RingsRight, Colorful, ColorfulRight)
# Set WindowBarSize <number> Set window bar size, in pixels. Default is 40.
# Set TypingSpeed <time> Set the typing speed of the terminal. Default is 50ms.
#
# Sleep:
# Sleep <time> Sleep for a set amount of <time> in seconds
#
# Type:
# Type[@<time>] "<characters>" Type <characters> into the terminal with a
# <time> delay between each character
#
# Keys:
# Escape[@<time>] [number] Press the Escape key
# Backspace[@<time>] [number] Press the Backspace key
# Delete[@<time>] [number] Press the Delete key
# Insert[@<time>] [number] Press the Insert key
# Down[@<time>] [number] Press the Down key
# Enter[@<time>] [number] Press the Enter key
# Space[@<time>] [number] Press the Space key
# Tab[@<time>] [number] Press the Tab key
# Left[@<time>] [number] Press the Left Arrow key
# Right[@<time>] [number] Press the Right Arrow key
# Up[@<time>] [number] Press the Up Arrow key
# Down[@<time>] [number] Press the Down Arrow key
# PageUp[@<time>] [number] Press the Page Up key
# PageDown[@<time>] [number] Press the Page Down key
# Ctrl+<key> Press the Control key + <key> (e.g. Ctrl+C)
#
# Display:
# Hide Hide the subsequent commands from the output
# Show Show the subsequent commands in the output
Output preview.gif
Require linutil
Require sh
Set Shell "bash"
Set FontFamily "JetBrainsMono Nerd Font"
Set FontSize 24
Set Width 1920
Set Height 1080
Sleep 1s
Type "linutil" Sleep 1s Enter
Sleep 5s
Left Sleep 2s
Down Sleep 1s
Down Sleep 1s
Down Sleep 1s
Down Sleep 2s
Right Sleep 3s
Type "/" Sleep 1s
Type@200ms "System Cleanup" Sleep 1s Enter
Sleep 2s
Enter Sleep 3s
Type "y" Sleep 15s # CONFIRMATION PROMPT
Escape

View File

@ -1,72 +0,0 @@
<!-- THIS FILE IS GENERATED AUTOMATICALLY. EDIT .github/CONTRIBUTING.md -->
# Contributing Guidelines for Linutil
Thank you for considering contributing to Linutil! We appreciate your effort in helping improve this project. To ensure that your contributions align with the goals and quality standards of Linutil, please follow these guidelines:
## 1. **Install Rust**:
Make sure you have Rust installed on your machine. You can install it by following the instructions at [rust-lang.org](https://www.rust-lang.org/tools/install).
## 2. **Fork and Clone the repo**
1. Make a fork of the repo in GitHub
2. Clone the fork
```bash
git clone https://github.com/YOUR_USERNAME_HERE/linutil.git
cd linutil
```
## 3. Make your changes
- **Edit the files you want to change**: Make your changes to the relevant files.
- **Test your changes**: Run `cargo run` to test your modifications in a local environment and ensure everything works as expected.
## 4. Understand the existing code
- **Have a clear reason**: Dont change the way things are done without a valid reason. If you propose an alteration, be prepared to explain why its necessary and how it improves the project.
- **Respect existing conventions**: Changes should align with the existing code style, design patterns, and overall project philosophy. If you want to introduce a new way of doing things, justify it clearly.
## 5. Learn from Past Pull Requests (PRs)
- **Check merged PRs**: Reviewing merged pull requests can give you an idea of what kind of contributions are accepted and how they are implemented.
- **Study rejected PRs**: This is especially important as it helps you avoid making similar mistakes or proposing changes that have already been considered and declined.
## 6. Write Clean, Descriptive Commit Messages
- **Be descriptive**: Your commit messages should clearly describe what the change does and why it was made.
- **Use the imperative mood**: For example, "Add feature X" or "Fix bug in Y", rather than "Added feature X" or "Fixed bug in Y".
- **Keep commits clean**: Avoid committing a change and then immediately following it with a fix for that change. Instead, amend your commit or squash it if needed.
## 7. Keep Your Pull Requests (PRs) Small and Focused
- **Make small, targeted PRs**: Focus on one feature or fix per pull request. This makes it easier to review and increases the likelihood of acceptance.
- **Avoid combining unrelated changes**: PRs that tackle multiple unrelated issues are harder to review and might be rejected because of a single problem.
## 8. Understand and Test the Code You Write
- **Review your code**: Before submitting your changes, take the time to review your code for readability, efficiency and performance. Consider how your changes affect the project.
- **Avoid using LLMs**: Don't submit AI-generated code without reviewing and testing it first. Ensure that any code you submit is thoroughly understood and meets the project's standards.
- **Testing Requirements**: Failure to conduct testing after multiple requests may result in the closure of your Pull Request.
## 9. Code Review and Feedback
- **Expect feedback**: PRs will undergo code review. Be open to feedback and willing to make adjustments as needed.
- **Participate in reviews**: If you feel comfortable, review other contributors' PRs as well. Peer review is a great way to learn and ensure high-quality contributions.
## 10. Contributing Is More Than Just Code
- **Test the tool**: Running tests and providing feedback on how the tool works in different environments is a valuable contribution.
- **Write well-formed issues**: Clearly describe bugs or problems you encounter, providing as much detail as possible, including steps to reproduce the issue.
- **Propose reasonable feature requests**: When suggesting new features, ensure they fit within the scope, style, and design of the project. Provide clear reasoning and use cases.
## 11. Documentation
- **Update the documentation**: If your change affects the functionality, please update the relevant documentation files to reflect this.
- **Automatic generation**: If you decide to add functionality through a new shell script, make sure to fill out all fields in `tab_data.toml` and run `cargo xtask docgen`.
## 12. License
- **Agree to the license**: By contributing to Linutil, you agree that your contributions will be licensed under the project's MIT license.
We appreciate your contributions and look forward to collaborating with you to make Linutil better!

View File

@ -1,4 +0,0 @@
# FAQ's
## How do I uninstall LinUtil?
* You do not have to uninstall LinUtil. As it is a script you run from your terminal it only loads into your RAM. This means as soon as you close LinUtil it will be deleted off your system.

View File

@ -1,76 +0,0 @@
# Welcome to the LinUtil Documentation!
[![Version](https://img.shields.io/github/v/release/ChrisTitusTech/linutil?color=%230567ff&label=Latest%20Release&style=for-the-badge)](https://github.com/ChrisTitusTech/linutil/releases/latest)
![GitHub Downloads (specific asset, all releases)](https://img.shields.io/github/downloads/ChrisTitusTech/linutil/linutil?label=Total%20Downloads&style=for-the-badge)
[![](https://dcbadge.limes.pink/api/server/https://discord.gg/bujFYKAHSp)](https://discord.gg/bujFYKAHSp)
[![Crates.io Version](https://img.shields.io/crates/v/linutil_tui?style=for-the-badge&color=%23af3a03)](https://crates.io/crates/linutil_tui) [![linutil AUR Version](https://img.shields.io/aur/version/linutil?style=for-the-badge&label=%5BAUR%5D%20linutil&color=%23230567ff)](https://aur.archlinux.org/packages/linutil) [![linutil-bin AUR Version](https://img.shields.io/aur/version/linutil-bin?style=for-the-badge&label=%5BAUR%5D%20linutil-bin&color=%23230567ff)](https://aur.archlinux.org/packages/linutil-bin)
## Running the latest release of LinUtil
To get started, run the following command in your terminal:
### Stable branch
```
curl -fsSL https://christitus.com/linux | sh
```
---
### Installation
LinUtil is also available as a package in various repositories:
[![Packaging status](https://repology.org/badge/vertical-allrepos/linutil.svg)](https://repology.org/project/linutil/versions)
<details>
<summary>Arch Linux</summary>
LinUtil can be installed on [Arch Linux](https://archlinux.org) with three different [AUR](https://aur.archlinux.org) packages:
- `linutil` - Stable release compiled from source
- `linutil-bin` - Stable release pre-compiled
- `linutil-git` - Compiled from the last commit (not recommended)
by running:
```bash
git clone https://aur.archlinux.org/<package>.git
cd linutil
makepkg -si
```
Replace `<package>` with your preferred package.
If you use [yay](https://github.com/Jguer/yay), [paru](https://github.com/Morganamilo/paru) or any other [AUR Helper](https://wiki.archlinux.org/title/AUR_helpers), it's even simpler:
```bash
paru -S linutil
```
Replace `paru` with your preferred helper and `linutil` with your preferred package.
</details>
<details>
<summary>Cargo</summary>
LinUtil can be installed via [Cargo](https://doc.rust-lang.org/cargo) with:
```bash
cargo install linutil
```
Note that crates installed using `cargo install` require manual updating with `cargo install --force` (update functionality is [included in LinUtil](https://christitustech.github.io/linutil/userguide/#applications-setup))
</details>
---
After you've ran the command, you should see a GUI on your screen; It will look something like this:
![preview](assets/preview.gif)
!!! info
LinUtil is updated weekly as of the time of writing. Consequently, features and functionalities may evolve, and the documentation may not always reflect the most current images or information.

View File

@ -25,3 +25,4 @@
## Community Feedback
- Encourage community input and suggestions for future development.

View File

@ -140,3 +140,4 @@ https://github.com/ChrisTitusTech/dwm-titus
- **Ollama**: This utility is designed to manage ollama in your system
- **Service Manager**: This utility is designed to manage services in your system
- **WiFi Manager**: This utility is designed to manage wifi in your system

View File

@ -1,12 +0,0 @@
{% extends "base.html" %}
{% block header %}
{{ super() }}
<div style="color: red; text-align: center; padding: 10px; font-size: 20px;">
<strong>Announcement:</strong> This documentation is still in progress.
</div>
{% endblock %}
{% block footer %}
{# Empty block to override the footer #}
{% endblock %}

View File

@ -21,7 +21,6 @@ ratatui = "0.29.0"
tui-term = "0.2.0"
temp-dir = "0.1.14"
time = { version = "0.3.36", features = ["local-offset", "macros", "formatting"] }
unicode-width = "0.2.0"
rand = { version = "0.8.5", optional = true }
linutil_core = { path = "../core", version = "24.9.28" }
tree-sitter-highlight = "0.24.3"
@ -30,6 +29,7 @@ textwrap = "0.16.1"
anstyle = "1.0.8"
ansi-to-tui = "7.0.0"
zips = "0.1.7"
regex = { version = "1.3", default-features = false, features = ["std"] }
[[bin]]
name = "linutil"

View File

@ -14,35 +14,30 @@ pub enum ConfirmStatus {
}
pub struct ConfirmPrompt {
pub names: Box<[String]>,
pub status: ConfirmStatus,
inner_area_height: usize,
names: Box<[String]>,
scroll: usize,
pub status: ConfirmStatus,
}
impl ConfirmPrompt {
pub fn new(names: &[&str]) -> Self {
let max_count_str = format!("{}", names.len());
pub fn new(names: Vec<&str>) -> Self {
let names = names
.iter()
.zip(1..)
.map(|(name, n)| {
let count_str = format!("{n}");
let space_str = (0..(max_count_str.len() - count_str.len()))
.map(|_| ' ')
.collect::<String>();
format!("{space_str}{n}. {name}")
})
.map(|(name, n)| format!(" {n}. {name}"))
.collect();
Self {
inner_area_height: 0,
names,
status: ConfirmStatus::None,
scroll: 0,
status: ConfirmStatus::None,
}
}
pub fn scroll_down(&mut self) {
if self.scroll < self.names.len() - 1 {
if self.scroll + self.inner_area_height < self.names.len() - 1 {
self.scroll += 1;
}
}
@ -72,9 +67,11 @@ impl FloatContent for ConfirmPrompt {
.title_style(Style::default().bold())
.style(Style::default());
frame.render_widget(block.clone(), area);
let inner_area = block.inner(area);
self.inner_area_height = inner_area.height as usize;
frame.render_widget(Clear, area);
frame.render_widget(block, area);
let paths_text = self
.names
@ -86,26 +83,25 @@ impl FloatContent for ConfirmPrompt {
})
.collect::<Text>();
frame.render_widget(Clear, inner_area);
frame.render_widget(List::new(paths_text), inner_area);
}
fn handle_key_event(&mut self, key: &KeyEvent) -> bool {
use KeyCode::*;
use ConfirmStatus::*;
use KeyCode::{Char, Down, Esc, Up};
self.status = match key.code {
Char('y') | Char('Y') => ConfirmStatus::Confirm,
Char('n') | Char('N') | Esc | Char('q') => ConfirmStatus::Abort,
Char('j') => {
Char('y') | Char('Y') => Confirm,
Char('n') | Char('N') | Esc | Char('q') => Abort,
Char('j') | Char('J') | Down => {
self.scroll_down();
ConfirmStatus::None
None
}
Char('k') => {
Char('k') | Char('K') | Up => {
self.scroll_up();
ConfirmStatus::None
None
}
_ => ConfirmStatus::None,
_ => None,
};
false
}
@ -123,8 +119,8 @@ impl FloatContent for ConfirmPrompt {
Box::new([
Shortcut::new("Continue", ["Y", "y"]),
Shortcut::new("Abort", ["N", "n", "q", "Esc"]),
Shortcut::new("Scroll up", ["k"]),
Shortcut::new("Scroll down", ["j"]),
Shortcut::new("Scroll up", ["k", "Up"]),
Shortcut::new("Scroll down", ["j", "Down"]),
Shortcut::new("Close linutil", ["CTRL-c"]),
]),
)

View File

@ -8,7 +8,7 @@ use ratatui::{
widgets::{Block, Borders, Paragraph},
Frame,
};
use unicode_width::UnicodeWidthChar;
use regex::RegexBuilder;
pub enum SearchAction {
None,
@ -17,7 +17,7 @@ pub enum SearchAction {
}
pub struct Filter {
search_input: Vec<char>,
search_input: String,
in_search_mode: bool,
input_position: usize,
items: Vec<ListEntry>,
@ -27,7 +27,7 @@ pub struct Filter {
impl Filter {
pub fn new() -> Self {
Self {
search_input: vec![],
search_input: String::new(),
in_search_mode: false,
input_position: 0,
items: vec![],
@ -62,47 +62,45 @@ impl Filter {
.collect();
} else {
self.items.clear();
let query_lower = self.search_input.iter().collect::<String>().to_lowercase();
for tab in tabs.iter() {
let mut stack = vec![tab.tree.root().id()];
while let Some(node_id) = stack.pop() {
let node = tab.tree.get(node_id).unwrap();
if node.value().name.to_lowercase().contains(&query_lower)
&& !node.has_children()
{
self.items.push(ListEntry {
node: node.value().clone(),
id: node.id(),
has_children: false,
});
if let Ok(regex) = self.regex_builder(&regex::escape(&self.search_input)) {
for tab in tabs {
let mut stack = vec![tab.tree.root().id()];
while let Some(node_id) = stack.pop() {
let node = tab.tree.get(node_id).unwrap();
if regex.is_match(&node.value().name) && !node.has_children() {
self.items.push(ListEntry {
node: node.value().clone(),
id: node.id(),
has_children: false,
});
}
stack.extend(node.children().map(|child| child.id()));
}
stack.extend(node.children().map(|child| child.id()));
}
self.items
.sort_unstable_by(|a, b| a.node.name.cmp(&b.node.name));
} else {
self.search_input.clear();
}
self.items.sort_by(|a, b| a.node.name.cmp(&b.node.name));
}
self.update_completion_preview();
}
fn update_completion_preview(&mut self) {
if self.search_input.is_empty() {
self.completion_preview = None;
return;
}
let input = self.search_input.iter().collect::<String>().to_lowercase();
self.completion_preview = self.items.iter().find_map(|item| {
let item_name_lower = item.node.name.to_lowercase();
if item_name_lower.starts_with(&input) {
Some(item_name_lower[input.len()..].to_string())
self.completion_preview = if self.items.is_empty() || self.search_input.is_empty() {
None
} else {
let pattern = format!("(?i)^{}", regex::escape(&self.search_input));
if let Ok(regex) = self.regex_builder(&pattern) {
self.items.iter().find_map(|item| {
regex
.find(&item.node.name)
.map(|mat| item.node.name[mat.end()..].to_string())
})
} else {
None
}
});
}
}
pub fn draw_searchbar(&self, frame: &mut Frame, area: Rect, theme: &Theme) {
@ -110,8 +108,10 @@ impl Filter {
let display_text = if !self.in_search_mode && self.search_input.is_empty() {
Span::raw("Press / to search")
} else {
let input_text = self.search_input.iter().collect::<String>();
Span::styled(input_text, Style::default().fg(theme.focused_color()))
Span::styled(
&self.search_input,
Style::default().fg(theme.focused_color()),
)
};
let search_color = if self.in_search_mode {
@ -135,25 +135,16 @@ impl Filter {
// Render cursor in search bar
if self.in_search_mode {
let cursor_position: usize = self.search_input[..self.input_position]
.iter()
.map(|c| c.width().unwrap_or(1))
.sum();
let x = area.x + cursor_position as u16 + 1;
let x = area.x + self.input_position as u16 + 1;
let y = area.y + 1;
frame.set_cursor_position(Position::new(x, y));
if let Some(preview) = &self.completion_preview {
let preview_x = area.x + self.search_input.len() as u16 + 1;
let preview_span =
Span::styled(preview, Style::default().fg(theme.search_preview_color()));
let preview_paragraph = Paragraph::new(preview_span).style(Style::default());
let preview_area = Rect::new(
x,
y,
(preview.len() as u16).min(area.width - cursor_position as u16 - 1),
1,
);
frame.render_widget(preview_paragraph, preview_area);
let preview_area = Rect::new(preview_x, y, preview.len() as u16, 1);
frame.render_widget(Paragraph::new(preview_span), preview_area);
}
}
}
@ -220,14 +211,35 @@ impl Filter {
}
}
fn regex_builder(&self, pattern: &str) -> Result<regex::Regex, regex::Error> {
RegexBuilder::new(pattern).case_insensitive(true).build()
}
fn complete_search(&mut self) -> SearchAction {
if let Some(completion) = self.completion_preview.take() {
self.search_input.extend(completion.chars());
self.input_position = self.search_input.len();
self.update_completion_preview();
SearchAction::Update
} else {
if self.completion_preview.is_none() {
SearchAction::None
} else {
let pattern = format!("(?i)^{}", self.search_input);
if let Ok(regex) = self.regex_builder(&pattern) {
self.search_input = self
.items
.iter()
.find_map(|item| {
if regex.is_match(&item.node.name) {
Some(item.node.name.clone())
} else {
None
}
})
.unwrap_or_default();
self.completion_preview = None;
self.input_position = self.search_input.len();
SearchAction::Update
} else {
SearchAction::None
}
}
}

View File

@ -137,7 +137,7 @@ impl AppState {
.map(|node| node.name.as_str())
.collect();
let prompt = ConfirmPrompt::new(&cmd_names);
let prompt = ConfirmPrompt::new(cmd_names);
self.focus = Focus::ConfirmationPrompt(Float::new(Box::new(prompt), 40, 40));
}
}
@ -798,7 +798,7 @@ impl AppState {
.map(|node| node.name.as_str())
.collect::<Vec<_>>();
let prompt = ConfirmPrompt::new(&cmd_names[..]);
let prompt = ConfirmPrompt::new(cmd_names);
self.focus = Focus::ConfirmationPrompt(Float::new(Box::new(prompt), 40, 40));
}
}