From 5fafca7665cd973707e19a742d7411768a86835f Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Tue, 24 Nov 2026 11:17:48 +0000 Subject: [PATCH 1/2] :bug: Correct UI CSS export and test restore flow Point the public CSS export to the generated file and test its build. Clarify component restoration and cover the deleted-file path. Update integration test documentation for the release bundle. AI-assisted-by: gpt-6.1-terra --- .serena/memories/common/changes.md | 1 + .serena/memories/frontend/ui-package.md | 2 +- common/src/app/common/files/validate.cljc | 5 +- common/src/app/common/types/file.cljc | 6 +- .../test/common_tests/files_changes_test.cljc | 14 ++++ .../logic/comp_creation_test.cljc | 10 ++- docs/technical-guide/developer/frontend.md | 6 +- frontend/packages/ui/package.json | 2 +- frontend/packages/ui/tests/build-css.test.ts | 77 +++++++++++++++++++ 9 files changed, 112 insertions(+), 11 deletions(-) create mode 100644 frontend/packages/ui/tests/build-css.test.ts diff --git a/.serena/memories/common/changes.md b/.serena/memories/common/changes.md index 5a0b567499..a498bc98a6 100644 --- a/.serena/memories/common/changes.md +++ b/.serena/memories/common/changes.md @@ -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`. diff --git a/.serena/memories/frontend/ui-package.md b/.serena/memories/frontend/ui-package.md index 4bf3bf869a..d9ab9e9e92 100644 --- a/.serena/memories/frontend/ui-package.md +++ b/.serena/memories/frontend/ui-package.md @@ -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`. diff --git a/common/src/app/common/files/validate.cljc b/common/src/app/common/files/validate.cljc index 9c292e6db6..d54e04bd7e 100644 --- a/common/src/app/common/files/validate.cljc +++ b/common/src/app/common/files/validate.cljc @@ -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) diff --git a/common/src/app/common/types/file.cljc b/common/src/app/common/types/file.cljc index 490981fb13..a295da9504 100644 --- a/common/src/app/common/types/file.cljc +++ b/common/src/app/common/types/file.cljc @@ -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))) - {}))) \ No newline at end of file + {}))) diff --git a/common/test/common_tests/files_changes_test.cljc b/common/test/common_tests/files_changes_test.cljc index bd497e72a7..18a07cce7d 100644 --- a/common/test/common_tests/files_changes_test.cljc +++ b/common/test/common_tests/files_changes_test.cljc @@ -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) diff --git a/common/test/common_tests/logic/comp_creation_test.cljc b/common/test/common_tests/logic/comp_creation_test.cljc index eb0fb36d01..6f9147663f 100644 --- a/common/test/common_tests/logic/comp_creation_test.cljc +++ b/common/test/common_tests/logic/comp_creation_test.cljc @@ -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 diff --git a/docs/technical-guide/developer/frontend.md b/docs/technical-guide/developer/frontend.md index 6a28339a8a..7df103655d 100644 --- a/docs/technical-guide/developer/frontend.md +++ b/docs/technical-guide/developer/frontend.md @@ -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 (Ctrl + b 1), interrupt the watch process with Ctrl + C and type: +Playwright serves the release bundle from frontend/resources/public, not the live sources. Before running the tests, build the frontend from the frontend window in the tmux session (Ctrl + b 1). Interrupt the watch process with Ctrl + C 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 diff --git a/frontend/packages/ui/package.json b/frontend/packages/ui/package.json index 64f6f57122..1196f2d440 100644 --- a/frontend/packages/ui/package.json +++ b/frontend/packages/ui/package.json @@ -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", diff --git a/frontend/packages/ui/tests/build-css.test.ts b/frontend/packages/ui/tests/build-css.test.ts new file mode 100644 index 0000000000..cb1b2c7763 --- /dev/null +++ b/frontend/packages/ui/tests/build-css.test.ts @@ -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); From 5aac5ab9bafe8f88e4553c23371fcea25e02d0cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bel=C3=A9n=20Albeza?= Date: Tue, 24 Nov 2026 12:58:25 +0100 Subject: [PATCH 2/2] :bug: Fix not rendering & computing into layout trailing white spaces (#13127) * :bug: Keep trailing spaces in WASM text bounds Skia's longest_line() and line widths leave out the spaces at the end of a line, so auto-width texts lost their trailing spaces in the selrect, and the tight text bounds cut them off too. Fonts that draw a glyph for spaces, like Zilla Slab Highlight, showed the gap. - Measure auto-width text with max_intrinsic_width(), which keeps trailing spaces. - Extend each line's tight bounds with the rects of its whole range, trailing spaces included. Closes #12998 AI-assisted-by: claude-opus-5-5 * :bug: Paint trailing spaces in WASM text Skia lays out the spaces at the end of a line but never paints them. Fonts that draw a glyph for spaces, like Zilla Slab Highlight, lost those glyphs on the WebGL renderer. - End each paragraph that ends in whitespace with a zero-size placeholder. The spaces are no longer trailing, so Skia measures and paints them with the right glyphs and paints. - Add it to the fill and stroke builders alike, so their layouts match. - Leave it out when it would wrap onto a line of its own in a fixed or auto-height box, which would add an empty line. A probe layout per paragraph decides this, cached per content version and box width. Closes #12998 AI-assisted-by: claude-opus-5-5 --- render-wasm/src/render/text.rs | 20 +- render-wasm/src/shapes/text.rs | 324 ++++++++++++++++++++++++++++++++- 2 files changed, 330 insertions(+), 14 deletions(-) diff --git a/render-wasm/src/render/text.rs b/render-wasm/src/render/text.rs index 491eb83248..65cf0f4366 100644 --- a/render-wasm/src/render/text.rs +++ b/render-wasm/src/render/text.rs @@ -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 = 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 = std::collections::HashMap::new(); @@ -62,9 +63,14 @@ pub fn stroke_paragraph_builder_group_from_text( } } - let stroke_paragraphs: Vec = (0..stroke_paragraphs_map.len()) + let mut stroke_paragraphs: Vec = (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); } diff --git a/render-wasm/src/shapes/text.rs b/render-wasm/src/shapes/text.rs index d3a15eb34c..65dbfb63f9 100644 --- a/render-wasm/src/shapes/text.rs +++ b/render-wasm/src/shapes/text.rs @@ -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>, +} + +/// 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>, } 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 { 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> { + 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> = 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(¶graph.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 { + 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); + } }