feat: make ui.Line renderable (#2743)

This commit is contained in:
三咲雅 · Misaki Masa 2025-05-10 11:50:06 +08:00 committed by GitHub
parent 3ae7673274
commit 41cba40072
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 150 additions and 128 deletions

View file

@ -1,19 +1,17 @@
## Which issue does this PR close? ## Which issue does this PR resolve?
<!-- <!--
For any fixes and enhancements, we usually require an associated issue to be filed where clearly detailed your proposed changes and why they are necessary, which ensures we are aligned and reduces the risk of re-work. For any fixes and enhancements, we usually require an associated issue to be filed where clearly detailed your proposed changes and why they are necessary, which ensures we are aligned and reduces the risk of re-work.
You can use GitHub syntax to link an issue to this PR, such as `Resolves #1000`, which indicates this PR will resolve issue #1000.
--> -->
<!-- Resolves #
You can use GitHub syntax to link an issue to this PR, such as `Closes #1000`, which indicates this PR will close issue #1000.
-->
Closes #
## Rationale of this PR ## Rationale of this PR
<!-- <!--
A clear and concise description of the rationale of this change, to help our reviewers understand your intent and why it is necessary. A clear and concise description of the rationale of the changes, to help our reviewers understand your intent and why it is necessary.
If this has already been detailed in the associated issue, please skip this section. If it already been detailed in the associated issue, please skip this section.
--> -->

View file

@ -26,14 +26,14 @@ Before you begin, ensure you have met the following requirements:
1. Fork the [Yazi repository](https://github.com/sxyazi/yazi) to your GitHub account. 1. Fork the [Yazi repository](https://github.com/sxyazi/yazi) to your GitHub account.
2. Clone your fork to your local machine: 2. Clone your fork to your local machine:
```sh ```sh
git clone https://github.com/<your-username>/yazi.git git clone https://github.com/<your-username>/yazi.git
``` ```
3. Set up the upstream remote: 3. Set up the upstream remote:
```sh ```sh
git remote add upstream https://github.com/sxyazi/yazi.git git remote add upstream https://github.com/sxyazi/yazi.git
``` ```
## Project Structure ## Project Structure
@ -72,29 +72,29 @@ A brief overview of the project's structure:
1. Ensure the latest stable Rust is installed: 1. Ensure the latest stable Rust is installed:
```sh ```sh
rustc --version rustc --version
cargo --version cargo --version
``` ```
2. Build the project: 2. Build the project:
```sh ```sh
cargo build cargo build
``` ```
3. Run the tests: 3. Run the tests:
```sh ```sh
cargo test --workspace --verbose cargo test --workspace --verbose
``` ```
4. Format the code (requires `rustfmt` nightly): 4. Format the code (requires `rustfmt` nightly):
```sh ```sh
rustup component add rustfmt --toolchain nightly rustup component add rustfmt --toolchain nightly
rustfmt +nightly **/*.rs rustfmt +nightly **/*.rs
``` ```
## How to Contribute ## How to Contribute
@ -120,22 +120,22 @@ Contributions related to the icon should be made upstream to facilitate easier a
1. Create a new branch for your changes: 1. Create a new branch for your changes:
```sh ```sh
git checkout -b your-branch-name git checkout -b your-branch-name
``` ```
2. Make your changes. Ensure that your code follows the project's [coding style](https://github.com/sxyazi/yazi/blob/main/rustfmt.toml) and passes all tests. 2. Make your changes. Ensure that your code follows the project's [coding style](https://github.com/sxyazi/yazi/blob/main/rustfmt.toml) and passes all tests.
3. Commit your changes with a descriptive commit message: 3. Commit your changes with a descriptive commit message:
```sh ```sh
git commit -m "feat: an awesome feature" git commit -m "feat: an awesome feature"
``` ```
4. Push your changes to your fork: 4. Push your changes to your fork:
```sh ```sh
git push origin your-branch-name git push origin your-branch-name
``` ```
## Pull Requests ## Pull Requests
@ -147,20 +147,20 @@ We want you to succeed, and it can be discouraging to find that a lot of re-work
1. Ensure your fork is up-to-date with the upstream repository: 1. Ensure your fork is up-to-date with the upstream repository:
```sh ```sh
git fetch upstream git fetch upstream
git checkout main git checkout main
git merge upstream/main git merge upstream/main
``` ```
2. Rebase your feature branch onto the `main` branch: 2. Rebase your feature branch onto the `main` branch:
```sh ```sh
git checkout your-branch-name git checkout your-branch-name
git rebase main git rebase main
``` ```
3. Create a pull request to the `main` branch of the upstream repository. Follow the pull request template and ensure that: 3. Create a pull request to the `main` branch of the upstream repository. Follow the pull request template and ensure that:
- Your code passes all tests and lints. - Your code passes all tests and lints.
- Your pull request description clearly explains the changes and why they are needed. - Your pull request description clearly explains the changes and why they are needed.
4. Address any review comments. Make sure to push updates to the same branch on your fork. 4. Address any review comments. Make sure to push updates to the same branch on your fork.

38
Cargo.lock generated
View file

@ -200,9 +200,9 @@ dependencies = [
[[package]] [[package]]
name = "backtrace" name = "backtrace"
version = "0.3.74" version = "0.3.75"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" checksum = "6806a6321ec58106fea15becdad98371e28d92ccbc7c8f1b3b6dd724fe8f1002"
dependencies = [ dependencies = [
"addr2line", "addr2line",
"cfg-if", "cfg-if",
@ -355,9 +355,9 @@ dependencies = [
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.21" version = "1.2.22"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8691782945451c1c383942c4874dbe63814f61cb57ef773cda2972682b7bb3c0" checksum = "32db95edf998450acc7881c932f94cd9b05c87b4b2599e8bab064753da4acfd1"
dependencies = [ dependencies = [
"jobserver", "jobserver",
"libc", "libc",
@ -416,9 +416,9 @@ dependencies = [
[[package]] [[package]]
name = "clap_complete" name = "clap_complete"
version = "4.5.48" version = "4.5.50"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be8c97f3a6f02b9e24cadc12aaba75201d18754b53ea0a9d99642f806ccdb4c9" checksum = "c91d3baa3bcd889d60e6ef28874126a0b384fd225ab83aa6d8a801c519194ce1"
dependencies = [ dependencies = [
"clap", "clap",
] ]
@ -819,9 +819,9 @@ dependencies = [
[[package]] [[package]]
name = "error-code" name = "error-code"
version = "3.3.1" version = "3.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d9305ccc6942a704f4335694ecd3de2ea531b114ac2d51f5f843750787a92f" checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59"
[[package]] [[package]]
name = "event-listener" name = "event-listener"
@ -1046,9 +1046,9 @@ dependencies = [
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.3.2" version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"libc", "libc",
@ -1276,7 +1276,7 @@ version = "0.1.33"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38f262f097c174adebe41eb73d66ae9c06b2844fb0da69969647bbddd9b0538a" checksum = "38f262f097c174adebe41eb73d66ae9c06b2844fb0da69969647bbddd9b0538a"
dependencies = [ dependencies = [
"getrandom 0.3.2", "getrandom 0.3.3",
"libc", "libc",
] ]
@ -1292,9 +1292,9 @@ dependencies = [
[[package]] [[package]]
name = "kqueue" name = "kqueue"
version = "1.0.8" version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7447f1ca1b7b563588a205fe93dea8df60fd981423a768bc1c0ded35ed147d0c" checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a"
dependencies = [ dependencies = [
"kqueue-sys", "kqueue-sys",
"libc", "libc",
@ -2348,9 +2348,9 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]] [[package]]
name = "signal-hook" name = "signal-hook"
version = "0.3.17" version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
dependencies = [ dependencies = [
"libc", "libc",
"signal-hook-registry", "signal-hook-registry",
@ -2647,9 +2647,9 @@ dependencies = [
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.44.2" version = "1.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48" checksum = "2513ca694ef9ede0fb23fe71a4ee4107cb102b9dc1930f6d0fd77aae068ae165"
dependencies = [ dependencies = [
"backtrace", "backtrace",
"bytes", "bytes",
@ -3320,9 +3320,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]] [[package]]
name = "winnow" name = "winnow"
version = "0.7.9" version = "0.7.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9fb597c990f03753e08d3c29efbfcf2019a003b4bf4ba19225c158e1549f0f3" checksum = "c06928c8748d81b05c9be96aad92e1b6ff01833332f281e8cfca3be4b35fc9ec"
dependencies = [ dependencies = [
"memchr", "memchr",
] ]

View file

@ -45,7 +45,7 @@ scopeguard = "1.2.0"
serde = { version = "1.0.219", features = [ "derive" ] } serde = { version = "1.0.219", features = [ "derive" ] }
serde_json = "1.0.140" serde_json = "1.0.140"
syntect = { version = "5.2.0", default-features = false, features = [ "parsing", "plist-load", "regex-onig" ] } syntect = { version = "5.2.0", default-features = false, features = [ "parsing", "plist-load", "regex-onig" ] }
tokio = { version = "1.44.2", features = [ "full" ] } tokio = { version = "1.45.0", features = [ "full" ] }
tokio-stream = "0.1.17" tokio-stream = "0.1.17"
tokio-util = "0.7.15" tokio-util = "0.7.15"
toml = { version = "0.8.22" } toml = { version = "0.8.22" }

View file

@ -25,7 +25,7 @@ yazi-shared = { path = "../yazi-shared", version = "25.4.8" }
# External dependencies # External dependencies
clap = { workspace = true } clap = { workspace = true }
clap_complete = "4.5.48" clap_complete = "4.5.50"
clap_complete_fig = "4.5.2" clap_complete_fig = "4.5.2"
clap_complete_nushell = "4.5.5" clap_complete_nushell = "4.5.5"
vergen-gitcl = { version = "1.0.8", features = [ "build", "rustc" ] } vergen-gitcl = { version = "1.0.8", features = [ "build", "rustc" ] }

View file

@ -31,7 +31,7 @@ yazi-shared = { path = "../yazi-shared", version = "25.4.8" }
# External build dependencies # External build dependencies
anyhow = { workspace = true } anyhow = { workspace = true }
clap = { workspace = true } clap = { workspace = true }
clap_complete = "4.5.48" clap_complete = "4.5.50"
clap_complete_fig = "4.5.2" clap_complete_fig = "4.5.2"
clap_complete_nushell = "4.5.5" clap_complete_nushell = "4.5.5"
serde_json = { workspace = true } serde_json = { workspace = true }

View file

@ -20,7 +20,7 @@ function Current:empty()
end end
return { return {
ui.Text(s):area(self._area):align(ui.Text.CENTER), ui.Line(s):area(self._area):align(ui.Line.CENTER),
} }
end end

View file

@ -104,8 +104,8 @@ function Header:redraw()
local left = self:children_redraw(self.LEFT) local left = self:children_redraw(self.LEFT)
return { return {
ui.Text(left):area(self._area), ui.Line(left):area(self._area),
ui.Text(right):area(self._area):align(ui.Text.RIGHT), ui.Line(right):area(self._area):align(ui.Line.RIGHT),
} }
end end

View file

@ -140,8 +140,8 @@ function Status:redraw()
return { return {
ui.Text(""):area(self._area):style(th.status.overall), ui.Text(""):area(self._area):style(th.status.overall),
ui.Text(left):area(self._area), ui.Line(left):area(self._area),
ui.Text(right):area(self._area):align(ui.Text.RIGHT), ui.Line(right):area(self._area):align(ui.Line.RIGHT),
table.unpack(ya.redraw_with(Progress:new(self._area, right_width))), table.unpack(ya.redraw_with(Progress:new(self._area, right_width))),
} }
end end

View file

@ -16,7 +16,7 @@ function M:peek(job)
if #folder.files == 0 then if #folder.files == 0 then
local done, err = folder.stage() local done, err = folder.stage()
local s = not done and "Loading..." or not err and "No items" or string.format("Error: %s", err) local s = not done and "Loading..." or not err and "No items" or string.format("Error: %s", err)
return ya.preview_widget(job, ui.Text(s):area(job.area):align(ui.Text.CENTER)) return ya.preview_widget(job, ui.Line(s):area(job.area):align(ui.Line.CENTER))
end end
local entities = {} local entities = {}

View file

@ -16,7 +16,7 @@ function M:peek(job)
ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock())) ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock()))
local _, err = ya.image_show(cache, job.area) local _, err = ya.image_show(cache, job.area)
ya.preview_widget(job, err and ui.Text(tostring(err)):wrap(ui.Text.WRAP)) ya.preview_widget(job, err and ui.Text(tostring(err)):area(job.area):wrap(ui.Text.WRAP))
end end
function M:seek() end function M:seek() end

View file

@ -14,7 +14,7 @@ function M:peek(job)
ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock())) ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock()))
local _, err = ya.image_show(cache, job.area) local _, err = ya.image_show(cache, job.area)
ya.preview_widget(job, err and ui.Text(tostring(err)):wrap(ui.Text.WRAP)) ya.preview_widget(job, err and ui.Text(tostring(err)):area(job.area):wrap(ui.Text.WRAP))
end end
function M:seek() end function M:seek() end

View file

@ -14,7 +14,7 @@ function M:peek(job)
ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock())) ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock()))
local _, err = ya.image_show(cache, job.area) local _, err = ya.image_show(cache, job.area)
ya.preview_widget(job, err and ui.Text(tostring(err)):wrap(ui.Text.WRAP)) ya.preview_widget(job, err and ui.Text(tostring(err)):area(job.area):wrap(ui.Text.WRAP))
end end
function M:seek(job) function M:seek(job)

View file

@ -14,7 +14,7 @@ function M:peek(job)
ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock())) ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock()))
local _, err = ya.image_show(cache, job.area) local _, err = ya.image_show(cache, job.area)
ya.preview_widget(job, err and ui.Text(tostring(err)):wrap(ui.Text.WRAP)) ya.preview_widget(job, err and ui.Text(tostring(err)):area(job.area):wrap(ui.Text.WRAP))
end end
function M:seek() end function M:seek() end

View file

@ -14,7 +14,7 @@ function M:peek(job)
ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock())) ya.sleep(math.max(0, rt.preview.image_delay / 1000 + start - os.clock()))
local _, err = ya.image_show(cache, job.area) local _, err = ya.image_show(cache, job.area)
ya.preview_widget(job, err and ui.Text(tostring(err)):wrap(ui.Text.WRAP)) ya.preview_widget(job, err and ui.Text(tostring(err)):area(job.area):wrap(ui.Text.WRAP))
end end
function M:seek(job) function M:seek(job)

View file

@ -1,4 +1,4 @@
use mlua::{Lua, MetaMethod, Table, UserData}; use mlua::{AnyUserData, Lua, MetaMethod, Table, UserData};
use ratatui::widgets::Borders; use ratatui::widgets::Borders;
use super::Area; use super::Area;

View file

@ -1,4 +1,4 @@
use mlua::{Lua, MetaMethod, Table, UserData, Value}; use mlua::{AnyUserData, Lua, MetaMethod, Table, UserData, Value};
use ratatui::widgets::{Borders, Widget}; use ratatui::widgets::{Borders, Widget};
use super::Area; use super::Area;
@ -99,7 +99,7 @@ impl UserData for Border {
ratatui::widgets::block::Position::Top ratatui::widgets::block::Position::Top
}; };
ud.borrow_mut::<Self>()?.titles.push((position, Line::try_from(line)?.0)); ud.borrow_mut::<Self>()?.titles.push((position, Line::try_from(line)?.inner));
Ok(ud) Ok(ud)
}, },
); );

View file

@ -1,4 +1,4 @@
use mlua::{ExternalError, Lua, MetaMethod, Table, UserData, UserDataMethods, Value}; use mlua::{AnyUserData, ExternalError, Lua, MetaMethod, Table, UserData, UserDataMethods, Value};
use ratatui::widgets::Widget; use ratatui::widgets::Widget;
use super::{Area, Span}; use super::{Area, Span};

View file

@ -2,9 +2,10 @@ use std::mem;
use ansi_to_tui::IntoText; use ansi_to_tui::IntoText;
use mlua::{AnyUserData, ExternalError, ExternalResult, IntoLua, Lua, MetaMethod, Table, UserData, UserDataMethods, Value}; use mlua::{AnyUserData, ExternalError, ExternalResult, IntoLua, Lua, MetaMethod, Table, UserData, UserDataMethods, Value};
use ratatui::widgets::Widget;
use unicode_width::UnicodeWidthChar; use unicode_width::UnicodeWidthChar;
use super::Span; use super::{Area, Span};
const LEFT: u8 = 0; const LEFT: u8 = 0;
const CENTER: u8 = 1; const CENTER: u8 = 1;
@ -12,7 +13,12 @@ const RIGHT: u8 = 2;
const EXPECTED: &str = "expected a string, Span, Line, or a table of them"; const EXPECTED: &str = "expected a string, Span, Line, or a table of them";
pub struct Line(pub(super) ratatui::text::Line<'static>); #[derive(Clone, Debug, Default)]
pub struct Line {
area: Area,
pub(super) inner: ratatui::text::Line<'static>,
}
impl Line { impl Line {
pub fn compose(lua: &Lua) -> mlua::Result<Table> { pub fn compose(lua: &Lua) -> mlua::Result<Table> {
@ -21,15 +27,15 @@ impl Line {
let parse = lua.create_function(|_, code: mlua::String| { let parse = lua.create_function(|_, code: mlua::String| {
let code = code.as_bytes(); let code = code.as_bytes();
let Some(line) = code.split_inclusive(|&b| b == b'\n').next() else { let Some(line) = code.split_inclusive(|&b| b == b'\n').next() else {
return Ok(Line(Default::default())); return Ok(Line::default());
}; };
let mut lines = line.into_text().into_lua_err()?.lines; let mut lines = line.into_text().into_lua_err()?.lines;
if lines.is_empty() { if lines.is_empty() {
return Ok(Line(Default::default())); return Ok(Line::default());
} }
Ok(Line(mem::take(&mut lines[0]))) Ok(Line { inner: mem::take(&mut lines[0]), ..Default::default() })
})?; })?;
let line = lua.create_table_from([ let line = lua.create_table_from([
@ -43,27 +49,38 @@ impl Line {
line.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?)); line.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?));
Ok(line) Ok(line)
} }
pub(super) fn render(
self,
buf: &mut ratatui::buffer::Buffer,
trans: impl Fn(yazi_config::popup::Position) -> ratatui::layout::Rect,
) {
let rect = self.area.transform(trans);
self.inner.render(rect, buf);
}
} }
impl TryFrom<Value> for Line { impl TryFrom<Value> for Line {
type Error = mlua::Error; type Error = mlua::Error;
fn try_from(value: Value) -> Result<Self, Self::Error> { fn try_from(value: Value) -> Result<Self, Self::Error> {
Ok(Self(match value { Ok(Self {
Value::Table(tb) => return Self::try_from(tb), inner: match value {
Value::String(s) => s.to_string_lossy().into(), Value::Table(tb) => return Self::try_from(tb),
Value::UserData(ud) => { Value::String(s) => s.to_string_lossy().into(),
if let Ok(Span(span)) = ud.take() { Value::UserData(ud) => {
span.into() if let Ok(Span(span)) = ud.take() {
} else if let Ok(Line(mut line)) = ud.take() { span.into()
line.spans.iter_mut().for_each(|s| s.style = line.style.patch(s.style)); } else if let Ok(line) = ud.take() {
line return Ok(line);
} else { } else {
Err(EXPECTED.into_lua_err())? Err(EXPECTED.into_lua_err())?
}
} }
} _ => Err(EXPECTED.into_lua_err())?,
_ => Err(EXPECTED.into_lua_err())?, },
})) ..Default::default()
})
} }
} }
@ -78,7 +95,7 @@ impl TryFrom<Table> for Line {
Value::UserData(ud) => { Value::UserData(ud) => {
if let Ok(Span(span)) = ud.take() { if let Ok(Span(span)) = ud.take() {
spans.push(span); spans.push(span);
} else if let Ok(Line(mut line)) = ud.take() { } else if let Ok(Line { inner: mut line, .. }) = ud.take() {
line.spans.iter_mut().for_each(|s| s.style = line.style.patch(s.style)); line.spans.iter_mut().for_each(|s| s.style = line.style.patch(s.style));
spans.extend(line.spans); spans.extend(line.spans);
} else { } else {
@ -88,30 +105,31 @@ impl TryFrom<Table> for Line {
_ => Err(EXPECTED.into_lua_err())?, _ => Err(EXPECTED.into_lua_err())?,
} }
} }
Ok(Self(spans.into())) Ok(Self { inner: spans.into(), ..Default::default() })
} }
} }
impl From<Line> for ratatui::text::Line<'static> { impl From<Line> for ratatui::text::Line<'static> {
fn from(value: Line) -> Self { value.0 } fn from(value: Line) -> Self { value.inner }
} }
impl UserData for Line { impl UserData for Line {
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
crate::impl_style_method!(methods, 0.style); crate::impl_area_method!(methods);
crate::impl_style_shorthands!(methods, 0.style); crate::impl_style_method!(methods, inner.style);
crate::impl_style_shorthands!(methods, inner.style);
methods.add_method("width", |_, Line(me), ()| Ok(me.width())); methods.add_method("width", |_, me, ()| Ok(me.inner.width()));
methods.add_function_mut("align", |_, (ud, align): (AnyUserData, u8)| { methods.add_function_mut("align", |_, (ud, align): (AnyUserData, u8)| {
ud.borrow_mut::<Self>()?.0.alignment = Some(match align { ud.borrow_mut::<Self>()?.inner.alignment = Some(match align {
CENTER => ratatui::layout::Alignment::Center, CENTER => ratatui::layout::Alignment::Center,
RIGHT => ratatui::layout::Alignment::Right, RIGHT => ratatui::layout::Alignment::Right,
_ => ratatui::layout::Alignment::Left, _ => ratatui::layout::Alignment::Left,
}); });
Ok(ud) Ok(ud)
}); });
methods.add_method("visible", |_, Line(me), ()| { methods.add_method("visible", |_, me, ()| {
Ok(me.iter().flat_map(|s| s.content.chars()).any(|c| c.width().unwrap_or(0) > 0)) Ok(me.inner.iter().flat_map(|s| s.content.chars()).any(|c| c.width().unwrap_or(0) > 0))
}); });
} }
} }

View file

@ -1,9 +1,10 @@
use mlua::{AnyUserData, ExternalError}; use mlua::{AnyUserData, ExternalError};
use super::{Bar, Border, Clear, Gauge, List, Table, Text}; use super::{Bar, Border, Clear, Gauge, Line, List, Table, Text};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum Renderable { pub enum Renderable {
Line(Line),
Text(Text), Text(Text),
List(List), List(List),
Bar(Bar), Bar(Bar),
@ -20,6 +21,7 @@ impl Renderable {
trans: impl Fn(yazi_config::popup::Position) -> ratatui::layout::Rect, trans: impl Fn(yazi_config::popup::Position) -> ratatui::layout::Rect,
) { ) {
match self { match self {
Self::Line(line) => line.render(buf, trans),
Self::Text(text) => text.render(buf, trans), Self::Text(text) => text.render(buf, trans),
Self::List(list) => list.render(buf, trans), Self::List(list) => list.render(buf, trans),
Self::Bar(bar) => bar.render(buf, trans), Self::Bar(bar) => bar.render(buf, trans),
@ -35,7 +37,9 @@ impl TryFrom<AnyUserData> for Renderable {
type Error = mlua::Error; type Error = mlua::Error;
fn try_from(ud: AnyUserData) -> Result<Self, Self::Error> { fn try_from(ud: AnyUserData) -> Result<Self, Self::Error> {
Ok(if let Ok(c) = ud.take::<crate::elements::Text>() { Ok(if let Ok(c) = ud.take::<crate::elements::Line>() {
Self::Line(c)
} else if let Ok(c) = ud.take::<crate::elements::Text>() {
Self::Text(c) Self::Text(c)
} else if let Ok(c) = ud.take::<crate::elements::List>() { } else if let Ok(c) = ud.take::<crate::elements::List>() {
Self::List(c) Self::List(c)

View file

@ -1,7 +1,7 @@
use std::mem; use std::mem;
use ansi_to_tui::IntoText; use ansi_to_tui::IntoText;
use mlua::{ExternalError, ExternalResult, IntoLua, Lua, MetaMethod, Table, UserData, Value}; use mlua::{AnyUserData, ExternalError, ExternalResult, IntoLua, Lua, MetaMethod, Table, UserData, Value};
use ratatui::widgets::Widget; use ratatui::widgets::Widget;
use super::{Area, Line, Span}; use super::{Area, Line, Span};
@ -74,7 +74,7 @@ impl TryFrom<Value> for Text {
Value::Table(tb) => return Self::try_from(tb), Value::Table(tb) => return Self::try_from(tb),
Value::String(s) => s.to_string_lossy().into(), Value::String(s) => s.to_string_lossy().into(),
Value::UserData(ud) => { Value::UserData(ud) => {
if let Ok(Line(line)) = ud.take() { if let Ok(Line { inner: line, .. }) = ud.take() {
line.into() line.into()
} else if let Ok(Span(span)) = ud.take() { } else if let Ok(Span(span)) = ud.take() {
span.into() span.into()
@ -101,7 +101,7 @@ impl TryFrom<Table> for Text {
Value::UserData(ud) => { Value::UserData(ud) => {
if let Ok(Span(span)) = ud.take() { if let Ok(Span(span)) = ud.take() {
lines.push(span.into()); lines.push(span.into());
} else if let Ok(Line(line)) = ud.take() { } else if let Ok(Line { inner: line, .. }) = ud.take() {
lines.push(line); lines.push(line);
} else { } else {
return Err(EXPECTED.into_lua_err()); return Err(EXPECTED.into_lua_err());

View file

@ -11,16 +11,18 @@ macro_rules! impl_style_method {
#[macro_export] #[macro_export]
macro_rules! impl_area_method { macro_rules! impl_area_method {
($methods:ident) => { ($methods:ident) => {
use mlua::{AnyUserData, IntoLua}; $methods.add_function_mut(
"area",
$methods.add_function_mut("area", |lua, (ud, area): (AnyUserData, Option<AnyUserData>)| { |lua, (ud, area): (mlua::AnyUserData, Option<mlua::AnyUserData>)| {
if let Some(v) = area { use mlua::IntoLua;
ud.borrow_mut::<Self>()?.area = $crate::elements::Area::try_from(v)?; if let Some(v) = area {
ud.into_lua(lua) ud.borrow_mut::<Self>()?.area = $crate::elements::Area::try_from(v)?;
} else { ud.into_lua(lua)
ud.borrow::<Self>()?.area.into_lua(lua) } else {
} ud.borrow::<Self>()?.area.into_lua(lua)
}); }
},
);
}; };
} }