Skip to content

Conversation

@javier-godoy
Copy link
Member

@javier-godoy javier-godoy commented Sep 15, 2025

Close #134

Summary by CodeRabbit

  • New Features

    • Added runtime column reordering support so columns can be reordered programmatically.
  • Bug Fixes

    • Improved header/footer styling to follow columns correctly after reordering.
    • Strengthened validation and error handling when selecting header/footer cells.
  • Tests

    • Added integration test verifying header cell reuse and style persistence across column reordering.

@coderabbitai
Copy link

coderabbitai bot commented Sep 15, 2025

Walkthrough

Adds reflection-based mapping from a header/footer grid cell to its owning column and uses that mapping to correctly compute column indexes (handling joined cells). Adds test API to reorder columns and an integration test verifying header cell reuse and class mutations after column reordering.

Changes

Cohort / File(s) Change summary
Core helper: cell→column mapping & selector refactor
src/main/java/com/flowingcode/vaadin/addons/gridhelpers/HeaderFooterStylesHelper.java
Introduces reflection to obtain a cell's column, caches the mapped column on CellSelector, replaces direct cell comparisons with column identity comparisons, updates getColumnIndex to count visible columns by column identity, adds static reflective resolution, @SneakyThrows usage and null checks, and refactors HeaderCellSelector/FooterCellSelector constructors/fields.
Test API: column reordering support
src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesCallables.java, src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesView.java
Adds void setColumnOrder(int... columnIndexes) to the public test callable interface and implements it in the view by mapping indices to grid.getColumns() and calling grid.setColumnOrder(...); also assigns keys to created columns.
Integration test: header cell mutability
src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesIT.java
Adds testHeaderCellMutability() which reorders columns via the new API, mutates HeaderCellWrapper instances, and asserts expected classes are present at the new header positions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • mlopezFC
  • paodb

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "fix: track columns instead of cells" is concise and directly describes the primary change in the changeset—shifting identity tracking from cells to columns in HeaderFooterStylesHelper and related selectors—so it clearly signals a targeted bugfix to reviewers.
Linked Issues Check ✅ Passed The PR implements a reflective mapping from a cell to its column and rewrites getColumnIndex to compare column identities rather than cell instances, which directly addresses issue #134's requirement to account for joined cells when computing column indexes; additionally the PR adds integration test changes to exercise header cell reuse and column reordering that validate the behavior. Based on the provided summaries, the code changes and new tests satisfy the linked issue's objective of producing correct column indexes for joined cells.
Out of Scope Changes Check ✅ Passed The modifications are focused on HeaderFooterStylesHelper and related selectors plus supporting test changes; there are no production public API signature changes outside test sources and the added test-only method is confined to test code, so I do not observe unrelated or extraneous changes outside the stated objective.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-134-2

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (6)
src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesCallables.java (1)

37-38: Document index base and expected invariants for setColumnOrder

Clarify that indices are zero-based and must be a permutation of current grid.getColumns() to avoid misuse in tests.

src/main/java/com/flowingcode/vaadin/addons/gridhelpers/HeaderFooterStylesHelper.java (4)

155-160: Guard reflection and provide clear failure semantics

When reflection isn’t available, return the cell itself as identity; otherwise, wrap reflective errors into IllegalStateException for debuggability.

-    @SneakyThrows
-    protected final /* AbstractColumn */ Object getColumn(CELL cell) {
-      AbstractCell.cast(cell);
-      Object result = AbstractCell_getColumn.invoke(cell);
-      return AbstractColumn.cast(result);
-    }
+    @SneakyThrows
+    protected final /* AbstractColumn or CELL */ Object getColumn(CELL cell) {
+      if (AbstractCell_getColumn == null) {
+        return cell; // fallback: use cell identity
+      }
+      try {
+        AbstractCell.cast(cell);
+        Object result = AbstractCell_getColumn.invoke(cell);
+        return AbstractColumn.cast(result);
+      } catch (Throwable t) {
+        throw new IllegalStateException("Unable to resolve owning column via reflection", t);
+      }
+    }

170-185: Null‑safety and tiny readability nit

Add a null-check when deriving curr to avoid surprising NPEs if Vaadin internals change. Also, rename variables for clarity.

-      Object curr = getColumn(getCell(row, c));
+      Object curr = Objects.requireNonNull(getColumn(getCell(row, c)), "cell/column identity must not be null");

206-215: Enrich exception message for faster diagnostics

Throw a descriptive message when the HeaderCell doesn’t belong to the grid.

-      throw new IllegalArgumentException();
+      throw new IllegalArgumentException("HeaderCell does not belong to any HeaderRow of this Grid");

230-239: Same as above for FooterCell

Improve the exception message to ease debugging.

-      throw new IllegalArgumentException();
+      throw new IllegalArgumentException("FooterCell does not belong to any FooterRow of this Grid");
src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesView.java (1)

113-119: Validate indices before reordering to prevent obscure failures

Check bounds and uniqueness to fail fast in tests.

   @Override
   public void setColumnOrder(int... columnIndexes) {
-    List<Column<Integer>> columns = grid.getColumns();
-    grid.setColumnOrder(
-        IntStream.of(columnIndexes).mapToObj(columns::get).collect(Collectors.toList()));
+    List<Column<Integer>> columns = grid.getColumns();
+    int size = columns.size();
+    // bounds
+    IntStream.of(columnIndexes).forEach(idx -> {
+      if (idx < 0 || idx >= size) {
+        throw new IllegalArgumentException("Index out of range: " + idx + " (size=" + size + ")");
+      }
+    });
+    // uniqueness and completeness
+    long distinct = IntStream.of(columnIndexes).distinct().count();
+    if (distinct != size) {
+      throw new IllegalArgumentException("Indices must be a permutation of 0.." + (size - 1));
+    }
+    grid.setColumnOrder(IntStream.of(columnIndexes).mapToObj(columns::get).collect(Collectors.toList()));
   }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 63685b7 and f71798d.

📒 Files selected for processing (4)
  • src/main/java/com/flowingcode/vaadin/addons/gridhelpers/HeaderFooterStylesHelper.java (4 hunks)
  • src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesCallables.java (1 hunks)
  • src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesIT.java (2 hunks)
  • src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesView.java (3 hunks)
🔇 Additional comments (4)
src/main/java/com/flowingcode/vaadin/addons/gridhelpers/HeaderFooterStylesHelper.java (2)

148-153: Capturing the owning column once is correct

Caching the identity to anchor the cell across joins/reorders is the right approach.


127-160: Confirm Vaadin Flow versions targeted (keep 24+ fallback)

Root pom.xml declares <vaadin.version> 23.3.15; profile "v23" has 23.3.5 and another profile sets 24.2.6 — repo targets both 23.x and 24.x. Verify that com.vaadin.flow.component.grid.AbstractRow$AbstractCell, com.vaadin.flow.component.grid.AbstractColumn and AbstractCell.getColumn() exist on every supported version; retain the fallback path for Vaadin 24+ if needed.

Applies to: src/main/java/com/flowingcode/vaadin/addons/gridhelpers/HeaderFooterStylesHelper.java lines 127–160 and 170–185.

src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesIT.java (1)

65-77: Good regression coverage for reordering + joined headers

The test captures the bug and validates identity tracking after setColumnOrder. Looks solid.

src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesView.java (1)

54-56: Setting both header and key is a nice touch

This helps with clarity and potential lookups. LGTM.

@javier-godoy javier-godoy marked this pull request as draft September 15, 2025 19:22
@javier-godoy javier-godoy marked this pull request as ready for review September 15, 2025 19:34
@sonarqubecloud
Copy link

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/main/java/com/flowingcode/vaadin/addons/gridhelpers/HeaderFooterStylesHelper.java (1)

127-141: Make reflection init fully non-fatal (catch SecurityException/others and keep working).

A SecurityException (setAccessible) or other linkage errors will currently bubble and fail class init. Fall back cleanly to the cell-identity path on any reflection failure.

Apply this diff:

 private static final Method AbstractCell_getColumn;

 static {
-    Method method = null;
-    try {
-      Class<?> AbstractCell =
-          Class.forName("com.vaadin.flow.component.grid.AbstractRow$AbstractCell");
-      method = AbstractCell.getDeclaredMethod("getColumn");
-      method.setAccessible(true);
-    } catch (ClassNotFoundException | NoSuchMethodException e) {
-      // Will use cell identity; keep field null.
-    }
-
-    AbstractCell_getColumn = method;
+    Method method = null;
+    try {
+      Class<?> abstractCell =
+          Class.forName("com.vaadin.flow.component.grid.AbstractRow$AbstractCell");
+      method = abstractCell.getDeclaredMethod("getColumn");
+      try {
+        method.setAccessible(true);
+      } catch (SecurityException ignore) {
+        // Best-effort; invocation may still work if public.
+      }
+    } catch (Throwable ignore) {
+      // Fallback: use cell identity; keep method null.
+    }
+    AbstractCell_getColumn = method;
 }
🧹 Nitpick comments (2)
src/main/java/com/flowingcode/vaadin/addons/gridhelpers/HeaderFooterStylesHelper.java (2)

39-39: Clean up imports after fallback refactor.

Remove unused imports once resolveColumnOrFallback is in place.

-import java.util.Objects;
-import lombok.SneakyThrows;

Also applies to: 43-43


170-175: Document intentional identity semantics.

Clarify that identity (==) is by design so joined cells/columns are counted once.

       Object last = null;
       Object target = getColumn();
       for (Column<?> c : helper.getGrid().getColumns()) {
         if (c.isVisible()) {
           Object curr = getColumn(getCell(row, c));
+          // Intentional identity check: joined cells/columns reuse the same instance.
           if (curr != last) {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f71798d and 8d4c9ee.

📒 Files selected for processing (4)
  • src/main/java/com/flowingcode/vaadin/addons/gridhelpers/HeaderFooterStylesHelper.java (4 hunks)
  • src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesCallables.java (1 hunks)
  • src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesIT.java (2 hunks)
  • src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesView.java (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesCallables.java
  • src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesView.java
  • src/test/java/com/flowingcode/vaadin/addons/gridhelpers/it/HeaderFooterStylesIT.java
🔇 Additional comments (2)
src/main/java/com/flowingcode/vaadin/addons/gridhelpers/HeaderFooterStylesHelper.java (2)

207-207: Constructor order is fine once fallback is safe.

Calling super(cell) before membership check is OK with the proposed safe fallback; nothing to change here.

If you don’t adopt the fallback change, consider moving super(cell) after the membership check to avoid possible NPE from Objects.requireNonNull when a foreign cell is passed.


231-231: Same note as header path.

Footer path mirrors header; fine with the safe fallback in place.

@javier-godoy javier-godoy marked this pull request as draft September 15, 2025 19:53
@javier-godoy
Copy link
Member Author

@brunoagretti Can you please give it a try in your project?

@brunoagretti brunoagretti marked this pull request as ready for review September 15, 2025 20:33
@brunoagretti
Copy link
Member

@javier-godoy I tried these changes in my project, and they successfully fixed the reported problem in #134 (comment)

@paodb paodb merged commit 9ecf02d into master Sep 16, 2025
5 checks passed
@paodb paodb deleted the fix-134-2 branch September 16, 2025 12:00
@javier-godoy javier-godoy moved this from To Do to Pending release in Flowing Code Addons Sep 16, 2025
@javier-godoy javier-godoy moved this from Pending release to Done in Flowing Code Addons Sep 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

Incorrect column index calculation when cells are joined

4 participants