A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
[model-apps] genpage: document lookup-write trap, hooks-order crash, styling gotchas (#200)
Jason Green620112863368
diff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.mdindex 9fef97445..446904960 100644--- a/plugins/model-apps/agents/genpage-page-builder.md+++ b/plugins/model-apps/agents/genpage-page-builder.md@@ -217,7 +217,8 @@ export default GeneratedComponent;- **Responsive design** — flexbox, relative units, never `100vh`/`100vw`- **WCAG AA accessibility** — ARIA labels, keyboard navigation, semantic HTML- **Error handling** — all async `dataApi` calls wrapped in try-catch-- **Lookup fields** — use `@OData.Community.Display.V1.FormattedValue` for display names+- **Lookup fields** — read display names via `@OData.Community.Display.V1.FormattedValue`; *set* a lookup on create/update with `_<field>_value: "/logicalSingular(guid)"`, never `@odata.bind` (the DataAPI silently drops it → orphaned row). See rules.md DataAPI Rule 13.+- **All hooks above early returns** — every `useMemo`/`useState`/`useEffect`/`useCallback` must precede any loading/empty `return`, or detail pages crash with React error #310 on first open. See rules.md Critical Rule 19.- **Entity logical names** — singular lowercase (e.g., `"account"`)- **No placeholders** — no TODOs, no ellipses, no "implement later" comments- **Top-level functions** — components and utilities as separate top-level functions, no nestingdiff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.mdindex fe8d0398d..ce2782f46 100644--- a/plugins/model-apps/references/rules.md+++ b/plugins/model-apps/references/rules.md@@ -24,6 +24,7 @@ Comprehensive rules for generating generative page code. Read this file during c16. **Overlays must be confined to the page container (`mountNode`)**: The generated page shares the DOM with the genpage *designer* — the preview is NOT an isolated iframe. Every Fluent surface that renders through a portal (`Dialog` via `DialogSurface`, `Popover`, `Menu`, `Tooltip`, `Combobox`/`Dropdown` listbox, `DatePicker`, `TimePicker`) defaults to portalling to `document.body` of the **designer**, so without a `mountNode` it escapes the preview and can cover the designer chrome — including the coding-agent panel. Establish a single `containerRef`/`mountNode` on the page root and thread it to every overlay. See **Special Patterns > Dialogs and Overlays**.17. **No full-viewport modal scrims; prefer non-modal or in-page panels**: A default `<Dialog>` is `modalType="modal"` — it draws a `position: fixed` backdrop and traps focus across the whole window, which in the designer blankets the agent panel and locks the user out (they can't even ask the agent to remove it). Default dialogs to `modalType="non-modal"` **and** pass `mountNode`, or use an in-page absolutely-positioned panel. The page root must establish a containing block (`position: relative` + `contain: layout`) so even a fixed-position overlay is clipped to the page. Never size overlays to the viewport. See **Special Patterns > Dialogs and Overlays**.18. **Never nest a `<Dialog>` inside another `<Dialog>`**: Stacked modal scrims and nested focus traps make dialogs impossible to dismiss reliably. Render sibling dialogs as separate top-level surfaces switched by state, never one `<Dialog>` as a child of another's JSX.+19. **All hooks above every early return — no conditional hook calls**: Detail/record pages crash with **minified React error #310** ("rendered more/fewer hooks than the previous render") on the *first* open of a record, then work on the second click. Cause: a hook — usually a `useMemo` deriving chart points or display rows from loaded data — sits *below* a loading/empty early return (`if (data.loading) return <Spinner/>`). On the first render data is still loading, the component early-returns and never reaches that `useMemo` (fewer hooks); when data arrives it renders past the return and calls the extra hook → the hook count differs between renders → #310. The "works the second time" intermittency (the cached render skips the loading branch) is the signature of this bug. **Fix:** place every `useMemo`/`useState`/`useEffect`/`useCallback` **above all early returns**, and make derived memos tolerate not-yet-loaded data (read from an always-initialized value, e.g. `data.rows ?? []`). Early returns are fine — they just must come *after* the last hook call. This is the React rules of hooks: never call a hook below a conditional `return`.---@@ -389,6 +390,19 @@ import { webDarkTheme, webLightTheme } from "@fluentui/react-components";**Root div scrolling:** The inner `styles.root` div must have `height: "100%"` and `overflowY: "auto"` so the page content is scrollable. The genpage host provides a fixed-height container — if neither the outer nor inner div establishes a scroll context, content below the fold is unreachable.+**Inherited text color does NOT follow the variable override.** `themeToVars` overrides CSS *variables*, but Fluent typography (`Text`, `Title`, `Body`, etc.) mostly **inherits** its `color` from the light-theme FluentProvider root — and inheritance passes the already-resolved value, so flipping `--colorNeutralForeground1` to white does not recolor inherited text (you get near-black text on a dark background, contrast ~1.07, effectively invisible). **Fix:** set `color: tokens.colorNeutralForeground1` on the page root (`styles.root`) so every descendant inherits the variable-resolved foreground. Raw `<button>` elements (e.g. custom "attention" rows) default to black `buttontext` and need an explicit `color` too. Status-color CSS vars (`--colorStatusDangerForeground1`, etc.) *do* resolve in inline styles via the `themeToVars` wrapper, so status tokens work fine.++**Pages opened via `navigateTo` are separate documents — they don't inherit the dashboard's dark mode.** A detail/dialog page reached through `Xrm.Navigation.navigateTo({ pageType: "generative", ... })` mounts fresh with no theme context. Pass the flag through `data` (`data: { darkMode: isDarkMode }`) and, on the target, read it from `pageInput.data` (see **Generative Page Navigation > Receiving navigation state**) and wrap the component in its own `themeToVars` two-div. A thin outer wrapper component is cleanest when the target page has multiple early-returns.++### Styling gotchas (Fluent + Griffel)++Recurring CSS bugs that type-check and compile but render wrong. Check for these before finishing a page:++1. **A bar/progress fill `<span>` with a `width`/`height` % but no `display` is invisible.** A `<span>` defaults to `display: inline`, which ignores width/height → a 0×0 box, so the colored fill never paints (only the track shows — looks like "the color got lost"). Symptom: computed `backgroundColor` is correct but `offsetWidth`/`offsetHeight` is `0`. Fix: add `display: "block"` (or `inline-block`) to the fill — or use a `<div>` for fills.+2. **Concatenated `makeStyles` classes lose status/warning colors to a shorthand-vs-longhand collision.** ``className={`${base} ${warning}`}`` (plain template string, not `mergeClasses`) where `base` sets a shorthand `border:` / `backgroundColor: "transparent"` and `warning` sets the longhand `borderColor` / `backgroundColor` — Griffel's atomic output plus the shorthand-vs-longhand cascade lets the base win, so the amber bg/border/text silently fall back to neutral. Fix: apply the status colors **inline** (`style={{ backgroundColor: tokens.colorStatusWarningBackground1, borderColor: tokens.colorStatusWarningBorder1 }}` — inline wins) or use `mergeClasses` instead of string concatenation.+3. **`tokens.fontFamilyNumeric` is Bahnschrift, not Segoe UI.** Using it for tabular numbers (counts, %, ranks, dates) renders those digits in Bahnschrift — visibly mismatched against Segoe UI everywhere else. Fix: use `tokens.fontFamilyBase` and keep `fontVariantNumeric: "tabular-nums"` for aligned digits.+4. **Gradient hero with white text: `colorPalette*Background2/3` tokens are light tints, not dark.** A gradient built from e.g. `colorPalettePurpleBackground3` / `colorPaletteTealBackground2` with `color: colorNeutralForegroundOnBrand` (white) renders white-on-light → unreadable; those `Background2/3` palette tokens are pale. Fix: build the gradient from the dark, saturated `colorPalette*Foreground2` stops (e.g. `colorPalettePurpleForeground2`, `colorPaletteTealForeground2`), which are dark enough for white text to pass AA.+### Data Caching Across NavigationsThe genpage platform **re-evaluates the module script on every navigation** — including when the user navigates back to a page they've already visited. This means module-level variables (e.g., `let _cache = null`) are reset on each visit, causing the component to re-fetch data and show a loading spinner even on return visits.@@ -499,6 +513,17 @@ select: ["subject", "_regardingobjectid_value"]const name = row["_regardingobjectid_value@OData.Community.Display.V1.FormattedValue"];```+13. **Setting a lookup on create/update — use `_<field>_value`, never `@odata.bind`** - To *write* a lookup via `createRow`/`updateRow`, set the FK key `_<field>_value` to a string of the form `/<entityLogicalNameSingular>(<guid>)` — singular logical name (e.g. `/account(<id>)`, `/systemuser(<id>)`). Clear it with `_<field>_value: null`. The writable row type in RuntimeTypes proves the shape — the FK column is typed as a template literal, e.g. `` _primarycontactid_value: `/contact(${string})` ``. **The trap:** the raw Dataverse Web API binds lookups with `"<PascalCaseNavProp>@odata.bind": "/<entitySetPlural>(<id>)"`. The DataAPI **silently ignores** any `@odata.bind` key (unknown property → dropped, no error) and creates the row **orphaned**, with the lookup null. Symptom: `createRow` resolves with no error, but the row isn't linked, so a child list filtered by that parent stays empty — looks like "the write didn't save." Don't mix the conventions: **DataAPI → `_field_value: "/logicalSingular(id)"`**; `@odata.bind` + `/setPlural(id)` is for raw Web API only.++```typescript+// WRONG — DataAPI silently drops @odata.bind → row created with null lookup (orphaned)+await dataApi.createRow("task", { subject: "Call", "[email protected]": "/accounts(<id>)" });++// CORRECT — set the FK _value to "/logicalSingular(guid)"+await dataApi.createRow("task", { subject: "Call", _regardingobjectid_value: `/account(${accountId})` });+await dataApi.updateRow("task", id, { _regardingobjectid_value: null }); // clear it+```+### DataGrid Requirements- Import `createTableColumn` from Fluent UI V9- Define all columns using `createTableColumn`