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.
You can use GitHub syntax to link an issue to this PR, such as `Resolves #1000`, which indicates this PR will resolve issue #1000.
-->
<!--
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 #
Resolves #
## 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.
-->

38
Cargo.lock generated
View file

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

View file

@ -45,7 +45,7 @@ scopeguard = "1.2.0"
serde = { version = "1.0.219", features = [ "derive" ] }
serde_json = "1.0.140"
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-util = "0.7.15"
toml = { version = "0.8.22" }

View file

@ -25,7 +25,7 @@ yazi-shared = { path = "../yazi-shared", version = "25.4.8" }
# External dependencies
clap = { workspace = true }
clap_complete = "4.5.48"
clap_complete = "4.5.50"
clap_complete_fig = "4.5.2"
clap_complete_nushell = "4.5.5"
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
anyhow = { workspace = true }
clap = { workspace = true }
clap_complete = "4.5.48"
clap_complete = "4.5.50"
clap_complete_fig = "4.5.2"
clap_complete_nushell = "4.5.5"
serde_json = { workspace = true }

View file

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

View file

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

View file

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

View file

@ -16,7 +16,7 @@ function M:peek(job)
if #folder.files == 0 then
local done, err = folder.stage()
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
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()))
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
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()))
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
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()))
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
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()))
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
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()))
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
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 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 super::Area;
@ -99,7 +99,7 @@ impl UserData for Border {
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)
},
);

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 super::{Area, Span};

View file

@ -2,9 +2,10 @@ use std::mem;
use ansi_to_tui::IntoText;
use mlua::{AnyUserData, ExternalError, ExternalResult, IntoLua, Lua, MetaMethod, Table, UserData, UserDataMethods, Value};
use ratatui::widgets::Widget;
use unicode_width::UnicodeWidthChar;
use super::Span;
use super::{Area, Span};
const LEFT: u8 = 0;
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";
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 {
pub fn compose(lua: &Lua) -> mlua::Result<Table> {
@ -21,15 +27,15 @@ impl Line {
let parse = lua.create_function(|_, code: mlua::String| {
let code = code.as_bytes();
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;
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([
@ -43,27 +49,38 @@ impl Line {
line.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?));
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 {
type Error = mlua::Error;
fn try_from(value: Value) -> Result<Self, Self::Error> {
Ok(Self(match value {
Ok(Self {
inner: match value {
Value::Table(tb) => return Self::try_from(tb),
Value::String(s) => s.to_string_lossy().into(),
Value::UserData(ud) => {
if let Ok(Span(span)) = ud.take() {
span.into()
} else if let Ok(Line(mut line)) = ud.take() {
line.spans.iter_mut().for_each(|s| s.style = line.style.patch(s.style));
line
} else if let Ok(line) = ud.take() {
return Ok(line);
} else {
Err(EXPECTED.into_lua_err())?
}
}
_ => Err(EXPECTED.into_lua_err())?,
}))
},
..Default::default()
})
}
}
@ -78,7 +95,7 @@ impl TryFrom<Table> for Line {
Value::UserData(ud) => {
if let Ok(Span(span)) = ud.take() {
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));
spans.extend(line.spans);
} else {
@ -88,30 +105,31 @@ impl TryFrom<Table> for Line {
_ => Err(EXPECTED.into_lua_err())?,
}
}
Ok(Self(spans.into()))
Ok(Self { inner: spans.into(), ..Default::default() })
}
}
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 {
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
crate::impl_style_method!(methods, 0.style);
crate::impl_style_shorthands!(methods, 0.style);
crate::impl_area_method!(methods);
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)| {
ud.borrow_mut::<Self>()?.0.alignment = Some(match align {
ud.borrow_mut::<Self>()?.inner.alignment = Some(match align {
CENTER => ratatui::layout::Alignment::Center,
RIGHT => ratatui::layout::Alignment::Right,
_ => ratatui::layout::Alignment::Left,
});
Ok(ud)
});
methods.add_method("visible", |_, Line(me), ()| {
Ok(me.iter().flat_map(|s| s.content.chars()).any(|c| c.width().unwrap_or(0) > 0))
methods.add_method("visible", |_, me, ()| {
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 super::{Bar, Border, Clear, Gauge, List, Table, Text};
use super::{Bar, Border, Clear, Gauge, Line, List, Table, Text};
#[derive(Clone, Debug)]
pub enum Renderable {
Line(Line),
Text(Text),
List(List),
Bar(Bar),
@ -20,6 +21,7 @@ impl Renderable {
trans: impl Fn(yazi_config::popup::Position) -> ratatui::layout::Rect,
) {
match self {
Self::Line(line) => line.render(buf, trans),
Self::Text(text) => text.render(buf, trans),
Self::List(list) => list.render(buf, trans),
Self::Bar(bar) => bar.render(buf, trans),
@ -35,7 +37,9 @@ impl TryFrom<AnyUserData> for Renderable {
type Error = mlua::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)
} else if let Ok(c) = ud.take::<crate::elements::List>() {
Self::List(c)

View file

@ -1,7 +1,7 @@
use std::mem;
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 super::{Area, Line, Span};
@ -74,7 +74,7 @@ impl TryFrom<Value> for Text {
Value::Table(tb) => return Self::try_from(tb),
Value::String(s) => s.to_string_lossy().into(),
Value::UserData(ud) => {
if let Ok(Line(line)) = ud.take() {
if let Ok(Line { inner: line, .. }) = ud.take() {
line.into()
} else if let Ok(Span(span)) = ud.take() {
span.into()
@ -101,7 +101,7 @@ impl TryFrom<Table> for Text {
Value::UserData(ud) => {
if let Ok(Span(span)) = ud.take() {
lines.push(span.into());
} else if let Ok(Line(line)) = ud.take() {
} else if let Ok(Line { inner: line, .. }) = ud.take() {
lines.push(line);
} else {
return Err(EXPECTED.into_lua_err());

View file

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