Compare commits
10
Commits
69265b4fd4
...
0f468e8661
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f468e8661 | ||
|
|
cb5e35f7cb | ||
|
|
694cccbc81 | ||
|
|
d24984cc38 | ||
|
|
f5eb82ee1b | ||
|
|
5490869f23 | ||
|
|
ca6d2e219e | ||
|
|
152d881f4f | ||
|
|
33df23c02a | ||
|
|
cbf63c6945 |
No files matched your search
@@ -13,7 +13,7 @@ Ely GPUI Component. A component library for GPUI, in light and dark.
|
||||
- Web views: `wry` 0.57 (Apache-2.0 OR MIT, default features off, macOS only) lays a child WKWebView over the window.
|
||||
- Terminal: `alacritty_terminal` 0.26 (Apache-2.0, default features off, native only) for the grid, its parser and the pseudo-terminal; `futures` carries its events. `vte` 0.15 (Apache-2.0 OR MIT), the parser it re-exports, reads `AnsiText`'s codes alone, so colored output builds for wasm32.
|
||||
- Diffs: `similar` 3.2 (Apache-2.0) for line and word diffs and three-way merges; its `unicode` feature splits words at punctuation.
|
||||
- Markdown: `pulldown-cmark` 0.13 (MIT, default features off) for CommonMark with tables, tasks, strikethrough, footnotes and math.
|
||||
- Markdown: `pulldown-cmark` 0.13 (MIT, default features off) for CommonMark with tables, tasks, strikethrough, footnotes and math; `BlockData::from_markdown` adds GitHub's alerts, a callout's form, and reads each field's inline Markdown from the source by offset, as written.
|
||||
- Pictures: `image` 0.25 (MIT OR Apache-2.0), the crate gpui decodes with, default features off; it turns decoded frames and rims map tiles.
|
||||
- Maps: Natural Earth's 110m countries (public domain). `assets/maps/countries.geojson`, trimmed by `scripts/countries.py` to an ISO code, a name and positions to 0.01°, backs `maps::WorldMap`; the gallery's tiles are cut from the same file, z0 to z3, by `scripts/tiles.py` with Pillow.
|
||||
- Web: on wasm32, `web-time` 1.1 (MIT OR Apache-2.0) gives the `Instant` gpui's executor returns, std's own natively; jiff takes `js`, rust-embed `debug-embed`, similar `wasm32_web_time`. The gallery's web entry takes `gpui_web`, `wasm-bindgen`, `js-sys` and `web-sys` as wasm-only dev-dependencies, and a Hebrew cut of Noto Sans Hebrew 2.003 (OFL, `examples/gallery/fonts`): gpui_web asks the browser for emoji and CJK alone. The `wasm-bindgen` CLI at Cargo.lock's version and binaryen's `wasm-opt` finish the bundle.
|
||||
@@ -177,12 +177,13 @@ Ely GPUI Component. A component library for GPUI, in light and dark.
|
||||
- A component that fills its container takes no width on its root: a block or a flex column stretches it, in a flex row the host gives it `flex_1`, and as a window's root it fills the window, since gpui sets a window root's auto sides to the window's size. A percent width ignores the root's own margins, so they push it past its container, and in a flex row it takes the whole row as its basis and leaves a `flex_1().min_w_0()` neighbor nothing. A root centered under a cap keeps `w_full`, since a flex column stretches no child with an auto side margin, and `mx_auto` needs a width to fill (`layout::Container`). So does a box that keeps a ratio: a block follows its ratio from a stretch, but a flex or grid box only from a set width, and callers may make one flex (`layout::AspectRatio`, and `primitives::framed` under VideoPlayer, CameraPreview, ModelViewer, ParticipantTile and InpaintCanvas). `Button::full_width` is its host asking, since a button takes no style. Each chapter's test holds its filling roots at the full width of a flex column in a padded block through `layout::tests::narrow_width`, which reads a root by its `debug_selector`.
|
||||
- A field's `Highlight` sets color, wash, weight, slant and strike per span; measuring and painting share one set of runs, so wrapped heights match.
|
||||
- A block editor keeps one undo for the document: text and structure together, as snapshots through `forms::History`; it takes Undo and Redo before its fields do.
|
||||
- A selection across a BlockEditor's fields lives in the editor (`blocks::span`): a press in a field drags into others, Shift-press reaches from the caret's field. The pressed field selects its own part; the editor sets the other end's and washes blocks between. The editor watches the focused end through `TextInput::edits`, which counts every edit, text changed or not: an edit there, once an input method commits, is rebuilt from the last snapshot as head, typed and tail in one undo step; a caret move or lost focus lets the span go, since gpui runs bindings before key listeners. Backspace, Delete, Cut and Enter take the span before the field acts; copy writes it as Markdown.
|
||||
- gpui calls focus listeners only while the window is active. A test that needs focus events activates its window with `window.activate_window()`.
|
||||
- A terminal takes Tab and Shift-Tab through bindings under `ElyTerminal`, ahead of focus moves; other keys go through `terminal::keys` in a key listener, and typed text through its input handler.
|
||||
- A shell in the gallery starts without startup files and with a fixed prompt, so captures show no user or host.
|
||||
- gpui has no `(ElementId, usize)` id. A child id names its index: `(self.id.clone(), format!("row-{ix}"))`.
|
||||
- Clippy's `single_range_in_vec_init` rejects `[a..b]` and `vec![a..b]`; bind the range first.
|
||||
- A component built on `lists::Tree` fills its box; the host gives it a height. A fixed-width column beside a `flex_1` one takes `flex_none`, or it shrinks.
|
||||
- A component built on `lists::Tree` fills its box; the host gives it a height. So does `documents::BlockEditor`, which scrolls in a `ScrollArea` through its own handle (`ScrollArea::track_scroll`) and brings the caret into view each time it moves, not each frame, so a wheel moves past a still caret. A fixed-width column beside a `flex_1` one takes `flex_none`, or it shrinks.
|
||||
- Editor rows read their text through `CodeEditor::row_text`: a multi-line ghost cuts its line, and the rest follows the ghost's last line.
|
||||
- gpui clears `debug_bounds` each frame: a test sees an element leave as well as appear.
|
||||
- Time reads `web_time::Instant`: std's compiles for wasm32 and panics in the browser. `scripts/check.sh` refuses std's in `src` and the gallery.
|
||||
@@ -202,7 +203,7 @@ Ely GPUI Component. A component library for GPUI, in light and dark.
|
||||
- A header that holds a name beside counts and actions wraps: `flex_wrap`, the name `flex_1` with `min_w(label_width)`, the rest one `flex_none` group that drops below.
|
||||
- Every header, row and strip works at 280px: a name keeps its minimum width, the rest wraps below or scrolls, and nothing draws past its box.
|
||||
- gpui takes a scroll box's reach from its direct children's bounds, and a block child stretches to the box. Content that scrolls sideways sets its least width on that child (`tables::body::least`).
|
||||
- gpui turns a wheel along the other axis onto a box that scrolls one way, and the page around it scrolls too. A box inside a scrolling page keeps its wheel to its axis with `layout::on_axis`, and so does the page.
|
||||
- gpui turns a wheel along the other axis onto a box that scrolls one way, and the page around it scrolls too. A box inside a scrolling page keeps its wheel to its axis with `layout::on_axis`, and so does the page. gpui also hands a wheel to every scroll box under the pointer, so a `ScrollArea` stops a wheel along an axis it has room on and passes one it cannot use, and a floating option list occludes (`forms::options::Popup`).
|
||||
- The focus color belongs to the focus ring. A chosen or shown item takes accent, as `forms::picks` and `lists::ListItem` do.
|
||||
- A box that shows a host's picture takes the picture's shape from the host (`ratio`), so nothing is cropped and a point given as a share lands on the picture. A focusable one keeps its focus border on an outer box, so the picture keeps that shape exactly (`media::ImageCropper`).
|
||||
- A default only the component can work out, such as a crop fitted to a picture it decodes, reaches the owner once through `window.defer` after render (`media::ImageUpload`).
|
||||
|
||||
@@ -202,7 +202,10 @@ pub fn editing(window: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
|
||||
"Blocks like a notebook's. Hover one for its handle: drag it to move the block, press it to turn, copy or delete it. / on an empty line lists every kind, and an empty line says so. Undo covers text and blocks alike.",
|
||||
cx,
|
||||
)
|
||||
.child(probe("doc-blocks", div().w(px(760.)).child(notes))),
|
||||
.child(probe(
|
||||
"doc-blocks",
|
||||
div().w(px(760.)).h(px(360.)).child(notes),
|
||||
)),
|
||||
)
|
||||
.child(
|
||||
section(
|
||||
@@ -210,7 +213,7 @@ pub fn editing(window: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
|
||||
"Code colored as code, math set as it is typed, diagrams the app draws from their source, dividers, tables that grow and merge cells, pictures to resize and align, pages to open, columns, and synced copies that change together.",
|
||||
cx,
|
||||
)
|
||||
.child(div().w(px(760.)).child(kinds)),
|
||||
.child(div().w(px(760.)).h(px(560.)).child(kinds)),
|
||||
)
|
||||
.child(
|
||||
section(
|
||||
|
||||
@@ -3,8 +3,7 @@ use std::rc::Rc;
|
||||
use gpui::{
|
||||
Animation, AnimationExt, AnyElement, App, ElementId, FocusHandle, FontWeight,
|
||||
InteractiveElement, IntoElement, MouseButton, ParentElement, Pixels, RenderOnce, Role,
|
||||
ScrollHandle, SharedString, StatefulInteractiveElement, Styled, Window, div, prelude::*, px,
|
||||
rems,
|
||||
ScrollHandle, SharedString, StatefulInteractiveElement, Styled, Window, div, prelude::*, rems,
|
||||
};
|
||||
|
||||
use super::button::label_size;
|
||||
@@ -96,7 +95,8 @@ impl RenderOnce for SegmentedControl {
|
||||
})
|
||||
.collect();
|
||||
// Last frame's strip width decides icons only.
|
||||
let strip = window.use_keyed_state((self.id.clone(), "strip-width"), cx, |_, _| Pixels::ZERO);
|
||||
let strip =
|
||||
window.use_keyed_state((self.id.clone(), "strip-width"), cx, |_, _| Pixels::ZERO);
|
||||
let shown = *strip.read(cx);
|
||||
let compact = self.segments.iter().all(|(_, _, icon)| icon.is_some())
|
||||
&& shown > Pixels::ZERO
|
||||
@@ -189,7 +189,9 @@ impl RenderOnce for SegmentedControl {
|
||||
.when_some(icon, |segment, icon| {
|
||||
segment.child(Icon::new(icon).size(icon_size).color(fg))
|
||||
})
|
||||
.when(compact, |segment| segment.tooltip(Tooltip::text(label.clone())))
|
||||
.when(compact, |segment| {
|
||||
segment.tooltip(Tooltip::text(label.clone()))
|
||||
})
|
||||
.when(!label.is_empty() && !compact, |segment| {
|
||||
segment.child(
|
||||
div()
|
||||
@@ -246,9 +248,10 @@ fn natural(
|
||||
let theme = cx.theme();
|
||||
let rem = window.rem_size();
|
||||
let (text, icon) = label_size(size);
|
||||
let pad = theme.control_padding(size).to_pixels(rem) * 2.0 + px(2.0);
|
||||
let pad = (theme.control_padding(size).to_pixels(rem) + theme.hairline()) * 2.0;
|
||||
let glyph = theme.icon_size(icon).to_pixels(rem) + rems(0.375).to_pixels(rem);
|
||||
segments.iter().fold(px(6.0), |sum, (_, label, icon)| {
|
||||
let strip = (rems(0.125).to_pixels(rem) + theme.hairline()) * 2.0;
|
||||
segments.iter().fold(strip, |sum, (_, label, icon)| {
|
||||
let width = text_width(label, text, FontWeight::SEMIBOLD, window, cx);
|
||||
sum + pad + width + if icon.is_some() { glyph } else { Pixels::ZERO }
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ use gpui::{
|
||||
use super::peers::Peer;
|
||||
use crate::{
|
||||
forms::TextInput,
|
||||
primitives::caret_bar,
|
||||
theme::{ActiveTheme, Radius, TextSize},
|
||||
typography::LEADING,
|
||||
};
|
||||
@@ -61,10 +62,9 @@ impl RenderOnce for RemoteCursor {
|
||||
return;
|
||||
}
|
||||
window.with_content_mask(Some(ContentMask { bounds }), |window| {
|
||||
window.paint_quad(fill(
|
||||
gpui::Bounds::new(caret.origin, size(bar, caret.size.height)),
|
||||
color,
|
||||
));
|
||||
let scale = window.scale_factor();
|
||||
let bar = caret_bar(caret.origin, bar, caret.size.height, scale);
|
||||
window.paint_quad(fill(bar, color));
|
||||
});
|
||||
let font = gpui::Font {
|
||||
weight: FontWeight::MEDIUM,
|
||||
|
||||
@@ -76,6 +76,7 @@ impl BlockEditor {
|
||||
}
|
||||
|
||||
pub(crate) fn undo(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.clear_span(window, cx);
|
||||
self.settle(true, cx);
|
||||
if let Some(previous) = self.history.undo(self.now(cx)) {
|
||||
log::info!("block editor: undo");
|
||||
@@ -84,6 +85,7 @@ impl BlockEditor {
|
||||
}
|
||||
|
||||
pub(crate) fn redo(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.clear_span(window, cx);
|
||||
if let Some(next) = self.history.redo(self.now(cx)) {
|
||||
log::info!("block editor: redo");
|
||||
self.restore(next, window, cx);
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
use std::ops::Range;
|
||||
|
||||
use pulldown_cmark::{Event, Parser};
|
||||
|
||||
use super::{BlockData, BlockKind, Media};
|
||||
|
||||
impl BlockData {
|
||||
/// The document as Markdown, GitHub's flavor: a callout is a `[!NOTE]` quote, a toggle a `<details>`, a diagram a `mermaid` fence, math a `math` fence. Fields already hold Markdown and pass through as written, so a blank line in prose starts a new block; a heading, caption, toggle title or table cell keeps one line, and a caption's lone bracket comes back escaped. HTML in a field is read as HTML. What Markdown has no form for takes its nearest: a table's merges, media's width and alignment, columns as paragraphs, a synced block as its text, video and embeds as links.
|
||||
pub fn to_markdown(blocks: &[BlockData]) -> String {
|
||||
let mut out = String::new();
|
||||
let mut previous: Option<&BlockKind> = None;
|
||||
let mut number = 0;
|
||||
for block in blocks {
|
||||
number = match block.kind {
|
||||
BlockKind::Numbered => number + 1,
|
||||
_ => 0,
|
||||
};
|
||||
let Some(text) = write(block, number) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(previous) = previous {
|
||||
out.push_str(if same_list(previous, &block.kind) {
|
||||
"\n"
|
||||
} else {
|
||||
"\n\n"
|
||||
});
|
||||
}
|
||||
out.push_str(&text);
|
||||
previous = Some(&block.kind);
|
||||
}
|
||||
out.push('\n');
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two kinds follow on in one Markdown list.
|
||||
fn same_list(previous: &BlockKind, next: &BlockKind) -> bool {
|
||||
let bulleted = |kind: &BlockKind| matches!(kind, BlockKind::Bullet | BlockKind::Todo(_));
|
||||
(bulleted(previous) && bulleted(next))
|
||||
|| (*previous == BlockKind::Numbered && *next == BlockKind::Numbered)
|
||||
}
|
||||
|
||||
/// One block as Markdown; nothing for an empty paragraph, which Markdown cannot hold.
|
||||
fn write(block: &BlockData, number: usize) -> Option<String> {
|
||||
let texts = &block.texts;
|
||||
let text = || texts[0].as_str();
|
||||
let written = match &block.kind {
|
||||
BlockKind::Paragraph | BlockKind::Synced(_) if text().trim().is_empty() => return None,
|
||||
BlockKind::Paragraph | BlockKind::Synced(_) => text().to_string(),
|
||||
BlockKind::Heading(level) => {
|
||||
let level = usize::from((*level).clamp(1, 6));
|
||||
format!("{} {}", "#".repeat(level), text().replace('\n', " "))
|
||||
}
|
||||
BlockKind::Bullet => item("- ", text()),
|
||||
BlockKind::Numbered => item(&format!("{number}. "), text()),
|
||||
BlockKind::Todo(done) => item(if *done { "- [x] " } else { "- [ ] " }, text()),
|
||||
BlockKind::Quote => quoted(text()),
|
||||
BlockKind::Callout => format!("> [!NOTE]\n{}", quoted(text())),
|
||||
BlockKind::Toggle(open) => {
|
||||
let open = if *open { " open" } else { "" };
|
||||
let title = texts[0].replace('\n', " ");
|
||||
let head = format!("<details{open}>\n<summary>{title}</summary>");
|
||||
match texts[1].trim() {
|
||||
"" => format!("{head}\n\n</details>"),
|
||||
body => format!("{head}\n\n{body}\n\n</details>"),
|
||||
}
|
||||
}
|
||||
BlockKind::Code => fenced(text(), ""),
|
||||
BlockKind::Diagram => fenced(text(), "mermaid"),
|
||||
BlockKind::Math => fenced(text(), "math"),
|
||||
BlockKind::Divider => "---".to_string(),
|
||||
BlockKind::Table { columns, .. } => table(texts, *columns),
|
||||
BlockKind::Image(media) => {
|
||||
let caption = brackets(&text().replace('\n', " "));
|
||||
format!("", address(media))
|
||||
}
|
||||
BlockKind::Video(media) | BlockKind::Embed(media) => {
|
||||
let words = if text().is_empty() {
|
||||
&media.source
|
||||
} else {
|
||||
text()
|
||||
};
|
||||
format!("[{words}]({})", address(media))
|
||||
}
|
||||
BlockKind::Columns(_) => {
|
||||
let filled: Vec<&str> = texts
|
||||
.iter()
|
||||
.map(|text| text.trim())
|
||||
.filter(|text| !text.is_empty())
|
||||
.collect();
|
||||
if filled.is_empty() {
|
||||
return None;
|
||||
}
|
||||
filled.join("\n\n")
|
||||
}
|
||||
};
|
||||
Some(written)
|
||||
}
|
||||
|
||||
/// A list item: the marker, then each further line under its text.
|
||||
fn item(marker: &str, text: &str) -> String {
|
||||
let indent = " ".repeat(marker.len());
|
||||
let mut lines = text.lines();
|
||||
let mut out = format!("{marker}{}", lines.next().unwrap_or_default());
|
||||
for line in lines {
|
||||
out.push('\n');
|
||||
out.push_str(&indent);
|
||||
out.push_str(line);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn quoted(text: &str) -> String {
|
||||
let lines: Vec<String> = text
|
||||
.split('\n')
|
||||
.map(|line| match line {
|
||||
"" => ">".to_string(),
|
||||
line => format!("> {line}"),
|
||||
})
|
||||
.collect();
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
/// Code between fences longer than any run of backticks inside it.
|
||||
fn fenced(text: &str, language: &str) -> String {
|
||||
let longest = text
|
||||
.split(|ch| ch != '`')
|
||||
.map(str::len)
|
||||
.max()
|
||||
.unwrap_or_default();
|
||||
let fence = "`".repeat(longest.max(2) + 1);
|
||||
format!("{fence}{language}\n{text}\n{fence}")
|
||||
}
|
||||
|
||||
fn table(texts: &[String], columns: usize) -> String {
|
||||
let row = |cells: &[String]| {
|
||||
let cells: Vec<String> = cells
|
||||
.iter()
|
||||
.map(|cell| pipes(cell).replace('\n', " "))
|
||||
.collect();
|
||||
format!("| {} |", cells.join(" | "))
|
||||
};
|
||||
let mut rows = texts.chunks(columns);
|
||||
let head = rows.next().expect("a table holds its header row");
|
||||
let mut out = vec![row(head), format!("|{}", " --- |".repeat(columns))];
|
||||
out.extend(rows.map(row));
|
||||
out.join("\n")
|
||||
}
|
||||
|
||||
/// A link's address, in angle brackets when it holds a space or a bracket.
|
||||
fn address(media: &Media) -> String {
|
||||
match media.source.contains([' ', '(', ')', '<', '>']) {
|
||||
true => format!("<{}>", media.source.replace('<', "\\<").replace('>', "\\>")),
|
||||
false => media.source.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A caption that cannot end its image early: a bracket left open or shut alone outside code, or a last backslash, is escaped.
|
||||
fn brackets(text: &str) -> String {
|
||||
let code: Vec<Range<usize>> = Parser::new(text)
|
||||
.into_offset_iter()
|
||||
.filter_map(|(event, range)| matches!(event, Event::Code(_)).then_some(range))
|
||||
.collect();
|
||||
let (mut open, mut lone, mut slashes) = (Vec::new(), Vec::new(), 0);
|
||||
for (at, ch) in text.char_indices() {
|
||||
let free = slashes % 2 == 0 && !code.iter().any(|span| span.contains(&at));
|
||||
match ch {
|
||||
'[' if free => open.push(at),
|
||||
']' if free && open.pop().is_none() => lone.push(at),
|
||||
_ => {}
|
||||
}
|
||||
slashes = if ch == '\\' { slashes + 1 } else { 0 };
|
||||
}
|
||||
lone.extend(open);
|
||||
let mut out = String::with_capacity(text.len() + lone.len() + 1);
|
||||
for (at, ch) in text.char_indices() {
|
||||
if lone.contains(&at) {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(ch);
|
||||
}
|
||||
if slashes % 2 == 1 {
|
||||
out.push('\\');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A cell's pipes escaped where they are not already, so none splits its row.
|
||||
fn pipes(cell: &str) -> String {
|
||||
let (mut out, mut slashes) = (String::with_capacity(cell.len()), 0);
|
||||
for ch in cell.chars() {
|
||||
if ch == '|' && slashes % 2 == 0 {
|
||||
out.push('\\');
|
||||
}
|
||||
slashes = if ch == '\\' { slashes + 1 } else { 0 };
|
||||
out.push(ch);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
use std::ops::Range;
|
||||
|
||||
use pulldown_cmark::{Event, Tag};
|
||||
|
||||
use super::{Reader, Toggle};
|
||||
use crate::documents::blocks::{BlockData, BlockKind};
|
||||
|
||||
/// An HTML tag: where it starts and ends, its name, whether it closes, and its attributes' names.
|
||||
struct Mark {
|
||||
at: usize,
|
||||
end: usize,
|
||||
closes: bool,
|
||||
name: String,
|
||||
attributes: Vec<String>,
|
||||
}
|
||||
|
||||
/// The tags in `html`, past comments; a quoted value is read as a value.
|
||||
fn marks(html: &str) -> Vec<Mark> {
|
||||
let bytes = html.as_bytes();
|
||||
let (mut marks, mut at) = (Vec::new(), 0);
|
||||
while let Some(found) = html[at..].find('<').map(|found| at + found) {
|
||||
if html[found..].starts_with("<!--") {
|
||||
at = html[found..]
|
||||
.find("-->")
|
||||
.map_or(html.len(), |end| found + end + 3);
|
||||
continue;
|
||||
}
|
||||
let closes = bytes.get(found + 1) == Some(&b'/');
|
||||
let name_at = found + 1 + usize::from(closes);
|
||||
let name_end = html[name_at..]
|
||||
.find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '-'))
|
||||
.map_or(html.len(), |end| name_at + end);
|
||||
if !bytes.get(name_at).is_some_and(u8::is_ascii_alphabetic) {
|
||||
at = found + 1;
|
||||
continue;
|
||||
}
|
||||
let (end, attributes) = attributes(html, name_end);
|
||||
marks.push(Mark {
|
||||
at: found,
|
||||
end,
|
||||
closes,
|
||||
name: html[name_at..name_end].to_ascii_lowercase(),
|
||||
attributes,
|
||||
});
|
||||
at = end;
|
||||
}
|
||||
marks
|
||||
}
|
||||
|
||||
/// Reads a tag's attributes from `from` to its `>`: where the tag ends, and the names.
|
||||
fn attributes(html: &str, from: usize) -> (usize, Vec<String>) {
|
||||
let bytes = html.as_bytes();
|
||||
let (mut names, mut word, mut value, mut quote) = (Vec::new(), None, false, None);
|
||||
for (at, byte) in bytes.iter().copied().enumerate().skip(from) {
|
||||
if let Some(open) = quote {
|
||||
if byte == open {
|
||||
(quote, value) = (None, false);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let ends =
|
||||
byte.is_ascii_whitespace() || byte == b'>' || (!value && matches!(byte, b'=' | b'/'));
|
||||
if !ends {
|
||||
match byte {
|
||||
b'"' | b'\'' => quote = Some(byte),
|
||||
_ => word = word.or(Some(at)),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(start) = word.take() {
|
||||
if !value {
|
||||
names.push(html[start..at].to_ascii_lowercase());
|
||||
}
|
||||
value = false;
|
||||
}
|
||||
match byte {
|
||||
b'=' => value = true,
|
||||
b'>' => return (at + 1, names),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(start) = word.filter(|_| !value) {
|
||||
names.push(html[start..].to_ascii_lowercase());
|
||||
}
|
||||
(html.len(), names)
|
||||
}
|
||||
|
||||
fn named<'a>(marks: &'a [Mark], name: &str, closes: bool, from: usize) -> Option<&'a Mark> {
|
||||
marks
|
||||
.iter()
|
||||
.find(|mark| mark.name == name && mark.closes == closes && mark.at >= from)
|
||||
}
|
||||
|
||||
impl Reader<'_> {
|
||||
pub(super) fn html_block(&mut self, range: Range<usize>) {
|
||||
let source = self.source;
|
||||
let block = &source[range.clone()];
|
||||
let marks = marks(block);
|
||||
let first = marks
|
||||
.first()
|
||||
.filter(|mark| block[..mark.at].trim().is_empty() && mark.name == "details");
|
||||
let Some(first) = first.filter(|mark| !mark.closes) else {
|
||||
self.html = true;
|
||||
return self.put(BlockKind::Paragraph, block.trim().to_string());
|
||||
};
|
||||
let summary = named(&marks, "summary", false, first.end);
|
||||
let shut = summary.and_then(|open| named(&marks, "summary", true, open.end));
|
||||
let (title, head) = match (summary, shut) {
|
||||
(Some(open), Some(shut)) => (block[open.end..shut.at].trim(), shut.end),
|
||||
_ => ("", first.end),
|
||||
};
|
||||
let head = range.start + head;
|
||||
self.toggle = Some(Toggle {
|
||||
open: first.attributes.iter().any(|name| name == "open"),
|
||||
title: title.to_string(),
|
||||
body: head,
|
||||
depth: 0,
|
||||
});
|
||||
self.scan_toggle(head, range.end);
|
||||
}
|
||||
|
||||
/// Skips a toggle's body, Markdown kept as written, to the `</details>` that closes it.
|
||||
pub(super) fn in_toggle(&mut self, event: Event, range: Range<usize>) {
|
||||
if let Event::Start(Tag::HtmlBlock) = event {
|
||||
self.scan_toggle(range.start, range.end);
|
||||
}
|
||||
}
|
||||
|
||||
/// Follows `<details>` tags in `from..to`; the close that matches the toggle's open ends it.
|
||||
fn scan_toggle(&mut self, from: usize, to: usize) {
|
||||
let source = self.source;
|
||||
let Some(mut depth) = self.toggle.as_ref().map(|toggle| toggle.depth) else {
|
||||
return;
|
||||
};
|
||||
let mut closed = None;
|
||||
let marks = marks(&source[from..to]);
|
||||
for mark in marks.into_iter().filter(|mark| mark.name == "details") {
|
||||
match (mark.closes, depth) {
|
||||
(false, _) => depth += 1,
|
||||
(true, 0) => {
|
||||
closed = Some(mark);
|
||||
break;
|
||||
}
|
||||
(true, _) => depth -= 1,
|
||||
}
|
||||
}
|
||||
let Some(close) = closed else {
|
||||
if let Some(toggle) = &mut self.toggle {
|
||||
toggle.depth = depth;
|
||||
}
|
||||
return;
|
||||
};
|
||||
self.end_toggle(from + close.at);
|
||||
self.html = true;
|
||||
let rest = source[from + close.end..to].trim();
|
||||
if !rest.is_empty() {
|
||||
self.put(BlockKind::Paragraph, rest.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn end_toggle(&mut self, end: usize) {
|
||||
let Some(toggle) = self.toggle.take() else {
|
||||
return;
|
||||
};
|
||||
let body = self.source[toggle.body..end].trim().to_string();
|
||||
self.bodies.push(toggle.body..end);
|
||||
if let Some((_, _, parts)) = &mut self.quote {
|
||||
parts.push(body);
|
||||
return;
|
||||
}
|
||||
self.emit_item();
|
||||
let kind = BlockKind::Toggle(toggle.open);
|
||||
self.out.push(BlockData::new(kind, [toggle.title, body]));
|
||||
}
|
||||
|
||||
/// A toggle the source never closes keeps the rest as its body.
|
||||
pub(super) fn unclosed(&mut self) {
|
||||
if let Some(toggle) = &self.toggle {
|
||||
log::error!(
|
||||
"block editor: the <details> at byte {} never closes; its body runs to the end",
|
||||
toggle.body
|
||||
);
|
||||
self.end_toggle(self.source.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
use std::ops::Range;
|
||||
|
||||
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
|
||||
|
||||
use super::{BlockData, BlockKind, Media};
|
||||
|
||||
mod details;
|
||||
|
||||
impl BlockData {
|
||||
/// Blocks from Markdown, as `to_markdown` writes it: inline Markdown stays as written in each field. A nested list comes out flat, and a quote or callout holds its paragraphs as text.
|
||||
pub fn from_markdown(source: &str) -> Vec<BlockData> {
|
||||
let options = Options::ENABLE_TABLES
|
||||
| Options::ENABLE_STRIKETHROUGH
|
||||
| Options::ENABLE_TASKLISTS
|
||||
| Options::ENABLE_MATH
|
||||
| Options::ENABLE_GFM;
|
||||
let mut reader = Reader {
|
||||
source,
|
||||
..Reader::default()
|
||||
};
|
||||
let mut events = Parser::new_ext(source, options).into_offset_iter();
|
||||
for (event, range) in events.by_ref() {
|
||||
reader.read(event, range);
|
||||
}
|
||||
reader.unclosed();
|
||||
let mut spans: Vec<Range<usize>> = events
|
||||
.reference_definitions()
|
||||
.iter()
|
||||
.map(|(_, definition)| definition.span.clone())
|
||||
.filter(|span| !reader.bodies.iter().any(|body| body.contains(&span.start)))
|
||||
.collect();
|
||||
spans.sort_by_key(|span| span.start);
|
||||
let definitions: Vec<&str> = spans.into_iter().map(|span| source[span].trim()).collect();
|
||||
if !definitions.is_empty() {
|
||||
reader.put(
|
||||
BlockKind::Paragraph,
|
||||
definitions.join(
|
||||
"
|
||||
",
|
||||
),
|
||||
);
|
||||
}
|
||||
log::debug!(
|
||||
"block editor: {} blocks read from markdown",
|
||||
reader.out.len()
|
||||
);
|
||||
reader.out
|
||||
}
|
||||
}
|
||||
|
||||
/// What a paragraph holds alone, which makes it a block of its own.
|
||||
#[derive(Default)]
|
||||
enum Sole {
|
||||
#[default]
|
||||
Nothing,
|
||||
Math(String),
|
||||
Image(String, Option<Range<usize>>),
|
||||
Mixed,
|
||||
}
|
||||
|
||||
/// Inline text being read: its stretch of the source, and how deep in inline tags.
|
||||
#[derive(Default)]
|
||||
struct Leaf {
|
||||
range: Option<Range<usize>>,
|
||||
depth: usize,
|
||||
sole: Sole,
|
||||
}
|
||||
|
||||
struct Item {
|
||||
kind: BlockKind,
|
||||
parts: Vec<String>,
|
||||
emitted: bool,
|
||||
}
|
||||
|
||||
struct Toggle {
|
||||
open: bool,
|
||||
title: String,
|
||||
body: usize,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Reader<'a> {
|
||||
source: &'a str,
|
||||
out: Vec<BlockData>,
|
||||
leaf: Option<Leaf>,
|
||||
/// The outermost quote: callout or not, depth, and its paragraphs.
|
||||
quote: Option<(bool, usize, Vec<String>)>,
|
||||
lists: Vec<bool>,
|
||||
items: Vec<Item>,
|
||||
code: Option<(BlockKind, String)>,
|
||||
/// Columns, cells so far, and the row being read.
|
||||
table: Option<(usize, Vec<String>, Vec<String>)>,
|
||||
toggle: Option<Toggle>,
|
||||
/// Toggle bodies, kept as written.
|
||||
bodies: Vec<Range<usize>>,
|
||||
html: bool,
|
||||
}
|
||||
|
||||
/// Inline lines as one field: each further line loses its indent and quote marks.
|
||||
fn clean(slice: &str, quotes: usize) -> String {
|
||||
let mut lines = slice.split('\n');
|
||||
let mut out = lines.next().unwrap_or_default().to_string();
|
||||
for line in lines {
|
||||
let mut line = line.trim_start();
|
||||
for _ in 0..quotes {
|
||||
line = line.strip_prefix('>').unwrap_or(line).trim_start();
|
||||
}
|
||||
out.push('\n');
|
||||
out.push_str(line);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Reader<'_> {
|
||||
fn read(&mut self, event: Event, range: Range<usize>) {
|
||||
if self.toggle.is_some() {
|
||||
return self.in_toggle(event, range);
|
||||
}
|
||||
if self.html {
|
||||
self.html = !matches!(event, Event::End(TagEnd::HtmlBlock));
|
||||
return;
|
||||
}
|
||||
if let Some((_, code)) = &mut self.code {
|
||||
match event {
|
||||
Event::Text(text) => code.push_str(&text),
|
||||
Event::End(TagEnd::CodeBlock) => self.end_code(),
|
||||
_ => {}
|
||||
}
|
||||
return;
|
||||
}
|
||||
match event {
|
||||
Event::Start(Tag::HtmlBlock) => self.html_block(range),
|
||||
Event::Start(Tag::Paragraph | Tag::Heading { .. } | Tag::TableCell) => {
|
||||
self.flush_leaf();
|
||||
self.leaf = Some(Leaf::default());
|
||||
}
|
||||
Event::End(TagEnd::Paragraph) => self.end_paragraph(),
|
||||
Event::End(TagEnd::Heading(level)) => {
|
||||
let text = self.leaf_text();
|
||||
self.put(BlockKind::Heading(level as u8), text);
|
||||
}
|
||||
Event::Start(Tag::BlockQuote(kind)) => match &mut self.quote {
|
||||
Some((_, depth, _)) => *depth += 1,
|
||||
None => {
|
||||
self.flush_leaf();
|
||||
self.quote = Some((kind.is_some(), 1, Vec::new()));
|
||||
}
|
||||
},
|
||||
Event::End(TagEnd::BlockQuote(_)) => self.end_quote(),
|
||||
Event::Start(Tag::CodeBlock(kind)) => {
|
||||
self.flush_leaf();
|
||||
let fence = match kind {
|
||||
CodeBlockKind::Fenced(language) => language.trim().to_string(),
|
||||
CodeBlockKind::Indented => String::new(),
|
||||
};
|
||||
let kind = match fence.as_str() {
|
||||
"mermaid" => BlockKind::Diagram,
|
||||
"math" => BlockKind::Math,
|
||||
_ => BlockKind::Code,
|
||||
};
|
||||
self.code = Some((kind, String::new()));
|
||||
}
|
||||
Event::Start(Tag::List(start)) => {
|
||||
self.flush_leaf();
|
||||
self.emit_item();
|
||||
self.lists.push(start.is_some());
|
||||
}
|
||||
Event::End(TagEnd::List(_)) => {
|
||||
self.lists.pop();
|
||||
}
|
||||
Event::Start(Tag::Item) => {
|
||||
let numbered = self.lists.last().copied().unwrap_or_default();
|
||||
let kind = match numbered {
|
||||
true => BlockKind::Numbered,
|
||||
false => BlockKind::Bullet,
|
||||
};
|
||||
self.items.push(Item {
|
||||
kind,
|
||||
parts: Vec::new(),
|
||||
emitted: false,
|
||||
});
|
||||
self.leaf = Some(Leaf::default());
|
||||
}
|
||||
Event::TaskListMarker(done) => {
|
||||
if let Some(item) = self.items.last_mut() {
|
||||
item.kind = BlockKind::Todo(done);
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::Item) => {
|
||||
self.flush_leaf();
|
||||
self.emit_item();
|
||||
self.items.pop();
|
||||
}
|
||||
Event::Rule => self.put(BlockKind::Divider, String::new()),
|
||||
Event::Start(Tag::Table(aligns)) => {
|
||||
self.table = Some((aligns.len(), Vec::new(), Vec::new()));
|
||||
}
|
||||
Event::End(TagEnd::TableCell) => {
|
||||
let text = self.leaf_text().replace("\\|", "|");
|
||||
if let Some((_, _, row)) = &mut self.table {
|
||||
row.push(text);
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::TableHead | TagEnd::TableRow) => {
|
||||
if let Some((columns, cells, row)) = &mut self.table {
|
||||
row.resize(*columns, String::new());
|
||||
cells.append(row);
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::Table) => self.end_table(),
|
||||
event => self.inline(event, range),
|
||||
}
|
||||
}
|
||||
|
||||
fn inline(&mut self, event: Event, range: Range<usize>) {
|
||||
let Some(leaf) = &mut self.leaf else {
|
||||
return;
|
||||
};
|
||||
let (start, end) = leaf.range.as_ref().map_or((range.start, range.end), |had| {
|
||||
(had.start.min(range.start), had.end.max(range.end))
|
||||
});
|
||||
leaf.range = Some(start..end);
|
||||
let top = leaf.depth == 0;
|
||||
if let (false, Sole::Image(_, alt)) =
|
||||
(top || matches!(event, Event::End(_)), &mut leaf.sole)
|
||||
{
|
||||
let had = alt.get_or_insert(range.clone());
|
||||
*had = had.start.min(range.start)..had.end.max(range.end);
|
||||
}
|
||||
match event {
|
||||
Event::Start(Tag::Image { dest_url, .. }) if top => {
|
||||
leaf.sole = match leaf.sole {
|
||||
Sole::Nothing => Sole::Image(dest_url.to_string(), None),
|
||||
_ => Sole::Mixed,
|
||||
};
|
||||
leaf.depth += 1;
|
||||
}
|
||||
Event::Start(_) => {
|
||||
if top {
|
||||
leaf.sole = Sole::Mixed;
|
||||
}
|
||||
leaf.depth += 1;
|
||||
}
|
||||
Event::End(_) => leaf.depth = leaf.depth.saturating_sub(1),
|
||||
Event::DisplayMath(math) if top => {
|
||||
leaf.sole = match leaf.sole {
|
||||
Sole::Nothing => Sole::Math(math.to_string()),
|
||||
_ => Sole::Mixed,
|
||||
};
|
||||
}
|
||||
_ if top => leaf.sole = Sole::Mixed,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn quotes(&self) -> usize {
|
||||
self.quote.as_ref().map_or(0, |(_, depth, _)| *depth)
|
||||
}
|
||||
|
||||
fn leaf_text(&mut self) -> String {
|
||||
let (source, quotes) = (self.source, self.quotes());
|
||||
self.leaf
|
||||
.take()
|
||||
.and_then(|leaf| leaf.range)
|
||||
.map(|range| clean(&source[range], quotes))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Text an item read before a block inside it began.
|
||||
fn flush_leaf(&mut self) {
|
||||
if self.leaf.as_ref().is_some_and(|leaf| leaf.range.is_some()) {
|
||||
let text = self.leaf_text();
|
||||
self.put(BlockKind::Paragraph, text);
|
||||
}
|
||||
self.leaf = None;
|
||||
}
|
||||
|
||||
/// Text where it belongs: in the open quote, the open item, or a block of its own.
|
||||
fn put(&mut self, kind: BlockKind, text: String) {
|
||||
if let Some((_, _, parts)) = &mut self.quote {
|
||||
parts.push(text);
|
||||
return;
|
||||
}
|
||||
if kind == BlockKind::Paragraph
|
||||
&& let Some(item) = self.items.last_mut()
|
||||
&& !item.emitted
|
||||
{
|
||||
item.parts.push(text);
|
||||
return;
|
||||
}
|
||||
self.emit_item();
|
||||
let data = match kind {
|
||||
BlockKind::Divider => BlockData::new(kind, Vec::<String>::new()),
|
||||
kind => BlockData::new(kind, [text]),
|
||||
};
|
||||
self.out.push(data);
|
||||
}
|
||||
|
||||
fn emit_item(&mut self) {
|
||||
let quoted = self.quote.is_some();
|
||||
let Some(item) = self.items.last_mut().filter(|item| !item.emitted) else {
|
||||
return;
|
||||
};
|
||||
item.emitted = true;
|
||||
if quoted {
|
||||
return;
|
||||
}
|
||||
let data = BlockData::new(item.kind.clone(), [item.parts.join("\n\n")]);
|
||||
self.out.push(data);
|
||||
}
|
||||
|
||||
fn end_paragraph(&mut self) {
|
||||
let alone = self.quote.is_none() && self.items.is_empty();
|
||||
let sole = self
|
||||
.leaf
|
||||
.as_mut()
|
||||
.map(|leaf| std::mem::take(&mut leaf.sole));
|
||||
match sole {
|
||||
Some(Sole::Math(math)) if alone => {
|
||||
self.leaf = None;
|
||||
self.put(BlockKind::Math, math.trim().to_string());
|
||||
}
|
||||
Some(Sole::Image(source, alt)) if alone => {
|
||||
self.leaf = None;
|
||||
let source_text = self.source;
|
||||
let caption = alt.map_or(String::new(), |alt| source_text[alt].to_string());
|
||||
self.put(BlockKind::Image(Media::new(source)), caption);
|
||||
}
|
||||
_ => {
|
||||
let text = self.leaf_text();
|
||||
self.put(BlockKind::Paragraph, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn end_quote(&mut self) {
|
||||
let Some((callout, depth, parts)) = &mut self.quote else {
|
||||
return;
|
||||
};
|
||||
*depth -= 1;
|
||||
if *depth > 0 {
|
||||
return;
|
||||
}
|
||||
let kind = match callout {
|
||||
true => BlockKind::Callout,
|
||||
false => BlockKind::Quote,
|
||||
};
|
||||
let text = parts.join("\n\n");
|
||||
self.quote = None;
|
||||
self.put(kind, text);
|
||||
}
|
||||
|
||||
fn end_code(&mut self) {
|
||||
let Some((kind, mut code)) = self.code.take() else {
|
||||
return;
|
||||
};
|
||||
if code.ends_with('\n') {
|
||||
code.pop();
|
||||
}
|
||||
self.put(kind, code);
|
||||
}
|
||||
|
||||
fn end_table(&mut self) {
|
||||
let Some((columns, mut cells, _)) = self.table.take() else {
|
||||
return;
|
||||
};
|
||||
if cells.len() < columns * 2 {
|
||||
cells.resize(columns * 2, String::new());
|
||||
}
|
||||
let kind = BlockKind::Table {
|
||||
columns,
|
||||
merged: Vec::new(),
|
||||
};
|
||||
self.emit_item();
|
||||
self.out.push(BlockData::new(kind, cells));
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ impl BlockEditor {
|
||||
}
|
||||
|
||||
/// The fields in reading order, as `(block, field)`: a closed toggle hides its body.
|
||||
fn reading_order(&self) -> Vec<(u64, usize)> {
|
||||
pub(super) fn reading_order(&self) -> Vec<(u64, usize)> {
|
||||
self.blocks
|
||||
.iter()
|
||||
.flat_map(|block| {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
mod content;
|
||||
mod edit;
|
||||
mod export;
|
||||
mod import;
|
||||
mod keys;
|
||||
mod kind;
|
||||
mod media;
|
||||
mod span;
|
||||
mod table;
|
||||
#[cfg(all(test, feature = "test-support"))]
|
||||
mod tests;
|
||||
@@ -11,8 +14,8 @@ mod view;
|
||||
use std::{collections::HashMap, rc::Rc};
|
||||
|
||||
use gpui::{
|
||||
App, AppContext as _, Context, Entity, EventEmitter, Focusable, Global, SharedString,
|
||||
Subscription, Window,
|
||||
App, AppContext as _, Context, Entity, EntityId, EventEmitter, Focusable, Global, ScrollHandle,
|
||||
SharedString, Subscription, Window,
|
||||
};
|
||||
|
||||
pub use kind::{Align, BlockKind, Media};
|
||||
@@ -71,7 +74,7 @@ struct Snapshot {
|
||||
caret: Option<(u64, usize, std::ops::Range<usize>)>,
|
||||
}
|
||||
|
||||
/// A document of blocks, Notion-like: prose, lists and to-dos, quotes and callouts, toggles, code, math, diagrams, dividers, tables, media, columns and synced blocks. Markdown at a paragraph's start changes its kind; `/` offers every kind; `@` and `:` suggest people and emoji; blocks drag by their handle. Undo covers text and structure alike.
|
||||
/// A document of blocks, Notion-like, that fills its box and scrolls, keeping the caret in view: prose, lists and to-dos, quotes and callouts, toggles, code, math, diagrams, dividers, tables, media, columns and synced blocks. Markdown at a paragraph's start changes its kind; `/` offers every kind; `@` and `:` suggest people and emoji; blocks drag by their handle. Undo covers text and structure alike.
|
||||
pub struct BlockEditor {
|
||||
pub(crate) blocks: Vec<Block>,
|
||||
next: u64,
|
||||
@@ -83,6 +86,10 @@ pub struct BlockEditor {
|
||||
typed_from: Option<(u64, usize, std::ops::Range<usize>)>,
|
||||
pub(crate) people: Vec<SharedString>,
|
||||
pub(crate) diagram: Option<RenderDiagram>,
|
||||
scroll: ScrollHandle,
|
||||
across: span::Across,
|
||||
/// The caret last brought into view: field, selection and length.
|
||||
revealed: Option<(EntityId, std::ops::Range<usize>, usize)>,
|
||||
_synced: Subscription,
|
||||
}
|
||||
|
||||
@@ -103,6 +110,9 @@ impl BlockEditor {
|
||||
typed_from: None,
|
||||
people: Vec::new(),
|
||||
diagram: None,
|
||||
scroll: ScrollHandle::new(),
|
||||
across: span::Across::default(),
|
||||
revealed: None,
|
||||
_synced: synced,
|
||||
};
|
||||
for data in blocks {
|
||||
@@ -261,6 +271,10 @@ impl BlockEditor {
|
||||
};
|
||||
match event {
|
||||
InputEvent::Changed => {
|
||||
let at = self.blocks[ix].fields.iter().position(|each| each == field);
|
||||
if at.is_some_and(|at| self.span_takes(key, at, window, cx)) {
|
||||
return;
|
||||
}
|
||||
let typed = field.focus_handle(cx).is_focused(window);
|
||||
if typed
|
||||
&& self.blocks[ix].kind == BlockKind::Paragraph
|
||||
|
||||
@@ -0,0 +1,482 @@
|
||||
use gpui::{
|
||||
ClipboardItem, Context, DispatchPhase, Focusable, IntoElement, MouseDownEvent, MouseMoveEvent,
|
||||
MouseUpEvent, Pixels, Point, Styled, Subscription, Window, canvas,
|
||||
};
|
||||
|
||||
use super::{BlockData, BlockEditor};
|
||||
|
||||
/// A place in a field: its block, the field, and a byte offset.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Spot {
|
||||
pub key: u64,
|
||||
pub field: usize,
|
||||
pub at: usize,
|
||||
}
|
||||
|
||||
/// A press in a field that may drag out of it, and a selection across fields as anchor and head.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Across {
|
||||
press: Option<Spot>,
|
||||
span: Option<(Spot, Spot)>,
|
||||
/// Watches the focused end: an edit there takes the selection's place, a caret move lets it go.
|
||||
held: Option<Subscription>,
|
||||
/// The focused end, and how many edits it had taken.
|
||||
holder: Option<((u64, usize), u64)>,
|
||||
}
|
||||
|
||||
/// What takes a selection's place: an edit already made at one end, nothing, or a break.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Put {
|
||||
Typed(u64, usize),
|
||||
Nothing,
|
||||
Break,
|
||||
}
|
||||
|
||||
impl BlockEditor {
|
||||
fn rank(&self, order: &[(u64, usize)], spot: Spot) -> Option<(usize, usize)> {
|
||||
let at = order
|
||||
.iter()
|
||||
.position(|each| *each == (spot.key, spot.field))?;
|
||||
Some((at, spot.at))
|
||||
}
|
||||
|
||||
/// The selection across fields, start first in reading order.
|
||||
pub(crate) fn span(&self) -> Option<(Spot, Spot)> {
|
||||
let (anchor, head) = self.across.span?;
|
||||
let order = self.reading_order();
|
||||
let forward = self.rank(&order, anchor)? <= self.rank(&order, head)?;
|
||||
Some(if forward {
|
||||
(anchor, head)
|
||||
} else {
|
||||
(head, anchor)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn pressing(&self) -> bool {
|
||||
self.across.press.is_some()
|
||||
}
|
||||
|
||||
/// The blocks wholly inside the selection, by place.
|
||||
pub(crate) fn washed(&self) -> Option<std::ops::Range<usize>> {
|
||||
let (start, end) = self.span()?;
|
||||
Some(self.index(start.key)? + 1..self.index(end.key)?)
|
||||
}
|
||||
|
||||
fn spot(
|
||||
&self,
|
||||
key: u64,
|
||||
field: usize,
|
||||
position: Point<Pixels>,
|
||||
cx: &Context<Self>,
|
||||
) -> Option<Spot> {
|
||||
let input = self.blocks[self.place(key, field)?].fields[field].read(cx);
|
||||
Some(Spot {
|
||||
key,
|
||||
field,
|
||||
at: input.offset_for_point(position),
|
||||
})
|
||||
}
|
||||
|
||||
/// A press in a field: with Shift, it selects from the caret's field to here; else a drag may start.
|
||||
pub(crate) fn pressed(
|
||||
&mut self,
|
||||
key: u64,
|
||||
field: usize,
|
||||
event: &MouseDownEvent,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let Some(here) = self.spot(key, field, event.position, cx) else {
|
||||
return;
|
||||
};
|
||||
let prior = self
|
||||
.caret
|
||||
.filter(|caret| *caret != (key, field))
|
||||
.and_then(|(key, field)| {
|
||||
let input = self.blocks.get(self.index(key)?)?.fields.get(field)?;
|
||||
let at = input.read(cx).cursor();
|
||||
Some(Spot { key, field, at })
|
||||
});
|
||||
self.clear_span(window, cx);
|
||||
self.across.press = None;
|
||||
match prior.filter(|_| event.modifiers.shift) {
|
||||
Some(prior) => {
|
||||
log::info!(
|
||||
"block editor: Shift selects from block {} to {key}",
|
||||
prior.key
|
||||
);
|
||||
self.across.span = Some((prior, here));
|
||||
self.show_span(window, cx);
|
||||
self.hold(window, cx);
|
||||
}
|
||||
None => self.across.press = Some(here),
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// The shown field nearest `position`: inside it, else closest above or below, then across.
|
||||
fn field_at(&self, position: Point<Pixels>, cx: &Context<Self>) -> Option<(u64, usize)> {
|
||||
let outside =
|
||||
|near: Pixels, far: Pixels, at: Pixels| (near - at).max(at - far).max(Pixels::ZERO);
|
||||
self.reading_order()
|
||||
.into_iter()
|
||||
.filter_map(|(key, field)| {
|
||||
let block = &self.blocks[self.index(key)?];
|
||||
let bounds = block.fields[field].read(cx).layout.as_ref()?.bounds;
|
||||
let dy = outside(bounds.top(), bounds.bottom(), position.y);
|
||||
let dx = outside(bounds.left(), bounds.right(), position.x);
|
||||
Some(((dy, dx), (key, field)))
|
||||
})
|
||||
.min_by(|one, two| one.0.partial_cmp(&two.0).expect("pixels are finite"))
|
||||
.map(|(_, field)| field)
|
||||
}
|
||||
|
||||
fn drag_to(&mut self, position: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(press) = self.across.press else {
|
||||
return;
|
||||
};
|
||||
let Some((key, field)) = self.field_at(position, cx) else {
|
||||
return;
|
||||
};
|
||||
if (key, field) == (press.key, press.field) {
|
||||
return self.clear_span(window, cx);
|
||||
}
|
||||
let Some(head) = self.spot(key, field, position, cx) else {
|
||||
return;
|
||||
};
|
||||
if self.across.span != Some((press, head)) {
|
||||
if self.across.span.is_none() {
|
||||
log::info!("block editor: a drag selects across blocks");
|
||||
}
|
||||
self.across.span = Some((press, head));
|
||||
self.show_span(window, cx);
|
||||
self.hold(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Follows a drag that began in a field until the button lifts.
|
||||
pub(crate) fn drag_listener(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
|
||||
let editor = cx.entity();
|
||||
canvas(
|
||||
|_, _, _| {},
|
||||
move |_, _, window, _| {
|
||||
let moved = editor.clone();
|
||||
window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
|
||||
if phase == DispatchPhase::Bubble && event.dragging() {
|
||||
moved.update(cx, |editor, cx| editor.drag_to(event.position, window, cx));
|
||||
}
|
||||
});
|
||||
let lifted = editor.clone();
|
||||
window.on_mouse_event(move |_: &MouseUpEvent, phase, _, cx| {
|
||||
if phase == DispatchPhase::Bubble {
|
||||
lifted.update(cx, |editor, cx| {
|
||||
editor.across.press = None;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
)
|
||||
.absolute()
|
||||
}
|
||||
|
||||
/// Selects each end field's part and whole fields between in the end blocks; the pressed field selects itself.
|
||||
fn show_span(&mut self, window: &Window, cx: &mut Context<Self>) {
|
||||
let Some((start, end)) = self.span() else {
|
||||
return;
|
||||
};
|
||||
let order = self.reading_order();
|
||||
let (from, to) = (self.rank(&order, start), self.rank(&order, end));
|
||||
let pressed = self.across.press.map(|press| (press.key, press.field));
|
||||
for block in &self.blocks {
|
||||
for (ix, field) in block.fields.iter().enumerate() {
|
||||
if pressed == Some((block.key, ix)) {
|
||||
continue;
|
||||
}
|
||||
let len = field.read(cx).text().len();
|
||||
let rank = order.iter().position(|each| *each == (block.key, ix));
|
||||
let ends = block.key == start.key || block.key == end.key;
|
||||
let want = match rank {
|
||||
Some(rank) if Some((rank, start.at)) == from => Some(start.at..len),
|
||||
Some(rank) if Some((rank, end.at)) == to => Some(0..end.at),
|
||||
Some(rank)
|
||||
if ends
|
||||
&& from
|
||||
.zip(to)
|
||||
.is_some_and(|(from, to)| from.0 < rank && rank < to.0) =>
|
||||
{
|
||||
Some(0..len)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let now = field.read(cx).selection();
|
||||
match want {
|
||||
Some(range) if range != now => {
|
||||
field.update(cx, |field, cx| field.select(range, cx))
|
||||
}
|
||||
None if !now.is_empty() && !field.focus_handle(cx).is_focused(window) => {
|
||||
let cursor = field.read(cx).cursor();
|
||||
field.update(cx, |field, cx| field.select(cursor..cursor, cx));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Lets the selection across fields go, and the end fields' parts with it.
|
||||
pub(crate) fn clear_span(&mut self, window: &Window, cx: &mut Context<Self>) {
|
||||
(self.across.held, self.across.holder) = (None, None);
|
||||
if self.across.span.take().is_none() {
|
||||
return;
|
||||
}
|
||||
log::debug!("block editor: the selection across blocks lets go");
|
||||
for field in self.blocks.iter().flat_map(|block| &block.fields) {
|
||||
let now = field.read(cx).selection();
|
||||
if !now.is_empty() && !field.focus_handle(cx).is_focused(window) {
|
||||
let cursor = field.read(cx).cursor();
|
||||
field.update(cx, |field, cx| field.select(cursor..cursor, cx));
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Watches the focused end field from the moment a selection spans fields.
|
||||
fn hold(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.across.held.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some((key, field)) = self.focused(window, cx) else {
|
||||
return;
|
||||
};
|
||||
let input =
|
||||
self.blocks[self.index(key).expect("a focused block is drawn")].fields[field].clone();
|
||||
let (edits, _) = input.read(cx).edits();
|
||||
self.across.holder = Some(((key, field), edits));
|
||||
self.across.held = Some(cx.observe_in(&input, window, move |editor, _, window, cx| {
|
||||
editor.held(key, field, window, cx)
|
||||
}));
|
||||
}
|
||||
|
||||
/// The focused end changed: an edit takes the selection's place once composing ends; focus or a caret leaving lets it go.
|
||||
fn held(&mut self, key: u64, field: usize, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let (Some((start, end)), Some(ix)) = (self.span(), self.index(key)) else {
|
||||
return;
|
||||
};
|
||||
let input = self.blocks[ix].fields[field].read(cx);
|
||||
let ((edits, composing), counted) = (input.edits(), self.across.holder.map(|(_, n)| n));
|
||||
if !input.focus_handle(cx).is_focused(window) {
|
||||
return self.clear_span(window, cx);
|
||||
}
|
||||
if Some(edits) != counted {
|
||||
if !composing {
|
||||
self.collapse_span(Put::Typed(key, field), window, cx);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let expected = match (key, field) {
|
||||
at if at == (start.key, start.field) => start.at..input.text().len(),
|
||||
at if at == (end.key, end.field) => 0..end.at,
|
||||
_ => 0..0,
|
||||
};
|
||||
if input.selection() != expected {
|
||||
self.clear_span(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection across fields as Markdown on the clipboard; false when there is none.
|
||||
pub(crate) fn copy_span(&self, cx: &mut Context<Self>) -> bool {
|
||||
let Some((start, end)) = self.span() else {
|
||||
return false;
|
||||
};
|
||||
let order = self.reading_order();
|
||||
let (Some(from), Some(to)) = (self.rank(&order, start), self.rank(&order, end)) else {
|
||||
return false;
|
||||
};
|
||||
let (Some(first), Some(last)) = (self.index(start.key), self.index(end.key)) else {
|
||||
return false;
|
||||
};
|
||||
let snapshot = self.snapshot(cx);
|
||||
let blocks: Option<Vec<BlockData>> = snapshot.blocks[first..=last]
|
||||
.iter()
|
||||
.map(|(key, data)| {
|
||||
let mut data = data.clone();
|
||||
for (ix, text) in data.texts.iter_mut().enumerate() {
|
||||
let rank = order.iter().position(|each| *each == (*key, ix));
|
||||
*text = match rank {
|
||||
Some(rank) if rank == from.0 => text.get(start.at..)?.to_string(),
|
||||
Some(rank) if rank == to.0 => text.get(..end.at)?.to_string(),
|
||||
Some(rank) if rank < from.0 || rank > to.0 => String::new(),
|
||||
_ => std::mem::take(text),
|
||||
};
|
||||
}
|
||||
Some(data)
|
||||
})
|
||||
.collect();
|
||||
let Some(blocks) = blocks else {
|
||||
log::error!("block editor: the selection across blocks no longer fits its text");
|
||||
return false;
|
||||
};
|
||||
let markdown = BlockData::to_markdown(&blocks);
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(markdown.trim_end().to_string()));
|
||||
log::info!("block editor: {} blocks copied as markdown", blocks.len());
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl BlockEditor {
|
||||
/// A field changed while a selection spans fields: the held end's edit is the selection's to take; another lets it go.
|
||||
pub(crate) fn span_takes(
|
||||
&mut self,
|
||||
key: u64,
|
||||
field: usize,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> bool {
|
||||
if self.across.span.is_none() {
|
||||
return false;
|
||||
}
|
||||
if self.across.holder.is_some_and(|(at, _)| at == (key, field)) {
|
||||
return true;
|
||||
}
|
||||
log::info!(
|
||||
"block editor: field {field} of block {key} changed; the selection across blocks lets go"
|
||||
);
|
||||
self.clear_span(window, cx);
|
||||
false
|
||||
}
|
||||
|
||||
/// Replaces the selection across fields with `put`, as one undo step. Two prose ends join, or part at a break.
|
||||
pub(crate) fn collapse_span(
|
||||
&mut self,
|
||||
put: Put,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<Spot> {
|
||||
let (start, end) = self.span()?;
|
||||
let typed_at = match put {
|
||||
Put::Typed(key, field) => Some((key, field)),
|
||||
Put::Nothing | Put::Break => None,
|
||||
};
|
||||
let was = |spot: Spot| {
|
||||
let (_, data) = self
|
||||
.current
|
||||
.blocks
|
||||
.iter()
|
||||
.find(|(key, _)| *key == spot.key)?;
|
||||
data.texts.get(spot.field).cloned()
|
||||
};
|
||||
let now = |spot: Spot| {
|
||||
let block = &self.blocks[self.place(spot.key, spot.field)?];
|
||||
Some(block.fields[spot.field].read(cx).text().to_string())
|
||||
};
|
||||
let parts = was(start).zip(was(end)).and_then(|(first, last)| {
|
||||
Some((
|
||||
first.get(..start.at)?.to_string(),
|
||||
last.get(end.at..)?.to_string(),
|
||||
))
|
||||
});
|
||||
let typed = parts.as_ref().and_then(|(head, tail)| match typed_at {
|
||||
Some(at) if at == (start.key, start.field) => {
|
||||
now(start)?.strip_prefix(head.as_str()).map(str::to_string)
|
||||
}
|
||||
Some(_) => now(end)?.strip_suffix(tail.as_str()).map(str::to_string),
|
||||
None => Some(String::new()),
|
||||
});
|
||||
let (Some((head, tail)), Some(typed)) = (parts, typed) else {
|
||||
log::error!("block editor: an edit across blocks landed outside its selection");
|
||||
self.clear_span(window, cx);
|
||||
return None;
|
||||
};
|
||||
let (first, last) = (self.index(start.key)?, self.index(end.key)?);
|
||||
let mut before = self.current.clone();
|
||||
before.caret = Some((start.key, start.field, start.at..start.at));
|
||||
self.history.record(before, false);
|
||||
let prose = |ix: usize| self.blocks[ix].kind.is_prose();
|
||||
let joins = first != last && prose(first) && prose(last);
|
||||
let at_end = typed_at == Some((end.key, end.field));
|
||||
let order = self.reading_order();
|
||||
let (from, to) = (self.rank(&order, start)?, self.rank(&order, end)?);
|
||||
let set = |spot: Spot, text: String, cx: &mut Context<Self>| {
|
||||
if let Some(ix) = self.place(spot.key, spot.field) {
|
||||
self.blocks[ix].fields[spot.field].update(cx, |field, cx| field.set_text(text, cx));
|
||||
}
|
||||
};
|
||||
let parts = joins && put == Put::Break;
|
||||
let caret = if parts {
|
||||
set(start, head.clone(), cx);
|
||||
None
|
||||
} else if joins {
|
||||
set(start, format!("{head}{typed}{tail}"), cx);
|
||||
Some(Spot {
|
||||
at: head.len() + typed.len(),
|
||||
..start
|
||||
})
|
||||
} else {
|
||||
for (key, field) in order.iter().take(to.0).skip(from.0 + 1) {
|
||||
if *key == start.key || *key == end.key {
|
||||
set(
|
||||
Spot {
|
||||
key: *key,
|
||||
field: *field,
|
||||
at: 0,
|
||||
},
|
||||
String::new(),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
}
|
||||
match at_end {
|
||||
true => {
|
||||
set(start, head.clone(), cx);
|
||||
set(end, format!("{typed}{tail}"), cx);
|
||||
Some(Spot {
|
||||
at: typed.len(),
|
||||
..end
|
||||
})
|
||||
}
|
||||
false => {
|
||||
set(start, format!("{head}{typed}"), cx);
|
||||
set(end, tail.clone(), cx);
|
||||
Some(Spot {
|
||||
at: head.len() + typed.len(),
|
||||
..start
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
let gone = if joins {
|
||||
first + 1..last + 1
|
||||
} else {
|
||||
first + 1..last.max(first + 1)
|
||||
};
|
||||
log::info!(
|
||||
"block editor: a selection across {} blocks is replaced",
|
||||
last - first + 1
|
||||
);
|
||||
self.blocks.drain(gone);
|
||||
let caret = match caret {
|
||||
Some(caret) => caret,
|
||||
None => {
|
||||
let key = self.fresh_key();
|
||||
let kind = self.blocks[first].kind.next();
|
||||
let data = BlockData {
|
||||
kind,
|
||||
texts: vec![tail],
|
||||
};
|
||||
let block = self.build(data, key, window, cx);
|
||||
self.blocks.insert(first + 1, block);
|
||||
Spot {
|
||||
key,
|
||||
field: 0,
|
||||
at: 0,
|
||||
}
|
||||
}
|
||||
};
|
||||
self.across = Across::default();
|
||||
self.after_change(cx);
|
||||
self.focus_field(caret.key, caret.field, Some(caret.at), window, cx);
|
||||
Some(caret)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
use super::{BlockData, BlockKind};
|
||||
use crate::documents::Media;
|
||||
|
||||
fn block(kind: BlockKind, texts: &[&str]) -> BlockData {
|
||||
BlockData::new(kind, texts.iter().copied())
|
||||
}
|
||||
|
||||
fn table(columns: usize, cells: &[&str]) -> BlockData {
|
||||
let kind = BlockKind::Table {
|
||||
columns,
|
||||
merged: Vec::new(),
|
||||
};
|
||||
block(kind, cells)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_kind_markdown_holds_comes_back_as_it_went() {
|
||||
let document = vec![
|
||||
block(BlockKind::Heading(1), &["Project *notes*"]),
|
||||
block(
|
||||
BlockKind::Paragraph,
|
||||
&["Blend **toward white**,\nthen `clamp`."],
|
||||
),
|
||||
block(BlockKind::Bullet, &["Tokens"]),
|
||||
block(BlockKind::Todo(true), &["Light and dark"]),
|
||||
block(BlockKind::Todo(false), &["Motion"]),
|
||||
block(BlockKind::Numbered, &["First"]),
|
||||
block(BlockKind::Numbered, &["Second"]),
|
||||
block(BlockKind::Quote, &["One line\nand the next"]),
|
||||
block(BlockKind::Callout, &["Drag blocks by their handle."]),
|
||||
block(
|
||||
BlockKind::Toggle(true),
|
||||
&["Why gamma?", "It keeps **midtones**."],
|
||||
),
|
||||
block(BlockKind::Toggle(false), &["Closed", ""]),
|
||||
block(BlockKind::Code, &["let fence = \"```\";\nlift(color)"]),
|
||||
block(BlockKind::Diagram, &["graph LR; a --> b"]),
|
||||
block(BlockKind::Math, &["c' = c + (1 - c)\\,t"]),
|
||||
block(BlockKind::Divider, &[]),
|
||||
table(2, &["Token", "Light", "a|b", "0.50"]),
|
||||
block(BlockKind::Image(Media::new("atrium.jpg")), &["An atrium"]),
|
||||
block(BlockKind::Heading(4), &["Deep"]),
|
||||
];
|
||||
let markdown = BlockData::to_markdown(&document);
|
||||
assert_eq!(BlockData::from_markdown(&markdown), document, "{markdown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_stay_tight_and_count_up() {
|
||||
let document = vec![
|
||||
block(BlockKind::Bullet, &["a"]),
|
||||
block(BlockKind::Todo(false), &["b"]),
|
||||
block(BlockKind::Numbered, &["c"]),
|
||||
block(BlockKind::Numbered, &["d\ne"]),
|
||||
block(BlockKind::Paragraph, &[""]),
|
||||
block(BlockKind::Callout, &["Note"]),
|
||||
];
|
||||
assert_eq!(
|
||||
BlockData::to_markdown(&document),
|
||||
"- a\n- [ ] b\n\n1. c\n2. d\n e\n\n> [!NOTE]\n> Note\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_written_by_hand_reads_as_blocks() {
|
||||
let source = "#### Deep\n\n- one\n - inner\n- two\n\n> quoted\nlazy\n\n| a | b |\n|---|---|\n| 1 |\n\nInline $x$ math\n\n<div>raw</div>\n";
|
||||
assert_eq!(
|
||||
BlockData::from_markdown(source),
|
||||
vec![
|
||||
block(BlockKind::Heading(4), &["Deep"]),
|
||||
block(BlockKind::Bullet, &["one"]),
|
||||
block(BlockKind::Bullet, &["inner"]),
|
||||
block(BlockKind::Bullet, &["two"]),
|
||||
block(BlockKind::Quote, &["quoted\nlazy"]),
|
||||
table(2, &["a", "b", "1", ""]),
|
||||
block(BlockKind::Paragraph, &["Inline $x$ math"]),
|
||||
block(BlockKind::Paragraph, &["<div>raw</div>"]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_markdown_cannot_hold_takes_its_nearest_form() {
|
||||
let document = vec![
|
||||
block(BlockKind::Columns(2), &["Left", "Right"]),
|
||||
block(BlockKind::Video(Media::new("clip.mp4")), &[""]),
|
||||
block(BlockKind::Synced("shared".into()), &["Kept"]),
|
||||
];
|
||||
assert_eq!(
|
||||
BlockData::to_markdown(&document),
|
||||
"Left\n\nRight\n\n[clip.mp4](clip.mp4)\n\nKept\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caption_keeps_its_marks_and_a_toggle_its_nested_details() {
|
||||
let document = vec![
|
||||
block(
|
||||
BlockKind::Image(Media::new("a.png")),
|
||||
&["**bold** and *slant*"],
|
||||
),
|
||||
block(
|
||||
BlockKind::Toggle(false),
|
||||
&[
|
||||
"Outer",
|
||||
"<details><summary>Inner</summary>x</details>\n\nAfter",
|
||||
],
|
||||
),
|
||||
block(BlockKind::Paragraph, &["Last"]),
|
||||
];
|
||||
let markdown = BlockData::to_markdown(&document);
|
||||
assert_eq!(BlockData::from_markdown(&markdown), document, "{markdown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_definitions_stay_with_the_document() {
|
||||
let source = "See [the site][id].\n\n[id]: https://ely.dev \"Ely\"\n";
|
||||
let blocks = BlockData::from_markdown(source);
|
||||
assert_eq!(
|
||||
blocks,
|
||||
vec![
|
||||
block(BlockKind::Paragraph, &["See [the site][id]."]),
|
||||
block(BlockKind::Paragraph, &["[id]: https://ely.dev \"Ely\""]),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
BlockData::from_markdown(&BlockData::to_markdown(&blocks)),
|
||||
blocks
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_toggle_left_open_keeps_the_rest_as_its_body() {
|
||||
assert_eq!(
|
||||
BlockData::from_markdown("<details>\n<summary>Open</summary>\n\nBody\n\nMore\n"),
|
||||
vec![block(BlockKind::Toggle(false), &["Open", "Body\n\nMore"])]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brackets_and_comments_keep_their_blocks() {
|
||||
let document = vec![
|
||||
block(
|
||||
BlockKind::Image(Media::new("a)b c<d>.png")),
|
||||
&[r"`[x` \[y\] [z]"],
|
||||
),
|
||||
block(
|
||||
BlockKind::Toggle(true),
|
||||
&["Closes", "<!-- </details> -->\n\nkept"],
|
||||
),
|
||||
block(
|
||||
BlockKind::Toggle(true),
|
||||
&["Opens", "<!-- <details> -->\n\nkept"],
|
||||
),
|
||||
block(
|
||||
BlockKind::Toggle(false),
|
||||
&["Quoted", r#"<div title="</details>">kept</div>"#],
|
||||
),
|
||||
block(BlockKind::Paragraph, &["After"]),
|
||||
];
|
||||
let markdown = BlockData::to_markdown(&document);
|
||||
assert_eq!(BlockData::from_markdown(&markdown), document, "{markdown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bracket_left_alone_comes_back_escaped_in_its_image() {
|
||||
let image = || BlockKind::Image(Media::new("a.png"));
|
||||
let document = vec![block(image(), &[r"a ] b [c\"])];
|
||||
assert_eq!(
|
||||
BlockData::from_markdown(&BlockData::to_markdown(&document)),
|
||||
vec![block(image(), &[r"a \] b \[c\\"])]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn math_with_a_blank_line_and_a_piped_cell_come_back() {
|
||||
let document = vec![
|
||||
block(BlockKind::Math, &["a = b\n\nc = d $$"]),
|
||||
table(2, &["Code", "Note", "`a|b`", "x | y"]),
|
||||
block(BlockKind::Paragraph, &["$$\nx\n$$"]),
|
||||
];
|
||||
let markdown = BlockData::to_markdown(&document);
|
||||
let mut expected = document.clone();
|
||||
expected[2] = block(BlockKind::Math, &["x"]);
|
||||
assert_eq!(BlockData::from_markdown(&markdown), expected, "{markdown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_line_fields_keep_one_line() {
|
||||
let document = vec![
|
||||
block(BlockKind::Heading(2), &["Two\nlines"]),
|
||||
block(BlockKind::Toggle(true), &["Title\nrest", "Body"]),
|
||||
block(BlockKind::Image(Media::new("a.png")), &["Cap\ntion"]),
|
||||
];
|
||||
assert_eq!(
|
||||
BlockData::from_markdown(&BlockData::to_markdown(&document)),
|
||||
vec![
|
||||
block(BlockKind::Heading(2), &["Two lines"]),
|
||||
block(BlockKind::Toggle(true), &["Title rest", "Body"]),
|
||||
block(BlockKind::Image(Media::new("a.png")), &["Cap tion"]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_tags_read_as_html_reads_them() {
|
||||
let document = vec![
|
||||
block(
|
||||
BlockKind::Toggle(true),
|
||||
&[
|
||||
r#"a <span title="</summary>">b</span>"#,
|
||||
"<details-extra>\n\nkept",
|
||||
],
|
||||
),
|
||||
block(BlockKind::Paragraph, &["After"]),
|
||||
];
|
||||
let markdown = BlockData::to_markdown(&document);
|
||||
assert_eq!(BlockData::from_markdown(&markdown), document, "{markdown}");
|
||||
let source = "<DETAILS class=\"x\" OPEN>\n<summary>T</summary>\n\nB\n\n</details>\n";
|
||||
assert_eq!(
|
||||
BlockData::from_markdown(source),
|
||||
vec![block(BlockKind::Toggle(true), &["T", "B"])]
|
||||
);
|
||||
let bare = "<details title=\"open\">\n\nBody\n\n</details>\n";
|
||||
assert_eq!(
|
||||
BlockData::from_markdown(bare),
|
||||
vec![block(BlockKind::Toggle(false), &["", "Body"])]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unquoted_value_runs_to_a_space() {
|
||||
let source = "<details data-url=https://ely.dev/open>\n\nBody\n\n</details>\n";
|
||||
assert_eq!(
|
||||
BlockData::from_markdown(source),
|
||||
vec![block(BlockKind::Toggle(false), &["", "Body"])]
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,9 @@ use gpui::{AppContext as _, Entity, Focusable, TestAppContext, VisualTestContext
|
||||
use super::{BlockData, BlockEditor, BlockKind};
|
||||
use crate::{forms, theme::Theme};
|
||||
|
||||
mod markdown;
|
||||
mod scroll;
|
||||
mod span;
|
||||
mod stale;
|
||||
|
||||
fn open(
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
use gpui::{
|
||||
AppContext as _, Entity, Modifiers, ParentElement, Pixels, Render, ScrollDelta, ScrollHandle,
|
||||
ScrollWheelEvent, Styled, TestAppContext, TouchPhase, VisualTestContext, div, point,
|
||||
prelude::*, px,
|
||||
};
|
||||
|
||||
use super::{BlockData, BlockEditor, BlockKind, caret, settle};
|
||||
use crate::{forms, theme::Theme};
|
||||
|
||||
const TALL: Pixels = px(200.0);
|
||||
|
||||
/// The editor in a box of its own at the top of a page that scrolls.
|
||||
struct Page(Entity<BlockEditor>, ScrollHandle);
|
||||
|
||||
impl Render for Page {
|
||||
fn render(&mut self, _: &mut gpui::Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
|
||||
div()
|
||||
.id("page")
|
||||
.size_full()
|
||||
.overflow_y_scroll()
|
||||
.track_scroll(&self.1)
|
||||
.child(div().h(TALL).child(self.0.clone()))
|
||||
.child(div().h(px(2000.0)))
|
||||
}
|
||||
}
|
||||
|
||||
fn open(cx: &mut TestAppContext) -> (Entity<BlockEditor>, ScrollHandle, &mut VisualTestContext) {
|
||||
cx.update(|cx| {
|
||||
Theme::init(cx);
|
||||
Theme::update(cx, |theme| theme.reduced_motion = true);
|
||||
forms::bind_keys(cx);
|
||||
crate::documents::bind_keys(cx);
|
||||
});
|
||||
let blocks = (0..30).map(|ix| BlockData::new(BlockKind::Paragraph, [format!("line {ix}")]));
|
||||
let page = ScrollHandle::new();
|
||||
let (view, cx) = cx.add_window_view({
|
||||
let page = page.clone();
|
||||
|window, cx| {
|
||||
Page(
|
||||
cx.new(|cx| BlockEditor::new(blocks.collect(), window, cx)),
|
||||
page,
|
||||
)
|
||||
}
|
||||
});
|
||||
let editor = view.read_with(cx, |view, _| view.0.clone());
|
||||
cx.update(|window, _| window.activate_window());
|
||||
still(cx);
|
||||
(editor, page, cx)
|
||||
}
|
||||
|
||||
/// Settles past reduced motion's 1 ms glides on the wall clock.
|
||||
fn still(cx: &mut VisualTestContext) {
|
||||
settle(cx);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
settle(cx);
|
||||
}
|
||||
|
||||
/// The focused caret's box in the window.
|
||||
fn shown(editor: &Entity<BlockEditor>, cx: &mut VisualTestContext) -> gpui::Bounds<Pixels> {
|
||||
cx.update(|window, cx| {
|
||||
let (key, ix) = editor
|
||||
.read(cx)
|
||||
.focused(window, cx)
|
||||
.expect("a field has focus");
|
||||
let at = editor.read(cx).index(key).expect("the block is there");
|
||||
editor.read(cx).blocks[at].fields[ix]
|
||||
.read(cx)
|
||||
.caret_bounds()
|
||||
.expect("laid out")
|
||||
})
|
||||
}
|
||||
|
||||
fn inside(caret: gpui::Bounds<Pixels>) -> bool {
|
||||
caret.top() >= px(0.0) && caret.bottom() <= TALL
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_caret_stays_in_view_as_blocks_are_added_at_the_end(cx: &mut TestAppContext) {
|
||||
let (editor, page, cx) = open(cx);
|
||||
caret(&editor, 29, 7, cx);
|
||||
still(cx);
|
||||
assert!(inside(shown(&editor, cx)), "{:?}", shown(&editor, cx));
|
||||
for _ in 0..4 {
|
||||
cx.simulate_keystrokes("enter");
|
||||
still(cx);
|
||||
assert!(inside(shown(&editor, cx)), "{:?}", shown(&editor, cx));
|
||||
}
|
||||
assert_eq!(page.offset().y, px(0.0), "the page stayed");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_wheel_scrolls_the_editor_and_leaves_its_caret(cx: &mut TestAppContext) {
|
||||
let (editor, page, cx) = open(cx);
|
||||
caret(&editor, 0, 0, cx);
|
||||
still(cx);
|
||||
let before = shown(&editor, cx);
|
||||
cx.simulate_event(ScrollWheelEvent {
|
||||
position: point(px(100.0), px(100.0)),
|
||||
delta: ScrollDelta::Pixels(point(px(0.0), px(-120.0))),
|
||||
modifiers: Modifiers::none(),
|
||||
touch_phase: TouchPhase::Moved,
|
||||
});
|
||||
still(cx);
|
||||
assert_eq!(
|
||||
shown(&editor, cx).top(),
|
||||
before.top() - px(120.0),
|
||||
"the editor scrolled"
|
||||
);
|
||||
assert_eq!(page.offset().y, px(0.0), "the page stayed");
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
use gpui::{
|
||||
Entity, EntityInputHandler, Modifiers, MouseButton, Pixels, Point, TestAppContext,
|
||||
VisualTestContext, point, px,
|
||||
};
|
||||
|
||||
use super::{BlockData, BlockEditor, BlockKind, blocks, caret, open, settle, text};
|
||||
use crate::theme::Theme;
|
||||
|
||||
/// Three paragraphs, settled where they stand: reduced motion ends the rows' first glide.
|
||||
fn three(cx: &mut TestAppContext) -> (Entity<BlockEditor>, &mut VisualTestContext) {
|
||||
let paragraph = |text: &str| BlockData::new(BlockKind::Paragraph, [text]);
|
||||
let blocks = vec![paragraph("alpha"), paragraph("beta"), paragraph("gamma")];
|
||||
let (editor, cx) = open(blocks, cx);
|
||||
cx.update(|_, cx| Theme::update(cx, |theme| theme.reduced_motion = true));
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
settle(cx);
|
||||
(editor, cx)
|
||||
}
|
||||
|
||||
/// Where byte `at` of block `ix`'s first field sits in the window.
|
||||
fn at(
|
||||
editor: &Entity<BlockEditor>,
|
||||
ix: usize,
|
||||
at: usize,
|
||||
cx: &mut VisualTestContext,
|
||||
) -> Point<Pixels> {
|
||||
cx.update(|_, cx| {
|
||||
let field = editor.read(cx).blocks[ix].fields[0].read(cx);
|
||||
let caret = field.bounds_for(at).expect("laid out");
|
||||
caret.origin + point(px(0.5), caret.size.height / 2.0)
|
||||
})
|
||||
}
|
||||
|
||||
/// Drags from `alpha` after two letters to `gamma` after three.
|
||||
fn drag(editor: &Entity<BlockEditor>, cx: &mut VisualTestContext) {
|
||||
let (from, to) = (at(editor, 0, 2, cx), at(editor, 2, 3, cx));
|
||||
cx.simulate_mouse_down(from, MouseButton::Left, Modifiers::none());
|
||||
cx.simulate_mouse_move(to, Some(MouseButton::Left), Modifiers::none());
|
||||
cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::none());
|
||||
settle(cx);
|
||||
}
|
||||
|
||||
fn spanned(editor: &Entity<BlockEditor>, cx: &mut VisualTestContext) -> Option<(usize, usize)> {
|
||||
cx.update(|_, cx| {
|
||||
editor
|
||||
.read(cx)
|
||||
.span()
|
||||
.map(|(start, end)| (start.at, end.at))
|
||||
})
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_drag_selects_across_blocks_and_typing_takes_its_place(cx: &mut TestAppContext) {
|
||||
let (editor, cx) = three(cx);
|
||||
drag(&editor, cx);
|
||||
assert_eq!(spanned(&editor, cx), Some((2, 3)));
|
||||
assert_eq!(cx.update(|_, cx| editor.read(cx).washed()), Some(1..2));
|
||||
let selected = |ix: usize, cx: &mut VisualTestContext| {
|
||||
cx.update(|_, cx| editor.read(cx).blocks[ix].fields[0].read(cx).selection())
|
||||
};
|
||||
assert_eq!((selected(0, cx), selected(2, cx)), (2..5, 0..3));
|
||||
cx.simulate_input("X");
|
||||
settle(cx);
|
||||
assert_eq!(
|
||||
blocks(&editor, cx),
|
||||
vec![text(BlockKind::Paragraph, "alXma")]
|
||||
);
|
||||
cx.simulate_keystrokes("secondary-z");
|
||||
settle(cx);
|
||||
assert_eq!(
|
||||
blocks(&editor, cx),
|
||||
vec![
|
||||
text(BlockKind::Paragraph, "alpha"),
|
||||
text(BlockKind::Paragraph, "beta"),
|
||||
text(BlockKind::Paragraph, "gamma"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn shift_press_selects_from_the_caret_and_backspace_joins(cx: &mut TestAppContext) {
|
||||
let (editor, cx) = three(cx);
|
||||
caret(&editor, 0, 1, cx);
|
||||
let to = at(&editor, 2, 3, cx);
|
||||
cx.simulate_mouse_down(to, MouseButton::Left, Modifiers::shift());
|
||||
cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::shift());
|
||||
settle(cx);
|
||||
assert_eq!(spanned(&editor, cx), Some((1, 3)));
|
||||
cx.simulate_keystrokes("backspace");
|
||||
settle(cx);
|
||||
assert_eq!(blocks(&editor, cx), vec![text(BlockKind::Paragraph, "ama")]);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn copy_takes_the_selection_as_markdown(cx: &mut TestAppContext) {
|
||||
let (editor, cx) = three(cx);
|
||||
drag(&editor, cx);
|
||||
cx.simulate_keystrokes("secondary-c");
|
||||
let copied = cx.read_from_clipboard().and_then(|item| item.text());
|
||||
assert_eq!(copied.as_deref(), Some("pha\n\nbeta\n\ngam"));
|
||||
cx.simulate_keystrokes("secondary-x");
|
||||
settle(cx);
|
||||
assert_eq!(
|
||||
blocks(&editor, cx),
|
||||
vec![text(BlockKind::Paragraph, "alma")]
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_key_that_moves_the_caret_lets_the_selection_go(cx: &mut TestAppContext) {
|
||||
let (editor, cx) = three(cx);
|
||||
drag(&editor, cx);
|
||||
cx.simulate_keystrokes("left");
|
||||
settle(cx);
|
||||
assert_eq!(spanned(&editor, cx), None);
|
||||
let gamma = cx.update(|_, cx| editor.read(cx).blocks[2].fields[0].read(cx).selection());
|
||||
assert!(gamma.is_empty(), "{gamma:?}");
|
||||
cx.simulate_input("Y");
|
||||
settle(cx);
|
||||
assert_eq!(blocks(&editor, cx).len(), 3);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn enter_replaces_the_selection_with_a_break(cx: &mut TestAppContext) {
|
||||
let (editor, cx) = three(cx);
|
||||
drag(&editor, cx);
|
||||
cx.simulate_keystrokes("enter");
|
||||
settle(cx);
|
||||
assert_eq!(
|
||||
blocks(&editor, cx),
|
||||
vec![
|
||||
text(BlockKind::Paragraph, "al"),
|
||||
text(BlockKind::Paragraph, "ma"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn original() -> Vec<(BlockKind, Vec<String>)> {
|
||||
["alpha", "beta", "gamma"]
|
||||
.map(|words| text(BlockKind::Paragraph, words))
|
||||
.to_vec()
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn enter_over_a_selection_undoes_in_one_step(cx: &mut TestAppContext) {
|
||||
let (editor, cx) = three(cx);
|
||||
drag(&editor, cx);
|
||||
cx.simulate_keystrokes("enter");
|
||||
settle(cx);
|
||||
cx.simulate_keystrokes("secondary-z");
|
||||
settle(cx);
|
||||
assert_eq!(blocks(&editor, cx), original());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn pasting_what_was_selected_still_takes_the_blocks_between(cx: &mut TestAppContext) {
|
||||
let (editor, cx) = three(cx);
|
||||
drag(&editor, cx);
|
||||
cx.write_to_clipboard(gpui::ClipboardItem::new_string("pha".into()));
|
||||
cx.simulate_keystrokes("secondary-v");
|
||||
settle(cx);
|
||||
assert_eq!(
|
||||
blocks(&editor, cx),
|
||||
vec![text(BlockKind::Paragraph, "alphama")]
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn backspace_from_the_end_of_a_block_takes_the_selection(cx: &mut TestAppContext) {
|
||||
let (editor, cx) = three(cx);
|
||||
let (from, to) = (at(&editor, 0, 5, cx), at(&editor, 2, 3, cx));
|
||||
cx.simulate_mouse_down(from, MouseButton::Left, Modifiers::none());
|
||||
cx.simulate_mouse_move(to, Some(MouseButton::Left), Modifiers::none());
|
||||
cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::none());
|
||||
settle(cx);
|
||||
assert_eq!(spanned(&editor, cx), Some((5, 3)));
|
||||
cx.simulate_keystrokes("backspace");
|
||||
settle(cx);
|
||||
assert_eq!(
|
||||
blocks(&editor, cx),
|
||||
vec![text(BlockKind::Paragraph, "alphama")]
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_composition_takes_the_selection_once_it_commits(cx: &mut TestAppContext) {
|
||||
let (editor, cx) = three(cx);
|
||||
drag(&editor, cx);
|
||||
let field = cx.update(|_, cx| editor.read(cx).blocks[0].fields[0].clone());
|
||||
cx.update(|window, cx| {
|
||||
field.update(cx, |input, cx| {
|
||||
input.replace_and_mark_text_in_range(None, "n", None, window, cx);
|
||||
input.replace_and_mark_text_in_range(None, "ni", None, window, cx);
|
||||
})
|
||||
});
|
||||
settle(cx);
|
||||
assert_eq!(blocks(&editor, cx).len(), 3, "composing waits");
|
||||
cx.update(|window, cx| {
|
||||
field.update(cx, |input, cx| {
|
||||
input.replace_text_in_range(None, "你", window, cx)
|
||||
})
|
||||
});
|
||||
settle(cx);
|
||||
assert_eq!(
|
||||
blocks(&editor, cx),
|
||||
vec![text(BlockKind::Paragraph, "al你ma")]
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn typing_after_shift_press_or_an_upward_drag_lands_once(cx: &mut TestAppContext) {
|
||||
let (editor, cx) = three(cx);
|
||||
caret(&editor, 0, 1, cx);
|
||||
let to = at(&editor, 2, 3, cx);
|
||||
cx.simulate_mouse_down(to, MouseButton::Left, Modifiers::shift());
|
||||
cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::shift());
|
||||
settle(cx);
|
||||
cx.simulate_input("Z");
|
||||
settle(cx);
|
||||
assert_eq!(
|
||||
blocks(&editor, cx),
|
||||
vec![text(BlockKind::Paragraph, "aZma")]
|
||||
);
|
||||
cx.simulate_keystrokes("secondary-z");
|
||||
settle(cx);
|
||||
let (from, to) = (at(&editor, 2, 3, cx), at(&editor, 0, 2, cx));
|
||||
cx.simulate_mouse_down(from, MouseButton::Left, Modifiers::none());
|
||||
cx.simulate_mouse_move(to, Some(MouseButton::Left), Modifiers::none());
|
||||
cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::none());
|
||||
settle(cx);
|
||||
assert_eq!(spanned(&editor, cx), Some((2, 3)));
|
||||
cx.simulate_input("Q");
|
||||
settle(cx);
|
||||
assert_eq!(
|
||||
blocks(&editor, cx),
|
||||
vec![text(BlockKind::Paragraph, "alQma")]
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,21 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::{
|
||||
AnyElement, App, Context, ElementId, InteractiveElement, IntoElement, MouseButton,
|
||||
ParentElement, Rems, Render, SharedString, Styled, Window, div, prelude::*,
|
||||
AnyElement, App, Axis, Context, ElementId, InteractiveElement, IntoElement, MouseButton,
|
||||
MouseDownEvent, ParentElement, Rems, Render, SharedString, Styled, Window, canvas, div,
|
||||
prelude::*,
|
||||
};
|
||||
|
||||
use super::{Block, BlockData, BlockEditor, BlockKind, matching};
|
||||
use super::{Block, BlockData, BlockEditor, BlockKind, matching, span::Put};
|
||||
use crate::{
|
||||
buttons::{ButtonVariant, IconButton},
|
||||
documents::suggest::{Offer, offers},
|
||||
forms::replace_trigger,
|
||||
forms::{Backspace, Choice, Down, Enter, Pick, Redo, Submit, Undo, Up},
|
||||
forms::{
|
||||
Backspace, Choice, Copy, Cut, Delete, DeleteWordLeft, Down, Enter, Pick, Redo, Submit,
|
||||
Undo, Up,
|
||||
},
|
||||
layout::{ScrollArea, bring_into_view},
|
||||
menus::{Menu, MenuItem, OverflowMenu},
|
||||
motion::Reorder,
|
||||
primitives::IconName,
|
||||
@@ -94,12 +99,17 @@ impl BlockEditor {
|
||||
let keys = div()
|
||||
.w_full()
|
||||
.capture_action(cx.listener(move |editor, _: &Enter, window, cx| {
|
||||
if editor.collapse_span(Put::Break, window, cx).is_some() {
|
||||
return cx.stop_propagation();
|
||||
}
|
||||
if editor.on_enter(key, ix, window, cx) {
|
||||
cx.stop_propagation();
|
||||
}
|
||||
}))
|
||||
.capture_action(cx.listener(move |editor, _: &Backspace, window, cx| {
|
||||
if editor.on_backspace(key, ix, window, cx) {
|
||||
if editor.collapse_span(Put::Nothing, window, cx).is_some()
|
||||
|| editor.on_backspace(key, ix, window, cx)
|
||||
{
|
||||
cx.stop_propagation();
|
||||
}
|
||||
}))
|
||||
@@ -117,7 +127,13 @@ impl BlockEditor {
|
||||
cx.stop_propagation();
|
||||
editor.on_submit(key, window, cx);
|
||||
}))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
cx.listener(move |editor, event: &MouseDownEvent, window, cx| {
|
||||
editor.pressed(key, ix, event, window, cx);
|
||||
cx.stop_propagation();
|
||||
}),
|
||||
)
|
||||
.child(field.clone());
|
||||
let slash = move |query: &str, at: usize, caret: usize| -> (Vec<Choice>, Pick) {
|
||||
let kinds = matching(query);
|
||||
@@ -141,6 +157,34 @@ impl BlockEditor {
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
/// Scrolls the focused caret into view once each time it moves; a wheel moves freely past a still one.
|
||||
fn reveal_caret(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some((key, ix)) = self.focused(window, cx) else {
|
||||
self.revealed = None;
|
||||
return;
|
||||
};
|
||||
let Some(block) = self.index(key).map(|at| &self.blocks[at]) else {
|
||||
return;
|
||||
};
|
||||
let field = block.fields[ix].read(cx);
|
||||
let at = (
|
||||
block.fields[ix].entity_id(),
|
||||
field.selection(),
|
||||
field.text().len(),
|
||||
);
|
||||
if self.revealed.as_ref() == Some(&at) {
|
||||
return;
|
||||
}
|
||||
let Some(caret) = field.caret_bounds() else {
|
||||
return;
|
||||
};
|
||||
self.revealed = Some(at);
|
||||
if bring_into_view(&self.scroll, caret, Axis::Vertical) {
|
||||
log::debug!("block editor: the caret came into view");
|
||||
window.request_animation_frame();
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle's menu: turn into another kind, duplicate or delete.
|
||||
fn menu(&self, key: u64, cx: &mut Context<Self>) -> Menu {
|
||||
let entity = cx.entity();
|
||||
@@ -182,6 +226,7 @@ impl Render for BlockEditor {
|
||||
let look = Look::new(cx);
|
||||
let colors = look.colors.clone();
|
||||
let focused = self.focused(window, cx).map(|(key, _)| key);
|
||||
let washed = self.washed().unwrap_or_default();
|
||||
let mut number = 0;
|
||||
let mut rows: Vec<(SharedString, AnyElement)> = Vec::new();
|
||||
for ix in 0..self.blocks.len() {
|
||||
@@ -233,6 +278,9 @@ impl Render for BlockEditor {
|
||||
.group(group.clone())
|
||||
.relative()
|
||||
.pl_16()
|
||||
.when(washed.contains(&ix), |row| {
|
||||
row.bg(colors.selection).rounded(look.radius)
|
||||
})
|
||||
.py_0p5()
|
||||
.child(content)
|
||||
.child(
|
||||
@@ -255,11 +303,36 @@ impl Render for BlockEditor {
|
||||
}),
|
||||
|list, (key, row)| list.row(key, row),
|
||||
);
|
||||
let start = cx.entity();
|
||||
div()
|
||||
.id(id.clone())
|
||||
let (start, editor) = (cx.entity(), cx.entity());
|
||||
let caret = canvas(
|
||||
move |_, window, cx| editor.update(cx, |editor, cx| editor.reveal_caret(window, cx)),
|
||||
|_, _, _, _| {},
|
||||
)
|
||||
.absolute();
|
||||
let column = div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.capture_action(cx.listener(|editor, _: &Copy, _, cx| {
|
||||
if editor.copy_span(cx) {
|
||||
cx.stop_propagation();
|
||||
}
|
||||
}))
|
||||
.capture_action(cx.listener(|editor, _: &Cut, window, cx| {
|
||||
if editor.copy_span(cx) {
|
||||
cx.stop_propagation();
|
||||
editor.collapse_span(Put::Nothing, window, cx);
|
||||
}
|
||||
}))
|
||||
.capture_action(cx.listener(|editor, _: &Delete, window, cx| {
|
||||
if editor.collapse_span(Put::Nothing, window, cx).is_some() {
|
||||
cx.stop_propagation();
|
||||
}
|
||||
}))
|
||||
.capture_action(cx.listener(|editor, _: &DeleteWordLeft, window, cx| {
|
||||
if editor.collapse_span(Put::Nothing, window, cx).is_some() {
|
||||
cx.stop_propagation();
|
||||
}
|
||||
}))
|
||||
.capture_action(cx.listener(|editor, _: &Undo, window, cx| {
|
||||
cx.stop_propagation();
|
||||
editor.undo(window, cx);
|
||||
@@ -271,7 +344,7 @@ impl Render for BlockEditor {
|
||||
.child(list)
|
||||
.child(
|
||||
div()
|
||||
.id((id, "end"))
|
||||
.id((id.clone(), "end"))
|
||||
.min_h_8()
|
||||
.cursor_text()
|
||||
.text_color(colors.fg_subtle)
|
||||
@@ -289,5 +362,13 @@ impl Render for BlockEditor {
|
||||
});
|
||||
}),
|
||||
)
|
||||
.child(caret)
|
||||
.when(self.pressing(), |column| {
|
||||
column.child(self.drag_listener(cx))
|
||||
});
|
||||
ScrollArea::new(id)
|
||||
.size_full()
|
||||
.track_scroll(&self.scroll)
|
||||
.child(column)
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@ use std::{rc::Rc, time::Duration};
|
||||
use gpui::{
|
||||
Anchor, Animation, AnimationExt, AnyElement, App, ClickEvent, Context, ElementId, Entity,
|
||||
FontWeight, HoverListenerMode, InteractiveElement, IntoElement, ParentElement, Pixels,
|
||||
RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Task, Window, anchored, canvas,
|
||||
div, point, prelude::*, relative,
|
||||
RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Task, Window, anchored,
|
||||
canvas, div, point, prelude::*, relative,
|
||||
};
|
||||
use web_time::Instant;
|
||||
|
||||
|
||||
+2
-1
@@ -114,7 +114,8 @@ pub use structure::{
|
||||
pub use switch::Switch;
|
||||
pub use tags::TagInput;
|
||||
pub(crate) use text::{
|
||||
Backspace, Down, Enter, Redo, Submit, Undo, Up, bind_keys, from_utf16, to_utf16,
|
||||
Backspace, Copy, Cut, Delete, DeleteWordLeft, Down, Enter, Redo, Submit, Undo, Up, bind_keys,
|
||||
from_utf16, to_utf16,
|
||||
};
|
||||
pub use text::{Highlight, History, InputEvent, TextInput};
|
||||
pub use transfer::TransferList;
|
||||
|
||||
@@ -321,6 +321,7 @@ impl Popup<'_> {
|
||||
})
|
||||
.max_w(window.viewport_size().width - theme.window_margin() * 2.0)
|
||||
.max_h(theme.list_max_height())
|
||||
.occlude()
|
||||
.overflow_y_scroll()
|
||||
.when_some(self.scroll, |list, handle| list.track_scroll(handle))
|
||||
.p_1()
|
||||
|
||||
+3
-1
@@ -129,7 +129,9 @@ impl RenderOnce for Switch {
|
||||
.id(self.id)
|
||||
.role(Role::Switch)
|
||||
.aria_toggled(self.on.into())
|
||||
.when_some(self.label.clone().or(self.name), |row, label| row.aria_label(label))
|
||||
.when_some(self.label.clone().or(self.name), |row, label| {
|
||||
row.aria_label(label)
|
||||
})
|
||||
.when(self.disabled, |row| {
|
||||
row.aria_description(i18n::text(cx, "state.unavailable", &[]))
|
||||
})
|
||||
|
||||
@@ -2,6 +2,7 @@ mod choices;
|
||||
mod colors;
|
||||
mod dates;
|
||||
mod other;
|
||||
mod popup;
|
||||
mod stale;
|
||||
mod structure;
|
||||
mod tags;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
use gpui::{
|
||||
Context, IntoElement, KeyUpEvent, Keystroke, Modifiers, ParentElement, Render, ScrollDelta,
|
||||
ScrollHandle, ScrollWheelEvent, Styled, TestAppContext, TouchPhase, Window, div, point,
|
||||
prelude::*, px,
|
||||
};
|
||||
|
||||
use super::setup;
|
||||
use crate::forms::{Choice, Select};
|
||||
|
||||
/// A long select at the top of a page that scrolls.
|
||||
struct Page(ScrollHandle);
|
||||
|
||||
impl Render for Page {
|
||||
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
||||
let choices = (0..40).map(|ix| Choice::new(format!("{ix}"), format!("Choice {ix}")));
|
||||
div()
|
||||
.id("page")
|
||||
.size_full()
|
||||
.overflow_y_scroll()
|
||||
.track_scroll(&self.0)
|
||||
.child(div().w(px(200.0)).child(Select::new("long", choices)))
|
||||
.child(div().h(px(2000.0)))
|
||||
}
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_wheel_over_an_open_list_leaves_the_page(cx: &mut TestAppContext) {
|
||||
setup(cx);
|
||||
let page = ScrollHandle::new();
|
||||
let (_, cx) = cx.add_window_view({
|
||||
let page = page.clone();
|
||||
|_, _| Page(page)
|
||||
});
|
||||
cx.run_until_parked();
|
||||
cx.update(|window, cx| window.focus_next(cx));
|
||||
cx.simulate_keystrokes("enter");
|
||||
cx.simulate_event(KeyUpEvent {
|
||||
keystroke: Keystroke::parse("enter").unwrap(),
|
||||
});
|
||||
cx.run_until_parked();
|
||||
let list = cx.debug_bounds("option-list").expect("the list opens");
|
||||
cx.simulate_event(ScrollWheelEvent {
|
||||
position: list.center(),
|
||||
delta: ScrollDelta::Pixels(point(px(0.0), px(-120.0))),
|
||||
modifiers: Modifiers::none(),
|
||||
touch_phase: TouchPhase::Moved,
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert_eq!(page.offset().y, px(0.0), "the page stayed");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use gpui::{AppContext, Context, IntoElement, Render, TestAppContext, Window};
|
||||
use gpui::{AppContext, Context, EntityInputHandler, IntoElement, Render, TestAppContext, Window};
|
||||
|
||||
use super::setup;
|
||||
use crate::forms::{TextInput, UnitInput};
|
||||
@@ -45,3 +45,24 @@ fn a_unit_gone_from_its_list_keeps_the_field(cx: &mut TestAppContext) {
|
||||
cx.run_until_parked();
|
||||
assert!(cx.debug_bounds("number-root").is_some());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn an_ime_finds_its_composition_before_the_next_layout(cx: &mut TestAppContext) {
|
||||
let (fields, cx) = super::open(1, false, cx);
|
||||
let field = fields[0].clone();
|
||||
super::focus(&field, cx);
|
||||
field.update(cx, |input, cx| input.set_text("abc", cx));
|
||||
cx.run_until_parked();
|
||||
let laid = field
|
||||
.read_with(cx, |input, _| input.bounds_for(3))
|
||||
.expect("laid out");
|
||||
let asked = cx.update(|window, cx| {
|
||||
field.update(cx, |input, cx| {
|
||||
input.replace_and_mark_text_in_range(None, "n", None, window, cx);
|
||||
let at = gpui::Bounds::new(laid.origin, gpui::size(gpui::px(200.), laid.size.height));
|
||||
input.bounds_for_range(3..4, at, window, cx)
|
||||
})
|
||||
});
|
||||
let asked = asked.expect("the candidate box has a place");
|
||||
assert_eq!(asked.origin, laid.origin, "at the caret, on its line");
|
||||
}
|
||||
@@ -8,7 +8,10 @@ use gpui::{
|
||||
};
|
||||
|
||||
use super::{Highlight, Layout, TextInput};
|
||||
use crate::theme::ActiveTheme;
|
||||
use crate::{
|
||||
primitives::{caret_bar, caret_width},
|
||||
theme::ActiveTheme,
|
||||
};
|
||||
|
||||
pub(crate) struct TextElement {
|
||||
input: Entity<TextInput>,
|
||||
@@ -214,7 +217,10 @@ impl Element for TextElement {
|
||||
) -> Prepaint {
|
||||
let theme = cx.theme();
|
||||
let (selection_color, caret_color) = (theme.colors.selection, theme.colors.focus);
|
||||
let caret_width = theme.caret_width().to_pixels(window.rem_size());
|
||||
let caret_width = caret_width(
|
||||
theme.caret_width().to_pixels(window.rem_size()),
|
||||
window.scale_factor(),
|
||||
);
|
||||
let input = self.input.read(cx);
|
||||
let (text, placeholder, runs) = shown_runs(input, window, cx);
|
||||
let font_size = window.text_style().font_size.to_pixels(window.rem_size());
|
||||
@@ -262,7 +268,10 @@ impl Element for TextElement {
|
||||
};
|
||||
let caret = caret_at
|
||||
.filter(|_| focused && caret_on && selection.is_empty())
|
||||
.map(|at| Bounds::new(bounds.origin + at - scroll, size(caret_width, line_height)));
|
||||
.map(|at| {
|
||||
let at = bounds.origin + at - scroll;
|
||||
caret_bar(at, caret_width, line_height, window.scale_factor())
|
||||
});
|
||||
self.input.update(cx, |input, _| input.scroll = scroll);
|
||||
Prepaint {
|
||||
lines,
|
||||
|
||||
@@ -107,6 +107,7 @@ impl EntityInputHandler for TextInput {
|
||||
if self.marked.is_none() {
|
||||
self.composing = Some(self.snapshot());
|
||||
}
|
||||
self.edits += 1;
|
||||
self.text.replace_range(range.clone(), text);
|
||||
self.marked = (!text.is_empty()).then(|| range.start..range.start + text.len());
|
||||
if self.marked.is_none() {
|
||||
@@ -126,19 +127,13 @@ impl EntityInputHandler for TextInput {
|
||||
fn bounds_for_range(
|
||||
&mut self,
|
||||
range_utf16: Range<usize>,
|
||||
bounds: Bounds<Pixels>,
|
||||
_: Bounds<Pixels>,
|
||||
_: &mut Window,
|
||||
_: &mut Context<Self>,
|
||||
) -> Option<Bounds<Pixels>> {
|
||||
let range = self.range_from_utf16(&range_utf16);
|
||||
let line_height = self.layout.as_ref()?.line_height;
|
||||
let start = self.position_for(self.display_offset(range.start))?;
|
||||
let end = self.position_for(self.display_offset(range.end))?;
|
||||
let origin = bounds.origin - self.scroll;
|
||||
Some(Bounds::from_corners(
|
||||
origin + start,
|
||||
origin + gpui::point(end.x, end.y + line_height),
|
||||
))
|
||||
let (start, end) = (self.bounds_for(range.start)?, self.bounds_for(range.end)?);
|
||||
Some(Bounds::from_corners(start.origin, end.bottom_left()))
|
||||
}
|
||||
|
||||
fn character_index_for_point(
|
||||
|
||||
+12
-1
@@ -12,7 +12,9 @@ use gpui::{
|
||||
Subscription, Task, Window, WrappedLine,
|
||||
};
|
||||
|
||||
pub(crate) use actions::{Backspace, Down, Enter, Redo, Submit, Undo, Up, bind_keys};
|
||||
pub(crate) use actions::{
|
||||
Backspace, Copy, Cut, Delete, DeleteWordLeft, Down, Enter, Redo, Submit, Undo, Up, bind_keys,
|
||||
};
|
||||
pub use edit::History;
|
||||
use edit::Snapshot;
|
||||
pub(crate) use edit::{from_utf16, to_utf16};
|
||||
@@ -66,6 +68,8 @@ pub struct TextInput {
|
||||
history: History<Snapshot>,
|
||||
/// The selection the last edit replaced.
|
||||
edited_from: Range<usize>,
|
||||
/// Edits applied, text changed or not.
|
||||
edits: u64,
|
||||
pub(crate) layout: Option<Layout>,
|
||||
pub(crate) scroll: Point<Pixels>,
|
||||
selecting: bool,
|
||||
@@ -120,6 +124,7 @@ impl TextInput {
|
||||
disabled: false,
|
||||
history: History::default(),
|
||||
edited_from: 0..0,
|
||||
edits: 0,
|
||||
layout: None,
|
||||
scroll: Point::default(),
|
||||
selecting: false,
|
||||
@@ -311,6 +316,11 @@ impl TextInput {
|
||||
self.edited_from.clone()
|
||||
}
|
||||
|
||||
/// How many edits it took, and whether an input method is composing.
|
||||
pub(crate) fn edits(&self) -> (u64, bool) {
|
||||
(self.edits, self.marked.is_some())
|
||||
}
|
||||
|
||||
pub(crate) fn replace(
|
||||
&mut self,
|
||||
range: Range<usize>,
|
||||
@@ -332,6 +342,7 @@ impl TextInput {
|
||||
if incoming.is_empty() && range.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.edits += 1;
|
||||
let composed = self.composing.take();
|
||||
let before = composed.clone().unwrap_or_else(|| self.snapshot());
|
||||
let caret = match &self.fit {
|
||||
|
||||
@@ -18,13 +18,19 @@ pub(crate) fn text_width(
|
||||
let font_size = cx.theme().text_size(size).to_pixels(window.rem_size());
|
||||
let run = TextRun {
|
||||
len: text.len(),
|
||||
font: Font { weight, ..window.text_style().font() },
|
||||
font: Font {
|
||||
weight,
|
||||
..window.text_style().font()
|
||||
},
|
||||
color: Hsla::default(),
|
||||
background_color: None,
|
||||
underline: None,
|
||||
strikethrough: None,
|
||||
};
|
||||
window.text_system().shape_line(text.clone(), font_size, &[run], None).width
|
||||
window
|
||||
.text_system()
|
||||
.shape_line(text.clone(), font_size, &[run], None)
|
||||
.width
|
||||
}
|
||||
|
||||
/// Keeps `width` at the parent's width; a change redraws once.
|
||||
|
||||
+40
-7
@@ -228,6 +228,7 @@ pub struct ScrollArea {
|
||||
base: Div,
|
||||
shadows: bool,
|
||||
vertical: bool,
|
||||
handle: Option<ScrollHandle>,
|
||||
body: SmallVec<[AnyElement; 2]>,
|
||||
}
|
||||
|
||||
@@ -238,10 +239,17 @@ impl ScrollArea {
|
||||
base: div(),
|
||||
shadows: false,
|
||||
vertical: false,
|
||||
handle: None,
|
||||
body: SmallVec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Scrolls through the owner's handle, so the owner can move it.
|
||||
pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
|
||||
self.handle = Some(handle.clone());
|
||||
self
|
||||
}
|
||||
|
||||
/// Soft edges where content continues.
|
||||
pub fn shadows(mut self) -> Self {
|
||||
self.shadows = true;
|
||||
@@ -267,8 +275,13 @@ impl ParentElement for ScrollArea {
|
||||
}
|
||||
}
|
||||
|
||||
fn track_activity(state: &Entity<Activity>, window: &mut Window, cx: &mut App) -> f32 {
|
||||
let offset = state.read(cx).handle.offset();
|
||||
fn track_activity(
|
||||
state: &Entity<Activity>,
|
||||
handle: &ScrollHandle,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> f32 {
|
||||
let offset = handle.offset();
|
||||
if state.read(cx).last != offset {
|
||||
state.update(cx, |activity, _| {
|
||||
activity.last = offset;
|
||||
@@ -291,8 +304,11 @@ impl RenderOnce for ScrollArea {
|
||||
active_at: None,
|
||||
hovered: false,
|
||||
});
|
||||
let handle = state.read(cx).handle.clone();
|
||||
let presence = track_activity(&state, window, cx);
|
||||
let handle = match self.handle {
|
||||
Some(handle) => handle,
|
||||
None => state.read(cx).handle.clone(),
|
||||
};
|
||||
let presence = track_activity(&state, &handle, window, cx);
|
||||
self.base
|
||||
.id(self.id)
|
||||
.relative()
|
||||
@@ -308,13 +324,28 @@ impl RenderOnce for ScrollArea {
|
||||
div()
|
||||
.id("scroll-body")
|
||||
.size_full()
|
||||
.when(self.vertical, |body| body.overflow_y_scroll().overflow_x_hidden())
|
||||
.when(self.vertical, |body| {
|
||||
body.overflow_y_scroll().overflow_x_hidden()
|
||||
})
|
||||
.when(!self.vertical, |body| body.overflow_scroll())
|
||||
.track_scroll(&handle)
|
||||
.on_scroll_wheel({
|
||||
let handle = handle.clone();
|
||||
move |event, window, cx| {
|
||||
let delta = event.delta.pixel_delta(window.line_height());
|
||||
let reach = handle.max_offset();
|
||||
let vertical = delta.y != Pixels::ZERO && reach.y > Pixels::ZERO;
|
||||
if vertical || (delta.x != Pixels::ZERO && reach.x > Pixels::ZERO) {
|
||||
cx.stop_propagation();
|
||||
}
|
||||
}
|
||||
})
|
||||
.map(|body| match self.vertical {
|
||||
// Children fill and never widen, so rows wrap.
|
||||
true => body.flex().flex_col().children(
|
||||
self.body.into_iter().map(|child| div().w_full().min_w_0().child(child)),
|
||||
self.body
|
||||
.into_iter()
|
||||
.map(|child| div().w_full().min_w_0().child(child)),
|
||||
),
|
||||
false => body.children(self.body),
|
||||
}),
|
||||
@@ -322,7 +353,9 @@ impl RenderOnce for ScrollArea {
|
||||
.when(self.shadows, |area| area.child(ScrollShadow::new(&handle)))
|
||||
.child(Scrollbar::new("scrollbar-y", &handle, Axis::Vertical).presence(presence))
|
||||
.when(!self.vertical, |area| {
|
||||
area.child(Scrollbar::new("scrollbar-x", &handle, Axis::Horizontal).presence(presence))
|
||||
area.child(
|
||||
Scrollbar::new("scrollbar-x", &handle, Axis::Horizontal).presence(presence),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
+49
-2
@@ -2,8 +2,8 @@ use std::time::Duration;
|
||||
|
||||
use gpui::{
|
||||
AnyElement, App, AppContext, Axis, Bounds, Context, InteractiveElement, IntoElement, Modifiers,
|
||||
MouseButton, ParentElement, Pixels, Point, Render, Styled, TestAppContext, VisualTestContext,
|
||||
Window, div, point, px,
|
||||
MouseButton, ParentElement, Pixels, Point, Render, StatefulInteractiveElement, Styled,
|
||||
TestAppContext, VisualTestContext, Window, div, point, px,
|
||||
};
|
||||
|
||||
use super::{Drawer, PaneGroup, SplitPane};
|
||||
@@ -254,3 +254,50 @@ fn invalid_sizes_after_a_drag_split_evenly(cx: &mut TestAppContext) {
|
||||
let second = cx.debug_bounds("second").expect("second").size.width;
|
||||
assert_eq!(first, second);
|
||||
}
|
||||
|
||||
/// A ScrollArea of `inner` content, 100px tall, in a page that scrolls.
|
||||
struct Nested(Pixels, gpui::ScrollHandle);
|
||||
|
||||
impl Render for Nested {
|
||||
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
||||
div()
|
||||
.id("page")
|
||||
.size_full()
|
||||
.overflow_y_scroll()
|
||||
.track_scroll(&self.1)
|
||||
.child(
|
||||
super::ScrollArea::new("area")
|
||||
.h(px(100.0))
|
||||
.child(div().h(self.0)),
|
||||
)
|
||||
.child(div().h(px(2000.0)))
|
||||
}
|
||||
}
|
||||
|
||||
fn wheel_page(inner: Pixels, cx: &mut TestAppContext) -> Pixels {
|
||||
cx.update(Theme::init);
|
||||
let page = gpui::ScrollHandle::new();
|
||||
let (_, cx) = cx.add_window_view({
|
||||
let page = page.clone();
|
||||
move |_, _| Nested(inner, page)
|
||||
});
|
||||
cx.run_until_parked();
|
||||
cx.simulate_event(gpui::ScrollWheelEvent {
|
||||
position: point(px(50.0), px(50.0)),
|
||||
delta: gpui::ScrollDelta::Pixels(point(px(0.0), px(-40.0))),
|
||||
modifiers: Modifiers::none(),
|
||||
touch_phase: gpui::TouchPhase::Moved,
|
||||
});
|
||||
cx.run_until_parked();
|
||||
page.offset().y
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_scroll_area_keeps_a_wheel_it_can_use(cx: &mut TestAppContext) {
|
||||
assert_eq!(wheel_page(px(500.0), cx), px(0.0));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_scroll_area_with_no_room_passes_the_wheel_on(cx: &mut TestAppContext) {
|
||||
assert_eq!(wheel_page(px(50.0), cx), px(-40.0));
|
||||
}
|
||||
+14
-5
@@ -218,7 +218,9 @@ impl RenderOnce for Tabs {
|
||||
.when_some(tab.icon, |item, icon| {
|
||||
item.child(Icon::new(icon).size(IconSize::Sm).color(fg))
|
||||
})
|
||||
.when(compact, |item| item.tooltip(Tooltip::text(tab.label.clone())))
|
||||
.when(compact, |item| {
|
||||
item.tooltip(Tooltip::text(tab.label.clone()))
|
||||
})
|
||||
.when(!compact, |item| item.child(tab.label.clone()))
|
||||
.when_some(tab.note.clone().filter(|_| !compact), |item, note| {
|
||||
item.child(div().text_color(colors.fg_subtle).child(note))
|
||||
@@ -293,13 +295,20 @@ impl RenderOnce for Tabs {
|
||||
fn natural(tabs: &[Choice], window: &Window, cx: &App) -> Pixels {
|
||||
let theme = cx.theme();
|
||||
let rem = window.rem_size();
|
||||
let pad = gpui::rems(0.75).to_pixels(rem) * 2.0 + gpui::px(2.0);
|
||||
let pad = (gpui::rems(0.75).to_pixels(rem) + theme.hairline()) * 2.0;
|
||||
let glyph = theme.icon_size(IconSize::Sm).to_pixels(rem) + gpui::rems(0.375).to_pixels(rem);
|
||||
let gap = gpui::rems(0.25).to_pixels(rem);
|
||||
tabs.iter().fold(Pixels::ZERO, |sum, tab| {
|
||||
let text = |text: &SharedString| text_width(text, TextSize::Sm, FontWeight::MEDIUM, window, cx);
|
||||
let note = tab.note.as_ref().map_or(Pixels::ZERO, |note| text(note) + gpui::rems(0.375).to_pixels(rem));
|
||||
let icon = if tab.icon.is_some() { glyph } else { Pixels::ZERO };
|
||||
let text =
|
||||
|text: &SharedString| text_width(text, TextSize::Sm, FontWeight::MEDIUM, window, cx);
|
||||
let note = tab.note.as_ref().map_or(Pixels::ZERO, |note| {
|
||||
text(note) + gpui::rems(0.375).to_pixels(rem)
|
||||
});
|
||||
let icon = if tab.icon.is_some() {
|
||||
glyph
|
||||
} else {
|
||||
Pixels::ZERO
|
||||
};
|
||||
sum + pad + icon + text(&tab.label) + note + gap
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
use gpui::{Bounds, Pixels, Point, size};
|
||||
|
||||
fn snap(logical: Pixels, least: f32, scale: f32) -> Pixels {
|
||||
Pixels::from((logical.as_f32() * scale).round().max(least) / scale)
|
||||
}
|
||||
|
||||
/// The width a caret paints at: whole device pixels, at least one.
|
||||
pub(crate) fn caret_width(width: Pixels, scale: f32) -> Pixels {
|
||||
snap(width, 1.0, scale)
|
||||
}
|
||||
|
||||
/// A caret bar at `origin`, `width` wide, snapped whole to device pixels so it keeps one width.
|
||||
pub(crate) fn caret_bar(
|
||||
origin: Point<Pixels>,
|
||||
width: Pixels,
|
||||
height: Pixels,
|
||||
scale: f32,
|
||||
) -> Bounds<Pixels> {
|
||||
Bounds::new(
|
||||
Point::new(snap(origin.x, f32::MIN, scale), origin.y),
|
||||
size(caret_width(width, scale), height),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpui::{point, px};
|
||||
|
||||
use super::caret_bar;
|
||||
|
||||
/// gpui's paint snapping: each edge alone, half toward zero.
|
||||
fn device(logical: f32, scale: f32) -> f32 {
|
||||
let value = logical * scale;
|
||||
(value.abs() - 0.5).ceil().copysign(value)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_keeps_one_device_width_wherever_it_stands() {
|
||||
for scale in [1.0, 1.25, 1.5, 2.0] {
|
||||
let widths: Vec<f32> = (0..200)
|
||||
.map(|step| {
|
||||
let bar = caret_bar(
|
||||
point(px(10.0 + step as f32 * 0.037), px(3.3)),
|
||||
px(1.5),
|
||||
px(18.0),
|
||||
scale,
|
||||
);
|
||||
device(bar.right().as_f32(), scale) - device(bar.left().as_f32(), scale)
|
||||
})
|
||||
.collect();
|
||||
let first = widths[0];
|
||||
assert!(first >= 1.0, "at {scale}x the caret shows");
|
||||
assert!(
|
||||
widths.iter().all(|width| *width == first),
|
||||
"at {scale}x the caret took widths {:?}",
|
||||
widths.iter().fold(Vec::new(), |mut seen, width| {
|
||||
if !seen.contains(width) {
|
||||
seen.push(*width);
|
||||
}
|
||||
seen
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
mod backdrop;
|
||||
mod caret;
|
||||
mod disclosure;
|
||||
mod divider;
|
||||
mod files;
|
||||
@@ -17,6 +18,7 @@ mod tooltip;
|
||||
mod tests;
|
||||
|
||||
pub use backdrop::{Backdrop, Place};
|
||||
pub(crate) use caret::{caret_bar, caret_width};
|
||||
pub use disclosure::Disclosure;
|
||||
pub use divider::Divider;
|
||||
pub use files::IconTheme;
|
||||
|
||||
@@ -22,7 +22,10 @@ impl Retired {
|
||||
/// Frees images no one else holds; call while painting.
|
||||
pub fn release(&mut self, window: &mut Window) {
|
||||
// A shared image may still be drawn; it waits.
|
||||
let (free, held): (Vec<_>, Vec<_>) = self.0.drain(..).partition(|image| Arc::strong_count(image) == 1);
|
||||
let (free, held): (Vec<_>, Vec<_>) = self
|
||||
.0
|
||||
.drain(..)
|
||||
.partition(|image| Arc::strong_count(image) == 1);
|
||||
self.0 = held;
|
||||
for image in free {
|
||||
if let Err(error) = window.drop_image(image) {
|
||||
|
||||
+27
-7
@@ -191,7 +191,9 @@ impl Render for Kept {
|
||||
.key_context("HostField")
|
||||
.track_focus(&self.field)
|
||||
.size(px(100.0))
|
||||
.on_action(move |_: &Indent, _, cx| view.update(cx, |kept, _| kept.indents += 1)),
|
||||
.on_action(move |_: &Indent, _, cx| {
|
||||
view.update(cx, |kept, _| kept.indents += 1)
|
||||
}),
|
||||
)
|
||||
.child(div().track_focus(&self.after).size(px(100.0)))
|
||||
}
|
||||
@@ -216,7 +218,11 @@ fn f6_leaves_a_field_that_keeps_tab(cx: &mut TestAppContext) {
|
||||
cx.simulate_keystrokes("tab");
|
||||
let after = view.read_with(cx, |kept, _| kept.after.clone());
|
||||
cx.simulate_keystrokes("f6");
|
||||
assert_eq!(view.read_with(cx, |kept, _| kept.indents), 1, "Tab stayed in the field");
|
||||
assert_eq!(
|
||||
view.read_with(cx, |kept, _| kept.indents),
|
||||
1,
|
||||
"Tab stayed in the field"
|
||||
);
|
||||
cx.update(|window, _| assert!(after.is_focused(window), "F6 moved on"));
|
||||
cx.simulate_keystrokes("shift-f6");
|
||||
let field = view.read_with(cx, |kept, _| kept.field.clone());
|
||||
@@ -238,7 +244,9 @@ impl Render for Painted {
|
||||
view.update(cx, |painted, _| {
|
||||
painted.retired.release(window);
|
||||
if let Some(image) = painted.image.clone() {
|
||||
window.paint_image(bounds, bounds, Default::default(), image, 0, false).expect("paints");
|
||||
window
|
||||
.paint_image(bounds, bounds, Default::default(), image, 0, false)
|
||||
.expect("paints");
|
||||
}
|
||||
})
|
||||
},
|
||||
@@ -252,7 +260,10 @@ fn a_retired_image_is_freed_at_the_next_paint(cx: &mut TestAppContext) {
|
||||
cx.update(Theme::init);
|
||||
let pixels = image::RgbaImage::from_pixel(2, 2, image::Rgba([1, 2, 3, 255]));
|
||||
let image = std::sync::Arc::new(gpui::RenderImage::new([image::Frame::new(pixels)]));
|
||||
let (view, cx) = cx.add_window_view(|_, _| Painted { image: Some(image), retired: super::Retired::default() });
|
||||
let (view, cx) = cx.add_window_view(|_, _| Painted {
|
||||
image: Some(image),
|
||||
retired: super::Retired::default(),
|
||||
});
|
||||
cx.run_until_parked();
|
||||
view.update(cx, |painted, cx| {
|
||||
let old = painted.image.take().expect("painted");
|
||||
@@ -260,7 +271,10 @@ fn a_retired_image_is_freed_at_the_next_paint(cx: &mut TestAppContext) {
|
||||
cx.notify();
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert!(view.read_with(cx, |painted, _| painted.retired.is_empty()), "the old image was freed");
|
||||
assert!(
|
||||
view.read_with(cx, |painted, _| painted.retired.is_empty()),
|
||||
"the old image was freed"
|
||||
);
|
||||
// One still held elsewhere waits until it is let go.
|
||||
let pixels = image::RgbaImage::from_pixel(2, 2, image::Rgba([4, 5, 6, 255]));
|
||||
let shared = std::sync::Arc::new(gpui::RenderImage::new([image::Frame::new(pixels)]));
|
||||
@@ -269,9 +283,15 @@ fn a_retired_image_is_freed_at_the_next_paint(cx: &mut TestAppContext) {
|
||||
cx.notify();
|
||||
});
|
||||
cx.run_until_parked();
|
||||
assert!(!view.read_with(cx, |painted, _| painted.retired.is_empty()), "a held image waits");
|
||||
assert!(
|
||||
!view.read_with(cx, |painted, _| painted.retired.is_empty()),
|
||||
"a held image waits"
|
||||
);
|
||||
drop(shared);
|
||||
view.update(cx, |_, cx| cx.notify());
|
||||
cx.run_until_parked();
|
||||
assert!(view.read_with(cx, |painted, _| painted.retired.is_empty()), "then it is freed");
|
||||
assert!(
|
||||
view.read_with(cx, |painted, _| painted.retired.is_empty()),
|
||||
"then it is freed"
|
||||
);
|
||||
}
|
||||
@@ -75,7 +75,9 @@ impl RenderOnce for ThemeSelector {
|
||||
.iter()
|
||||
.fold(
|
||||
SegmentedControl::new(self.id, *words),
|
||||
|control, (_, words, icon)| control.segment(*words, i18n::text(cx, words, &[]), Some(*icon)),
|
||||
|control, (_, words, icon)| {
|
||||
control.segment(*words, i18n::text(cx, words, &[]), Some(*icon))
|
||||
},
|
||||
)
|
||||
.on_change(move |value, window, cx| {
|
||||
let (chosen, _, _) = Appearance::ALL
|
||||
|
||||
+10
-2
@@ -6,9 +6,9 @@ use gpui::{
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use crate::{
|
||||
typography::Ellipsis,
|
||||
primitives::{Icon, IconName, Tooltip},
|
||||
theme::{ActiveTheme, ControlSize, IconSize, Radius, TextSize},
|
||||
typography::Ellipsis,
|
||||
};
|
||||
|
||||
/// A row of tools, grouped and divided.
|
||||
@@ -145,7 +145,15 @@ impl RenderOnce for StatusBar {
|
||||
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let theme = cx.theme();
|
||||
// Narrow, both sides shrink and labels end in an ellipsis.
|
||||
let side = || div().flex().items_center().gap_0p5().h_full().min_w_0().overflow_hidden();
|
||||
let side = || {
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_0p5()
|
||||
.h_full()
|
||||
.min_w_0()
|
||||
.overflow_hidden()
|
||||
};
|
||||
self.base
|
||||
.flex()
|
||||
.flex_none()
|
||||
|
||||
+19
-4
@@ -184,11 +184,18 @@ pub struct ZoomControl {
|
||||
|
||||
impl ZoomControl {
|
||||
pub fn new(id: impl Into<ElementId>) -> Self {
|
||||
Self { id: id.into(), owned: None }
|
||||
Self {
|
||||
id: id.into(),
|
||||
owned: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows `percent` and hands each press to `on_zoom`.
|
||||
pub fn owned(mut self, percent: u32, on_zoom: impl Fn(ZoomStep, &mut Window, &mut App) + 'static) -> Self {
|
||||
pub fn owned(
|
||||
mut self,
|
||||
percent: u32,
|
||||
on_zoom: impl Fn(ZoomStep, &mut Window, &mut App) + 'static,
|
||||
) -> Self {
|
||||
self.owned = Some((percent, Rc::new(on_zoom)));
|
||||
self
|
||||
}
|
||||
@@ -263,7 +270,11 @@ fn owned(id: ElementId, percent: u32, on_zoom: OnZoom, cx: &App) -> impl IntoEle
|
||||
.flex_none()
|
||||
.items_center()
|
||||
.gap_0p5()
|
||||
.child(IconButton::new("zoom-out", IconName::ZoomOut).size(ControlSize::Sm).on_click(press(ZoomStep::Out)))
|
||||
.child(
|
||||
IconButton::new("zoom-out", IconName::ZoomOut)
|
||||
.size(ControlSize::Sm)
|
||||
.on_click(press(ZoomStep::Out)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("zoom-reset")
|
||||
@@ -279,7 +290,11 @@ fn owned(id: ElementId, percent: u32, on_zoom: OnZoom, cx: &App) -> impl IntoEle
|
||||
.child(AnimatedNumber::new("zoom-value", percent as f64).size(TextSize::Sm))
|
||||
.child(div().text_size(theme.text_size(TextSize::Sm)).child("%")),
|
||||
)
|
||||
.child(IconButton::new("zoom-in", IconName::ZoomIn).size(ControlSize::Sm).on_click(press(ZoomStep::In)))
|
||||
.child(
|
||||
IconButton::new("zoom-in", IconName::ZoomIn)
|
||||
.size(ControlSize::Sm)
|
||||
.on_click(press(ZoomStep::In)),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -12,6 +12,7 @@ use super::{
|
||||
links::Target,
|
||||
view::Terminal,
|
||||
};
|
||||
use crate::primitives::caret_bar;
|
||||
|
||||
/// How a terminal paints: font and cell, ink, and the colors of what it marks.
|
||||
pub(crate) struct Look {
|
||||
@@ -161,10 +162,11 @@ pub(crate) fn grid(
|
||||
(CursorShape::HollowBlock, _) | (_, false) => {
|
||||
outline(Bounds::new(origin, cell), look.caret, BorderStyle::Solid)
|
||||
}
|
||||
(CursorShape::Beam, true) => fill(
|
||||
Bounds::new(origin, size(look.caret_width, cell.height)),
|
||||
look.caret,
|
||||
),
|
||||
(CursorShape::Beam, true) => {
|
||||
let scale = window.scale_factor();
|
||||
let bar = caret_bar(origin, look.caret_width, cell.height, scale);
|
||||
fill(bar, look.caret)
|
||||
}
|
||||
(CursorShape::Underline, true) => fill(
|
||||
Bounds::new(
|
||||
origin + point(Pixels::ZERO, cell.height - look.caret_width),
|
||||
|
||||
@@ -179,6 +179,11 @@ impl Theme {
|
||||
px(1.0)
|
||||
}
|
||||
|
||||
/// A border's width, which does not scale: `border_1`.
|
||||
pub fn hairline(&self) -> Pixels {
|
||||
px(1.0)
|
||||
}
|
||||
|
||||
pub fn caret_width(&self) -> Rems {
|
||||
px_to_rems(1.5)
|
||||
}
|
||||
|
||||
@@ -12,3 +12,14 @@
|
||||
- [x] G7 Issue #6: `shell::ColumnShell`, a sidebar that runs to the window's top with the traffic lights, beside one or two panes that bring their own headers; tested
|
||||
- [x] G8 Issue #6: a Layout story, `stories.json`, AGENTS.md and the PRD line; the story runs live on the site
|
||||
- [x] G9 Push, deploy, reply on #6 and #7, close #6
|
||||
|
||||
# GitHub round, 2026-10-08
|
||||
|
||||
- [x] G10 CI: `cargo fmt` on the files the last commits left unformatted; then the narrow-layout commits: fmt, and `Theme::hairline` for their raw px
|
||||
- [x] G11 Issue #7: a caret is a whole number of device pixels wide at a device pixel, so it never shows thin then thick; tested
|
||||
- [x] G12 Issue #7: an IME asks for its candidate box past the laid-out text; the box clamps to the last layout, as `bounds_for` does; tested
|
||||
- [x] G13 Issue #12: a floating option list occludes, so the wheel scrolls the list and not the page under it; tested
|
||||
- [x] G14 Issue #7: BlockEditor scrolls in its own `ScrollArea` with its scrollbar and keeps the caret in view as blocks are added; tested
|
||||
- [x] G15 Issue #7: BlockEditor turns into Markdown and back; tested. Six reviews: the fifth finding (a slash ended an unquoted HTML value) fixed and tested; the sixth, at the owner's word, passed
|
||||
- [x] G16 Issue #7: a selection across blocks: drag or Shift-press selects, copy, cut, delete and typing act on it, undo restores; tested
|
||||
- [x] G17 Push, reply on #7 and #12
|
||||
Reference in new issue
Block a user