fast icon indicating copy to clipboard operation
fast copied to clipboard

Corrupted DOM View Ordering in `RepeatBehavior.prototype.updateSortedViews` for 10+ items due to default alphabetical sort

Open codeCraft-Ritik opened this issue 1 month ago • 0 comments


🐛 Bug Report

When an observable array containing 10 or more elements is sorted or reversed, RepeatBehavior.prototype.updateSortedViews renders DOM views in an incorrect, corrupted order because it uses JavaScript's default lexicographical .sort() on an index array.

💻 Repro or Code Sample

import { customElement, FASTElement, html, observable, repeat } from "@microsoft/fast-element";

const template = html<MyList>`
    <ul>
        ${repeat(x => x.items, html<number>`<li id="item-${x}">${x}</li>`)}
    </ul>
`;

@customElement({ name: "my-list", template })
export class MyList extends FASTElement {
    @observable items: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // 11 items

    reverseItems() {
        // Reverse array in place (triggers observer.addSort)
        this.items.reverse();
    }
}

// In the DOM:
const el = document.createElement("my-list") as MyList;
document.body.appendChild(el);

// Trigger reversal
el.reverseItems();

// Inspect rendered DOM nodes:
const renderedText = Array.from(el.shadowRoot!.querySelectorAll("li")).map(li => li.textContent);
console.log("Rendered DOM Order:", renderedText);

🤔 Expected Behavior

After calling this.items.reverse(), the list in the DOM should reflect the exact order of this.items:

["10", "9", "8", "7", "6", "5", "4", "3", "2", "1", "0"]

😯 Current Behavior

The DOM nodes are rendered in corrupted order with element 2 incorrectly moved to the head of the list:

["2", "10", "9", "8", "7", "6", "5", "4", "3", "1", "0"]

Root Cause Analysis

In packages/fast-element/src/templating/repeat.ts, lines 243–268 define updateSortedViews:

private updateSortedViews(sorts: Sort[]): void {
    const views = this.views;

    for (let i = 0, ii = sorts.length; i < ii; ++i) {
        const sortedItems = sorts[i].sorted!.slice();
        const unsortedItems = sortedItems.slice().sort(); // <--- Line 248: BUG

        for (let j = 0, jj = sortedItems.length; j < jj; ++j) {
            const sortedIndex: number = sortedItems.find(
                value => sortedItems[j] === unsortedItems[value], // <--- Line 251: BUG
            ) as number;

            if (sortedIndex !== j) {
                const removedItems = unsortedItems.splice(sortedIndex, 1);
                unsortedItems.splice(j, 0, ...removedItems);
                const neighbor = views[j];
                const location = neighbor ? neighbor.firstChild : this.location;

                views[sortedIndex].remove();
                views[sortedIndex].insertBefore(location);
                const removedViews = views.splice(sortedIndex, 1);
                views.splice(j, 0, ...removedViews);
            }
        }
    }
}

Two bugs interact to corrupt view ordering:

  1. Lexicographical sort on Line 248: sortedItems.slice().sort() calls Array.prototype.sort() without a numeric comparator (a, b) => a - b. In JavaScript, .sort() converts numbers to strings. For 11 elements (0..10), unsortedItems becomes [0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9]. The initial assumption that unsortedItems represents ascending sequential indices 0..N-1 is broken.
  2. Value vs Index Confusion on Line 251: sortedItems.find() returns the matching element value, not its index. Furthermore, the predicate unsortedItems[value] attempts an inverted lookup instead of finding the current location of the view in unsortedItems. The position that needs to be moved from views is simply unsortedItems.indexOf(sortedItems[j]).

💁 Possible Solution

Use indexOf to find the current position of the target item in unsortedItems, and sort unsortedItems numerically:

private updateSortedViews(sorts: Sort[]): void {
    const views = this.views;

    for (let i = 0, ii = sorts.length; i < ii; ++i) {
        const sortedItems = sorts[i].sorted!.slice();
        // Sort numerically, not lexicographically
        const unsortedItems = sortedItems.slice().sort((a, b) => a - b);

        for (let j = 0, jj = sortedItems.length; j < jj; ++j) {
            // Find current index of the target item in the working list
            const sortedIndex = unsortedItems.indexOf(sortedItems[j]);

            if (sortedIndex !== j && sortedIndex !== -1) {
                const removedItems = unsortedItems.splice(sortedIndex, 1);
                unsortedItems.splice(j, 0, ...removedItems);
                const neighbor = views[j];
                const location = neighbor ? neighbor.firstChild : this.location;

                views[sortedIndex].remove();
                views[sortedIndex].insertBefore(location);
                const removedViews = views.splice(sortedIndex, 1);
                views.splice(j, 0, ...removedViews);
            }
        }
    }
}

🔦 Context

Any table, grid, or list component built with FAST that permits user sorting (e.g. clicking a column header to sort ascending/descending) or array reversals on datasets with 10 or more rows produces visual data corruption. The internal model items has one order, while the rendered DOM displays completely different rows at the top.

🌍 Your Environment

  • OS & Device: Windows 11 / macOS / Linux on PC
  • Browser: Microsoft Edge, Google Chrome, Mozilla Firefox, Apple Safari
  • Version: @microsoft/fast-element 1.8.0 / @microsoft/fast 1.8.0

codeCraft-Ritik avatar Oct 12 '26 04:10 codeCraft-Ritik