use std::sync::Arc;
use super::{
code_tokens::{TokenStyles, code_tokens},
names,
part_style::PartStyle,
recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe},
theme::{Themed, current_theme},
};
use crate::{
app::{
Accelerator,
theme::{BorderSize, PaletteColor, RadiusSize, Theme, TypographyStyle},
},
code::{CodeToken, CodeTokenizer},
components::Row,
core::KeyWords,
layout::Alignment,
node::{Element, Node, TextColor, border::Border as Line},
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum KbdVariant {
#[default]
Default,
Plain,
}
names!(KbdVariant {
Default => "default",
Plain => "plain",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum KbdSize {
Sm,
#[default]
Md,
Lg,
}
names!(KbdSize {
Sm => "sm",
Md => "md",
Lg => "lg",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum KeyPlatform {
#[default]
Standard,
Mac,
}
impl KeyPlatform {
pub fn current() -> Self {
if cfg!(any(target_os = "macos", target_os = "ios")) {
Self::Mac
} else {
Self::Standard
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KbdPart {
Root,
Key,
Label,
Separator,
}
names!(KbdPart {
Root => "root",
Key => "key",
Label => "label",
Separator => "separator",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KbdState {
Sequence,
Mac,
}
names!(KbdState {
Sequence => "sequence",
Mac => "mac",
});
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KbdKey {
pub label: Arc<str>,
pub name: Arc<str>,
pub modifier: bool,
}
pub type KbdRenderer = Arc<dyn Fn(KbdView) -> Element + Send + Sync>;
pub struct Kbd {
steps: Vec<Vec<Arc<str>>>,
platform: KeyPlatform,
variant: Name,
size: Name,
separator_text: Arc<str>,
label: Option<Arc<str>>,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Kbd {
fn of(steps: Vec<Vec<Arc<str>>>) -> Self {
Self {
steps,
platform: KeyPlatform::default(),
variant: KbdVariant::default().into(),
size: KbdSize::default().into(),
separator_text: super::current_locale().keys.then.clone(),
label: None,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
pub fn new(key: &str) -> Self {
Self::of(vec![vec![Arc::from(key)]])
}
pub fn shortcut(keys: &str) -> Self {
Self::of(vec![split(keys)])
}
pub fn sequence<S: AsRef<str>>(steps: impl IntoIterator<Item = S>) -> Self {
Self::of(steps.into_iter().map(|step| split(step.as_ref())).collect())
}
pub fn accelerator(accelerator: &Accelerator) -> Self {
let modifiers = accelerator.modifiers;
let mut keys: Vec<Arc<str>> = [
(modifiers.ctrl, "Ctrl"),
(modifiers.alt, "Alt"),
(modifiers.shift, "Shift"),
(modifiers.meta, "Meta"),
]
.into_iter()
.filter(|(held, _)| *held)
.map(|(_, name)| Arc::from(name))
.collect();
keys.push(accelerator.key.clone());
Self::of(vec![keys])
}
pub fn platform(mut self, platform: KeyPlatform) -> Self {
self.platform = platform;
self
}
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = variant.into();
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
pub fn separator_text(mut self, text: &str) -> Self {
self.separator_text = Arc::from(text);
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
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 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 build(self, theme: &Theme) -> Element {
let case = Case {
variant: Some(self.variant),
size: Some(self.size),
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(KbdState::Sequence, self.steps.len() > 1)
.state(KbdState::Mac, self.platform == KeyPlatform::Mac);
let platform = self.platform;
let view = KbdView {
steps: {
let locale = super::current_locale();
self
.steps
.iter()
.map(|step| keys_of(step, platform, &locale.keys))
.collect()
},
platform,
variant: self.variant,
size: self.size,
separator_text: self.separator_text,
label: self.label,
recipe: theme
.resolve::<Kbd>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
id: self.id,
key: self.key,
};
match theme.renderer::<Kbd>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<Kbd> for Element {
fn from(kbd: Kbd) -> Self {
kbd.build(¤t_theme())
}
}
fn split(keys: &str) -> Vec<Arc<str>> {
let mut parted = Vec::new();
let mut key = String::new();
for character in keys.chars() {
if character == '+' && !key.trim().is_empty() {
parted.push(Arc::from(key.trim()));
key.clear();
} else if character == '+' {
key = "+".to_owned();
} else {
key.push(character);
}
}
if !key.trim().is_empty() {
parted.push(Arc::from(key.trim()));
} else if key == " " {
parted.push(Arc::from(" "));
}
parted
}
fn modifier<'a>(folded: &str, platform: KeyPlatform, keys: &'a KeyWords) -> Option<(u8, &'a str, &'a str, &'a str)> {
Some(match folded {
"ctrl" | "control" => (0, &keys.ctrl, &keys.ctrl, "⌃"),
"alt" | "option" | "opt" => (1, &keys.alt, &keys.option, "⌥"),
"shift" => (2, &keys.shift, &keys.shift, "⇧"),
"meta" => (3, &keys.meta, &keys.cmd, "⌘"),
"cmd" | "command" => (3, &keys.cmd, &keys.cmd, "⌘"),
"super" => (3, &keys.super_key, &keys.cmd, "⌘"),
"win" | "windows" => (3, &keys.win, &keys.cmd, "⌘"),
"mod" if platform == KeyPlatform::Mac => (3, &keys.ctrl, &keys.cmd, "⌘"),
"mod" => (0, &keys.ctrl, &keys.cmd, "⌘"),
_ => return None,
})
}
fn named<'a>(folded: &str, keys: &'a KeyWords) -> Option<(&'a str, &'a str, &'a str)> {
Some(match folded {
"enter" | "return" => (&keys.enter, "↩", &keys.enter),
"escape" | "esc" => (&keys.esc, &keys.esc, &keys.esc),
"backspace" => (&keys.backspace, "⌫", &keys.backspace),
"delete" | "del" => (&keys.delete, "⌦", &keys.delete_name),
"tab" => (&keys.tab, "⇥", &keys.tab),
"space" | "spacebar" => (&keys.space, &keys.space, &keys.space),
"arrowup" => ("↑", "↑", &keys.up),
"arrowdown" => ("↓", "↓", &keys.down),
"arrowleft" => ("←", "←", &keys.left),
"arrowright" => ("→", "→", &keys.right),
"pageup" => (&keys.page_up, "⇞", &keys.page_up),
"pagedown" => (&keys.page_down, "⇟", &keys.page_down),
"home" => (&keys.home, "↖", &keys.home),
"end" => (&keys.end, "↘", &keys.end),
"capslock" => (&keys.caps_lock, "⇪", &keys.caps_lock),
_ => return None,
})
}
fn keys_of(step: &[Arc<str>], platform: KeyPlatform, words: &KeyWords) -> Vec<KbdKey> {
let mac = platform == KeyPlatform::Mac;
let mut keys: Vec<(u8, KbdKey)> = step
.iter()
.map(|written| {
if written.as_ref() == " " {
let space = words.space.clone();
return (
u8::MAX,
KbdKey {
label: space.clone(),
name: space,
modifier: false,
},
);
}
let folded: String = written
.chars()
.filter(|character| !character.is_whitespace())
.flat_map(char::to_lowercase)
.collect();
if let Some((rank, word, mac_word, glyph)) = modifier(&folded, platform, words) {
let (label, name) = if mac { (glyph, mac_word) } else { (word, word) };
return (
rank,
KbdKey {
label: Arc::from(label),
name: Arc::from(name),
modifier: true,
},
);
}
if let Some((word, mac_label, name)) = named(&folded, words) {
let label = if mac { mac_label } else { word };
let name = if mac && name == &*words.enter {
&*words.return_key
} else {
name
};
return (
u8::MAX,
KbdKey {
label: Arc::from(label),
name: Arc::from(name),
modifier: false,
},
);
}
let label: Arc<str> = if written.chars().count() == 1 {
Arc::from(written.to_uppercase())
} else {
written.clone()
};
(
u8::MAX,
KbdKey {
label: label.clone(),
name: label,
modifier: false,
},
)
})
.collect();
if mac {
keys.sort_by_key(|(rank, _)| *rank);
}
keys.into_iter().map(|(_, key)| key).collect()
}
pub struct KbdView {
pub steps: Vec<Vec<KbdKey>>,
pub platform: KeyPlatform,
pub variant: Name,
pub size: Name,
pub separator_text: Arc<str>,
pub label: Option<Arc<str>>,
pub recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl KbdView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn plain(&self) -> bool {
self.variant == Name::from(KbdVariant::Plain)
}
pub fn written(&self, step: &[KbdKey]) -> String {
let join = if self.platform == KeyPlatform::Mac { "" } else { "+" };
step.iter().map(|key| key.label.as_ref()).collect::<Vec<_>>().join(join)
}
pub fn name(&self) -> String {
if let Some(label) = &self.label {
return label.to_string();
}
self
.steps
.iter()
.map(|step| step.iter().map(|key| key.name.as_ref()).collect::<Vec<_>>().join("+"))
.collect::<Vec<_>>()
.join(&format!(" {} ", self.separator_text))
}
pub fn root(&self) -> Row {
let mut root = Row::new()
.align_items(Alignment::Center)
.part(&self.part(KbdPart::Root))
.describe("a11y_role", "text")
.describe("a11y_name", self.name());
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root
}
pub fn label(&self, text: &str) -> Row {
let part = self.part(KbdPart::Label);
Row::new().part(&part).child(part.text(text).nowrap())
}
pub fn key_cap(&self, key: &KbdKey) -> Row {
Row::new()
.align_items(Alignment::Center)
.part(&self.part(KbdPart::Key))
.child(self.label(&key.label))
}
pub fn between(&self) -> Row {
let part = self.part(KbdPart::Separator);
Row::new().part(&part).child(part.text(&self.separator_text).nowrap())
}
pub fn render(self) -> Element {
let mut root = self.root();
for (index, step) in self.steps.iter().enumerate() {
if index > 0 {
root = root.child(self.between());
}
if self.plain() {
root = root.child(self.label(&self.written(step)));
} else {
for key in step {
root = root.child(self.key_cap(key));
}
}
}
root.into()
}
}
impl crate::ui::Styled for Kbd {
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 Kbd {
const NAME: &'static str = "kbd";
type Renderer = KbdRenderer;
fn parts() -> crate::ui::Declared {
KbdPart::declared()
}
fn states() -> crate::ui::Declared {
KbdState::declared()
}
fn recipe() -> Recipe {
use KbdPart::{Key, Label, Root, Separator};
use PaletteColor::*;
let mut recipe = Recipe::new()
.base(Root, |s| s.gap(4.0))
.base(Key, |s| {
s.height(20.0)
.padding_x(6.0)
.radius(RadiusSize::Sm)
.background(Muted)
.foreground(MutedForeground)
.border(Line::inside(BorderSize::Sm, PaletteColor::Border))
})
.base(Label, |s| {
s.typography(TypographyStyle::Mono)
.font_size(11.0)
.line_height(1.0)
.foreground(MutedForeground)
})
.base(Separator, |s| {
s.typography(TypographyStyle::Caption)
.font_size(11.0)
.foreground(MutedForeground)
});
for (size, height, padding, font, gap) in [(KbdSize::Sm, 16.0, 4.0, 10.0, 4.0), (KbdSize::Lg, 24.0, 7.0, 12.0, 6.0)]
{
recipe = recipe
.size(size, Root, |s| s.gap(gap))
.size(size, Key, |s| s.height(height).padding_x(padding))
.size(size, Label, |s| s.font_size(font))
.size(size, Separator, |s| s.font_size(font));
}
recipe
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InlineCodePart {
Root,
Label,
}
names!(InlineCodePart {
Root => "root",
Label => "label",
});
pub type InlineCodeRenderer = Arc<dyn Fn(InlineCodeView) -> Element + Send + Sync>;
pub struct InlineCode {
text: Arc<str>,
language: Option<Arc<str>>,
tokenizer: Option<CodeTokenizer>,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl InlineCode {
pub fn new(text: &str) -> Self {
Self {
text: Arc::from(text),
language: None,
tokenizer: None,
states: Vec::new(),
rules: Recipe::new(),
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 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 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 build(self, theme: &Theme) -> Element {
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states,
};
let colored = self.language.is_some() || self.tokenizer.is_some();
let tokens = code_tokens(&self.text, self.language.as_deref(), self.tokenizer.as_ref());
let view = InlineCodeView {
text: self.text,
language: self.language,
tokens: colored.then_some(tokens),
recipe: theme
.resolve::<InlineCode>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
id: self.id,
key: self.key,
};
match theme.renderer::<InlineCode>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<InlineCode> for Element {
fn from(code: InlineCode) -> Self {
code.build(¤t_theme())
}
}
pub struct InlineCodeView {
pub text: Arc<str>,
pub language: Option<Arc<str>>,
pub tokens: Option<Arc<[CodeToken]>>,
pub recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl InlineCodeView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn root(&self) -> Row {
let mut root = Row::new()
.align_items(Alignment::Center)
.part(&self.part(InlineCodePart::Root))
.describe("a11y_role", "code")
.describe("a11y_name", self.text.clone());
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root
}
pub fn label(&self) -> Element {
let part = self.part(InlineCodePart::Label);
let Some(tokens) = &self.tokens else {
return part.text(&self.text).nowrap().into();
};
let rest = part.rest();
let mut base = rest.text.resolve(self.theme());
base.color = match rest.foreground.unwrap_or(PaletteColor::Foreground.into()) {
TextColor::Color(color) => color,
TextColor::Palette(role) => self.theme().palette_color(role),
};
let styles = TokenStyles::new(&self.recipe, &["root", "label"], base, None);
let spans = styles.spans(&self.text, 0..self.text.len(), tokens);
Element::from_node(Node::rich_text(spans).text_wrap(false))
}
pub fn render(self) -> Element {
let label = self.label();
self.root().child(label).into()
}
}
impl crate::ui::Styled for InlineCode {
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 InlineCode {
const NAME: &'static str = "inline_code";
type Renderer = InlineCodeRenderer;
fn parts() -> crate::ui::Declared {
InlineCodePart::declared()
}
fn recipe() -> Recipe {
use InlineCodePart::{Label, Root};
Recipe::new()
.base(Root, |s| {
s.padding_x(5.0)
.padding_y(1.0)
.radius(RadiusSize::Sm)
.background(PaletteColor::Muted)
.foreground(PaletteColor::Foreground)
})
.base(Label, |s| {
s.typography(TypographyStyle::Mono)
.font_size(13.0)
.foreground(PaletteColor::Foreground)
})
}
}