Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions packages/shared/widget-harness/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# @mendix/widget-harness

Renders real pluggable widgets in a plain browser page, with props backed by a live in-memory data store.
No mxbuild, Mendix runtime, JVM or Docker. It fakes only the pluggable widget API props (`mendix` typings)
and the data behind them; it is not a Mendix client.

## Layout

- `src/store`: framework-agnostic core (no React, no Jest). `DataStore` holds entity objects;
`LiveList` is a `ListValue` source that applies filter conditions, sort order, offset and limit,
total count and `hasMoreItems`, and goes `loading` → `available` after a configurable delay.
- `src/filters/builders.ts`: implementation of `mendix/filters/builders`. `evaluateFilter` runs the trees it builds.
- `src/props/Harness.ts`: live props on top of the store: list attributes, expressions, widgets, actions,
editable values and selections. `harness.version` changes whenever a widget-visible value changes.
- `host/`: Vite page that mounts a scenario and passes the widget fresh props on every change.
- `e2e/`: Playwright tests against the host page.

## Run

```sh
cd packages/shared/widget-harness
pnpm run dev # http://localhost:5199/?scenario=datagrid-basic&delay=50
pnpm exec playwright install chromium # once
pnpm run test:e2e
```

In the page, `window.harness` exposes the harness (`harness.store`, `harness.calls`) and scenario handles,
so tests can change data and check recorded actions.

## Semantics worth knowing

- Attribute ids are the attribute names from the scenario schema.
- String comparisons and `contains`/`starts-with`/`ends-with` are case-insensitive, like XPath in Mendix.
- Empty values sort first in ascending order.
- A store change reloads every `LiveList` (like refresh in client), unless `reloadOnStoreChange: false`.
- Formatting is fixed en-US: numbers via `Big#toString`, booleans as Yes/No, dates as `M/D/YYYY HH:mm`.
81 changes: 81 additions & 0 deletions packages/shared/widget-harness/e2e/datagrid-basic.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { expect, Locator, Page, test } from "@playwright/test";

// Fixture: host/fixtures/people.ts. 30 people, page size 10, ages 20..49 all distinct.
const FIRST_NAME = 2;
const AGE = 4;

class Grid {
readonly root: Locator;
readonly rows: Locator;

constructor(public readonly page: Page) {
this.root = page.locator(".mx-name-datagrid1");
this.rows = this.root.locator(".widget-datagrid-grid-body [role=row]");
}

column(n: number): Locator {
return this.rows.locator(`[role=gridcell]:nth-child(${n})`);
}

header(name: string): Locator {
return this.root.getByRole("button", { name: `sort ${name}` });
}

get pagingStatus(): Locator {
return this.root.locator(".paging-status");
}
}

test.beforeEach(async ({ page }) => {
await page.goto("/?scenario=datagrid-basic");
});

test("renders the first page of rows from the store", async ({ page }) => {
const grid = new Grid(page);
await expect(grid.rows).toHaveCount(10);
await expect(grid.column(FIRST_NAME).first()).toHaveText("Loretta");
await expect(grid.pagingStatus).toHaveText("1 to 10 of 30");
});

test("sorts by a column ascending, then descending", async ({ page }) => {
const grid = new Grid(page);
await grid.header("Age").click();
await expect(grid.column(AGE).first()).toHaveText("20");
await expect(grid.column(AGE).nth(9)).toHaveText("29");

await grid.header("Age").click();
await expect(grid.column(AGE).first()).toHaveText("49");
await expect(grid.column(AGE).nth(9)).toHaveText("40");
});

test("filters rows with the column text filter, case-insensitively", async ({ page }) => {
const grid = new Grid(page);
await grid.root.getByRole("textbox", { name: "filter" }).fill("ADA");

await expect(grid.rows).toHaveCount(3);
await expect(grid.column(FIRST_NAME)).toHaveText(["Ada", "Ada", "Ada"]);
await expect(grid.pagingStatus).toHaveText("1 to 3 of 3");
});

test("pages through the data source", async ({ page }) => {
const grid = new Grid(page);
await grid.root.getByRole("button", { name: "Go to next page" }).click();
await expect(grid.pagingStatus).toHaveText("11 to 20 of 30");
await expect(grid.column(AGE).first()).toHaveText("30");

await grid.root.getByRole("button", { name: "Go to last page" }).click();
await expect(grid.pagingStatus).toHaveText("21 to 30 of 30");
await expect(grid.rows).toHaveCount(10);
});

test("re-renders when the store changes and records row click actions", async ({ page }) => {
const grid = new Grid(page);
await expect(grid.column(FIRST_NAME).first()).toHaveText("Loretta");

await page.evaluate(() => (window as any).harness.harness.store.update("p01", { firstName: "Zed" }));
await expect(grid.column(FIRST_NAME).first()).toHaveText("Zed");

await grid.column(AGE).nth(1).click();
const calls = await page.evaluate(() => (window as any).harness.harness.calls);
expect(calls).toEqual([{ name: "onClickRow", item: "p02" }]);
});
3 changes: 3 additions & 0 deletions packages/shared/widget-harness/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import config from "@mendix/eslint-config-web-widgets/widget-ts.mjs";

export default config;
27 changes: 27 additions & 0 deletions packages/shared/widget-harness/host/fixtures/people.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { InputRecord, Schema } from "../../src/main";

export const peopleSchema: Schema = {
Person: {
attributes: {
firstName: "String",
lastName: "String",
age: "Integer",
active: "Boolean",
color: { type: "Enum", values: { red: "Red", green: "Green", blue: "Blue" } }
}
}
};

const firstNames = ["Loretta", "Chad", "Ada", "Brian", "Cleo", "Dmitri", "Elena", "Farah", "Gus", "Hana"];
const lastNames = ["Moss", "Kent", "Lovelace", "Okafor", "Novak"];
const colors = ["red", "green", "blue"];

/** 30 people; ids "p01".."p30"; ages 20..49 in a shuffled but fixed order. */
export const people: InputRecord[] = Array.from({ length: 30 }, (_, i) => ({
id: `p${String(i + 1).padStart(2, "0")}`,
firstName: firstNames[i % firstNames.length],
lastName: lastNames[i % lastNames.length],
age: 20 + ((i * 7) % 30),
active: i % 2 === 0,
color: colors[i % colors.length]
}));
12 changes: 12 additions & 0 deletions packages/shared/widget-harness/host/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Widget harness</title>
</head>
<body>
<div id="root" class="mx-page"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
30 changes: 30 additions & 0 deletions packages/shared/widget-harness/host/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { ReactElement, useSyncExternalStore } from "react";
import { createRoot } from "react-dom/client";
import { ScenarioFactory, ScenarioInstance } from "./scenario";
import { filters } from "../src/main";
import "./styles.scss";

const scenarios: Record<string, () => Promise<{ default: ScenarioFactory }>> = {
"datagrid-basic": () => import("./scenarios/datagrid-basic")
};

function Host({ instance }: { instance: ScenarioInstance }): ReactElement {
useSyncExternalStore(instance.harness.subscribe, () => instance.harness.version);
return instance.render();
}

async function start(): Promise<void> {
const name = new URLSearchParams(window.location.search).get("scenario") ?? "datagrid-basic";
const load = scenarios[name];
const root = document.getElementById("root")!;
if (!load) {
root.textContent = `Unknown scenario "${name}". Available: ${Object.keys(scenarios).join(", ")}`;
return;
}
const instance = (await load()).default();
Object.assign(window, { harness: { ...instance.expose, harness: instance.harness, filters } });
// No StrictMode: Datagrid's setup runs once per mount, as in the Mendix client.
createRoot(root).render(<Host instance={instance} />);
}

start();
12 changes: 12 additions & 0 deletions packages/shared/widget-harness/host/scenario.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { ReactElement } from "react";
import type { Harness } from "../src/props/Harness";

export interface ScenarioInstance {
harness: Harness;
/** Called on every harness change; must read live values so the widget gets fresh props. */
render(): ReactElement;
/** Extra handles exposed on `window.harness` for tests. */
expose?: Record<string, unknown>;
}

export type ScenarioFactory = () => ScenarioInstance;
103 changes: 103 additions & 0 deletions packages/shared/widget-harness/host/scenarios/datagrid-basic.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import DatagridTextFilter from "@mendix/datagrid-text-filter-web/src/DatagridTextFilter";
import Datagrid from "@mendix/datagrid-web/src/Datagrid";
import type { ColumnsType, DatagridContainerProps } from "@mendix/datagrid-web/typings/DatagridProps";
import { dynamic, Harness } from "../../src/main";
import { people, peopleSchema } from "../fixtures/people";
import { ScenarioFactory } from "../scenario";

const delay = Number(new URLSearchParams(window.location.search).get("delay") ?? 50);

const create: ScenarioFactory = () => {
const harness = new Harness(peopleSchema, { Person: people });
const datasource = harness.list({ entity: "Person", delay });
const selection = harness.selectionMulti();
const onClick = harness.listAction("onClickRow");

function column(attr: string, header: string, extra: Partial<ColumnsType> = {}): ColumnsType {
return {
showContentAs: "attribute",
attribute: harness.listAttribute("Person", attr),
header: dynamic(header),
visible: dynamic(true),
exportType: "default",
sortable: true,
resizable: true,
draggable: false,
hidable: "yes",
allowEventPropagation: true,
width: "autoFill",
size: 1,
minWidth: "auto",
minWidthLimit: 100,
alignment: "left",
wrapText: false,
...extra
};
}

function props(): DatagridContainerProps {
return {
name: "datagrid1",
// The Mendix client passes the mx-name class through `class`.
class: "mx-name-datagrid1",
datasource: datasource.value,
refreshInterval: 0,
columns: [
column("firstName", "First name", {
filter: (
<DatagridTextFilter
name="textFilter1"
class="mx-name-textFilter1"
attrChoice="auto"
attributes={[]}
defaultFilter="contains"
adjustable
delay={100}
placeholder={dynamic("Search")}
/>
)
}),
column("lastName", "Last name"),
column("age", "Age"),
column("color", "Color")
],
columnsFilterable: true,
onClickTrigger: "single",
onClick,
itemSelection: selection.value,
itemSelectionMethod: "checkbox",
autoSelect: false,
itemSelectionMode: "toggle",
showSelectAllToggle: true,
enableSelectAll: false,
keepSelection: false,
selectionCounterPosition: "bottom",
loadingType: "spinner",
refreshIndicator: false,
pageSize: 10,
pagination: "buttons",
useCustomPagination: false,
showPagingButtons: "always",
showNumberOfRows: true,
pagingPosition: "bottom",
showEmptyPlaceholder: "none",
columnsSortable: true,
columnsResizable: true,
columnsDraggable: false,
columnsHidable: true,
configurationStorageType: "localStorage",
storeFiltersInPersonalization: false,
selectAllText: dynamic("Select all"),
selectAllTemplate: dynamic("Select all %d rows"),
allSelectedText: dynamic("All %d rows selected")
};
}

return {
harness,
render: () => <Datagrid {...props()} />,
expose: { datasource, selection }
};
};

export default create;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {};
11 changes: 11 additions & 0 deletions packages/shared/widget-harness/host/shims/mendix.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// The real `mendix` package only ships typings; const enums from it are inlined by tsc but not by esbuild.
export const ValueStatus = {
Available: "available",
Unavailable: "unavailable",
Loading: "loading"
} as const;

export const FormatterType = {
Number: "number",
DateTime: "datetime"
} as const;
12 changes: 12 additions & 0 deletions packages/shared/widget-harness/host/styles.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
@import "../../../modules/data-widgets/src/themesource/datawidgets/web/variables";
@import "../../../modules/data-widgets/src/themesource/datawidgets/web/pagination-bar";
@import "../../../modules/data-widgets/src/themesource/datawidgets/web/datagrid";
@import "../../../modules/data-widgets/src/themesource/datawidgets/web/datagrid-filters";
@import "../../../modules/data-widgets/src/themesource/datawidgets/web/datagrid-dropdown-filter";
@import "../../../modules/data-widgets/src/themesource/datawidgets/web/refresh-indicator";
@import "../../../modules/data-widgets/src/themesource/datawidgets/web/three-state-checkbox";

body {
font-family: sans-serif;
margin: 16px;
}
29 changes: 29 additions & 0 deletions packages/shared/widget-harness/host/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";

const here = (path: string): string => fileURLToPath(new URL(path, import.meta.url));
const repoRoot = here("../../../../");

export default defineConfig({
root: here("."),
resolve: {
alias: [
{ find: /^mendix$/, replacement: here("./shims/mendix.ts") },
{ find: /^mendix\/filters\/builders$/, replacement: here("../src/filters/builders.ts") },
{ find: /^mendix\/filters$/, replacement: here("./shims/mendix-filters.ts") },
// Workspace libraries are consumed from source so the harness needs no prior build.
{
find: /^@mendix\/(widget-plugin-[a-z-]+|filter-commons)\/(.*)$/,
replacement: `${repoRoot}packages/shared/$1/src/$2`
},
{ find: /^big\.js$/, replacement: here("../node_modules/big.js/big.mjs") }
],
dedupe: ["react", "react-dom", "mobx", "mobx-react-lite"]
},
server: {
port: 5199,
strictPort: true,
fs: { allow: [repoRoot] }
},
css: { preprocessorOptions: { scss: { quietDeps: true, silenceDeprecations: ["import", "global-builtin"] } } }
});
Loading
Loading