use std::{
ops::Range,
sync::{Arc, Mutex},
time::Duration,
};
use super::{
code_tokens::{TokenStyles, code_tokens, code_tokens_kept},
icons, names,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
scroll_area::{ScrollArea, ScrollAreaOrientation, ScrollAreaPart},
shared::{fading, glyph, one_line, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::{Ctx, Timeout},
events::{MouseEvent, TextInputEvent},
theme::{BorderSize, CodeScheme, IconSize, PaletteColor, RadiusSize, Theme, TypographyStyle},
window::Window,
},
code::{CodeToken, CodeTokenizer},
components::{Column, LineGutter, Row, TextInput},
core::{ElementRef, Signal},
layout::{
Alignment,
layout_kind::Justify,
quad::RichTextSpan,
text_style::{TextAlign, TextStyle},
},
node::{
Element, Node, TextColor,
border::Border,
dimension::Dimension,
gradient::{Gradient, GradientStop},
},
ui::{Length, PartStyle},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CodeBlockPart {
Root,
Header,
Title,
Copy,
CopyIcon,
Body,
Code,
LineNumber,
Marked,
}
names!(CodeBlockPart {
Root => "root",
Header => "header",
Title => "title",
Copy => "copy",
CopyIcon => "copy_icon",
Body => "body",
Code => "code",
LineNumber => "line_number",
Marked => "marked",
});
const OWN_PARTS: &[&str] = &[
"root",
"header",
"title",
"copy",
"copy_icon",
"body",
"code",
"line_number",
"marked",
];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CodeBlockState {
Header,
LineNumbers,
Wrap,
Copied,
CopyFailed,
Framed,
}
names!(CodeBlockState {
Header => "header",
LineNumbers => "line_numbers",
Wrap => "wrap",
Copied => "copied",
CopyFailed => "copy_failed",
Framed => "framed",
});
pub type CodeBlockRenderer = Arc<dyn Fn(CodeBlockView) -> Element + Send + Sync>;
pub const CODE_BLOCK_COPIED_FOR: Duration = Duration::from_secs(2);
pub const CODE_BLOCK_WINDOWED_LINES: usize = 400;
const CHUNK: usize = 64;
type CopyHandler = Arc<dyn Fn(&str) + Send + Sync>;
#[derive(Clone)]
pub struct CodeBlock {
code: Arc<str>,
language: Option<Arc<str>>,
tokenizer: Option<CodeTokenizer>,
scheme: Option<Arc<CodeScheme>>,
kept: Option<Arc<Mutex<crate::code::LineCache>>>,
title: Option<Arc<str>>,
label: Option<Arc<str>>,
line_numbers: bool,
first_line: usize,
highlighted: Vec<usize>,
wrap: bool,
min_height: Option<Length>,
max_height: Option<Length>,
copy_button: bool,
copy_label: Arc<str>,
copied_text: Arc<str>,
copy_failed_text: Arc<str>,
copy_text: Option<Arc<str>>,
on_copy: Vec<CopyHandler>,
selectable: bool,
framed: bool,
row_height: f32,
header: Option<bool>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
pub const CODE_BLOCK_ROW_HEIGHT: f32 = 21.0;
impl CodeBlock {
pub fn new(code: &str) -> Self {
Self {
code: Arc::from(code.strip_suffix('\n').unwrap_or(code)),
language: None,
tokenizer: None,
scheme: None,
kept: None,
title: None,
label: None,
line_numbers: false,
first_line: 1,
highlighted: Vec::new(),
wrap: false,
min_height: None,
max_height: None,
copy_button: true,
copy_label: super::current_locale().editing.copy_code.clone(),
copied_text: super::current_locale().editing.copied.clone(),
copy_failed_text: super::current_locale().editing.copy_failed.clone(),
copy_text: None,
on_copy: Vec::new(),
selectable: true,
framed: true,
row_height: CODE_BLOCK_ROW_HEIGHT,
header: None,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn language(mut self, language: &str) -> Self {
self.language = Some(Arc::from(language));
self
}
pub fn tokenizer(mut self, tokenizer: impl Into<CodeTokenizer>) -> Self {
self.tokenizer = Some(tokenizer.into());
self
}
pub fn token_style(self, name: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.style(name, style)
}
pub fn code_scheme(mut self, scheme: CodeScheme) -> Self {
self.scheme = Some(Arc::new(scheme));
self
}
pub fn title(mut self, title: &str) -> Self {
self.title = Some(Arc::from(title));
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn line_numbers(mut self, line_numbers: bool) -> Self {
self.line_numbers = line_numbers;
self
}
pub fn first_line(mut self, number: usize) -> Self {
self.first_line = number;
self
}
pub fn highlight_lines(mut self, lines: impl IntoIterator<Item = usize>) -> Self {
self.highlighted.extend(lines);
self
}
pub fn wrap(mut self, wrap: bool) -> Self {
self.wrap = wrap;
self
}
pub fn min_height(mut self, height: impl Into<Length>) -> Self {
self.min_height = Some(height.into());
self
}
pub fn max_height(mut self, height: impl Into<Length>) -> Self {
self.max_height = Some(height.into());
self
}
pub fn copy_button(mut self, copy_button: bool) -> Self {
self.copy_button = copy_button;
self
}
pub fn copy_label(mut self, label: &str) -> Self {
self.copy_label = Arc::from(label);
self
}
pub fn copied_text(mut self, text: &str) -> Self {
self.copied_text = Arc::from(text);
self
}
pub fn copy_failed_text(mut self, text: &str) -> Self {
self.copy_failed_text = Arc::from(text);
self
}
pub fn copy_text(mut self, text: &str) -> Self {
self.copy_text = Some(Arc::from(text));
self
}
pub fn on_copy(mut self, handler: impl Fn(&str) + Send + Sync + 'static) -> Self {
self.on_copy.push(Arc::new(handler));
self
}
pub fn selectable(mut self, selectable: bool) -> Self {
self.selectable = selectable;
self
}
pub fn framed(mut self, framed: bool) -> Self {
self.framed = framed;
self
}
pub fn header(mut self, header: bool) -> Self {
self.header = Some(header);
self
}
pub fn row_height(mut self, height: f32) -> Self {
self.row_height = height.max(1.0);
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn mount(self, ctx: &mut Ctx) -> Element {
ctx.mount::<CodeBlockHost>(CodeBlockProps(Arc::new(self)))
}
pub fn build(self, theme: &Theme) -> Element {
self.build_with(theme, None)
}
pub(crate) fn kept_lines(mut self, kept: Arc<Mutex<crate::code::LineCache>>) -> Self {
self.kept = Some(kept);
self
}
fn windowed(&self, mounted: bool) -> bool {
(mounted || self.bounded()) && self.code.bytes().filter(|byte| *byte == b'\n').count() >= CODE_BLOCK_WINDOWED_LINES
}
fn bounded(&self) -> bool {
matches!(self.max_height, Some(Length::Px(_)))
}
fn build_with(self, theme: &Theme, host: Option<&CodeBlockHost>) -> Element {
let copied = host.map(|host| host.copied.clone());
let has_header = self
.header
.unwrap_or(self.copy_button || self.title.is_some() || self.language.is_some());
let is_copied = copied.as_ref().is_some_and(|copied| copied.on.get());
let copy_failed = copied.as_ref().is_some_and(|copied| copied.failed.get());
let mut case = Case::new()
.breakpoint(super::current_breakpoint())
.state(CodeBlockState::Header, has_header)
.state(CodeBlockState::LineNumbers, self.line_numbers)
.state(CodeBlockState::Wrap, self.wrap)
.state(CodeBlockState::Copied, is_copied)
.state(CodeBlockState::CopyFailed, copy_failed)
.state(CodeBlockState::Framed, self.framed);
for state in &self.states {
case = case.state(state.clone(), true);
}
let kept = self.kept.clone().or_else(|| host.map(|host| host.lines.clone()));
let tokens = code_tokens_kept(
&self.code,
self.language.as_deref(),
self.tokenizer.as_ref(),
kept.as_deref(),
);
let shown = host.and_then(|host| host.follow.window.get());
let window = self.windowed(host.is_some()).then(|| CodeWindow {
lines: shown.map(|(start, end, _)| start..end),
width: shown.map(|(.., width)| width as f32).filter(|width| *width > 0.0),
follow: host.map(|host| host.follow.clone()),
screen: host
.and_then(|host| host.follow.screen_height())
.filter(|height| *height > 0.0),
});
let view = CodeBlockView {
code: self.code,
language: self.language,
tokenizer: self.tokenizer,
scheme: self.scheme,
tokens,
lines_window: window,
title: self.title,
label: self.label,
line_numbers: self.line_numbers,
first_line: self.first_line,
highlighted: self.highlighted,
wrap: self.wrap,
min_height: self.min_height,
max_height: self.max_height,
copy_button: self.copy_button,
copy_label: self.copy_label,
copied_text: self.copied_text,
copy_failed_text: self.copy_failed_text,
copy_text: self.copy_text,
copied: is_copied,
copy_failed,
on_copy: self.on_copy,
selectable: self.selectable,
framed: self.framed,
row_height: self.row_height,
has_header,
recipe: theme
.resolve::<CodeBlock>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
forced: self.forced,
window: super::theme::current_window(),
shown_copied: copied,
id: self.id,
key: self.key,
};
match theme.renderer::<CodeBlock>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<CodeBlock> for Element {
fn from(block: CodeBlock) -> Self {
if block.windowed(true) {
let key = block.key.clone();
let props = CodeBlockProps(Arc::new(block));
return match key {
Some(key) => Element::component_keyed::<CodeBlockHost>(key, props),
None => Element::component::<CodeBlockHost>(props),
};
}
block.build(¤t_theme())
}
}
struct CodeWindow {
lines: Option<Range<usize>>,
width: Option<f32>,
follow: Option<Follow>,
screen: Option<f32>,
}
#[derive(Clone)]
struct Follow {
window: Signal<Option<(usize, usize, u32)>>,
geometry: Arc<Mutex<Option<Geometry>>>,
content: ElementRef,
room: ElementRef,
screen: Arc<Mutex<Option<Window>>>,
all: Signal<bool>,
}
impl Follow {
fn screen_height(&self) -> Option<f32> {
self
.screen
.lock()
.unwrap()
.as_ref()
.map(|screen| screen.info().logical_size().height)
.filter(|height| *height > 0.0)
}
fn follow(&self) {
let Some(geometry) = self.geometry.lock().unwrap().clone() else {
return;
};
if !self.content.is_attached() {
return;
}
let content = self.content.bounds();
let screen = self.screen_height().unwrap_or(f32::INFINITY);
let (mut top, mut bottom) = (0.0f32, screen);
if geometry.bounded && self.room.is_attached() {
let room = self.room.bounds();
top = top.max(room.y);
bottom = bottom.min(room.y + room.height);
}
let from = (top - content.y).max(0.0);
let to = (bottom - content.y).min(content.height);
let shown = self.window.get_untracked();
let lines = if to > from {
geometry.window(from, to - from)
} else {
match shown {
Some((start, end, _)) => start..end,
None => return,
}
};
let width = if geometry.wraps {
content.width.round() as u32
} else {
0
};
let next = Some((lines.start, lines.end, width));
if shown != next {
self.window.set(next);
}
}
}
#[derive(Clone, Debug, PartialEq)]
struct Geometry {
top: f32,
pitch: f32,
rows_before: Arc<[u32]>,
wraps: bool,
bounded: bool,
}
impl Geometry {
fn window(&self, scrolled: f32, height: f32) -> Range<usize> {
let lines = self.rows_before.len().saturating_sub(1);
let line_at = |y: f32| {
let row = ((y - self.top) / self.pitch.max(1.0)).max(0.0) as u32;
self
.rows_before
.partition_point(|before| *before <= row)
.saturating_sub(1)
};
let first = line_at(scrolled);
let last = line_at(scrolled + height.max(self.pitch));
let start = (first / CHUNK).saturating_sub(1) * CHUNK;
let end = ((last / CHUNK + 2) * CHUNK).min(lines);
start.min(end)..end
}
}
#[derive(Clone)]
struct Copied {
on: Signal<bool>,
failed: Signal<bool>,
off: Timeout,
}
pub struct CodeBlockView {
pub code: Arc<str>,
pub language: Option<Arc<str>>,
pub tokenizer: Option<CodeTokenizer>,
pub scheme: Option<Arc<CodeScheme>>,
pub tokens: Arc<[CodeToken]>,
lines_window: Option<CodeWindow>,
pub title: Option<Arc<str>>,
pub label: Option<Arc<str>>,
pub line_numbers: bool,
pub first_line: usize,
pub highlighted: Vec<usize>,
pub wrap: bool,
pub min_height: Option<Length>,
pub max_height: Option<Length>,
pub copy_button: bool,
pub copy_label: Arc<str>,
pub copied_text: Arc<str>,
pub copy_failed_text: Arc<str>,
pub copy_text: Option<Arc<str>>,
pub copied: bool,
pub copy_failed: bool,
on_copy: Vec<CopyHandler>,
pub selectable: bool,
pub framed: bool,
pub row_height: f32,
pub has_header: bool,
pub recipe: ResolvedRecipe,
forced: Option<Interaction>,
window: Option<Window>,
shown_copied: Option<Copied>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl CodeBlockView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn name(&self) -> Arc<str> {
self
.label
.clone()
.or_else(|| self.title.clone())
.or_else(|| self.language.clone())
.unwrap_or_else(|| super::current_locale().editing.code.clone())
}
pub fn heading(&self) -> Option<Arc<str>> {
self.title.clone().or_else(|| self.language.clone())
}
pub fn lines(&self) -> Vec<&str> {
self.code.split('\n').collect()
}
fn code_style(&self) -> TextStyle {
let part = self.part(CodeBlockPart::Code);
let mut style = part.rest().text.resolve(self.theme());
style.color = self.color_of(&part, PaletteColor::Foreground);
style.line_height = self.row_height / style.font_size.max(1.0);
style
}
fn code_padding(&self) -> (f32, f32, f32, f32) {
let rest = self.part(CodeBlockPart::Code).rest();
let style = self.code_style();
let natural = style.font_size * self.theme().typography_style(TypographyStyle::Mono).line_height;
let leading = ((self.row_height - natural) / 2.0).max(0.0);
let start = self.px(rest.padding_start.or(rest.padding_x));
let end = self.px(rest.padding_end.or(rest.padding_x));
let top = (self.px(rest.padding_top.or(rest.padding_y)) - leading).max(0.0);
let bottom = (self.px(rest.padding_bottom.or(rest.padding_y)) - leading).max(0.0);
(start, end, top, bottom)
}
fn code_input(&self) -> Element {
let style = self.code_style();
let (start, end, top, bottom) = self.code_padding();
let number_part = self.part(CodeBlockPart::LineNumber);
let number_rest = number_part.rest();
let gap = self.px(number_rest.padding_end.or(number_rest.padding_x));
let digits = self.number(self.lines().len().saturating_sub(1)).len() as f32;
let numbers = if self.line_numbers {
digits * style.font_size * 0.6 + gap
} else {
0.0
};
let mut number_style = number_part.rest().text.resolve(self.theme());
number_style.line_height = style.line_height;
let mut gutter = LineGutter::new(number_style)
.first_line(self.first_line)
.numbers(self.line_numbers)
.gap(gap)
.color(number_rest.foreground.unwrap_or(PaletteColor::MutedForeground.into()))
.marked_color(
self
.part(CodeBlockPart::Code)
.rest()
.foreground
.unwrap_or(PaletteColor::Foreground.into()),
);
if !self.highlighted.is_empty() {
let band = match self.part(CodeBlockPart::Marked).rest().background {
Some(crate::node::BackgroundColor::Palette(role)) => TextColor::Palette(role),
Some(crate::node::BackgroundColor::Color(color)) => TextColor::Color(color),
_ => TextColor::Palette(PaletteColor::Highlight),
};
gutter = gutter.marked(self.highlighted.iter().copied(), band);
}
let mut input = TextInput::styled(Signal::new(self.code.to_string()), style)
.multiline()
.wrap(self.wrap)
.tokens(self.input_tokens())
.line_gutter(gutter)
.padding_left(start + numbers)
.padding_right(end)
.padding_top(top)
.padding_bottom(bottom)
.on_input(|event: TextInputEvent| event.prevent_default())
.tab_index(0)
.describe("a11y_role", "code")
.describe("a11y_name", self.name())
.describe("a11y_readonly", "true");
if let Some(language) = &self.language {
input = input.describe("a11y_language", language.clone());
}
input = if self.wrap {
input.width(Dimension::Pct(100.0))
} else {
input.flex_full(1.0, 0.0, None)
};
if let Some(id) = &self.id {
input = input.id(format!("{id}-code"));
}
input.into()
}
fn token_styles(&self) -> TokenStyles {
TokenStyles::new(&self.recipe, OWN_PARTS, self.code_style(), self.scheme.clone())
}
fn input_tokens(&self) -> crate::components::InputTokens {
self.token_styles().input_tokens(&self.code, &self.tokens)
}
fn color_of(&self, part: &ResolvedPart, otherwise: PaletteColor) -> crate::node::color::Color {
match part.rest().foreground {
Some(TextColor::Color(color)) => color,
Some(TextColor::Palette(role)) => self.theme().palette_color(role),
None => self.theme().palette_color(otherwise),
}
}
pub fn spans(&self, code: &str) -> Vec<RichTextSpan> {
let tokens = if code == &*self.code {
self.tokens.clone()
} else {
code_tokens(code, self.language.as_deref(), self.tokenizer.as_ref())
};
self.token_styles().spans(code, 0..code.len(), &tokens)
}
fn line_ranges(&self) -> Vec<Range<usize>> {
let mut start = 0;
self
.code
.split('\n')
.map(|line| {
let range = start..start + line.len();
start = range.end + 1;
range
})
.collect()
}
fn copy(&self) -> impl Fn(MouseEvent) + Send + Sync + 'static {
let (code, window, handlers, copied) = (
self.copy_text.clone().unwrap_or_else(|| self.code.clone()),
self.window.clone(),
self.on_copy.clone(),
self.shown_copied.clone(),
);
move |_| {
match (&window, &copied) {
(Some(window), Some(copied)) => {
let copied = copied.clone();
window.request_copy_then(code.to_string(), move |written| {
copied.on.set(written);
copied.failed.set(!written);
copied.off.restart();
});
}
(Some(window), None) => window.request_copy(code.to_string()),
(None, _) => {}
}
for handler in &handlers {
handler(&code);
}
}
}
pub fn header(&self) -> Option<Element> {
let heading = self.heading();
if !self.has_header {
return None;
}
let mut bar = Row::new()
.align_items(Alignment::Center)
.justify(Justify::SpaceBetween)
.part(&self.part(CodeBlockPart::Header));
let mut title = Row::new().flex_shrink(1.0).min_width(0.0);
if let Some(heading) = &heading {
title = title.child(one_line(&self.part(CodeBlockPart::Title).unnamed(), heading));
}
if let Some(id) = &self.id {
title = title.id(format!("{id}-title"));
}
bar = bar.child(title);
if self.copy_button {
bar = bar.child(self.copy_control());
}
Some(bar.into())
}
pub fn copy_control(&self) -> Element {
let part = self.part(CodeBlockPart::Copy).forced(self.forced);
let (name, icon) = if self.copy_failed {
(self.copy_failed_text.clone(), icons::ALERT_CIRCLE)
} else if self.copied {
(self.copied_text.clone(), icons::CHECK)
} else {
(self.copy_label.clone(), icons::COPY)
};
let mut button = pressable(&part, false)
.describe("a11y_role", "button")
.describe("a11y_name", name)
.child(glyph(&self.part(CodeBlockPart::CopyIcon), Name::from(icon), false))
.on_click(self.copy());
if let Some(id) = &self.id {
button = button.id(format!("{id}-copy"));
}
button.into()
}
fn line_pitch(&self) -> f32 {
let style = self.code_style();
style.font_size * style.line_height
}
fn number(&self, index: usize) -> String {
(self.first_line + index).to_string()
}
fn is_highlighted(&self, index: usize) -> bool {
self.highlighted.contains(&(self.first_line + index))
}
fn unwrapped(&self) -> Element {
let ranges = self.line_ranges();
let (_, _, top, bottom) = self.code_padding();
self.unwrapped_lines(&self.token_styles(), &ranges, 0..ranges.len(), (top, bottom))
}
fn unwrapped_lines(
&self,
styles: &TokenStyles,
ranges: &[Range<usize>],
lines: Range<usize>,
(pad_top, pad_bottom): (f32, f32),
) -> Element {
let code_part = self.part(CodeBlockPart::Code).unnamed();
if lines.is_empty() {
return Column::new().into();
}
let whole = lines.len() == ranges.len();
let bytes = ranges[lines.start].start..ranges[lines.end - 1].end;
let mut code = Node::rich_text(styles.spans(&self.code, bytes, &self.tokens)).text_wrap(false);
if self.selectable {
code = code.selectable(true);
}
let mut code = Element::from_node(code);
if whole && let Some(id) = &self.id {
code = Row::new().id(format!("{id}-code")).child(code).into();
}
let mut row = Row::new()
.align_items(Alignment::Start)
.part(&code_part)
.padding_top(pad_top)
.padding_bottom(pad_bottom);
if self.line_numbers {
let mut column = Column::new()
.align_items(Alignment::End)
.part(&self.part(CodeBlockPart::LineNumber));
if !whole {
column = column.min_width(self.numbers_width());
}
let spans = lines
.clone()
.map(|index| {
let mut text = self.number(index);
if index + 1 < lines.end {
text.push('\n');
}
RichTextSpan {
text,
style: self.number_style(Some(self.is_highlighted(index))),
}
})
.collect::<Vec<_>>();
let mut numbers = Node::rich_text(spans).text_wrap(false).text_align(TextAlign::Right);
if !whole {
numbers = numbers.width(Dimension::Pct(100.0));
}
column = column.child(Element::from_node(numbers));
row = row.child(column);
}
row = row.child(code);
if !lines.clone().any(|index| self.is_highlighted(index)) {
return row.into();
}
let pitch = self.line_pitch();
let (top, bottom) = (pad_top, pad_bottom);
let height = top + bottom + pitch * lines.len() as f32;
let band = self
.part(CodeBlockPart::Marked)
.rest()
.background
.unwrap_or(PaletteColor::Highlight.into());
let clear = crate::node::BackgroundColor::Color(crate::node::color::Color::new(0, 0, 0, 0));
let mut stops = Vec::new();
for index in lines.clone().filter(|index| self.is_highlighted(*index)) {
let at = index - lines.start;
let (from, to) = (
(top + pitch * at as f32) / height,
(top + pitch * (at + 1) as f32) / height,
);
stops.extend([
GradientStop::at(clear.clone(), from),
GradientStop::at(band.clone(), from),
GradientStop::at(band.clone(), to),
GradientStop::at(clear.clone(), to),
]);
}
row
.flex_full(1.0, 0.0, None)
.background_gradient(Gradient::linear(180.0, stops))
.into()
}
fn numbers_width(&self) -> f32 {
let lines = self.code.bytes().filter(|byte| *byte == b'\n').count() + 1;
let digits = self.number(lines.saturating_sub(1)).len() as f32;
let number_part = self.part(CodeBlockPart::LineNumber);
digits * self.code_style().font_size * 0.6
+ self.px(number_part.rest().padding_end.or(number_part.rest().padding_x))
}
fn px(&self, spacing: Option<crate::node::SpacingValue>) -> f32 {
match spacing {
Some(crate::node::SpacingValue::Dimension(Dimension::Px(px))) => px,
Some(crate::node::SpacingValue::Theme(size)) => match self.theme().spacing_value(size) {
Dimension::Px(px) => px,
_ => 0.0,
},
_ => 0.0,
}
}
fn number_style(&self, highlighted: Option<bool>) -> TextStyle {
let part = self.part(CodeBlockPart::LineNumber);
let mut style = part.rest().text.resolve(self.theme());
style.line_height = self.code_style().line_height;
style.color = if highlighted == Some(true) {
self.color_of(&self.part(CodeBlockPart::Code), PaletteColor::Foreground)
} else {
self.color_of(&part, PaletteColor::MutedForeground)
};
style
}
fn wrapped(&self) -> Element {
let ranges = self.line_ranges();
let (_, _, top, bottom) = self.code_padding();
let mut column = self.wrapped_lines(&self.token_styles(), &ranges, 0..ranges.len(), (top, bottom));
if let Some(id) = &self.id {
column = column.id(format!("{id}-code"));
}
column.into()
}
fn wrapped_lines(
&self,
styles: &TokenStyles,
ranges: &[Range<usize>],
lines: Range<usize>,
(pad_top, pad_bottom): (f32, f32),
) -> Column {
let code_part = self.part(CodeBlockPart::Code).unnamed();
let marked = self.part(CodeBlockPart::Marked);
let number_part = self.part(CodeBlockPart::LineNumber);
let numbers_width = self.numbers_width();
let rest = code_part.rest();
let (start, end) = (
self.px(rest.padding_start.or(rest.padding_x)),
self.px(rest.padding_end.or(rest.padding_x)),
);
let mut column = Column::new()
.width(Dimension::Pct(100.0))
.part(&code_part)
.padding_left(0.0)
.padding_right(0.0)
.padding_top(pad_top)
.padding_bottom(pad_bottom);
for index in lines {
let mut row = Row::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Start)
.padding_left(start)
.padding_right(end);
if self.is_highlighted(index) {
row = row.part(&marked);
}
if self.line_numbers {
let number = Element::from_node(
Node::rich_text(vec![RichTextSpan {
text: self.number(index),
style: self.number_style(Some(self.is_highlighted(index))),
}])
.text_wrap(false)
.text_align(TextAlign::Right),
);
row = row.child(
Column::new()
.width(numbers_width)
.flex_shrink(0.0)
.align_items(Alignment::End)
.part(&number_part)
.child(number),
);
}
let mut text = Node::rich_text(styles.spans(&self.code, ranges[index].clone(), &self.tokens));
if self.selectable {
text = text.selectable(true);
}
row = row.child(
Column::new()
.flex_full(1.0, 1.0, Some(0.0))
.min_width(0.0)
.child(Element::from_node(text).map_node(|node| node.width(Dimension::Pct(100.0)))),
);
column = column.child(row);
}
column
}
fn windowed_lines(&self, window: &CodeWindow) -> Element {
let ranges = self.line_ranges();
let count = ranges.len();
let styles = self.token_styles();
let pitch = self.line_pitch();
let (start, end, top, bottom) = self.code_padding();
let advance = self.code_style().font_size * 0.6;
let numbers = if self.line_numbers { self.numbers_width() } else { 0.0 };
let width = window
.width
.or_else(|| window.follow.as_ref().map(|follow| follow.content.width()))
.unwrap_or(0.0);
let room = width - start - end - numbers;
let chars: Vec<usize> = ranges
.iter()
.map(|range| self.code[range.clone()].chars().count())
.collect();
let mut rows_before = Vec::with_capacity(count + 1);
let mut rows = 0u32;
for chars in &chars {
rows_before.push(rows);
rows += if self.wrap && room > advance {
((*chars as f32 * advance) / room).ceil().max(1.0) as u32
} else {
1
};
}
rows_before.push(rows);
let geometry = Geometry {
top,
pitch,
rows_before: rows_before.into(),
wraps: self.wrap,
bounded: self.max_height.is_some(),
};
let lines = window.lines.clone().unwrap_or_else(|| {
let height = if geometry.bounded {
self.code_room_height()
} else {
window.screen.unwrap_or(1200.0)
};
geometry.window(0.0, height)
});
let lines = lines.start.min(count)..lines.end.min(count);
let above = top + geometry.rows_before[lines.start] as f32 * pitch;
let below = (geometry.rows_before[count] - geometry.rows_before[lines.end]) as f32 * pitch + bottom;
if let Some(follow) = &window.follow {
*follow.geometry.lock().unwrap() = Some(geometry);
}
let shown: Element = if self.wrap {
self.wrapped_lines(&styles, &ranges, lines, (0.0, 0.0)).into()
} else {
self.unwrapped_lines(&styles, &ranges, lines, (0.0, 0.0))
};
let mut column = Column::new()
.align_items(Alignment::Stretch)
.child(Column::new().height(above))
.child(shown)
.child(Column::new().height(below));
column = if self.wrap {
column.width(Dimension::Pct(100.0))
} else {
let longest = chars.iter().copied().max().unwrap_or(0) as f32;
column
.flex_full(1.0, 0.0, None)
.min_width(longest * advance + start + end + numbers)
};
if let Some(follow) = &window.follow {
column = column.ref_element(follow.content.clone());
if follow.all.get() {
column = column.background(PaletteColor::Selection);
}
let all = follow.all.clone();
column = column.on_mouse_down(move |_: MouseEvent| {
if all.get_untracked() {
all.set(false);
}
});
}
if let Some(id) = &self.id {
column = column.id(format!("{id}-code"));
}
column.into()
}
fn code_room_height(&self) -> f32 {
let header = match (self.has_header, self.part(CodeBlockPart::Header).rest().height) {
(true, Some(Length::Px(height))) => height,
_ => 0.0,
};
match self.max_height {
Some(Length::Px(max)) => (max - header).max(0.0),
_ => 0.0,
}
}
pub fn body(&self) -> Element {
let content = match (&self.lines_window, self.selectable, self.wrap) {
(Some(window), ..) => self.windowed_lines(window),
(None, true, _) => self.code_input(),
(None, false, true) => self.wrapped(),
(None, false, false) => self.unwrapped(),
};
let orientation = match (self.wrap, self.max_height.is_some()) {
(true, _) => ScrollAreaOrientation::Vertical,
(false, false) => ScrollAreaOrientation::Horizontal,
(false, true) => ScrollAreaOrientation::Both,
};
let header = if self.has_header {
self.part(CodeBlockPart::Header).rest().height
} else {
None
};
let header = match header {
Some(Length::Px(height)) => height,
_ => 0.0,
};
let mut area = ScrollArea::new()
.width(Length::Fill)
.orientation(orientation)
.fill_width(true)
.child(content);
if !self.selectable || self.lines_window.is_some() {
area = area.label(&self.name());
}
if let Some(Length::Px(max)) = self.max_height {
area = area.max_height((max - header).max(0.0));
}
let mut body = Column::new()
.width(Dimension::Pct(100.0))
.part(&self.part(CodeBlockPart::Body));
if let Some(Length::Px(min)) = self.min_height {
let least = (min - header).max(0.0);
area = area.style(ScrollAreaPart::Root, move |style| style.min_height(least));
body = body.min_height(least);
}
if self.max_height.is_some()
&& let Some(follow) = self.lines_window.as_ref().and_then(|window| window.follow.as_ref())
{
body = body.ref_element(follow.room.clone());
}
body.child(area).into()
}
pub fn root(&self) -> Column {
let mut root = Column::new()
.align_items(Alignment::Stretch)
.part(&self.part(CodeBlockPart::Root))
.describe("a11y_role", "code")
.describe("a11y_name", self.name());
if let Some(language) = &self.language {
root = root.describe("a11y_language", language.clone());
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
if let Some(follow) = self.lines_window.as_ref().and_then(|window| window.follow.as_ref()) {
let (all, code) = (follow.all.clone(), self.code.clone());
root = root
.on_select_all({
let all = all.clone();
move |_: crate::app::events::EditEvent| all.set(true)
})
.on_copy(move |event: crate::app::events::CopyEvent| {
if all.get_untracked() {
event.set_text(code.to_string());
}
});
}
root
}
pub fn render(self) -> Element {
let mut root = self.root();
if let Some(header) = self.header() {
root = root.child(header);
}
root.child(self.body()).into()
}
}
impl crate::ui::Styled for CodeBlock {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for CodeBlock {
const NAME: &'static str = "code_block";
type Renderer = CodeBlockRenderer;
fn parts() -> crate::ui::Declared {
CodeBlockPart::declared()
}
fn states() -> crate::ui::Declared {
CodeBlockState::declared()
}
fn recipe() -> Recipe {
use CodeBlockPart::*;
use PaletteColor::{
Background, Border as Edge, Destructive, Foreground, Highlight, HighlightForeground, MutedForeground, Success,
};
Recipe::new()
.base(Root, |s| s.width(Length::Fill).foreground(Foreground))
.state(CodeBlockState::Framed, Root, |s| {
s.background(Background)
.border(Border::inside(BorderSize::Sm, Edge))
.radius(RadiusSize::Lg)
})
.base(Header, |s| {
s.height(36.0)
.background(PaletteColor::Bar)
.underline(Border::inside(BorderSize::Sm, Edge))
.padding_start(14.0)
.padding_end(6.0)
.gap(8.0)
})
.base(Title, |s| {
s.typography(TypographyStyle::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(Copy, |s| {
fading(
s.square(28.0)
.radius(RadiusSize::Md)
.foreground(Foreground)
.cursor(crate::node::CursorIcon::Pointer),
)
})
.hovered(Copy, |s| s.background(Highlight).foreground(HighlightForeground))
.pressed(Copy, |s| s.veil(PaletteColor::StatePressed))
.focus_visible(Copy, |s| s.focus_ring())
.base(CopyIcon, |s| s.square(Length::Icon(IconSize::Md)))
.state(CodeBlockState::Copied, CopyIcon, |s| s.foreground(Success))
.state(CodeBlockState::CopyFailed, CopyIcon, |s| s.foreground(Destructive))
.base(Code, |s| {
s.typography(TypographyStyle::Mono)
.font_size(13.0)
.foreground(Foreground)
.padding_x(14.0)
.padding_y(14.0)
})
.base(LineNumber, |s| {
s.typography(TypographyStyle::Mono)
.font_size(13.0)
.foreground(MutedForeground)
.padding_end(16.0)
})
.base(Marked, |s| s.background(Highlight))
}
}
#[derive(Clone)]
struct CodeBlockProps(Arc<CodeBlock>);
impl PartialEq for CodeBlockProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for CodeBlockProps {}
struct CodeBlockHost {
copied: Copied,
follow: Follow,
lines: Arc<Mutex<crate::code::LineCache>>,
}
impl Component for CodeBlockHost {
type Props = CodeBlockProps;
fn create(ctx: &mut Ctx) -> Self {
let (on, failed) = (ctx.signal(false), ctx.signal(false));
let off = ctx.create_timeout(CODE_BLOCK_COPIED_FOR, {
let (on, failed) = (on.clone(), failed.clone());
move || {
on.set(false);
failed.set(false);
}
});
Self {
copied: Copied { on, failed, off },
lines: Arc::default(),
follow: Follow {
window: Signal::new(None),
geometry: Arc::default(),
content: ElementRef::new(),
room: ElementRef::new(),
screen: Arc::default(),
all: ctx.signal(false),
},
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let block = (*ctx.props::<CodeBlockProps>().0).clone();
*self.follow.screen.lock().unwrap() = super::theme::current_window();
if !block.windowed(true) {
*self.follow.geometry.lock().unwrap() = None;
}
let element = block.build_with(¤t_theme(), Some(self));
for watched in [&self.follow.content, &self.follow.room] {
let follow = self.follow.clone();
watched.observe_rect_before_paint(move |_| follow.follow());
}
element
}
fn after_layout(&self) {
self.follow.follow();
}
}