use std::{
cell::RefCell,
collections::{HashMap, HashSet},
rc::Rc,
};
use arc_motion::{arc_spring_with_options, is_reduced_motion, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
App, ClipboardItem, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, Window,
base::StyledExt as _, canvas, div, point, prelude::*, px,
};
#[derive(Clone, Debug, PartialEq)]
pub enum JsonValue {
Null,
Bool(bool),
Number(f64),
String(SharedString),
Array(Vec<JsonValue>),
Object(Vec<(SharedString, JsonValue)>),
}
impl JsonValue {
pub fn null() -> Self {
Self::Null
}
pub fn bool(v: bool) -> Self {
Self::Bool(v)
}
pub fn number(v: f64) -> Self {
Self::Number(v)
}
pub fn string(v: impl Into<SharedString>) -> Self {
Self::String(v.into())
}
pub fn array(items: impl IntoIterator<Item = JsonValue>) -> Self {
Self::Array(items.into_iter().collect())
}
pub fn object(entries: impl IntoIterator<Item = (impl Into<SharedString>, JsonValue)>) -> Self {
Self::Object(entries.into_iter().map(|(k, v)| (k.into(), v)).collect())
}
pub fn is_branch(&self) -> bool {
matches!(self, Self::Array(_) | Self::Object(_))
}
pub fn type_name(&self) -> &'static str {
match self {
Self::Null => "null",
Self::Bool(_) => "boolean",
Self::Number(_) => "number",
Self::String(_) => "string",
Self::Array(_) => "array",
Self::Object(_) => "object",
}
}
pub fn primitive_text(&self) -> String {
match self {
Self::Null => "null".to_string(),
Self::Bool(b) => b.to_string(),
Self::Number(n) => {
if n.fract().abs() < 1e-9 {
format!("{}", *n as i64)
} else {
format!("{n}")
}
}
Self::String(s) => s.to_string(),
Self::Array(a) => format!("[{}]", a.len()),
Self::Object(o) => format!("{{{}}}", o.len()),
}
}
pub fn to_pretty_json(&self, indent: usize) -> String {
let pad = " ".repeat(indent);
let child_pad = " ".repeat(indent + 1);
match self {
Self::Null => "null".to_string(),
Self::Bool(b) => b.to_string(),
Self::Number(_) => self.primitive_text(),
Self::String(s) => format!("{:?}", s.as_ref()),
Self::Array(items) => {
if items.is_empty() {
return "[]".to_string();
}
let inner: Vec<String> = items
.iter()
.map(|it| format!("{child_pad}{}", it.to_pretty_json(indent + 1)))
.collect();
format!("[\n{}\n{pad}]", inner.join(",\n"))
}
Self::Object(entries) => {
if entries.is_empty() {
return "{}".to_string();
}
let inner: Vec<String> = entries
.iter()
.map(|(k, v)| {
format!(
"{child_pad}{:?}: {}",
k.as_ref(),
v.to_pretty_json(indent + 1)
)
})
.collect();
format!("{{\n{}\n{pad}}}", inner.join(",\n"))
}
}
}
}
#[derive(Clone, Debug)]
pub struct JsonFlatRow {
pub path: SharedString,
pub key_label: Option<SharedString>,
pub value: JsonValue,
pub depth: usize,
pub parent_path: Option<SharedString>,
pub is_branch: bool,
pub is_open: bool,
pub count: usize,
pub more_hidden: Option<usize>,
}
fn is_ident(s: &str) -> bool {
let mut chars = s.chars();
match chars.next() {
Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
_ => return false,
}
chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
}
pub fn json_child_path(parent: &str, key: &str, is_index: bool) -> SharedString {
if is_index {
SharedString::from(format!("{parent}[{key}]"))
} else if is_ident(key) {
SharedString::from(format!("{parent}.{key}"))
} else {
SharedString::from(format!("{parent}[{key:?}]"))
}
}
pub fn json_branches_to_depth(
value: &JsonValue,
root_name: &str,
max_depth: usize,
) -> Vec<SharedString> {
let mut out = Vec::new();
fn walk(
v: &JsonValue,
path: &str,
depth: usize,
max_depth: usize,
out: &mut Vec<SharedString>,
) {
if depth >= max_depth || !v.is_branch() {
return;
}
out.push(SharedString::from(path.to_string()));
match v {
JsonValue::Array(items) => {
for (i, it) in items.iter().enumerate() {
let cp = json_child_path(path, &i.to_string(), true);
walk(it, cp.as_ref(), depth + 1, max_depth, out);
}
}
JsonValue::Object(entries) => {
for (k, it) in entries {
let cp = json_child_path(path, k.as_ref(), false);
walk(it, cp.as_ref(), depth + 1, max_depth, out);
}
}
_ => {}
}
}
walk(value, root_name, 0, max_depth, &mut out);
out
}
pub fn json_all_branches(value: &JsonValue, root_name: &str) -> Vec<SharedString> {
json_branches_to_depth(value, root_name, usize::MAX)
}
pub fn search_json_tree(
value: &JsonValue,
root_name: &str,
needle: &str,
) -> (HashSet<SharedString>, HashSet<SharedString>) {
let q = needle.trim().to_lowercase();
let mut matches = HashSet::new();
let mut ancestors = HashSet::new();
if q.is_empty() {
return (matches, ancestors);
}
let mut stack: Vec<SharedString> = Vec::new();
fn visit(
v: &JsonValue,
path: SharedString,
key_name: Option<&str>,
q: &str,
stack: &mut Vec<SharedString>,
matches: &mut HashSet<SharedString>,
ancestors: &mut HashSet<SharedString>,
) {
let key_hit = key_name.is_some_and(|k| k.to_lowercase().contains(q));
let val_hit = !v.is_branch() && v.primitive_text().to_lowercase().contains(q);
if key_hit || val_hit {
matches.insert(path.clone());
for anc in stack.iter() {
ancestors.insert(anc.clone());
}
}
match v {
JsonValue::Array(items) => {
stack.push(path.clone());
for (i, it) in items.iter().enumerate() {
let idx_s = i.to_string();
let cp = json_child_path(path.as_ref(), &idx_s, true);
visit(it, cp, None, q, stack, matches, ancestors);
}
stack.pop();
}
JsonValue::Object(entries) => {
stack.push(path.clone());
for (k, it) in entries {
let cp = json_child_path(path.as_ref(), k.as_ref(), false);
visit(it, cp, Some(k.as_ref()), q, stack, matches, ancestors);
}
stack.pop();
}
_ => {}
}
}
visit(
value,
SharedString::from(root_name.to_string()),
None,
&q,
&mut stack,
&mut matches,
&mut ancestors,
);
(matches, ancestors)
}
pub fn flatten_json_rows(
root: &JsonValue,
root_name: &str,
expanded: &HashSet<SharedString>,
auto_open: &HashSet<SharedString>,
pages: &HashMap<SharedString, usize>,
page_size: usize,
) -> Vec<JsonFlatRow> {
let mut out = Vec::new();
struct WalkOptions<'a> {
expanded: &'a HashSet<SharedString>,
auto_open: &'a HashSet<SharedString>,
pages: &'a HashMap<SharedString, usize>,
page_size: usize,
}
fn walk(
v: &JsonValue,
path: SharedString,
key_label: Option<SharedString>,
depth: usize,
parent: Option<SharedString>,
options: &WalkOptions<'_>,
out: &mut Vec<JsonFlatRow>,
) {
let WalkOptions {
expanded,
auto_open,
pages,
page_size,
} = options;
let is_branch = v.is_branch();
let count = match v {
JsonValue::Array(a) => a.len(),
JsonValue::Object(o) => o.len(),
_ => 0,
};
let is_open = is_branch && (expanded.contains(&path) || auto_open.contains(&path));
out.push(JsonFlatRow {
path: path.clone(),
key_label,
value: v.clone(),
depth,
parent_path: parent,
is_branch,
is_open,
count,
more_hidden: None,
});
if !is_open {
return;
}
let limit = (pages.get(&path).copied().unwrap_or(1) * (*page_size).max(1)).max(1);
match v {
JsonValue::Array(items) => {
let take = items.len().min(limit);
for (i, it) in items.iter().take(take).enumerate() {
let idx_s = SharedString::from(i.to_string());
let cp = json_child_path(path.as_ref(), idx_s.as_ref(), true);
walk(
it,
cp,
Some(idx_s),
depth + 1,
Some(path.clone()),
options,
out,
);
}
if items.len() > take {
out.push(JsonFlatRow {
path: SharedString::from(format!("{path}#more")),
key_label: None,
value: JsonValue::Null,
depth: depth + 1,
parent_path: Some(path),
is_branch: false,
is_open: false,
count: 0,
more_hidden: Some(items.len() - take),
});
}
}
JsonValue::Object(entries) => {
let take = entries.len().min(limit);
for (k, it) in entries.iter().take(take) {
let cp = json_child_path(path.as_ref(), k.as_ref(), false);
walk(
it,
cp,
Some(k.clone()),
depth + 1,
Some(path.clone()),
options,
out,
);
}
if entries.len() > take {
out.push(JsonFlatRow {
path: SharedString::from(format!("{path}#more")),
key_label: None,
value: JsonValue::Null,
depth: depth + 1,
parent_path: Some(path),
is_branch: false,
is_open: false,
count: 0,
more_hidden: Some(entries.len() - take),
});
}
}
_ => {}
}
}
walk(
root,
SharedString::from(root_name.to_string()),
Some(SharedString::from(root_name.to_string())),
0,
None,
&WalkOptions {
expanded,
auto_open,
pages,
page_size,
},
&mut out,
);
out
}
fn paint_chevron_right(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
let rad = angle_deg.to_radians();
let (c, s) = (rad.cos(), rad.sin());
let rot = |dx: f32, dy: f32| point(px(cx + dx * c - dy * s), px(cy + dx * s + dy * c));
let mut pb = PathBuilder::stroke(px(1.5));
pb.move_to(rot(-2.0, -3.5));
pb.line_to(rot(2.0, 0.0));
pb.line_to(rot(-2.0, 3.5));
if let Ok(path) = pb.build() {
window.paint_path(path, color);
}
}
type CopyCallback = Rc<dyn Fn(&str, &str, &mut Window, &mut App)>;
#[derive(Clone)]
struct JsonViewerInternal {
expanded: HashSet<SharedString>,
pages: HashMap<SharedString, usize>,
selected_path: SharedString,
last_copied: Option<SharedString>,
focus_handle: FocusHandle,
}
#[derive(IntoElement)]
pub struct JsonViewer {
id: ElementId,
data: JsonValue,
root_name: SharedString,
default_expand_depth: usize,
query: SharedString,
page_size: usize,
copyable: bool,
show_path: bool,
on_copy: Option<CopyCallback>,
}
impl JsonViewer {
pub fn new(id: impl Into<ElementId>, data: JsonValue) -> Self {
Self {
id: id.into(),
data,
root_name: SharedString::from("root"),
default_expand_depth: 2,
query: SharedString::from(""),
page_size: 50,
copyable: true,
show_path: true,
on_copy: None,
}
}
pub fn root_name(mut self, name: impl Into<SharedString>) -> Self {
self.root_name = name.into();
self
}
pub fn default_expand_depth(mut self, depth: usize) -> Self {
self.default_expand_depth = depth;
self
}
pub fn query(mut self, query: impl Into<SharedString>) -> Self {
self.query = query.into();
self
}
pub fn page_size(mut self, size: usize) -> Self {
self.page_size = size.max(1);
self
}
pub fn copyable(mut self, copyable: bool) -> Self {
self.copyable = copyable;
self
}
pub fn show_path(mut self, show: bool) -> Self {
self.show_path = show;
self
}
pub fn on_copy(mut self, cb: impl Fn(&str, &str, &mut Window, &mut App) + 'static) -> Self {
self.on_copy = Some(Rc::new(cb));
self
}
}
impl RenderOnce for JsonViewer {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let _reduced = is_reduced_motion(cx);
let init_expanded: HashSet<SharedString> = json_branches_to_depth(
&self.data,
self.root_name.as_ref(),
self.default_expand_depth,
)
.into_iter()
.collect();
let init_root = self.root_name.clone();
let state_cell = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), SharedString::from("jv-state")),
cx,
|_, cx| {
Rc::new(RefCell::new(JsonViewerInternal {
expanded: init_expanded,
pages: HashMap::new(),
selected_path: init_root,
last_copied: None,
focus_handle: cx.focus_handle(),
}))
},
)
.read(cx)
.clone();
let (matches, auto_open) =
search_json_tree(&self.data, self.root_name.as_ref(), self.query.as_ref());
let (expanded_set, pages_map, selected_path, last_copied, focus_handle) = {
let st = state_cell.borrow();
(
st.expanded.clone(),
st.pages.clone(),
st.selected_path.clone(),
st.last_copied.clone(),
st.focus_handle.clone(),
)
};
let rows = flatten_json_rows(
&self.data,
self.root_name.as_ref(),
&expanded_set,
&auto_open,
&pages_map,
self.page_size,
);
let all_branches = json_all_branches(&self.data, self.root_name.as_ref());
let st_exp_all = state_cell.clone();
let st_col_all = state_cell.clone();
let root_for_col = self.root_name.clone();
let toolbar = div()
.w_full()
.px(Spacing::S3)
.py(Spacing::S2)
.bg(colors.surface_muted)
.border_b_1()
.border_color(colors.border)
.flex()
.flex_row()
.items_center()
.justify_between()
.gap(Spacing::S2)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.text_secondary)
.child(format!("{} ({} nodes)", self.root_name, rows.len())),
)
.when(!self.query.trim().is_empty(), |this| {
this.child(
div()
.px(px(6.0))
.py(px(1.0))
.rounded(Radii::PILL)
.bg(oklab_mix(colors.accent, colors.surface, 0.16))
.text_size(px(11.0))
.text_color(colors.accent)
.child(format!("{} matches", matches.len())),
)
}),
)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.child(
div()
.px(Spacing::S2)
.py(px(3.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.cursor_pointer()
.hover(|h| h.bg(colors.surface_raised))
.text_size(px(11.0))
.text_color(colors.text_secondary)
.on_mouse_down(MouseButton::Left, move |_, window, _| {
let mut st = st_exp_all.borrow_mut();
st.expanded = all_branches.iter().cloned().collect();
window.refresh();
})
.child("Expand all"),
)
.child(
div()
.px(Spacing::S2)
.py(px(3.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.cursor_pointer()
.hover(|h| h.bg(colors.surface_raised))
.text_size(px(11.0))
.text_color(colors.text_secondary)
.on_mouse_down(MouseButton::Left, move |_, window, _| {
let mut st = st_col_all.borrow_mut();
st.expanded.clear();
st.expanded.insert(root_for_col.clone());
window.refresh();
})
.child("Collapse"),
),
);
let rows_for_key = rows.clone();
let st_key = state_cell.clone();
let mut tree_body = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from("jv-tree"),
))
.w_full()
.py(Spacing::S2)
.flex()
.flex_col()
.track_focus(&focus_handle)
.role(Role::Tree)
.on_key_down(move |ev: &KeyDownEvent, window, _| {
if rows_for_key.is_empty() {
return;
}
let key = ev.keystroke.key.as_str();
let mut st = st_key.borrow_mut();
let idx = rows_for_key
.iter()
.position(|r| r.path == st.selected_path)
.unwrap_or(0);
match key {
"down" => {
let next = (idx + 1).min(rows_for_key.len() - 1);
st.selected_path = rows_for_key[next].path.clone();
window.refresh();
}
"up" => {
let next = idx.saturating_sub(1);
st.selected_path = rows_for_key[next].path.clone();
window.refresh();
}
"right" => {
let r = &rows_for_key[idx];
if r.is_branch && !r.is_open {
st.expanded.insert(r.path.clone());
window.refresh();
} else if idx + 1 < rows_for_key.len() {
st.selected_path = rows_for_key[idx + 1].path.clone();
window.refresh();
}
}
"left" => {
let r = &rows_for_key[idx];
if r.is_branch && r.is_open {
st.expanded.remove(&r.path);
window.refresh();
} else if let Some(parent) = &r.parent_path {
st.selected_path = parent.clone();
window.refresh();
}
}
"enter" | "space" => {
let r = &rows_for_key[idx];
if r.is_branch {
if !st.expanded.remove(&r.path) {
st.expanded.insert(r.path.clone());
}
window.refresh();
}
}
"home" => {
st.selected_path = rows_for_key[0].path.clone();
window.refresh();
}
"end" => {
st.selected_path = rows_for_key.last().unwrap().path.clone();
window.refresh();
}
_ => {}
}
});
let selected_bg = oklab_mix(colors.accent, colors.surface, 0.10);
let match_bg = oklab_mix(colors.warning, colors.surface, 0.16);
let chev_col = colors.text_muted;
for row in rows {
let indent_px = (row.depth as f32) * 18.0 + 10.0;
if let Some(hidden) = row.more_hidden {
let parent = row.parent_path.clone().unwrap_or_default();
let st_more = state_cell.clone();
tree_body = tree_body.child(
div()
.w_full()
.h(px(30.0))
.pl(px(indent_px + 18.0))
.pr(Spacing::S3)
.flex()
.flex_row()
.items_center()
.cursor_pointer()
.hover(|h| h.bg(colors.surface_muted))
.on_mouse_down(MouseButton::Left, move |_, window, _| {
let mut st = st_more.borrow_mut();
*st.pages.entry(parent.clone()).or_insert(1) += 1;
window.refresh();
})
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.accent)
.child(format!("Show more ({hidden} hidden)…")),
),
);
continue;
}
let is_selected = row.path == selected_path;
let is_match = matches.contains(&row.path);
let chev_deg = if row.is_branch {
arc_spring_with_options(
(
self.id.clone(),
SharedString::from(format!("jv-c-{}", row.path)),
),
if row.is_open { 90.0 } else { 0.0 },
SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
window,
cx,
)
.value
} else {
0.0
};
let val_color = match &row.value {
JsonValue::String(_) => colors.success,
JsonValue::Number(_) => colors.warning,
JsonValue::Bool(_) => colors.accent,
JsonValue::Null => colors.text_muted,
JsonValue::Array(_) | JsonValue::Object(_) => colors.text_secondary,
};
let val_preview: SharedString = match &row.value {
JsonValue::String(s) => SharedString::from(format!("\"{s}\"")),
JsonValue::Array(_) => SharedString::from(if row.is_open {
format!("[ {} items", row.count)
} else {
format!("[ {} items ]", row.count)
}),
JsonValue::Object(_) => SharedString::from(if row.is_open {
format!("{{ {} keys", row.count)
} else {
format!("{{ {} keys }}", row.count)
}),
other => SharedString::from(other.primitive_text()),
};
let row_path = row.path.clone();
let row_is_branch = row.is_branch;
let st_row = state_cell.clone();
let fh_row = focus_handle.clone();
let copy_val_path = row.path.clone();
let copy_val_text = match &row.value {
JsonValue::String(s) => s.to_string(),
other if other.is_branch() => other.to_pretty_json(0),
other => other.primitive_text(),
};
let st_cv = state_cell.clone();
let cb_cv = self.on_copy.clone();
let copy_path_str = row.path.clone();
let st_cp = state_cell.clone();
let cb_cp = self.on_copy.clone();
let mut row_el = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("jv-r-{}", row.path)),
))
.w_full()
.h(px(30.0))
.pl(px(indent_px))
.pr(Spacing::S3)
.flex()
.flex_row()
.items_center()
.justify_between()
.gap(Spacing::S2)
.cursor_pointer()
.role(Role::TreeItem)
.when(is_selected, |this| this.bg(selected_bg))
.when(!is_selected && is_match, |this| this.bg(match_bg))
.hover(|h| h.bg(colors.surface_muted))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
window.focus(&fh_row, cx);
let mut st = st_row.borrow_mut();
st.selected_path = row_path.clone();
if row_is_branch && !st.expanded.remove(&row_path) {
st.expanded.insert(row_path.clone());
}
window.refresh();
});
let mut left = div()
.flex_1()
.min_w(px(0.0))
.flex()
.flex_row()
.items_center()
.gap(px(6.0));
if row.is_branch {
left = left.child(
div().w(px(14.0)).h(px(14.0)).flex_none().child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let cx_p =
f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
let cy_p = f32::from(bounds.origin.y)
+ f32::from(bounds.size.height) * 0.5;
paint_chevron_right(cx_p, cy_p, chev_deg, chev_col, window);
},
)
.w_full()
.h_full(),
),
);
} else {
left = left.child(div().w(px(14.0)).h(px(14.0)).flex_none());
}
if let Some(key_lbl) = row.key_label {
left = left.child(
div()
.text_size(px(13.0))
.font_medium()
.text_color(if is_match {
colors.accent
} else {
colors.foreground
})
.child(format!("{key_lbl}:")),
);
}
left = left.child(
div()
.text_size(px(13.0))
.text_color(val_color)
.child(val_preview),
);
row_el = row_el.child(left);
if self.copyable && is_selected {
row_el = row_el.child(
div()
.flex_none()
.flex()
.flex_row()
.items_center()
.gap(Spacing::S1)
.child(
div()
.px(px(6.0))
.py(px(2.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.text_size(px(11.0))
.text_color(colors.text_secondary)
.cursor_pointer()
.hover(|h| h.bg(colors.surface_raised))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
cx.stop_propagation();
cx.write_to_clipboard(ClipboardItem::new_string(
copy_val_text.clone(),
));
st_cv.borrow_mut().last_copied = Some(SharedString::from(
format!("value @ {copy_val_path}"),
));
if let Some(cb) = &cb_cv {
cb("value", copy_val_path.as_ref(), window, cx);
}
window.refresh();
})
.child("Copy val"),
)
.child(
div()
.px(px(6.0))
.py(px(2.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.text_size(px(11.0))
.text_color(colors.text_secondary)
.cursor_pointer()
.hover(|h| h.bg(colors.surface_raised))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
cx.stop_propagation();
cx.write_to_clipboard(ClipboardItem::new_string(
copy_path_str.to_string(),
));
st_cp.borrow_mut().last_copied =
Some(SharedString::from(format!("path {copy_path_str}")));
if let Some(cb) = &cb_cp {
cb("path", copy_path_str.as_ref(), window, cx);
}
window.refresh();
})
.child("Path"),
),
);
}
tree_body = tree_body.child(row_el);
}
let mut root = div()
.id(self.id.clone())
.w_full()
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.overflow_hidden()
.flex()
.flex_col()
.child(toolbar)
.child(tree_body);
if self.show_path {
root = root.child(
div()
.w_full()
.px(Spacing::S3)
.py(Spacing::S2)
.border_t_1()
.border_color(colors.border)
.bg(colors.surface_muted)
.flex()
.flex_row()
.items_center()
.justify_between()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.child(selected_path),
)
.when_some(last_copied, |this, note| {
this.child(
div()
.text_size(px(11.0))
.text_color(colors.success)
.child(format!("Copied {note}")),
)
}),
);
}
root
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn search_opens_ancestors_and_pagination_creates_more_row() {
let data = JsonValue::object([
("service", JsonValue::string("arc-ui")),
(
"items",
JsonValue::array([
JsonValue::number(1.0),
JsonValue::number(2.0),
JsonValue::number(3.0),
JsonValue::object([("secret", JsonValue::string("needle"))]),
]),
),
]);
let (matches, ancestors) = search_json_tree(&data, "root", "needle");
assert!(matches.contains(&SharedString::from("root.items[3].secret")));
assert!(ancestors.contains(&SharedString::from("root")));
assert!(ancestors.contains(&SharedString::from("root.items")));
assert!(ancestors.contains(&SharedString::from("root.items[3]")));
let expanded: HashSet<SharedString> =
[SharedString::from("root"), SharedString::from("root.items")]
.into_iter()
.collect();
let rows = flatten_json_rows(
&data,
"root",
&expanded,
&HashSet::new(),
&HashMap::new(),
2,
);
assert!(rows.iter().any(|r| r.more_hidden == Some(2)));
}
}