Merge remote-tracking branch 'origin/develop' into develop

This commit is contained in:
Andrey Antukh 2026-11-24 13:12:23 +01:00
commit 495df7ef66
11 changed files with 442 additions and 25 deletions

View File

@ -11,6 +11,7 @@
## Application and schema validation
- `process-changes` validates the change vector once by default, reduces it and then processes collected touched changes; `verify? false` is for callers that already validated. `:set` delegates to `ctn/set-shape-attr`, while `:assign` decodes attrs before per-attr sets. Component touched and copy rules are in `mem:common/components`.
- `:restore-component` restores only the component record: it removes `:objects` and `:deleted`, optionally updates the main instance page, and takes a variant's `:variant-id` from the existing main shape. `prepare-restore-component` generates separate `:add-obj` changes before it to restore the shape tree. Affected-file validation conservatively selects the referenced page for the restore operation itself.
- `shape-tree/add-shape` falls back invalid parents or frames to root and keeps parent `:shapes` a vector without duplicate IDs. `delete-shape` removes descendants from the objects map as well as unlinking the parent; render-wasm deletion has different undo internals.
- Page-object maps can carry metadata indexes. Rebuild them with `start-page-index` / `update-page-index` as appropriate; frontend commit application calls `ctst/update-object-indices` after page changes.
- `update-file` uses change-scoped schema validation: `touched-page-ids` selects pages while non-page data is checked whole. Register new change types as page-writing or file-level; unknown types fall back to the full schema check, which loads every page. Referential integrity and repair are in `mem:common/components`.

View File

@ -1,6 +1,6 @@
# Shared UI package
- `frontend/packages/ui` builds `@penpot/ui`, a React/Vite library separate from the CLJS Design System. Keep reusable primitives independent of the Penpot app store. React and ReactDOM are peers and must remain external to the library build.
- The Vite build emits ESM and type declarations and copies `dist/ui.css` to `frontend/resources/public/css/ui.css`. If shared styles are stale, check the package build and copy before debugging CLJS.
- The Vite build emits ESM and type declarations; the public `@penpot/ui/style.css` export resolves to `dist/ui.css`, which the build also copies to `frontend/resources/public/css/ui.css`. If shared styles are stale, check the package build and copy before debugging CLJS.
- From `frontend/packages/ui`, use `pnpm run build`, `pnpm run watch` or `pnpm run test`. From `frontend/`, `pnpm run build:app:libs` builds app-side packages; `pnpm run build:storybook`, `watch:storybook` and `test:storybook` cover Storybook. Validate changed exports in both the package and consuming app or Storybook.
- Other packages under `frontend/packages/` are workspace dependencies and need not implement behavior in CLJS. App components and the CLJS Design System are described in `mem:frontend/ui-cljs`; text editing is `mem:frontend/text-editor`.

View File

@ -953,9 +953,8 @@
:mod-page
(conj page-ids id)
;; restore-component resurrects a deleted component (touches the
;; component definition) and places its main instance on a page
;; (touches that page's shape tree)
;; Conservatively validate the referenced page as well as the
;; restored component. Separate add-obj changes restore shapes.
:restore-component
(conj page-ids page-id)

View File

@ -652,7 +652,9 @@
(ctkl/mark-component-deleted component-id)))))
(defn restore-component
"Recover a deleted component and all its shapes and put all this again in place."
"Restore a deleted component record, optionally updating its main instance page.
Remove the stored objects and, for a variant, take its variant id from the
existing main instance shape. This does not restore shapes to the page."
[file-data component-id page-id]
(let [update-page? (not (nil? page-id))
component (ctkl/get-component file-data component-id true)
@ -1382,4 +1384,4 @@
(get (:objects container) %2)))
refs
(:shapes shape)))
{})))
{})))

View File

@ -172,6 +172,20 @@
:child-id child-id
:component-id component-id}))
(t/deftest restore-component-alone-does-not-restore-shapes
(let [{:keys [data page-id main-id child-id component-id]} (make-deleted-component)
deleted (ch/process-changes data [{:type :del-obj :id main-id :page-id page-id}])
restored (ch/process-changes deleted [{:type :restore-component
:id component-id :page-id page-id}])
component (get-in restored [:components component-id])]
(t/is (true? (get-in deleted [:components component-id :deleted])))
(t/is (some? (get-in deleted [:components component-id :objects main-id])))
(t/is (not (contains? component :deleted)))
(t/is (not (contains? component :objects)))
(t/is (= page-id (:main-instance-page component)))
(t/is (nil? (get-in restored [:pages-index page-id :objects main-id])))
(t/is (nil? (get-in restored [:pages-index page-id :objects child-id])))))
(t/deftest update-component-does-not-carry-the-objects-map
(let [{:keys [data component-id]} (make-deleted-component)
changes (pcb/update-component (pcb/with-library-data (pcb/empty-changes nil) data)

View File

@ -471,7 +471,7 @@
page-deleted
(:objects page-deleted))
file' (thf/apply-changes file changes)
file' (thf/apply-changes file-deleted changes)
;; ==== Get
component1' (thc/get-component file' :component1 :include-deleted? false)
@ -483,12 +483,20 @@
saved-objects' (:objects component1')]
;; ==== Check
(t/is (true? (:deleted (thc/get-component file-deleted :component1 :include-deleted? true))))
(t/is (nil? (ths/get-shape file-deleted :main1-root)))
(t/is (nil? (ths/get-shape file-deleted :main1-child)))
(t/is (some? component1'))
(t/is (nil? (:deleted component1')))
(t/is (some? copy1-root'))
(t/is (some? main1-root'))
(t/is (some? main1-child'))
(t/is (ctk/main-instance? main1-root'))
(t/is (ctk/main-instance-of? (:id main1-root') (:id page) component1'))
(t/is (= (:id main1-root') (:parent-id main1-child')))
(t/is (some #{(:id main1-child')} (:shapes main1-root')))
(t/is (some #{(:id main1-root')}
(:shapes (get-in (thf/current-page file') [:objects (:parent-id main1-root')]))))
(t/is (nil? saved-objects'))))
(t/deftest test-instantiate-component

View File

@ -303,15 +303,15 @@ Ensure your development environment docker image is up to date.
**NOTE** You can learn more about how to set up, start and stop our development environment [here](/technical-guide/developer/devenv)
#### Release mode
#### Build the frontend
This is not required, but it may be convenient to compile Penpot in release mode before running the tests. This way they will be much quicker and stable. For this, go to the frontend window in the tmux session (<code class="language-bash">Ctrl + b 1</code>), interrupt the watch process with <code class="language-bash">Ctrl + C</code> and type:
Playwright serves the release bundle from <code class="language-bash">frontend/resources/public</code>, not the live sources. Before running the tests, build the frontend from the frontend window in the tmux session (<code class="language-bash">Ctrl + b 1</code>). Interrupt the watch process with <code class="language-bash">Ctrl + C</code> and run:
```bash
./scripts/build
```
Obviously, in this mode if you make changes to the source code, you will need to repeat the build manually each time. It may be useful to use wath mode when debugging a single test, and use release mode to run all the suite.
Rebuild after product code or asset changes, or after switching to a branch with different sources or assets. Changes only to integration specs do not require a rebuild. Watch mode does not replace the release build for these tests.
### Running the integration tests

View File

@ -16,7 +16,7 @@
"import": "./dist/menu.js",
"types": "./dist/menu.d.ts"
},
"./style.css": "./dist/style.css"
"./style.css": "./dist/ui.css"
},
"scripts": {
"watch": "vite build --watch",

View File

@ -0,0 +1,77 @@
import {
cpSync,
mkdtempSync,
mkdirSync,
readFileSync,
rmSync,
symlinkSync,
} from "node:fs";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { expect, it } from "vitest";
it("exports the built CSS and copies it to the app", () => {
const packageDir = path.resolve(import.meta.dirname, "..");
const frontendDir = path.resolve(packageDir, "../..");
const temporaryDir = mkdtempSync(path.join(os.tmpdir(), "penpot-ui-build-"));
const isolatedFrontend = path.join(temporaryDir, "frontend");
const isolatedPackage = path.join(isolatedFrontend, "packages", "ui");
try {
mkdirSync(isolatedPackage, { recursive: true });
for (const entry of [
"src",
"package.json",
"vite.config.mts",
"tsconfig.json",
"tsconfig.lib.json",
"tsconfig.spec.json",
"tsconfig.storybook.json",
".babelrc",
]) {
cpSync(path.join(packageDir, entry), path.join(isolatedPackage, entry), {
recursive: true,
});
}
symlinkSync(
path.join(packageDir, "node_modules"),
path.join(isolatedPackage, "node_modules"),
);
symlinkSync(
path.join(frontendDir, "node_modules"),
path.join(isolatedFrontend, "node_modules"),
);
symlinkSync(
path.join(frontendDir, "src"),
path.join(isolatedFrontend, "src"),
);
const build = spawnSync(
process.execPath,
[
path.join(frontendDir, "node_modules/vite/bin/vite.js"),
"build",
"--configLoader",
"runner",
],
{ cwd: isolatedPackage, encoding: "utf8" },
);
expect(build.status, `${build.stdout}\n${build.stderr}`).toBe(0);
const resolve = createRequire(
path.join(isolatedPackage, "package.json"),
).resolve;
const exportedCss = resolve("@penpot/ui/style.css");
const css = readFileSync(exportedCss, "utf8");
const copiedCss = readFileSync(
path.join(isolatedFrontend, "resources/public/css/ui.css"),
"utf8",
);
expect(css.length).toBeGreaterThan(0);
expect(copiedCss).toBe(css);
} finally {
rmSync(temporaryDir, { recursive: true, force: true });
}
}, 120_000);

View File

@ -3,11 +3,11 @@ use crate::{
error::Result,
math::{Point, Rect},
shapes::{
add_text_with_tabs, calculate_text_layout_data, set_paint_fill, vertical_align_offset,
ListMarker, ListStyleType, Paragraph as TextParagraph, ParagraphBuilderGroup,
ParagraphLayout, Stroke, StrokeKind, TextContent, TextDecorationSegment, TextDirection,
LIST_MARKER_CENTER_FACTOR, LIST_MARKER_GAP_FACTOR, LIST_MARKER_MIN_RADIUS,
LIST_MARKER_RADIUS_FACTOR,
add_text_with_tabs, add_trailing_space_anchor, calculate_text_layout_data, set_paint_fill,
vertical_align_offset, ListMarker, ListStyleType, Paragraph as TextParagraph,
ParagraphBuilderGroup, ParagraphLayout, Stroke, StrokeKind, TextContent,
TextDecorationSegment, TextDirection, LIST_MARKER_CENTER_FACTOR, LIST_MARKER_GAP_FACTOR,
LIST_MARKER_MIN_RADIUS, LIST_MARKER_RADIUS_FACTOR,
},
utils::{get_fallback_fonts, get_font_collection},
};
@ -29,8 +29,9 @@ pub fn stroke_paragraph_builder_group_from_text(
let mut paragraph_group = Vec::new();
let remove_stroke_alpha = use_shadow.unwrap_or(false) && !stroke.is_transparent();
let mut group_layer_opacity: Option<f32> = None;
let anchors = text_content.trailing_space_anchors();
for paragraph in text_content.paragraphs() {
for (index, paragraph) in text_content.paragraphs().iter().enumerate() {
let mut stroke_paragraphs_map: std::collections::HashMap<usize, ParagraphBuilder> =
std::collections::HashMap::new();
@ -62,9 +63,14 @@ pub fn stroke_paragraph_builder_group_from_text(
}
}
let stroke_paragraphs: Vec<ParagraphBuilder> = (0..stroke_paragraphs_map.len())
let mut stroke_paragraphs: Vec<ParagraphBuilder> = (0..stroke_paragraphs_map.len())
.filter_map(|i| stroke_paragraphs_map.remove(&i))
.collect();
if anchors.get(index).copied().unwrap_or(false) {
stroke_paragraphs
.iter_mut()
.for_each(add_trailing_space_anchor);
}
paragraph_group.push(stroke_paragraphs);
}

View File

@ -21,7 +21,7 @@ use skia_safe::{
};
use std::borrow::Cow;
use std::cell::Cell;
use std::cell::{Cell, RefCell};
use std::collections::HashSet;
use std::rc::Rc;
use unicode_segmentation::UnicodeSegmentation;
@ -90,9 +90,8 @@ pub struct TextContentSize {
const DEFAULT_TEXT_CONTENT_SIZE: f32 = 0.01;
/// Matches `marginRight: "1px"` on `.paragraph-set` in the HTML text renderer
/// (`frontend/src/app/main/ui/shapes/text/styles.cljs`). DOM `getBoundingClientRect`
/// includes that margin in auto-width measurements; Skia `longest_line()` does not.
/// The 1px `marginRight` of `.paragraph-set` (frontend `shapes/text/styles.cljs`), which DOM
/// auto-width measurements include and Skia `max_intrinsic_width()` does not.
const PARAGRAPH_SET_MARGIN_RIGHT: f32 = 1.0;
impl TextContentSize {
@ -455,6 +454,15 @@ pub struct TextContent {
/// Box size the gradient and image shaders were built for. They are relative
/// to the whole box, so a new size must rebuild them.
layout_paint_size: Option<(f32, f32)>,
trailing_space_anchors: RefCell<Option<TrailingSpaceAnchors>>,
}
/// Which paragraphs get a trailing space anchor, for one content version and width.
#[derive(Debug, Clone)]
struct TrailingSpaceAnchors {
content_version: u64,
width: f32,
anchored: Rc<Vec<bool>>,
}
impl PartialEq for TextContent {
@ -480,6 +488,7 @@ impl TextContent {
layout_width: None,
layout_paint_origin: None,
layout_paint_size: None,
trailing_space_anchors: RefCell::new(None),
}
}
@ -497,6 +506,7 @@ impl TextContent {
layout_width: None,
layout_paint_origin: None,
layout_paint_size: None,
trailing_space_anchors: RefCell::new(None),
}
}
@ -648,6 +658,16 @@ impl TextContent {
max_y = max_y.max(line_baseline + line.descent as f32);
min_x = min_x.min(x + line.left as f32);
max_x = max_x.max(x + line.left as f32 + line.width as f32);
// line.width drops trailing spaces, which some fonts paint.
for text_box in paragraph.get_rects_for_range(
line.start_index..line.end_index,
RectHeightStyle::Tight,
RectWidthStyle::Tight,
) {
min_x = min_x.min(x + text_box.rect.left);
max_x = max_x.max(x + text_box.rect.right);
}
has_lines = true;
}
y_accum += paragraph.height();
@ -971,9 +991,10 @@ impl TextContent {
) -> Vec<ParagraphBuilderGroup> {
let fonts = get_font_collection();
let fallback_fonts = get_fallback_fonts();
let anchors = self.trailing_space_anchors();
let mut paragraph_group = Vec::new();
for paragraph in self.paragraphs() {
for (index, paragraph) in self.paragraphs().iter().enumerate() {
let mut paragraph_style = paragraph.paragraph_to_style();
if let Some(align) = align_override {
paragraph_style.set_text_align(align);
@ -1048,15 +1069,81 @@ impl TextContent {
if !has_text {
builder.add_text(" ");
}
if anchors.get(index).copied().unwrap_or(false) {
add_trailing_space_anchor(&mut builder);
}
paragraph_group.push(vec![builder]);
}
paragraph_group
}
/// Per paragraph, whether its builders end with [`add_trailing_space_anchor`].
///
/// Only paragraphs ending in whitespace get one, unless the anchor would wrap onto a
/// line of its own, which would add an empty line.
pub fn trailing_space_anchors(&self) -> Rc<Vec<bool>> {
let width = if self.grow_type() == GrowType::AutoWidth {
f32::MAX
} else {
self.bounds.width()
};
if let Some(cached) = self.trailing_space_anchors.borrow().as_ref() {
if cached.content_version == self.content_version
&& cached.width == width
&& cached.anchored.len() == self.paragraphs.len()
{
return Rc::clone(&cached.anchored);
}
}
let anchored: Rc<Vec<bool>> = Rc::new(
self.paragraphs
.iter()
.map(|paragraph| {
ends_with_trailing_space(paragraph)
&& (width == f32::MAX || self.anchor_shares_last_line(paragraph, width))
})
.collect(),
);
*self.trailing_space_anchors.borrow_mut() = Some(TrailingSpaceAnchors {
content_version: self.content_version,
width,
anchored: Rc::clone(&anchored),
});
anchored
}
/// Whether an anchored `paragraph` laid out at `width` keeps the anchor next to text.
fn anchor_shares_last_line(&self, paragraph: &Paragraph, width: f32) -> bool {
let fallback_fonts = get_fallback_fonts();
let mut builder =
ParagraphBuilder::new(&paragraph.paragraph_to_style(), get_font_collection());
let mut text_len = 0;
for span in paragraph.children() {
let style = span.to_style(
&self.bounds(),
fallback_fonts,
false,
paragraph.line_height(),
);
let text = span.apply_text_transform();
text_len += text.encode_utf16().count();
builder.push_style(&style);
add_text_with_tabs(&mut builder, &text, span.font_size);
}
add_trailing_space_anchor(&mut builder);
let mut probe = builder.build();
probe.layout(width);
probe
.get_line_metrics()
.last()
.is_some_and(|line| line.start_index < text_len)
}
/// Performs an Auto Width text layout.
fn text_layout_auto_width(&self) -> TextContentLayoutResult {
// Left-aligned MAX-width pass: longest_line() is glyph width, not the huge container.
// Left-aligned MAX-width pass. max_intrinsic_width() keeps trailing spaces;
// longest_line() drops them.
let mut measure_builders = self.paragraph_builders(
None,
false,
@ -1076,7 +1163,7 @@ impl TextContent {
.iter()
.flatten()
.fold(0.0_f32, |auto_width, paragraph| {
f32::max(paragraph.longest_line(), auto_width)
f32::max(paragraph.max_intrinsic_width(), auto_width)
})
.ceil();
@ -1442,6 +1529,7 @@ impl Default for TextContent {
layout_width: None,
layout_paint_origin: None,
layout_paint_size: None,
trailing_space_anchors: RefCell::new(None),
}
}
}
@ -1680,6 +1768,31 @@ fn capitalize_words(text: &str) -> String {
}
/// Add `text`, pushing every '\t' as a one em wide placeholder.
/// Ends a paragraph with a zero-size placeholder, so Skia doesn't trim the spaces before it
/// and measures and paints them.
pub fn add_trailing_space_anchor(builder: &mut ParagraphBuilder) {
builder.add_placeholder(&PlaceholderStyle::new(
0.0,
0.0,
PlaceholderAlignment::Baseline,
TextBaseline::Alphabetic,
0.0,
));
}
fn ends_with_trailing_space(paragraph: &Paragraph) -> bool {
paragraph
.children()
.iter()
.rev()
.map(|span| span.apply_text_transform())
.find(|text| !text.is_empty())
.and_then(|text| text.chars().last())
.is_some_and(|ch| {
ch.is_whitespace() && !matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')
})
}
pub fn add_text_with_tabs(builder: &mut ParagraphBuilder, text: &str, font_size: f32) {
let tab = PlaceholderStyle::new(
font_size,
@ -2731,4 +2844,201 @@ mod tests {
layout.clear();
assert!(layout.needs_update());
}
/// A laid-out 200x100 text at the origin with one paragraph of `text`.
fn plain_text_shape(grow_type: GrowType, text: &str) -> Shape {
let mut content = TextContent::new(Rect::from_xywh(0.0, 0.0, 200.0, 100.0), grow_type);
content.add_paragraph(test_paragraph(&[text]));
let mut shape = Shape::new(Uuid::nil());
shape.set_shape_type(shapes::Type::Text(content));
shape.set_selrect(0.0, 0.0, 200.0, 100.0);
shape
}
fn auto_width_of(text: &str) -> f32 {
let mut content =
TextContent::new(Rect::from_xywh(0.0, 0.0, 200.0, 100.0), GrowType::AutoWidth);
content.add_paragraph(test_paragraph(&[text]));
content
.update_layout(Rect::from_xywh(0.0, 0.0, 200.0, 100.0))
.width
}
#[test]
fn auto_width_includes_trailing_spaces() {
let mut resources = RenderResources::try_new_headless().expect("headless resources");
let _guard = TestRenderResourcesGuard::install(&mut resources);
let trimmed = auto_width_of("hello");
let with_spaces = auto_width_of("hello ");
assert!(
with_spaces > trimmed + 3.0,
"trimmed: {trimmed}, with spaces: {with_spaces}"
);
}
#[test]
fn auto_width_counts_leading_and_trailing_spaces_alike() {
let mut resources = RenderResources::try_new_headless().expect("headless resources");
let _guard = TestRenderResourcesGuard::install(&mut resources);
let leading = auto_width_of(" hello");
let trailing = auto_width_of("hello ");
assert!(
(leading - trailing).abs() < 1.0,
"leading: {leading}, trailing: {trailing}"
);
}
#[test]
fn extrect_includes_trailing_spaces() {
let mut resources = RenderResources::try_new_headless().expect("headless resources");
let _guard = TestRenderResourcesGuard::install(&mut resources);
for grow_type in [GrowType::Fixed, GrowType::AutoHeight] {
let trimmed = text_extrect(&plain_text_shape(grow_type, "hello"));
let with_spaces = text_extrect(&plain_text_shape(grow_type, "hello "));
assert!(
with_spaces.right() > trimmed.right() + 3.0,
"{grow_type:?}: trimmed {trimmed:?}, with spaces {with_spaces:?}"
);
}
}
/// A laid-out fixed or auto-height text, `width` wide, with one paragraph of `text`.
fn laid_out_content(grow_type: GrowType, text: &str, width: f32) -> TextContent {
let selrect = Rect::from_xywh(0.0, 0.0, width, 100.0);
let mut content = TextContent::new(selrect, grow_type);
content.add_paragraph(test_paragraph(&[text]));
content.update_layout(selrect);
content
}
/// Glyphs Skia paints for each paragraph of `builders` laid out at `width`.
fn painted_glyphs(builders: &mut [ParagraphBuilderGroup], width: f32) -> Vec<usize> {
build_paragraphs_from_paragraph_builders(builders, width)
.into_iter()
.flatten()
.map(|mut paragraph| {
let mut count = 0;
paragraph.visit(|_, info| {
if let Some(info) = info {
count += info.count();
}
});
count
})
.collect()
}
fn hello_width() -> f32 {
let content = laid_out_content(GrowType::AutoWidth, "hello", 200.0);
content.size.width
}
#[test]
fn trailing_spaces_are_painted() {
let mut resources = RenderResources::try_new_headless().expect("headless resources");
let _guard = TestRenderResourcesGuard::install(&mut resources);
for grow_type in [GrowType::Fixed, GrowType::AutoHeight, GrowType::AutoWidth] {
let content = laid_out_content(grow_type, "hello ", 200.0);
let mut builders = content.paragraph_builder_group_from_text(None);
let width = content.get_width(200.0);
assert_eq!(
painted_glyphs(&mut builders, width),
vec![8],
"{grow_type:?}"
);
}
}
#[test]
fn trailing_spaces_are_painted_by_strokes() {
let mut resources = RenderResources::try_new_headless().expect("headless resources");
let _guard = TestRenderResourcesGuard::install(&mut resources);
let content = laid_out_content(GrowType::Fixed, "hello ", 200.0);
let mut stroke = shapes::Stroke::new_center_stroke(
1.0,
shapes::StrokeStyle::Solid,
None,
None,
None,
None,
);
stroke.fill = solid_fill();
let (mut builders, _) = crate::render::text::stroke_paragraph_builder_group_from_text(
&content,
&stroke,
&content.bounds(),
None,
);
assert_eq!(painted_glyphs(&mut builders, 200.0), vec![8]);
}
#[test]
fn a_paragraph_of_only_spaces_is_painted() {
let mut resources = RenderResources::try_new_headless().expect("headless resources");
let _guard = TestRenderResourcesGuard::install(&mut resources);
let content = laid_out_content(GrowType::Fixed, " ", 200.0);
let mut builders = content.paragraph_builder_group_from_text(None);
assert_eq!(painted_glyphs(&mut builders, 200.0), vec![3]);
}
#[test]
fn only_paragraphs_ending_in_whitespace_get_an_anchor() {
let mut resources = RenderResources::try_new_headless().expect("headless resources");
let _guard = TestRenderResourcesGuard::install(&mut resources);
let selrect = Rect::from_xywh(0.0, 0.0, 200.0, 100.0);
let mut content = TextContent::new(selrect, GrowType::Fixed);
for text in ["hello ", " hello", "", "hello\t"] {
content.add_paragraph(test_paragraph(&[text]));
}
content.update_layout(selrect);
assert_eq!(
*content.trailing_space_anchors(),
vec![true, false, false, true]
);
}
#[test]
fn no_anchor_when_it_would_wrap_onto_its_own_line() {
let mut resources = RenderResources::try_new_headless().expect("headless resources");
let _guard = TestRenderResourcesGuard::install(&mut resources);
let width = hello_width();
for grow_type in [GrowType::Fixed, GrowType::AutoHeight] {
let trimmed = laid_out_content(grow_type, "hello", width);
let content = laid_out_content(grow_type, "hello ", width);
assert_eq!(
*content.trailing_space_anchors(),
vec![false],
"{grow_type:?}"
);
assert_eq!(content.size.height, trimmed.size.height, "{grow_type:?}");
}
}
#[test]
fn trailing_space_anchor_keeps_the_height() {
let mut resources = RenderResources::try_new_headless().expect("headless resources");
let _guard = TestRenderResourcesGuard::install(&mut resources);
for grow_type in [GrowType::Fixed, GrowType::AutoHeight, GrowType::AutoWidth] {
let trimmed = laid_out_content(grow_type, "hello", 200.0);
let content = laid_out_content(grow_type, "hello ", 200.0);
assert_eq!(
*content.trailing_space_anchors(),
vec![true],
"{grow_type:?}"
);
assert_eq!(content.size.height, trimmed.size.height, "{grow_type:?}");
}
}
#[test]
fn caret_past_a_trailing_space_anchor_stays_at_the_text_end() {
let mut resources = RenderResources::try_new_headless().expect("headless resources");
let _guard = TestRenderResourcesGuard::install(&mut resources);
let content = laid_out_content(GrowType::Fixed, "hello ", 200.0);
let position = content
.get_caret_position_from_shape_coords(&Point::new(190.0, 5.0))
.expect("caret position");
assert_eq!(position.offset, 8);
}
}