diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-17-native-image-editorconfig-switch-hide-list.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-17-native-image-editorconfig-switch-hide-list.json new file mode 100644 index 0000000000..74ecaab410 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-17-native-image-editorconfig-switch-hide-list.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-11-17", "symptom": "every native Image (Native Mobile Resources 12.6.0) mxcli created failed mx check 11.13.0 with CE0463 — its `imageUrl` text template was written with a template where mx update-widgets writes none", "cause": "the Image's editorConfig hides the image-source properties it is not using with hidePropertiesIn(t, v, function(s){switch(s){case \"image\": return L.filter(p => \"imageObject\" !== p); …; default: return L}}(v.datasource)) — a list computed by a switch in an immediately-invoked function, which the extractor could not read, so no rule hid imageUrl under the default source", "file": "mdl/executor/editorconfig_iife_switch.go (iifeSwitchHideRules), mdl/executor/editorconfig_extract.go (extractVisibilityRulesFromJS)", "fix": "read that exact shape — unguarded, at a function's statement level, each case keeping one member of a known string-array constant, default the whole list — as one `notin` rule per member over the cases that keep it; any other shape stays unread", "insight": "diffing the stored widget against a copy run through `mx update-widgets` named the exact property (Object.imageUrl TextTemplate set vs null) — but the Type was identical, so the cause was visibility, not the definition. A CE0463 with a clean Type diff points at editorConfig", "refs": [], "test": "mdl/executor/editorconfig_iife_switch_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-17-native-own-editable-read-as-core.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-17-native-own-editable-read-as-core.json new file mode 100644 index 0000000000..13b899dc73 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-17-native-own-editable-read-as-core.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-11-17", "symptom": "`check` refused `nativeslider s1 (editable: 'default')` with \"`Editable: default` is not an Editable value [MDL-WIDGET19]\" — the form describe prints — so a native page with a slider, range slider, rating or toggle buttons could not be described and re-run", "cause": "those native widgets declare an `editable` enumeration of their own (default | never) and no Editability system property; exec writes `editable:` to that key (the CustomWidget's Editable stays Always), but validateConsumableConditional judged the name as the core Editable", "file": "mdl/executor/validate_widgets.go (validateConsumableConditional), mdl/executor/pluggable_own_core_name.go (defDeclaresOwnKey)", "fix": "skip the core Editable value check when the widget's definition maps an `editable` key of its own; validatePluggableEnumValues judges the value against the package's keys", "insight": "same class as ako/mxcli#2180 (a widget's own key spelled like a core name), but `editable` is deliberately not in pages.coreNamesPluggableKeysShadow because a CustomWidget stores Editable itself — so only check was wrong; exec already wrote the own key. Dumping the stored CustomWidget (Editable: Always) settled which layer to touch", "refs": ["ako/mxcli#2180"], "test": "mdl/executor/native_editable_own_property_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-17-native-widget-described-as-web-keyword.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-17-native-widget-described-as-web-keyword.json new file mode 100644 index 0000000000..619e2f74d5 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-17-native-widget-described-as-web-keyword.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-11-17", "symptom": "with Native Mobile Resources installed, describe printed a native widget left at its defaults under the last segment of its id: `nativegallery`/`nativebadge`/`nativeimage` came out as the web `gallery`/`badge`/`image` (re-run rebuilt the page with the WEB widget, check clean), and `activityindicator`, `backgroundgradient`, `notifications`, `qrcode`, `repeater`, `safeareaview`, `signature` were refused on re-run (MDL-WIDGET25); a native gallery with a data source was described as the web gallery too", "cause": "extractCustomWidgetType's default returned the id's last segment, which routes describe — `gallery`/`image` landed in the web widgets' dedicated branches — and the bare branch (a pluggable widget with no non-default content) printed that segment instead of asking pluggableWidgetHeader, which the generic branch already used", "file": "mdl/executor/cmd_pages_describe_pluggable.go (extractCustomWidgetType), mdl/executor/cmd_pages_describe_output.go (bare custom-widget branch)", "fix": "a last segment naming a dedicated branch is routed as `customwidget`; the bare branch names a widget with no branch of its own through pluggableWidgetHeader (definition keyword where it round-trips, else the id form)", "insight": "#1463 fixed the native/web keyword collision at init and load time but not on the way out: describe had a second, independent name derivation. Probing every widget of a package (39 pages, describe -> check -> exec) found it in minutes where the one-widget repro hid it: only widgets left at their defaults took the bare branch, so a widget with any setting described correctly", "refs": [], "test": "mdl/executor/describe_native_widget_keyword_test.go"} diff --git a/.claude/skills/fix-issue/findings/modelsdk/2026-11-17-generated-widget-type-allowupload-onchange-caption.json b/.claude/skills/fix-issue/findings/modelsdk/2026-11-17-generated-widget-type-allowupload-onchange-caption.json new file mode 100644 index 0000000000..611ed05165 --- /dev/null +++ b/.claude/skills/fix-issue/findings/modelsdk/2026-11-17-generated-widget-type-allowupload-onchange-caption.json @@ -0,0 +1 @@ +{"area": "modelsdk", "date": "2026-11-17", "symptom": "native Signature, Bottom sheet and Maps (Native Mobile Resources 12.6.0) created by mxcli failed mx check 11.13.0 with CE0463 on every instance", "cause": "the definition generated from the .mpk differed from mx update-widgets in three attributes: AllowUpload false where the image property declares allowUpload=\"true\" (not parsed at all); OnChangeProperty \"\" where the attribute declares onChange (parsed, but createDefaultValueType hard-coded \"\"); an enumeration caption trimmed where Mendix stores the element text verbatim, trailing newline and indentation included", "file": "modelsdk/widgets/mpk/mpk.go (AllowUpload, EnumValue.RawCaption), modelsdk/widgets/augment.go (createDefaultValueType, buildEnumValuesArray, syncDefinitionAttrs)", "fix": "parse allowUpload; write p.AllowUpload and p.OnChange into the generated ValueType and sync AllowUpload onto augmented templates; keep the raw caption beside the trimmed one and write the raw one", "insight": "mx check runs on macOS through Docker: debian:bookworm-slim plus libicu72, libuuid1, libfreetype6, fontconfig, with LD_PRELOAD of libuuid.so.1 and libfreetype.so.6 (libSkiaSharp does not link uuid). A baseline mx check of the untouched fixture is what separates the 4 new CE0463 from the 105 the fixture already had", "refs": [], "test": "modelsdk/widgets/native_definition_attrs_test.go, modelsdk/widgets/mpk/native_attrs_test.go"} diff --git a/.claude/skills/mendix/custom-widgets/SKILL.md b/.claude/skills/mendix/custom-widgets/SKILL.md index 08efda6fb0..72a4e17a52 100644 --- a/.claude/skills/mendix/custom-widgets/SKILL.md +++ b/.claude/skills/mendix/custom-widgets/SKILL.md @@ -146,7 +146,7 @@ If a widget you have installed is not found, extract its definition: mxcli widget init -p app.mpr ``` -The keyword is the widget id's last segment; a **native** widget (`com.mendix.widget.native.*`) is prefixed `native` (`nativeimage`, `nativebadge`). +The keyword is the widget id's last segment; a **native** widget (`com.mendix.widget.native.*`) is prefixed `native` (`nativeimage`, `nativebadge`). Native widgets' required settings, platform, slots and own `editable`: [reference/native-widgets.md](reference/native-widgets.md). A project definition never takes a built-in keyword (`image`, `radiobuttons`, …) for another widget id: it warns and stays `pluggablewidget ''`; delete a stale native `image.def.json` / `radiobuttons.def.json` and re-run `widget init` (mendixlabs/mxcli#1463). ## Built-in Pluggable Widgets diff --git a/.claude/skills/mendix/custom-widgets/reference/native-widgets.md b/.claude/skills/mendix/custom-widgets/reference/native-widgets.md new file mode 100644 index 0000000000..3410986086 --- /dev/null +++ b/.claude/skills/mendix/custom-widgets/reference/native-widgets.md @@ -0,0 +1,17 @@ +# Native mobile widgets + +Supporting reference for [custom-widgets](../SKILL.md). + +The 39 widgets of Native Mobile Resources (`nativegallery`, `nativeslider`, `nativebottomsheet`, `nativebarchart`, …) need no template in mxcli. After `widget init`, each one is built from the project's own `.mpk` file. + +- **Set what the widget requires.** `check` warns (MDL-WIDGET56) about each required setting left out: a gallery's data source, a slider's attribute, a repeater's `template { … }` content, a chart's series. mxbuild fails the build on each with CE0642. +- **Use them on native pages only.** `check` warns (MDL-WIDGET55) about a native widget on a web page, and about a web widget (`combobox`, `datagrid`, `image`, …) on a native page. +- **Slot names come from the definition.** A native gallery's item slot is `template { … }`, not `content`; `check` lists a widget's slots when one is wrong (MDL-WIDGET26). +- **Slider, Range slider, Rating, Toggle buttons:** `editable:` is the widget's own setting, `default` or `never`. It is not the core `Editable`. + +```sql +nativegallery g1 (datasource: database from Module.Item, phoneColumns: 2) { + template { dynamictext t1 (Content: '{1}', ContentParams: ({1} = Title)) } +} +nativeslider s1 (valueAttribute: Score, editable: never) +``` diff --git a/.claude/skills/mendix/manage-navigation/SKILL.md b/.claude/skills/mendix/manage-navigation/SKILL.md index f1d7764d46..bf8e8effc2 100644 --- a/.claude/skills/mendix/manage-navigation/SKILL.md +++ b/.claude/skills/mendix/manage-navigation/SKILL.md @@ -10,19 +10,20 @@ description: "Inspect and change navigation profiles in MDL — home pages, menu | lines | section | |---|---| -| 32-41 | When to Use This Skill | -| 42-60 | Navigation Concepts | -| 61-78 | Show Commands (Read-Only) | -| 79-382 | CREATE OR MODIFY NAVIGATION | -| 383-421 | Change One Item: ALTER NAVIGATION | -| 422-432 | Round-Trip Workflow | -| 433-454 | Catalog Queries | -| 455-494 | Common Patterns | -| 495-547 | Menu Documents (standalone, reusable) | -| 548-618 | Offline Profiles | -| 619-635 | Checklist | -| 636-639 | Offline synchronization (`CREATE NAVIGATION … SYNC (…)`) | -| 640-642 | Menu documents (CREATE OR MODIFY/DESCRIBE/DROP MENU) | +| 33-42 | When to Use This Skill | +| 43-63 | Navigation Concepts | +| 64-81 | Show Commands (Read-Only) | +| 82-385 | CREATE OR MODIFY NAVIGATION | +| 386-424 | Change One Item: ALTER NAVIGATION | +| 425-435 | Round-Trip Workflow | +| 436-457 | Catalog Queries | +| 458-497 | Common Patterns | +| 498-550 | Menu Documents (standalone, reusable) | +| 551-621 | Offline Profiles | +| 622-673 | Native Profiles | +| 674-691 | Checklist | +| 692-695 | Offline synchronization (`CREATE NAVIGATION … SYNC (…)`) | +| 696-698 | Menu documents (CREATE OR MODIFY/DESCRIBE/DROP MENU) | # Navigation Management Skill @@ -49,7 +50,9 @@ Use when the user asks to: | `Phone` | `PhoneOffline` | | `Tablet` | `TabletOffline` | - An invented name (`Mobile`, `Desktop`) is an error, not a new profile: Mendix routes on **User-Agent** to its own kinds, so a profile the platform does not define can never be reached. Native profiles are a different document type and are not creatable from MDL. + An invented name (`Mobile`, `Desktop`) is an error, not a new profile: Mendix routes on **User-Agent** to its own kinds, so a profile the platform does not define can never be reached. + + Native profiles are a different document type (`Navigation$NativeNavigationProfile`, no `Kind` property — identified purely by `$Type` + `Name`) and have their own, separate closed set: currently just `NativePhone`. `create or modify navigation NativePhone` creates it the same way the web kinds are created. Hybrid is not supported (no reference document exists for it). A freshly created NativePhone profile has no bottom bar menu items — fill them with a `{ }` block (flat, `OnClick: show page` only, no `Icon:` — see "Native Profiles" below) if the home page's layout requires a bottom bar (CE6108). - **Offline Profiles** — An offline profile makes the app work without a connection (a PWA with a local database that syncs). It is not a different document — same properties as its online twin — but it **constrains every page it can reach**, see below. - **Home Page** — The default page shown after login. Can be a PAGE or MICROFLOW. - **Role-Based Home Pages** — Override the default home page per user role (e.g., admins see a dashboard, users see a task list). @@ -616,12 +619,65 @@ starts empty and Studio Pro fills it from the entities the reachable pages use; only rows that differ from the defaults (`syncMode: Online`, no constraint) are stored. MDL does not author per-entity sync modes — set those in Studio Pro. +## Native Profiles + +`NativePhone` is created the same way: + +```sql +mdl 1; +create or modify navigation NativePhone + home page NativeMobile.Home_Native; +``` + +It is a different document type (`Navigation$NativeNavigationProfile`) from the +web kinds above — no `Kind` property, identified purely by `$Type` + `Name` — +but the statement and the create-then-fill flow are the same. + +**The bottom bar is the profile's `{ }` block, reusing the same item syntax as +the web kinds — but it is flat and page-only.** A native profile's bottom bar +(`NativePages$BottomBarItem`) has no sub-menus and stores only a page, unlike +the web `Menu`, so: + +```sql +mdl 1; +create or modify navigation NativePhone + home page NativeMobile.Home_Native + { + menu item 'Home' ( OnClick: show page NativeMobile.Home_Native, Icon: glyph 57377 ) + }; +``` + +- Every item needs `OnClick: show page …` — any other action (`call microflow`, + `call nanoflow`, `sign out`, …) and an item with no action are rejected (the + native bottom bar has no other action). A page argument is rejected too. +- Nested `menu 'caption' { … }` sub-items are rejected — Mendix's bottom bar + menu cannot nest. +- `Icon: glyph ` is the one confirmed icon shape for a native bottom bar + item — a numeric code, matching the one real reference document + (`Forms$GlyphIcon`). A collection or image icon (`Forms$IconCollectionIcon`/ + `Forms$ImageIcon`) is rejected — that shape has never been confirmed as + valid here; add it in Studio Pro instead. + +If the home page's layout has "Bottom bar" enabled, Mendix requires that page +to appear in the profile's bottom bar menu and reports **CE6108** ("If the +bottom bar is enabled on a home page, then that page must be included in the +bottom bar menu of the native navigation profile...") until it does. Either +include the page in the `{ }` block as above, or point the home page at a +layout with no bottom bar. + +A profile with no home page at all (`create navigation NativePhone;` with +nothing else) is a valid **empty** profile — Mendix requires a home page before +the profile can actually route anywhere, reported as **CE0527** ("Select a +default home page for this profile in the navigation document") until one is +set, same as leaving a web profile's home page unset. + ## Checklist -- [ ] Profile name is one of Mendix's web kinds (`Responsive`/`Phone`/`Tablet`, or their `*Offline` twins) — an invented name is an error, not a new profile +- [ ] Profile name is one of Mendix's web kinds (`Responsive`/`Phone`/`Tablet`, or their `*Offline` twins), or the native kind (`NativePhone`) — an invented name is an error, not a new profile - [ ] For an **offline** profile, no page it can reach binds an attribute across more than one association (CE6206) - [ ] For an **offline** profile, `progressive web app ( Precaching: true )` is set — without it no page opens offline - [ ] `app title` is set — a new project's browser tab reads `Mendix - ` otherwise +- [ ] For a **native** profile whose home page's layout requires a bottom bar (CE6108), the `{ }` block includes that page — flat items only, `OnClick: show page` only; `Icon: glyph ` is supported, a collection or image icon is not (add those in Studio Pro) - [ ] All PAGE/MICROFLOW targets are fully qualified (`Module.Name`) - [ ] Role references in `for` clauses are fully qualified (`Module.Role`) - [ ] Menu items are in `{ }` with no `;` between them; sub-menu items in `menu 'caption' { ... }` diff --git a/CHANGELOG.md b/CHANGELOG.md index a4aae40112..8eb410f145 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- **`check` warns about a required pluggable-widget setting left unset** (MDL-WIDGET56) — a native gallery without a data source, a slider without an attribute or a repeater without content passed `check` and exec, then failed the build with CE0642 ("Property 'X' is required"), or CE4899 for a text. `check` now reads the installed package and warns about each required setting the script leaves out. A setting with a usable default, or one the widget hides in its current configuration, is not reported. Measured on the 39 native widgets placed with no settings: `check` reports exactly the 30 settings that `mx check` 11.13.0 reports. +- **`check` warns about a pluggable widget on a page of the other platform** (MDL-WIDGET55) — a web widget such as `combobox`, `datagrid` or `image` on a native page, or a native one such as `nativeslider` or `nativegallery` on a web page. Both passed `check` and exec before. The platform comes from the widget's package (embedded template or the project's `.mpk`). A page is judged only when its layout's platform is known, from the script or the project. It is a warning: what mxbuild reports for either case is not measured. - **Lint `MPR017`: a Boolean flag a decision tests but which can only ever hold one value** (ako/mxcli#2403) — the branch it guards is unreachable, and the flow reads as though it has a safety interlock when it has none. Nothing else reports it: the model is valid and the build is clean. The test is the attribute's **reachable value set** — its default plus every literal any Create/Change activity assigns — not "is it ever written". The defect this comes from is a reset flag that *is* written, only ever to `false`, so a "never written" rule would have missed the case it was raised for; and a default of `true` with the only write `false` is two values, so that guard can change state once and is correctly not reported. Four exclusions keep a write the rule cannot see from reading as no write: bound to a page widget (a user may type into it), assigned from an expression rather than a literal, calculated, or not read in any condition. Writes are collected from every module including Marketplace ones, while only the project's own attributes are reported. Boolean only for now — enumerating "the literals I could see" is a far weaker claim for other types. @@ -68,6 +70,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **`check` rejects a value of the wrong type in a `declare`, `set` or `return`** (ako/mxcli#1258) — `declare $X Integer = 'abc';`, `set $X = 'abc';` and a `return` of the wrong type in a flow with a return type passed `check` and `exec` and failed the build with CE0117 (Mendix CLI 2: CE0844). The value is now checked against the declared primitive type with the rule already used for call arguments: Integer and Long pass into each other and widen to Decimal, every other primitive mismatch is reported as E009. `empty` into a Boolean, enumerations, objects, lists and values of unknown kind stay silent, and a computed Decimal into an Integer or Long by `declare` or `set` is left to MDL041. Measured on MxBuild 11.16.1 over 216 microflows. - **`check` rejects an expression that reads a variable nothing defines** (ako/mxcli#1258) — `return $Nope + 1;` with no `$Nope` anywhere passed `check` and `exec` and failed the build with CE0109 "Undefined variable". New MDL098, for the expressions of return, if, declare, set, create/change members, log, show message and validation feedback, in microflows and nanoflows. A name counts as defined if a parameter or any statement of the flow produces it, or it is one MxBuild accepts with no declaration (`$currentUser`, `$currentSession`, `$latestError`, `$latestHttpResponse`, `$latestSoapFault`, `$currentIndex`, `$currentObject`). Measured on MxBuild 11.16.1. - **`check` rejects `returns T as $R` when a path ends the flow without `$R`** (ako/mxcli#1258) — MDL003 exempts the AS clause because the end event returns `$R`, which holds only while `$R` has a value there. A flow with a path off its end and no top-level `$R` passed `check` and `exec` and failed the build with CE0109 "Undefined variable" (or CE0108 when `$R` is defined only inside a branch or loop). New MDL097, microflow and nanoflow. Measured on MxBuild 11.16.1. +- **`describe` names a native mobile widget by its own keyword** — a native widget left at its defaults was described under the last part of its id. So `nativegallery`, `nativebadge` and `nativeimage` came out as the web `gallery`, `badge` and `image`, and re-running the description replaced them with the web widget while `check` passed. Seven more (`activityindicator`, `qrcode`, `repeater`, `safeareaview`, `signature`, `notifications`, `backgroundgradient`) came out under names no widget has, and were refused on re-run (MDL-WIDGET25). A native gallery with a data source was described as the web gallery as well. Each is now described by the keyword `widget init` gave it, or as `pluggablewidget ''` when the project has no definition for it. Measured with Native Mobile Resources 12.6.0 on 11.13.0: all 39 native widgets now describe, pass `check` and re-run as Unchanged. +- **Native Image, Signature, Bottom sheet and Maps widgets build without CE0463** — with Native Mobile Resources 12.6.0 installed, each of these widgets that mxcli created failed `mx check` 11.13.0 with "The definition of this widget has changed". There were four causes: + - **Image:** the widget's editor hides the image-source settings it is not using, with a list worked out by a `switch`. mxcli could not read that, so it wrote the Image URL text, which Mendix leaves empty. + - **Signature:** `allowUpload` on its image setting was not read. + - **Bottom sheet:** the `onChange` of its trigger attribute was not written. + - **Maps:** an option caption was trimmed, while Mendix stores it exactly as the package writes it. + All 39 native widgets now pass `mx check` without CE0463. +- **`check` accepts a native widget's own `editable` setting** — the native Slider, Range slider, Rating and Toggle buttons have an `editable` setting of their own (`default` or `never`). `check` read it as the core Editable and refused `editable: 'default'` (MDL-WIDGET19), which is how `describe` prints it, so such a page could not be described and run again. The value is now checked against the widget's own values, as exec already wrote it. - **`fix widgets` and `fix design-properties` use the project's own Mendix version of `mx`** (ako/mxcli#2321) — they took the version as a preference, so on macOS an `mx` on PATH or another Studio Pro install ran, and `mx update-widgets` refused with "Project is in different Mendix version". They now take an `mx` of exactly the project's version. On Linux that version is downloaded when it is missing. On macOS and Windows, where no matching `mx` is installed, they say which version is needed and how to pass it with `--mx`. - **Parallel `mxcli exec` runs on one project no longer lose each other's writes** (ako/mxcli#2326) — measured with 8 parallel scripts: every process reported success and 2 to 6 of the 16 entities were missing (the reporter saw all of them fail instead). A script, or a `-c`, that writes now holds the project's lock (`.mxcli/write.lock`) for its whole run. A second writer waits up to 60 seconds, then changes nothing and exits 75, naming the holder. A lock left by a crashed run is taken over. Read-only runs take no lock. With the lock, all 16 entities land in every round. - **`run restart` names the secret it cannot replay** (ako/mxcli#2313) — a restart refused because of a literal secret printed only a generic `--db-password @env:` hint. The `--constant X=@env:VAR` references are recorded and replayed, so the hint read as if they were not. The refusal now lists each flag stored redacted, such as `--constant Helpdesk.OpenRouterKey` or `--db-password`, and says that the values given as references are replayed. @@ -1792,6 +1802,27 @@ Headline: **Widgets become first-class MDL rather than a second dialect.** Every - **`make digest-status` measures how far the bug-pattern digest has fallen behind**, per area — coverage is computed rather than quoted, because a figure written into prose is stale the next time anyone appends a finding. +- **`create navigation NativePhone`** — the native counterpart to web navigation + profile creation (`f2e7c67a`, `b032ec05`). A native profile has no `Kind` + property at all (`Navigation$NativeNavigationProfile`, identified purely by + `$Type` + `Name`), so it gets its own builder rather than a branch in the web + one. Unlike the web kinds, no live Studio Pro create-and-read-back exists for + native profiles (PED/MCP explicitly rejects native profile authoring), so the + shape is pinned against a real Studio-Pro-authored NativePhone profile instead + — see the doc comment on `newNativeProfileBson`. `UpdateNavigationProfile` + now writes bottom bar menu items too (`NativePages$BottomBarItem`), reusing + the profile's `{ }` block as the web kinds do — so a home page whose layout + requires a bottom bar can be added to it directly, clearing **CE6108** + instead of needing Studio Pro. The native bottom bar is flat and page-only, + unlike the web `Menu`: a nested `MENU 'caption' { … }` group or an `OnClick` + other than `SHOW PAGE` is rejected rather than guessed at. Its icon is a + numeric glyph code — `Icon: glyph ` — round-tripping through + `Forms$GlyphIcon`, the one shape confirmed against a real Studio-Pro-authored + NativePhone profile; a collection or image icon (`Forms$IconCollectionIcon`/ + `Forms$ImageIcon`) remains unconfirmed for a native item and is rejected — + see the doc comment on `navBottomBarItemBson`. Hybrid remains unsupported — + no reference document exists for it either. + ### Changed - **A generated domain model is laid out, not stacked in one row** — every `CREATE ENTITY` with no `@Position` used the same *y*, so a 40-entity model opened in Studio Pro as a single horizontal line 6,950px wide with the boxes overlapping, since the 150px step is narrower than an entity box. Unreadable at any zoom (reported against a 40-entity model on 11.13). diff --git a/cmd/mxcli/main.go b/cmd/mxcli/main.go index 13cbe3d207..a26230bba0 100644 --- a/cmd/mxcli/main.go +++ b/cmd/mxcli/main.go @@ -9,6 +9,7 @@ import ( "io" "os" "path/filepath" + "runtime/debug" "strings" "github.com/mendixlabs/mxcli/mdl/backend" @@ -384,9 +385,51 @@ func executeMDL(projectPath, mdlCmd string, setup ...func(*executor.Executor)) { } } +// devVersionFromBuildInfo derives a version string from Go's automatic VCS +// build stamping, which `go build`/`go run` populate from the surrounding git +// checkout even when no -ldflags -X main.Version=... was passed (`make build`'s +// LDFLAGS sets Version explicitly via `git describe` for release-style builds; +// this is the fallback for a bare `go build ./cmd/mxcli` during local mxcli +// development). Without this, an unstamped build silently fell back to the +// literal "0.1.0" below, which is indistinguishable from a real release and +// carries no git identity at all — a real gap surfaced by +// native-pwa-migrator's mxcli version-check tests expecting to trace a binary +// back to a source revision. Returns "" if no VCS revision is available (e.g. +// building outside a git checkout), leaving the "0.1.0" fallback as an +// explicitly-unidentifiable last resort. +func devVersionFromBuildInfo() string { + info, ok := debug.ReadBuildInfo() + if !ok { + return "" + } + var revision string + var modified bool + for _, setting := range info.Settings { + switch setting.Key { + case "vcs.revision": + revision = setting.Value + case "vcs.modified": + modified = setting.Value == "true" + } + } + if revision == "" { + return "" + } + short := revision + if len(short) > 8 { + short = short[:8] + } + if modified { + return "0.0.0-dev+g" + short + ".dirty" + } + return "0.0.0-dev+g" + short +} + func init() { if Version != "" { version = Version + } else if dev := devVersionFromBuildInfo(); dev != "" { + version = dev } if BuildTime != "" { rootCmd.Version = version + " (" + BuildTime + ")" diff --git a/cmd/mxcli/syntax/features_misc.go b/cmd/mxcli/syntax/features_misc.go index 6816ac7ca3..99ee2fe9bf 100644 --- a/cmd/mxcli/syntax/features_misc.go +++ b/cmd/mxcli/syntax/features_misc.go @@ -542,10 +542,11 @@ DISCONNECT;`, -- Browse the available names with: -- LIST ICON COLLECTIONS / DESCRIBE ICON COLLECTION Module.Name -- --- is one of Mendix's fixed web kinds, and the profile is CREATED if --- the project does not have it yet: --- Responsive Phone Tablet online --- ResponsiveOffline PhoneOffline TabletOffline offline +-- is one of Mendix's fixed web or native kinds, and the profile is +-- CREATED if the project does not have it yet: +-- Responsive Phone Tablet online (web) +-- ResponsiveOffline PhoneOffline TabletOffline offline (web) +-- NativePhone native -- -- SYNC configures offline synchronization, and an offline profile downloads -- NOTHING until its entities have one -- a profile with no SYNC block builds, @@ -595,7 +596,15 @@ DISCONNECT;`, -- -- An OFFLINE profile restricts every page it can reach -- an attribute may be -- bound across at most ONE association hop (CE6206). Creating one reports the --- documents in the project that already exceed that.`, +-- documents in the project that already exceed that. +-- +-- A NATIVE profile (Navigation$NativeNavigationProfile, no Kind property) has +-- a { } block too -- its bottom bar -- but it is FLAT and PAGE-ONLY +-- (NativePages$BottomBarItem): no nested MENU groups, no OnClick other than +-- SHOW PAGE. Its icon is a numeric glyph code -- Icon: GLYPH -- not a +-- qualified name; a collection or image icon is unconfirmed for a native +-- bottom bar item and rejected. A home page whose layout has "Bottom bar" +-- enabled must appear in this block, or Mendix reports CE6108.`, Example: `mdl 1; CREATE OR MODIFY NAVIGATION Responsive APP TITLE 'Order Desk' @@ -615,6 +624,12 @@ CREATE OR MODIFY NAVIGATION TabletOffline HOME PAGE Maintenance.Request_Overview { MENU ITEM 'Requests' ( OnClick: SHOW PAGE Maintenance.Request_Overview ) + }; + +CREATE OR MODIFY NAVIGATION NativePhone + HOME PAGE MyModule.Home_Native + { + MENU ITEM 'Home' ( OnClick: SHOW PAGE MyModule.Home_Native, Icon: GLYPH 57377 ) };`, SeeAlso: []string{"navigation.show"}, }) diff --git a/docs/01-project/MDL_QUICK_REFERENCE.md b/docs/01-project/MDL_QUICK_REFERENCE.md index bb298d4abf..e45a48b61b 100644 --- a/docs/01-project/MDL_QUICK_REFERENCE.md +++ b/docs/01-project/MDL_QUICK_REFERENCE.md @@ -927,14 +927,16 @@ alter workflow Module.OrderApproval { | Show menu tree | `list navigation menu [Profile];` | One row per item, with the **Address** `alter navigation` takes (`'Admin' > 'Users'`, `'Home'@2`) | | Show home pages | `list navigation homes;` | Home page assignments across profiles | | Describe navigation | `describe navigation [Profile];` | Full MDL output (round-trippable) | -| Native home | `home nanoflow Mod.Flow` | A native profile's flow home; mxcli writes a native profile's home pages and sync only | +| Native home | `home nanoflow Mod.Flow` | A native profile's flow home; mxcli writes a native profile's home pages, sync and bottom bar only | | Create/modify navigation | `create or modify navigation Profile ...;` | Writes the clauses it states (a `{ }` block replaces the whole menu) — and **creates** the profile if the project does not have it | | Alter navigation | `alter navigation Profile { insert after 'Home' { menu item … } drop 'Old'; … };` | Edits one profile in place: `insert before\|after\|into { … }`, `insert { … }`, `replace with { … }`, `move before\|after\|into `, `drop , …`, `set ( Caption:, OnClick:, Icon: \| none ) on `, `set home page\|microflow M.X [for Role]`, `drop home page for Role`, `set/drop login page`, `set/drop not found page`. `` is a caption path `'Admin' > 'Users'` (`@n` among equal captions). Untouched items stay as stored; a refusal writes nothing | | Offline sync | `sync ( sync Mod.Entity all; ... )` | A clause of CREATE NAVIGATION. Modes: `online`, `all`, `where ''`, `never`, `none`, `none preserve data`. **Not** Studio Pro's captions — its "All Objects" is `all`, its "By XPath" is `where`. An offline profile downloads nothing without this | | Progressive web app | `progressive web app ( Precaching: true )` / `progressive web app off` | A clause of CREATE NAVIGATION: Studio Pro's *Progressive web app* settings. An offline profile without them gets no service worker, so no page opens offline (mendixlabs/mxcli#1377). Keys: `Precaching` (default false), `InstallPrompt` (default true); omitted, the stored settings stay | | Application title / icon | `app title 'Order Desk'` · `app icon Mod.Images.Logo` / `app icon none` | Clauses of CREATE NAVIGATION: Studio Pro's *Application title* (the browser tab's `Mendix - ` prefix in a new project) and *Application icon*. The title is written in the project's default language, other languages kept; the icon is an image, resolved by `check --references` and exec, and must be a square PNG at least 512 px wide (CE6859; exec refuses another). Omitted, both stay as stored (ako/mxcli#1756) | -| Profile kinds | `Responsive` · `Phone` · `Tablet` · `ResponsiveOffline` · `PhoneOffline` · `TabletOffline` | A closed set. An invented name (`Mobile`) is an error, not a new profile: the runtime routes on User-Agent to Mendix's own kinds. Native profiles are a different document type and are not creatable | +| Profile kinds (web) | `Responsive` · `Phone` · `Tablet` · `ResponsiveOffline` · `PhoneOffline` · `TabletOffline` | A closed set. An invented name (`Mobile`) is an error, not a new profile: the runtime routes on User-Agent to Mendix's own kinds | +| Profile kinds (native) | `NativePhone` | A separate closed set — different document type (`Navigation$NativeNavigationProfile`, no `Kind` property). Hybrid is not creatable (no reference document exists for it) | | Offline profiles | `create or modify navigation TabletOffline ...;` | Same properties as the online twin, but every page the profile can reach may bind an attribute across **at most one** association hop (**CE6206**). Creating one reports the documents that already exceed that | +| Native profiles | `create or modify navigation NativePhone home page MyModule.Home_Native { menu item 'Home' ( OnClick: show page MyModule.Home_Native ) };` | The `{ }` block is the bottom bar: flat and page-only — no sub-menus, no `OnClick` other than `show page`. Its icon is `Icon: glyph ` (a numeric code); a collection or image icon is unconfirmed for a native item and rejected. Needed when the home page's layout requires a bottom bar (**CE6108**) | Menu items are the profile's children, in `{ }` after its clauses, with no `;` between them: `menu item 'Caption' ( OnClick: show page M.P, Icon: … )`, where @@ -1020,6 +1022,10 @@ navigation` is a **full replacement**, re-running that output DELETED the icon the comment had just declined to describe. A `$Type` this build does not know is still flagged rather than guessed at. +On a **native** bottom bar item, only `Icon: glyph ` is a confirmed, +round-tripping shape (see the Native profiles row above) -- a collection or +image icon there is rejected. + ## Project Settings | Statement | Syntax | Notes | diff --git a/mdl/backend/modelsdk/navigation_bottombar_test.go b/mdl/backend/modelsdk/navigation_bottombar_test.go new file mode 100644 index 0000000000..49405c4408 --- /dev/null +++ b/mdl/backend/modelsdk/navigation_bottombar_test.go @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Pinned against native-pwa-migrator's fixtures/native-phone-minimal: a real +// Studio-Pro-authored NativePhone profile whose one BottomBarItem is +// +// { $Type: "NativePages$BottomBarItem", +// Caption: { $Type: "Texts$Text", Items: [3, [{ $Type: "Texts$Translation", +// LanguageCode: "en_US", Text: "Home" }]] }, +// Icon: { $Type: "Forms$GlyphIcon", Code: 57377 }, +// Page: "NativeMobile.Home_Native" } +// +// (marker re-verified directly against the fixture's raw BSON, not copied from +// navCaptionBson — see navBottomBarCaptionBson's doc comment). mxcli writes +// Icon only as a Forms$GlyphIcon (see navBottomBarItemBson's doc comment), so +// these tests check the four keys mxcli owns, glyph-icon acceptance, and the +// rejections that keep it from guessing a shape Studio Pro has never +// confirmed. +package modelsdkbackend + +import ( + "fmt" + "testing" + + "go.mongodb.org/mongo-driver/v2/bson" + + "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/sdk/pages" +) + +func TestNavBottomBarItemBson_MatchesTheFixtureShape(t *testing.T) { + got, err := navBottomBarItemBson(types.NavMenuItemSpec{Caption: "Home", Page: "NativeMobile.Home_Native"}) + if err != nil { + t.Fatalf("navBottomBarItemBson: %v", err) + } + if v, _ := profileKey(got, "$Type"); v != "NativePages$BottomBarItem" { + t.Errorf("$Type = %v", v) + } + if v, _ := profileKey(got, "Page"); v != "NativeMobile.Home_Native" { + t.Errorf("Page = %v", v) + } + // No icon given — Icon stays an explicit null. See + // TestNavBottomBarItemBson_AcceptsGlyphIcon for the non-nil case. + if v, ok := profileKey(got, "Icon"); !ok || v != nil { + t.Errorf("Icon = %#v, want an explicit null", v) + } + + caption, ok := profileKey(got, "Caption") + if !ok { + t.Fatal("no Caption key at all") + } + captionDoc, ok := caption.(bson.D) + if !ok { + t.Fatalf("Caption is %T, want bson.D", caption) + } + if v, _ := profileKey(captionDoc, "$Type"); v != "Texts$Text" { + t.Errorf("Caption.$Type = %v", v) + } + items, ok := profileKey(captionDoc, "Items") + if !ok { + t.Fatal("Caption: no Items key at all") + } + arr, ok := items.(bson.A) + if !ok || len(arr) != 2 { + t.Fatalf("Caption.Items = %#v, want [marker, translation]", items) + } + if arr[0] != int32(3) { + t.Errorf("Caption.Items marker = %v, want 3 (measured on the fixture, not navCaptionBson's 1)", arr[0]) + } + translation, ok := arr[1].(bson.D) + if !ok { + t.Fatalf("Caption.Items[1] is %T, want bson.D", arr[1]) + } + if v, _ := profileKey(translation, "$Type"); v != "Texts$Translation" { + t.Errorf("Translation.$Type = %v", v) + } + if v, _ := profileKey(translation, "Text"); v != "Home" { + t.Errorf("Translation.Text = %v", v) + } +} + +func TestNavBottomBarItemBson_RejectsSubItems(t *testing.T) { + _, err := navBottomBarItemBson(types.NavMenuItemSpec{ + Caption: "Home", Page: "M.Home", + Items: []types.NavMenuItemSpec{{Caption: "Sub", Page: "M.Sub"}}, + }) + if err == nil { + t.Fatal("expected an error for a nested item — the native bottom bar is flat") + } +} + +func TestNavBottomBarItemBson_RejectsMicroflow(t *testing.T) { + _, err := navBottomBarItemBson(types.NavMenuItemSpec{Caption: "Home", Microflow: "M.DoStuff"}) + if err == nil { + t.Fatal("expected an error for a microflow target — BottomBarItem has no microflow action") + } +} + +func TestNavBottomBarItemBson_RequiresAPage(t *testing.T) { + _, err := navBottomBarItemBson(types.NavMenuItemSpec{Caption: "Home"}) + if err == nil { + t.Fatal("expected an error when neither a page nor a microflow is given") + } +} + +func TestNavBottomBarItemBson_RejectsIcon(t *testing.T) { + for name, spec := range map[string]types.NavMenuItemSpec{ + "collection icon": {Caption: "Home", Page: "M.Home", Icon: "Atlas_Core.Atlas.home"}, + "image icon": {Caption: "Home", Page: "M.Home", Icon: "M.Images.Logo", IconKind: types.MenuIconImage}, + } { + if _, err := navBottomBarItemBson(spec); err == nil { + t.Errorf("%s: expected an error — only a glyph icon is confirmed for native bottom bar items", name) + } + } +} + +// Matches the fixture's exact shape: { $Type: "Forms$GlyphIcon", Code: 57377 }. +func TestNavBottomBarItemBson_AcceptsGlyphIcon(t *testing.T) { + got, err := navBottomBarItemBson(types.NavMenuItemSpec{ + Caption: "Home", Page: "NativeMobile.Home_Native", IconKind: types.MenuIconGlyph, IconCode: 57377, + }) + if err != nil { + t.Fatalf("navBottomBarItemBson: %v", err) + } + icon, ok := profileKey(got, "Icon") + if !ok || icon == nil { + t.Fatal("Icon key missing or null, want a Forms$GlyphIcon") + } + d, ok := icon.(bson.D) + if !ok { + t.Fatalf("Icon is %T, want bson.D", icon) + } + if v, _ := profileKey(d, "$Type"); v != "Forms$GlyphIcon" { + t.Errorf("Icon.$Type = %v, want Forms$GlyphIcon", v) + } + if v, _ := profileKey(d, "Code"); v != int32(57377) { + t.Errorf("Icon.Code = %v (%T), want int32 57377", v, v) + } +} + +func TestNavPatchNativeProfile_LeavesBottomBarItemsAloneWithoutAMenuBlock(t *testing.T) { + // Mirrors navPatchWebProfile's own rule for Menu: a CREATE OR REPLACE + // NAVIGATION statement with no MENU clause must not wipe an existing menu. + before := newNativeProfileBson("NativePhone") + wantBefore, ok := profileKey(before, "BottomBarItems") + if !ok { + t.Fatal("fixture setup: no BottomBarItems key at all") + } + got, err := navPatchNativeProfile(before, types.NavigationProfileSpec{HasMenu: false}) + if err != nil { + t.Fatalf("navPatchNativeProfile: %v", err) + } + gotAfter, ok := profileKey(got, "BottomBarItems") + if !ok { + t.Fatal("BottomBarItems key vanished") + } + if fmt.Sprintf("%v", wantBefore) != fmt.Sprintf("%v", gotAfter) { + t.Errorf("BottomBarItems changed without a MENU clause: %v -> %v", wantBefore, gotAfter) + } +} + +func TestNavPatchNativeProfile_BuildsBottomBarItemsFromMenuItems(t *testing.T) { + doc := newNativeProfileBson("NativePhone") + got, err := navPatchNativeProfile(doc, types.NavigationProfileSpec{ + HasMenu: true, + MenuItems: []types.NavMenuItemSpec{{Caption: "Home", Page: "NativeMobile.Home_Native"}}, + }) + if err != nil { + t.Fatalf("navPatchNativeProfile: %v", err) + } + v, ok := profileKey(got, "BottomBarItems") + if !ok { + t.Fatal("no BottomBarItems key at all") + } + arr, ok := v.(bson.A) + if !ok || len(arr) != 2 { + t.Fatalf("BottomBarItems = %#v, want [marker, item]", v) + } + if arr[0] != int32(2) { + t.Errorf("BottomBarItems marker = %v, want 2", arr[0]) + } + item, ok := arr[1].(bson.D) + if !ok { + t.Fatalf("BottomBarItems[1] is %T, want bson.D", arr[1]) + } + if v, _ := profileKey(item, "$Type"); v != "NativePages$BottomBarItem" { + t.Errorf("item $Type = %v", v) + } +} + +func TestNavPatchNativeProfile_PropagatesABottomBarItemError(t *testing.T) { + doc := newNativeProfileBson("NativePhone") + _, err := navPatchNativeProfile(doc, types.NavigationProfileSpec{ + HasMenu: true, + MenuItems: []types.NavMenuItemSpec{{Caption: "Bad", Microflow: "M.DoStuff"}}, + }) + if err == nil { + t.Fatal("expected the microflow-target error to propagate out of navPatchNativeProfile") + } +} + +// The executor hands an item's OnClick over as a built client action +// (ako/mxcli#980), not as the legacy Page field, so the bottom bar's page is +// read from a show-page action — and every other action is refused rather than +// written as an item with no page. +func TestNavBottomBarItemBson_ReadsThePageFromTheAction(t *testing.T) { + got, err := navBottomBarItemBson(types.NavMenuItemSpec{Caption: "Home", + Action: &pages.PageClientAction{PageName: "NativeMobile.Home_Native"}}) + if err != nil { + t.Fatalf("navBottomBarItemBson: %v", err) + } + if v, _ := profileKey(got, "Page"); v != "NativeMobile.Home_Native" { + t.Errorf("Page = %v, want the show-page action's page", v) + } + + for name, spec := range map[string]types.NavMenuItemSpec{ + "microflow action": {Caption: "X", Action: &pages.MicroflowClientAction{MicroflowName: "M.F"}}, + "nanoflow action": {Caption: "X", Action: &pages.NanoflowClientAction{NanoflowName: "M.N"}}, + "sign out": {Caption: "X", SignOut: true}, + "page argument": {Caption: "X", Action: &pages.PageClientAction{PageName: "M.P", + ParameterMappings: []*pages.PageClientParameterMapping{{}}}}, + "no action": {Caption: "X", Action: &pages.NoClientAction{}}, + "kept action": {Caption: "X", KeepAction: []byte{0}}, + } { + if _, err := navBottomBarItemBson(spec); err == nil { + t.Errorf("%s: accepted, want a refusal", name) + } + } +} diff --git a/mdl/backend/modelsdk/navigation_caption_test.go b/mdl/backend/modelsdk/navigation_caption_test.go new file mode 100644 index 0000000000..13db52c107 --- /dev/null +++ b/mdl/backend/modelsdk/navigation_caption_test.go @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Pinned against native-pwa-migrator's fixtures/native-phone-minimal — its +// Responsive profile's Menu.Items[…].Caption (this exact call site), its +// AppTitle, and its NativePhone profile's BottomBarItem.Caption are all +// { $Type: "Texts$Text", Items: [3, [{ $Type: "Texts$Translation", … }]] }. +// Walking every Texts$Text.Items occurrence in that fixture and a second, +// unrelated fixture (expr-checker-minimal) found marker 3 in all 7300+ +// occurrences and zero exceptions — see navCaptionBson's doc comment. +package modelsdkbackend + +import ( + "testing" + + "go.mongodb.org/mongo-driver/v2/bson" + + "github.com/mendixlabs/mxcli/mdl/types" +) + +func TestNavCaptionBson_MatchesTheFixtureShape(t *testing.T) { + got := navCaptionBson("Home") + if v, _ := profileKey(got, "$Type"); v != "Texts$Text" { + t.Errorf("$Type = %v", v) + } + items, ok := profileKey(got, "Items") + if !ok { + t.Fatal("no Items key at all") + } + arr, ok := items.(bson.A) + if !ok || len(arr) != 2 { + t.Fatalf("Items = %#v, want [marker, translation]", items) + } + if arr[0] != int32(3) { + t.Errorf("Items marker = %v, want 3 (measured on the fixture, not the old 1)", arr[0]) + } + translation, ok := arr[1].(bson.D) + if !ok { + t.Fatalf("Items[1] is %T, want bson.D", arr[1]) + } + if v, _ := profileKey(translation, "$Type"); v != "Texts$Translation" { + t.Errorf("Translation.$Type = %v", v) + } + if v, _ := profileKey(translation, "Text"); v != "Home" { + t.Errorf("Translation.Text = %v", v) + } +} + +// The regression this fixes is on the caption, only reachable through the +// full menu item — assert on the wiring, not just the helper. +func TestNavMenuItemBson_CaptionMarkerMatchesTheFixture(t *testing.T) { + item, err := navMenuItemBson(types.NavMenuItemSpec{Caption: "Home", Page: "M.Home"}) + if err != nil { + t.Fatalf("navMenuItemBson: %v", err) + } + caption, ok := profileKey(item, "Caption") + if !ok { + t.Fatal("no Caption key at all") + } + captionDoc, ok := caption.(bson.D) + if !ok { + t.Fatalf("Caption is %T, want bson.D", caption) + } + items, ok := profileKey(captionDoc, "Items") + if !ok { + t.Fatal("Caption: no Items key at all") + } + arr, ok := items.(bson.A) + if !ok || len(arr) == 0 { + t.Fatalf("Caption.Items = %#v", items) + } + if arr[0] != int32(3) { + t.Errorf("Caption.Items marker = %v, want 3", arr[0]) + } +} diff --git a/mdl/backend/modelsdk/navigation_native_test.go b/mdl/backend/modelsdk/navigation_native_test.go index cf08d3bc64..267003a3f7 100644 --- a/mdl/backend/modelsdk/navigation_native_test.go +++ b/mdl/backend/modelsdk/navigation_native_test.go @@ -57,14 +57,20 @@ func TestNativeProfile_ReadsBottomBarActionAndIcon(t *testing.T) { func TestNativeProfile_WritesSync(t *testing.T) { doc := bson.D{{Key: "$Type", Value: "Navigation$NativeNavigationProfile"}, {Key: "Name", Value: "NativePhone"}, {Key: "OfflineEntityConfigs", Value: bson.A{navMarkerItems}}} - out := navPatchNativeProfile(doc, types.NavigationProfileSpec{HasSync: true, + out, err := navPatchNativeProfile(doc, types.NavigationProfileSpec{HasSync: true, OfflineEntities: []types.NavOfflineEntitySpec{{Entity: "M.Order", SyncMode: "All"}}}) + if err != nil { + t.Fatal(err) + } cfgs := navGetArray(out, "OfflineEntityConfigs") if len(cfgs) != 2 || navGetString(cfgs[1].(bson.D), "Entity") != "M.Order" { t.Errorf("sync not written: %v", cfgs) } // CONTROL: no sync block leaves the stored list alone. - out = navPatchNativeProfile(doc, types.NavigationProfileSpec{}) + out, err = navPatchNativeProfile(doc, types.NavigationProfileSpec{}) + if err != nil { + t.Fatal(err) + } if len(navGetArray(out, "OfflineEntityConfigs")) != 1 { t.Errorf("a statement without sync changed the list") } diff --git a/mdl/backend/modelsdk/navigation_omitted_clause_test.go b/mdl/backend/modelsdk/navigation_omitted_clause_test.go index 44b13a4808..f2100c62ee 100644 --- a/mdl/backend/modelsdk/navigation_omitted_clause_test.go +++ b/mdl/backend/modelsdk/navigation_omitted_clause_test.go @@ -167,9 +167,12 @@ func TestNavPatchNativeProfile_OmittedRoleHomesKeepStored(t *testing.T) { {Key: "Name", Value: "NativePhone"}, {Key: "RoleBasedNativeHomePages", Value: bson.A{navMarkerHomeItems, roleHome}}, } - out := navPatchNativeProfile(doc, types.NavigationProfileSpec{ + out, err := navPatchNativeProfile(doc, types.NavigationProfileSpec{ HomePages: []types.NavHomePageSpec{{IsPage: true, Target: "M.Home"}}, }) + if err != nil { + t.Fatal(err) + } items := navGetArray(out, "RoleBasedNativeHomePages") if len(items) != 2 || navGetString(items[1].(bson.D), "HomePagePage") != "M.UserHome" { t.Errorf("role-based native home page not kept: %v", items) diff --git a/mdl/backend/modelsdk/navigation_profile_add.go b/mdl/backend/modelsdk/navigation_profile_add.go index 42f740c1e0..01521f963d 100644 --- a/mdl/backend/modelsdk/navigation_profile_add.go +++ b/mdl/backend/modelsdk/navigation_profile_add.go @@ -43,9 +43,10 @@ func (b *Backend) AddNavigationProfile(navDocID model.ID, name string) error { if b.writer == nil { return fmt.Errorf("AddNavigationProfile: not connected for writing") } - kind, ok := types.CanonicalProfileKind(name) + kind, isNative, ok := resolveProfileKind(name) if !ok { - return fmt.Errorf("cannot create navigation profile %q: Mendix's web profiles are %s", name, strings.Join(types.WebProfileKindNames(), ", ")) + return fmt.Errorf("cannot create navigation profile %q: Mendix's web profiles are %s, and its native profiles are %s", + name, strings.Join(types.WebProfileKindNames(), ", "), strings.Join(types.NativeProfileKindNames(), ", ")) } raw, err := b.reader.GetRawUnitBytes(string(navDocID)) @@ -71,7 +72,12 @@ func (b *Backend) AddNavigationProfile(navDocID model.ID, name string) error { } } - profile := newWebProfileBson(kind) + var profile bson.D + if isNative { + profile = newNativeProfileBson(kind) + } else { + profile = newWebProfileBson(kind) + } if !b.declaresThrowPartialSyncError() { profile = withoutKey(profile, "ThrowPartialSyncError") } @@ -105,6 +111,22 @@ func withoutKey(d bson.D, key string) bson.D { return out } +// resolveProfileKind maps a user-written profile name to its canonical Kind (web) +// or Name (native) and reports which family it belongs to. The two lookups are +// kept apart rather than merged into one map: a web profile is identified by its +// Kind property, a native profile has no Kind at all and is identified purely by +// $Type + Name (see the doc comment on newNativeProfileBson) — blurring the two +// would make it easy to build a profile with the wrong shape for its own $Type. +func resolveProfileKind(name string) (kind string, isNative bool, ok bool) { + if k, ok := types.CanonicalProfileKind(name); ok { + return k, false, true + } + if k, ok := types.CanonicalNativeProfileKind(name); ok { + return k, true, true + } + return "", false, false +} + // newWebProfileBson builds an empty profile of the given kind, with every key a // Studio Pro-authored one carries and nothing it does not. // @@ -153,3 +175,83 @@ func newWebProfileBson(kind string) bson.D { {Key: "ThrowPartialSyncError", Value: true}, } } + +// newNativeProfileBson builds an empty NativePhone profile. +// +// Unlike the web kinds, this shape is NOT pinned by adding a profile through +// Studio Pro's own model API and reading back what it materialised — that +// channel does not exist for native profiles at all, on any machine: PED/MCP +// explicitly rejects native profile authoring (docs/03-development/ +// PED_MCP_CAPABILITIES.md, mdl/backend/mcp/navigation.go), independent of this +// repo's own environment. The best available evidence instead is a real +// Studio-Pro-authored NativePhone profile from native-pwa-migrator's +// fixtures/native-phone-minimal (a raw BSON dump of the .mxunit file, not a PED +// read) — but that document is a CONFIGURED profile, not a freshly-created one, +// so it proves the key set, $Type names, and storage keys, not which values are +// Studio Pro's create-time defaults versus this fixture author's choices. +// +// A native profile has no Kind property at all (confirmed against +// modelsdk/gen/navigation/types.go: NativeNavigationProfile carries no `kind` +// field, unlike NavigationProfile) — it is distinguished purely by $Type + Name. +// +// Per-field provenance, so a future re-pin knows what to re-check: +// - Name, $Type: definitional. +// - OfflineEntityConfigs, RoleBasedNativeHomePages: the fixture's own document +// carries these EMPTY (marker 3 / marker 1 respectively) even though it is +// otherwise configured — direct evidence of the unconfigured state, not an +// inference. +// - NativeHomePage: written explicit nil here, NOT the fixture's configured +// home page — this is exactly what UpdateNavigationProfile fills in +// afterwards (mirrors NotFoundHomepage/ProgressiveWebAppSettings on the web +// side: an unset single child is an explicit null, never an empty +// placeholder sub-document). Backed by a real signal in the decoder, not a +// guess: NativeNavigationProfile.InitFromRaw only sets nativeHomePage +// `if child, err := codec.DecodeChild(raw, "NativeHomePage"); err == nil`, +// i.e. the shipped read path already treats a missing/null NativeHomePage as +// an ordinary, non-error state. +// - BottomBarItems: empty, marker 2 — the fixture's own (non-empty) BottomBarItems +// uses marker 2, and the marker is per-field-type rather than count-dependent +// (proven by newWebProfileBson itself: HomeItems/AppTitle.Items/ +// OfflineEntityConfigs are all empty in that SAME reference document yet use +// three different markers — 3, 3, 3 vs Menu.Items' 1 — so an empty +// collection keeps its type's marker rather than switching to some +// "generic empty" one). UpdateNavigationProfile does not patch BottomBarItems +// for native profiles (a separate, already-tracked gap), so this value +// persists until Studio Pro or a future writer sets it. +// - ApplyScreenTransition, EncryptionDbEnabled, LocalFileEncryptionEnabled, +// LoggingEnabled, NativeNavigationEnabled, OtaEnabled, +// SessionCookieEncryptionEnabled: false, and ScreenNavigationTransition/ +// PopupNavigationTransition: "SystemDefault" — carried from the fixture. +// These are opt-in toggles a minimal fixture is unlikely to have touched, +// but that is inference, not measurement. +// - NetworkTimeoutMs (60000) and ThrowPartialSyncError (false): carried from +// the fixture as observed values. Flagged as the least-certain fields here — +// unlike the booleans above, there is no structural reason to expect these +// specific values are Studio Pro's create-time defaults rather than this +// fixture author's settings that happen not to have been touched. +// - HermesEnabled: deliberately OMITTED. modelsdk/gen exposes a setter for it, +// but the fixture's real document does not carry this key at all — writing +// a value here would be exactly the "assembled from a guess" failure mode +// this whole feature exists to avoid. +func newNativeProfileBson(kind string) bson.D { + return bson.D{ + {Key: "$ID", Value: navID()}, + {Key: "$Type", Value: "Navigation$NativeNavigationProfile"}, + {Key: "ApplyScreenTransition", Value: false}, + {Key: "BottomBarItems", Value: bson.A{int32(2)}}, + {Key: "EncryptionDbEnabled", Value: false}, + {Key: "LocalFileEncryptionEnabled", Value: false}, + {Key: "LoggingEnabled", Value: false}, + {Key: "Name", Value: kind}, + {Key: "NativeHomePage", Value: nil}, + {Key: "NativeNavigationEnabled", Value: false}, + {Key: "NetworkTimeoutMs", Value: int32(60000)}, + {Key: "OfflineEntityConfigs", Value: bson.A{int32(3)}}, + {Key: "OtaEnabled", Value: false}, + {Key: "PopupNavigationTransition", Value: "SystemDefault"}, + {Key: "RoleBasedNativeHomePages", Value: bson.A{int32(1)}}, + {Key: "ScreenNavigationTransition", Value: "SystemDefault"}, + {Key: "SessionCookieEncryptionEnabled", Value: false}, + {Key: "ThrowPartialSyncError", Value: false}, + } +} diff --git a/mdl/backend/modelsdk/navigation_profile_add_test.go b/mdl/backend/modelsdk/navigation_profile_add_test.go index a546faf9b4..7d99107634 100644 --- a/mdl/backend/modelsdk/navigation_profile_add_test.go +++ b/mdl/backend/modelsdk/navigation_profile_add_test.go @@ -112,6 +112,122 @@ func TestNoKindCarriesProgressiveWebAppSettings(t *testing.T) { } } +func TestResolveProfileKind(t *testing.T) { + for _, tc := range []struct { + name string + wantKind string + wantNative bool + wantOK bool + }{ + {"phone", "Phone", false, true}, + {" Responsive ", "Responsive", false, true}, + {"TabletOffline", "TabletOffline", false, true}, + {"nativephone", "NativePhone", true, true}, + {" NativePhone ", "NativePhone", true, true}, + {"Mobile", "", false, false}, + {"Hybrid", "", false, false}, + } { + kind, isNative, ok := resolveProfileKind(tc.name) + if ok != tc.wantOK || kind != tc.wantKind || isNative != tc.wantNative { + t.Errorf("resolveProfileKind(%q) = (%q, %v, %v), want (%q, %v, %v)", + tc.name, kind, isNative, ok, tc.wantKind, tc.wantNative, tc.wantOK) + } + } +} + +func TestNewNativeProfileMatchesTheFixtureKeySet(t *testing.T) { + // Every key native-pwa-migrator's fixtures/native-phone-minimal carries on its + // real, Studio-Pro-authored NativePhone profile, and nothing it does not — + // same discipline as TestNewWebProfileMatchesTheStudioProKeySet, except this + // reference is a configured document (see newNativeProfileBson's doc comment + // for why no fresher one exists). A key mxcli invents, or one it omits, is + // the failure that passes mx check and then will not open in Studio Pro. + want := []string{ + "$ID", "$Type", "ApplyScreenTransition", "BottomBarItems", + "EncryptionDbEnabled", "LocalFileEncryptionEnabled", "LoggingEnabled", + "Name", "NativeHomePage", "NativeNavigationEnabled", "NetworkTimeoutMs", + "OfflineEntityConfigs", "OtaEnabled", "PopupNavigationTransition", + "RoleBasedNativeHomePages", "ScreenNavigationTransition", + "SessionCookieEncryptionEnabled", "ThrowPartialSyncError", + } + got := newNativeProfileBson("NativePhone") + if len(got) != len(want) { + t.Errorf("NativePhone: %d keys, want %d", len(got), len(want)) + } + for _, k := range want { + if _, ok := profileKey(got, k); !ok { + t.Errorf("NativePhone: missing key %q", k) + } + } + if v, _ := profileKey(got, "Name"); v != "NativePhone" { + t.Errorf("NativePhone: Name = %v", v) + } + if v, _ := profileKey(got, "$Type"); v != "Navigation$NativeNavigationProfile" { + t.Errorf("NativePhone: $Type = %v", v) + } + // A native profile has no Kind property at all — confirmed against + // modelsdk/gen/navigation/types.go, which gives NativeNavigationProfile no + // `kind` field. Unlike the web builder, Kind must never appear here. + if _, ok := profileKey(got, "Kind"); ok { + t.Error("NativePhone: has a Kind key, but native profiles have none") + } +} + +func TestNativeProfileStartsWithNoHomePage(t *testing.T) { + // UpdateNavigationProfile's navPatchNativeProfile only overwrites + // NativeHomePage when the CREATE statement gives one — so a bare + // `create navigation NativePhone;` leaves this constructor's value in place. + // It must be an explicit null, not the fixture's configured home page. + v, ok := profileKey(newNativeProfileBson("NativePhone"), "NativeHomePage") + if !ok { + t.Fatal("NativePhone: no NativeHomePage key at all") + } + if v != nil { + t.Errorf("NativePhone: NativeHomePage = %#v, want an explicit null", v) + } +} + +func TestNativeProfileStartsWithEmptyChildCollections(t *testing.T) { + // OfflineEntityConfigs and RoleBasedNativeHomePages are stored EMPTY on the + // fixture's own (otherwise configured) document — direct evidence of the + // unconfigured state. BottomBarItems is only rewritten by + // UpdateNavigationProfile when the CREATE statement has a MENU block (see + // navPatchNativeProfile), so a freshly created profile must start empty here + // rather than carrying the fixture's configured bottom bar item forward. + for _, tc := range []struct { + key string + marker int32 + }{ + {"OfflineEntityConfigs", 3}, + {"RoleBasedNativeHomePages", 1}, + {"BottomBarItems", 2}, + } { + v, ok := profileKey(newNativeProfileBson("NativePhone"), tc.key) + if !ok { + t.Fatalf("NativePhone: no %s key at all", tc.key) + } + arr, ok := v.(bson.A) + if !ok { + t.Fatalf("NativePhone: %s is %T, want bson.A", tc.key, v) + } + if len(arr) != 1 { + t.Errorf("NativePhone: %s has %d entries beyond the marker, want 0", tc.key, len(arr)-1) + } + if len(arr) == 1 && arr[0] != tc.marker { + t.Errorf("NativePhone: %s marker = %v, want %d", tc.key, arr[0], tc.marker) + } + } +} + +func TestNativeProfileHasNoHermesEnabledKey(t *testing.T) { + // modelsdk/gen exposes a HermesEnabled setter, but the fixture's real + // document does not carry this key — writing a value here would be exactly + // the "assembled from a guess" failure mode this feature exists to avoid. + if _, ok := profileKey(newNativeProfileBson("NativePhone"), "HermesEnabled"); ok { + t.Error("NativePhone: has a HermesEnabled key, but the reference document does not") + } +} + func TestOfflineProfilesStartWithNoEntityConfigs(t *testing.T) { // Studio Pro DERIVES the offline entity list from the pages the profile // reaches; only rows that deviate from the defaults are stored. An empty diff --git a/mdl/backend/modelsdk/navigation_write.go b/mdl/backend/modelsdk/navigation_write.go index 4f8412a630..8172389cc6 100644 --- a/mdl/backend/modelsdk/navigation_write.go +++ b/mdl/backend/modelsdk/navigation_write.go @@ -12,6 +12,7 @@ import ( "github.com/mendixlabs/mxcli/mdl/bsonutil" "github.com/mendixlabs/mxcli/mdl/types" "github.com/mendixlabs/mxcli/model" + "github.com/mendixlabs/mxcli/sdk/pages" ) // UpdateNavigationProfile patches a navigation profile's home pages, login page, @@ -82,7 +83,11 @@ func (b *Backend) UpdateNavigationProfile(navDocID model.ID, profileName string, } found = true if navGetString(profDoc, "$Type") == "Navigation$NativeNavigationProfile" { - profiles[i] = navPatchNativeProfile(profDoc, spec) + patched, perr := navPatchNativeProfile(profDoc, spec) + if perr != nil { + return fmt.Errorf("UpdateNavigationProfile: %w", perr) + } + profiles[i] = patched } else { patched, err := navPatchWebProfile(profDoc, spec) if err != nil { @@ -324,7 +329,7 @@ func navGetDoc(doc bson.D, key string) bson.D { return nil } -func navPatchNativeProfile(doc bson.D, spec types.NavigationProfileSpec) bson.D { +func navPatchNativeProfile(doc bson.D, spec types.NavigationProfileSpec) (bson.D, error) { // Patch a copy: navSetField writes in place, and a caller's stored profile // must not change under it when no field is appended. doc = append(bson.D(nil), doc...) @@ -369,13 +374,141 @@ func navPatchNativeProfile(doc bson.D, spec types.NavigationProfileSpec) bson.D // A native profile stores its offline configs as a web profile does. The // executor refuses the clauses this writer cannot apply to a native - // profile (its bottom bar, login and not-found pages, on sync error), so - // none is ignored in silence (ako/mxcli#980). + // profile (login and not-found pages, on sync error), so none is ignored + // in silence (ako/mxcli#980). if spec.HasSync { doc = navSetField(doc, "OfflineEntityConfigs", navOfflineConfigs(navGetArray(doc, "OfflineEntityConfigs"), spec.OfflineEntities)) } - return doc + if spec.HasMenu { + barItems := bson.A{int32(2)} + for _, mi := range spec.MenuItems { + bar, err := navBottomBarItemBson(mi) + if err != nil { + return nil, err + } + barItems = append(barItems, bar) + } + doc = navSetField(doc, "BottomBarItems", barItems) + } + return doc, nil +} + +// navBottomBarItemBson builds a NativePages$BottomBarItem from a menu item spec. +// +// Mendix's native bottom bar is flat and page-only — NativePages$BottomBarItem +// (modelsdk/gen/nativepages) has no Items property (no sub-menus, unlike the web +// Menu's Menus$MenuItem) and its only navigation target is Page, a by-name +// reference to Forms$Page (its pre-8.15.0 Action property, which could carry a +// microflow action, is gone on every Mendix version this project targets — see +// nativepages.VersionInfos). A spec built from MDL's shared NavMenuItemSpec can +// carry either of those, so both are rejected explicitly rather than silently +// dropped, matching this project's "no silent unsupported migrations" stance. +// +// Icon: the one real reference document (native-pwa-migrator's +// fixtures/native-phone-minimal) has a Forms$GlyphIcon on its bottom bar item +// — a numeric Code, not a qualified name — so that is the one shape written +// here, from `Icon: glyph ` (IconKind glyph). A collection or image icon +// is still rejected: neither has been confirmed as a valid choice for a native +// BottomBarItem specifically — the fixture's GlyphIcon is exactly the different +// convention that makes them unconfirmed. Emitting an unconfirmed shape risks +// the failure this project exists to avoid — a document that builds clean and +// will not open in Studio Pro — so they stay rejected until a real +// Studio-Pro-authored example of either is found to pin against. +func navBottomBarItemBson(mi types.NavMenuItemSpec) (bson.D, error) { + if len(mi.Items) > 0 { + return nil, fmt.Errorf("native bottom bar item %q: sub-items are not supported — Mendix's native bottom bar menu is flat", mi.Caption) + } + page, err := navBottomBarPage(mi) + if err != nil { + return nil, err + } + icon, err := navBottomBarIconBson(mi) + if err != nil { + return nil, err + } + return bson.D{ + {Key: "$ID", Value: navID()}, + {Key: "$Type", Value: "NativePages$BottomBarItem"}, + {Key: "Caption", Value: navBottomBarCaptionBson(mi.Caption)}, + {Key: "Icon", Value: icon}, + {Key: "Page", Value: page}, + }, nil +} + +// navBottomBarIconBson is a bottom bar item's Icon: a Forms$GlyphIcon for a +// glyph, nil for no icon. That is the one icon shape pinned against a real +// Studio-Pro-authored document — see the fixture comment on +// navigation_bottombar_test.go — so a collection or image icon is refused. +func navBottomBarIconBson(mi types.NavMenuItemSpec) (any, error) { + switch { + case mi.IconKind == types.MenuIconGlyph: + return bson.D{ + {Key: "$ID", Value: navID()}, + {Key: "$Type", Value: "Forms$GlyphIcon"}, + {Key: "Code", Value: int32(mi.IconCode)}, + }, nil + case mi.Icon != "" || mi.IconKind != types.MenuIconNone: + return nil, fmt.Errorf("native bottom bar item %q: only a glyph icon is supported — a collection or image icon is unconfirmed for native bottom bar items; use Icon: glyph , or set it in Studio Pro", mi.Caption) + } + return nil, nil +} + +// navBottomBarPage is the page a bottom bar item opens. The executor hands the +// item's OnClick over as a built client action (ako/mxcli#980), a caller other +// than the executor only the legacy Page target; either way the only action a +// BottomBarItem can store is a by-name Page, so every other one — a microflow, +// nanoflow, sign out, an action kept from storage — is refused rather than +// written as nothing. +func navBottomBarPage(mi types.NavMenuItemSpec) (string, error) { + refuse := func(what string) (string, error) { + return "", fmt.Errorf("native bottom bar item %q: %s is not supported — the native bottom bar can only open a page", mi.Caption, what) + } + switch { + case len(mi.KeepAction) > 0: + return refuse("a stored action the item does not restate") + case mi.Microflow != "": + return refuse("a microflow target") + case mi.SignOut: + return refuse("sign out") + } + page := mi.Page + switch a := mi.Action.(type) { + case nil, *pages.NoClientAction: + case *pages.PageClientAction: + if len(a.ParameterMappings) > 0 { + return refuse("a page argument") + } + page = a.PageName + default: + return refuse(fmt.Sprintf("the action %T", a)) + } + if page == "" { + return "", fmt.Errorf("native bottom bar item %q: a page target is required — the native bottom bar has no other action", mi.Caption) + } + return page, nil +} + +// navBottomBarCaptionBson builds a BottomBarItem's Caption (Texts$Text). +// +// Written separately from navCaptionBson (rather than calling it) because this +// helper predates that one's marker fix and the two write paths (native bottom +// bar vs. web menu items) are independent; both now emit the same marker-3 +// shape — see navCaptionBson's doc comment. +func navBottomBarCaptionBson(text string) bson.D { + return bson.D{ + {Key: "$ID", Value: navID()}, + {Key: "$Type", Value: "Texts$Text"}, + {Key: "Items", Value: bson.A{ + int32(3), + bson.D{ + {Key: "$ID", Value: navID()}, + {Key: "$Type", Value: "Texts$Translation"}, + {Key: "LanguageCode", Value: model.AuthoringLanguage()}, + {Key: "Text", Value: text}, + }, + }}, + } } // navMergeRoleHomes is a profile's role-based home pages after a statement that @@ -511,6 +644,16 @@ func navMenuIconBson(spec types.NavMenuItemSpec) interface{} { return append(doc, bson.E{Key: "Image", Value: spec.Icon}) } +// navCaptionBson builds a web MENU ITEM's caption (Texts$Text). +// +// Items marker is 3, not 1: confirmed by walking every Texts$Text.Items +// occurrence (7300+ across two real Studio-Pro-authored fixtures, including +// this exact call site — a web profile's Menu.Items[…].Caption — plus that +// same profile's AppTitle and a NativePhone profile's BottomBarItem.Caption, +// see navBottomBarCaptionBson) — marker 3 in every single case, matching +// modelsdk/codec's own default for an unregistered PartList child type +// (Texts$Translation has no codec.RegisterListMarker override — see +// modelsdk/codec/defaults.go's lookupListMarker). func navCaptionBson(text string) bson.D { return bson.D{ {Key: "$ID", Value: navID()}, diff --git a/mdl/backend/navigation.go b/mdl/backend/navigation.go index d3e6daaa9e..d76f7dfa92 100644 --- a/mdl/backend/navigation.go +++ b/mdl/backend/navigation.go @@ -12,10 +12,12 @@ type NavigationBackend interface { ListNavigationDocuments() ([]*types.NavigationDocument, error) GetNavigation() (*types.NavigationDocument, error) UpdateNavigationProfile(navDocID model.ID, profileName string, spec types.NavigationProfileSpec) error - // AddNavigationProfile appends a new WEB navigation profile (Responsive, - // Phone or Tablet). Mendix's set is fixed, so this takes a kind rather than - // an arbitrary name. Callers create then update: this leaves the profile - // empty and UpdateNavigationProfile fills it. + // AddNavigationProfile appends a new web (Responsive, Phone, Tablet, or their + // *Offline twins) or native (NativePhone) navigation profile. Mendix's set is + // fixed for both families, so this takes a kind/name rather than an + // arbitrary one. Callers create then update: this leaves the profile empty + // (or, for native, with its home page/menu still unset) and + // UpdateNavigationProfile fills it. AddNavigationProfile(navDocID model.ID, name string) error // OpenNavigationProfileForMutation loads the navigation document and diff --git a/mdl/executor/cmd_navigation.go b/mdl/executor/cmd_navigation.go index 5b794576da..5b76b90832 100644 --- a/mdl/executor/cmd_navigation.go +++ b/mdl/executor/cmd_navigation.go @@ -90,14 +90,18 @@ func execCreateNavigation(ctx *ExecContext, s *ast.CreateNavigationStmt) error { // User-Agent — not on viewport width — so a device-specific front end could // not be built from MDL at all (ako/mxcli-maintenance §7). // - // Mendix's web profiles are a closed set, so an unknown name is still an - // error: creating "Phone" is adding the profile the platform defines, - // while creating "Mobile" would be inventing one that can never route. + // Mendix's web and native profiles are both closed sets, so an unknown + // name is still an error: creating "Phone" or "NativePhone" is adding a + // profile the platform defines, while creating "Mobile" would be + // inventing one that can never route. kind, ok := types.CanonicalProfileKind(s.ProfileName) + if !ok { + kind, ok = types.CanonicalNativeProfileKind(s.ProfileName) + } if !ok { return mdlerrors.NewNotFoundMsg("navigation profile", s.ProfileName, - fmt.Sprintf("navigation profile not found: %s (available: %s; Mendix's web profiles are %s)", - s.ProfileName, profileNames(nav), strings.Join(types.WebProfileKindNames(), ", "))) + fmt.Sprintf("navigation profile not found: %s (available: %s; Mendix's web profiles are %s, and its native profiles are %s)", + s.ProfileName, profileNames(nav), strings.Join(types.WebProfileKindNames(), ", "), strings.Join(types.NativeProfileKindNames(), ", "))) } if err := ctx.Backend.AddNavigationProfile(nav.ID, kind); err != nil { return mdlerrors.NewBackend("create navigation profile", err) @@ -199,10 +203,10 @@ func warnOfflineWithoutPWA(ctx *ExecContext, s *ast.CreateNavigationStmt, kind s // checkProfileClauses refuses what the statement says that the profile cannot // take, before anything is written (ako/mxcli#980). // -// A native profile's writer sets its home pages and offline sync and nothing -// else, so a menu block, login or not-found page or on-sync-error clause on one -// was dropped in silence: the statement reported "updated" and the bottom bar -// stayed as it was. Its flow home is a nanoflow — `home microflow` there is +// A native profile's writer sets its home pages, offline sync and bottom bar +// (the { } block) and nothing else, so a login or not-found page or +// on-sync-error clause on one was dropped in silence: the statement reported +// "updated" and the profile stayed as it was. Its flow home is a nanoflow — `home microflow` there is // what describe used to print, so it is read as the nanoflow and warned about — // while a web profile's is a microflow, so `home nanoflow` there is refused. func checkProfileClauses(ctx *ExecContext, s *ast.CreateNavigationStmt, isNative bool) error { @@ -220,8 +224,6 @@ func checkProfileClauses(ctx *ExecContext, s *ast.CreateNavigationStmt, isNative "and leaving it out is how it used to be dropped without a word — remove it from the statement and set it in Studio Pro", s.ProfileName, what) } switch { - case s.HasMenuBlock: - return refuse("its bottom bar (the { } block)") case s.LoginPage != nil: return refuse("login page") case s.NotFoundPage != nil: @@ -817,25 +819,11 @@ func outputNavigationProfile(ctx *ExecContext, p *types.NavigationProfile) { } } - // A native profile's bottom bar is not written by mxcli, so it is not a - // { } block exec would have to refuse: it is listed as comments, each item - // as it would read (ako/mxcli#980). - if p.IsNative && len(p.MenuItems) > 0 { - fmt.Fprintln(ctx.Output, " -- bottom bar (not written by mxcli; set it in Studio Pro):") - var bar strings.Builder - printMenuMDL(ctx, &bar, p.MenuItems, 0, "CREATE NAVIGATION") - for _, line := range strings.Split(strings.TrimRight(bar.String(), "\n"), "\n") { - fmt.Fprintf(ctx.Output, " -- %s\n", strings.TrimPrefix(line, "-- ")) - } - fmt.Fprintln(ctx.Output, ";") - fmt.Fprintln(ctx.Output) - return - } - - // Menu items: the profile's children, in { } after its clauses (R2). + // Menu items: the profile's children, in { } after its clauses (R2). A + // native profile's are its bottom bar, written by the same block. if len(p.MenuItems) > 0 { fmt.Fprintln(ctx.Output, "{") - printMenuMDL(ctx, ctx.Output, p.MenuItems, 1, "CREATE NAVIGATION") + printMenuMDLFor(ctx, ctx.Output, p.MenuItems, 1, "CREATE NAVIGATION", p.IsNative) fmt.Fprintln(ctx.Output, "};") } else { fmt.Fprintln(ctx.Output, ";") @@ -879,7 +867,17 @@ func menuItemTarget(item *types.NavMenuItem) string { // (renderClientActionMDL), so every kind a menu item stores — a nanoflow call, // open link, create object — and every `with ( … )` setting prints, and what // MDL cannot express is said in a comment rather than left out (ako/mxcli#980). +// +// native is true for a NativePhone profile's bottom bar: CREATE NAVIGATION can +// author only a glyph icon there (see navBottomBarItemBson), so a collection or +// image icon — which the web Menu can reproduce — gets the "not reproducible" +// note instead of an Icon: property. func printMenuMDL(ctx *ExecContext, w io.Writer, items []*types.NavMenuItem, depth int, reproducer string) { + printMenuMDLFor(ctx, w, items, depth, reproducer, false) +} + +// printMenuMDLFor is printMenuMDL with the native flag above. +func printMenuMDLFor(ctx *ExecContext, w io.Writer, items []*types.NavMenuItem, depth int, reproducer string, native bool) { indent := strings.Repeat(" ", depth) for _, item := range items { var props []string @@ -895,7 +893,7 @@ func printMenuMDL(ctx *ExecContext, w io.Writer, items []*types.NavMenuItem, dep // has no OnClick on one, so the rewrite keeps it only as stored. actionNote = fmt.Sprintf("-- menu %s: its action (%s) belongs to a sub-menu and has no MDL form there", menuCaptionNote(item.Caption), onClick) } - if icon := menuItemIconMDL(item); icon != "" { + if icon := menuItemIconMDL(item, native); icon != "" { props = append(props, "Icon: "+icon) } propList := "" @@ -905,12 +903,12 @@ func printMenuMDL(ctx *ExecContext, w io.Writer, items []*types.NavMenuItem, dep if len(item.Items) > 0 { // Sub-menu container fmt.Fprintf(w, "%smenu %s%s {\n", indent, mdlQuote(ctx, item.Caption), propList) - printMenuMDL(ctx, w, item.Items, depth+1, reproducer) + printMenuMDLFor(ctx, w, item.Items, depth+1, reproducer, native) fmt.Fprintf(w, "%s}\n", indent) } else { fmt.Fprintf(w, "%smenu item %s%s\n", indent, mdlQuote(ctx, item.Caption), propList) } - if note := menuItemIconNote(item, reproducer); note != "" { + if note := menuItemIconNote(item, reproducer, native); note != "" { fmt.Fprintf(w, "%s%s\n", indent, note) } if actionNote != "" { @@ -941,8 +939,13 @@ func legacyMenuItemOnClick(item *types.NavMenuItem) string { // All three of Mendix's icon elements have a form now. Only the collection one // used to, so DESCRIBE emitted a comment for a glyph or image icon — and since // CREATE NAVIGATION is a full replacement, re-running that output DELETED the -// icon it had just declined to describe. -func menuItemIconMDL(item *types.NavMenuItem) string { +// icon it had just declined to describe. A native bottom bar item can +// reproduce only a glyph icon (navBottomBarItemBson); a collection or image +// icon there falls through to the note. +func menuItemIconMDL(item *types.NavMenuItem, native bool) string { + if native && types.MenuIconKindOf(item.IconType) != types.MenuIconGlyph { + return "" + } switch types.MenuIconKindOf(item.IconType) { case types.MenuIconGlyph: // The code is the whole identity of a glyph. Without it there is nothing @@ -968,18 +971,21 @@ func menuItemIconMDL(item *types.NavMenuItem) string { // menuItemIconNote flags an icon DESCRIBE still cannot round-trip, so re-running // the output loses it visibly rather than silently. // -// All three icon elements are reproducible now, so this fires only on what is -// genuinely beyond the language: a stored $Type this build does not know, or a -// variant whose payload is missing (a glyph with no Code, a named icon with no -// name) — where emitting a clause would rebuild a DIFFERENT icon rather than the -// same one. Guessing between polymorphic variants is the failure mode that -// produces a document mxbuild accepts and Studio Pro cannot open. -func menuItemIconNote(item *types.NavMenuItem, reproducer string) string { +// All three icon elements are reproducible now on a web menu item, so this +// fires only on what is genuinely beyond the language: a stored $Type this +// build does not know, or a variant whose payload is missing (a glyph with no +// Code, a named icon with no name) — where emitting a clause would rebuild a +// DIFFERENT icon rather than the same one. On a native bottom bar item only a +// glyph icon is reproducible (navBottomBarItemBson); a collection or image +// icon there gets this note too. Guessing between +// polymorphic variants is the failure mode that produces a document mxbuild +// accepts and Studio Pro cannot open. +func menuItemIconNote(item *types.NavMenuItem, reproducer string, native bool) string { if item.IconType == "" { return "" } // If there is a clause for it, there is nothing to flag. - if menuItemIconMDL(item) != "" { + if menuItemIconMDL(item, native) != "" { return "" } target := item.Icon diff --git a/mdl/executor/cmd_navigation_icon_roundtrip_test.go b/mdl/executor/cmd_navigation_icon_roundtrip_test.go index 2b9f6d519d..b462316ad2 100644 --- a/mdl/executor/cmd_navigation_icon_roundtrip_test.go +++ b/mdl/executor/cmd_navigation_icon_roundtrip_test.go @@ -60,14 +60,14 @@ func TestMenuIconMDL_RoundTripsEveryVariant(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - got := menuItemIconMDL(&tc.item) + got := menuItemIconMDL(&tc.item, false) if got != tc.want { t.Fatalf("menuItemIconMDL = %q, want %q", got, tc.want) } // It must also re-parse to the same kind, or DESCRIBE emits something // that reads back as a different icon — which is what the bare form // would have done for an image icon. - if note := menuItemIconNote(&tc.item, "CREATE NAVIGATION"); note != "" { + if note := menuItemIconNote(&tc.item, "CREATE NAVIGATION", false); note != "" { t.Errorf("still flagged as unreproducible: %q", note) } }) @@ -86,10 +86,10 @@ func TestMenuIconMDL_DeclinesWhatItCannotRebuild(t *testing.T) { // A $Type this build does not know must never be guessed at. {IconType: "Forms$SomeFutureIcon", Icon: "M.X.y"}, } { - if got := menuItemIconMDL(&item); got != "" { + if got := menuItemIconMDL(&item, false); got != "" { t.Errorf("%s: emitted %q, want no clause", item.IconType, got) } - if note := menuItemIconNote(&item, "CREATE NAVIGATION"); !strings.Contains(note, "not reproducible") { + if note := menuItemIconNote(&item, "CREATE NAVIGATION", false); !strings.Contains(note, "not reproducible") { t.Errorf("%s: dropped silently instead of being flagged: %q", item.IconType, note) } } diff --git a/mdl/executor/cmd_navigation_icon_test.go b/mdl/executor/cmd_navigation_icon_test.go index 1a8de1055b..fedb563837 100644 --- a/mdl/executor/cmd_navigation_icon_test.go +++ b/mdl/executor/cmd_navigation_icon_test.go @@ -10,6 +10,7 @@ import ( "github.com/mendixlabs/mxcli/mdl/ast" "github.com/mendixlabs/mxcli/mdl/types" "github.com/mendixlabs/mxcli/mdl/visitor" + "github.com/mendixlabs/mxcli/model" ) // menuMDL renders items through the DESCRIBE emitter. @@ -19,6 +20,13 @@ func menuMDL(items []*types.NavMenuItem) string { return b.String() } +// nativeMenuMDL is menuMDL for a NativePhone profile's bottom bar. +func nativeMenuMDL(items []*types.NavMenuItem) string { + var b bytes.Buffer + printMenuMDLFor(nil, &b, items, 0, "CREATE NAVIGATION", true) + return b.String() +} + // DESCRIBE emits re-executable MDL, so an icon it read must come back out — the // alternative is output that silently rewrites the menu when replayed. The // hyphenated segment has to be re-quoted: `align-center` lexes as HYPHENATED_ID, @@ -137,6 +145,69 @@ func TestPrintMenuMDL_StillFlagsWhatItCannotRebuild(t *testing.T) { } } +// A native profile's bottom bar cannot author an IconCollectionIcon +// (navBottomBarItemBson accepts only a glyph) even though the web Menu +// reproduces one fine. DESCRIBE must flag it instead of emitting a property +// that would fail on replay. +func TestPrintMenuMDL_NativeNeverEmitsAnIconCollectionIcon(t *testing.T) { + got := nativeMenuMDL([]*types.NavMenuItem{{ + Caption: "Home", + Page: "NativeMobile.Home_Native", + Icon: "Atlas_Core.Atlas.home", + IconType: "Forms$IconCollectionIcon", + }}) + stmt := strings.SplitN(got, "\n", 2)[0] + if strings.Contains(stmt, "Icon:") { + t.Errorf("emitted an Icon: property for a native bottom bar item, which replay would reject: %q", got) + } + if !strings.Contains(got, "-- icon") || !strings.Contains(got, "Atlas_Core.Atlas.home") { + t.Errorf("the unreproducible native icon was dropped silently: %q", got) + } +} + +// A native bottom bar item's glyph IS reproducible — the one icon shape +// navBottomBarItemBson accepts — so it gets `Icon: glyph `, not a note, +// and that output parses back to the same glyph. +func TestPrintMenuMDL_NativeRoundTripsAGlyphIcon(t *testing.T) { + got := nativeMenuMDL([]*types.NavMenuItem{{ + Caption: "Home", + Page: "NativeMobile.Home_Native", + IconType: "Forms$GlyphIcon", + IconCode: 57377, + }}) + want := "menu item 'Home' ( OnClick: show page NativeMobile.Home_Native, Icon: glyph 57377 )\n" + if got != want { + t.Errorf("got %q, want %q", got, want) + } + + script := "create or modify navigation NativePhone {\n" + got + "};" + prog, errs := visitor.Build(script) + if len(errs) > 0 { + t.Fatalf("DESCRIBE emitted output its own parser rejects:\n%s\nerrors: %v", script, errs) + } + stmt, ok := prog.Statements[0].(*ast.CreateNavigationStmt) + if !ok || len(stmt.MenuItems) != 1 { + t.Fatalf("re-parsed to %T", prog.Statements[0]) + } + if it := stmt.MenuItems[0]; it.IconKind != types.MenuIconGlyph || it.IconCode != 57377 { + t.Errorf("round trip changed the glyph: got (%v, %d), want (glyph, 57377)", it.IconKind, it.IconCode) + } +} + +// Exec hands a native item's glyph to the writer as IconKind/IconCode, the +// same fields a web item's glyph travels in. +func TestExecNativeNavigation_PassesTheGlyphIcon(t *testing.T) { + var got types.NavigationProfileSpec + mb := nativeNav() + mb.UpdateNavigationProfileFunc = func(_ model.ID, _ string, spec types.NavigationProfileSpec) error { got = spec; return nil } + if _, err := runNav(t, mb, "create or modify navigation NativePhone { menu item 'Home' ( OnClick: show page M.P, Icon: glyph 57377 ) };"); err != nil { + t.Fatal(err) + } + if len(got.MenuItems) != 1 || got.MenuItems[0].IconKind != types.MenuIconGlyph || got.MenuItems[0].IconCode != 57377 { + t.Errorf("spec.MenuItems = %+v, want one item with a glyph 57377", got.MenuItems) + } +} + // No icon means no clause and no note — the common case must stay clean. func TestPrintMenuMDL_SilentWhenThereIsNoIcon(t *testing.T) { got := menuMDL([]*types.NavMenuItem{{Caption: "Dashboard", Page: "M.Dash"}}) diff --git a/mdl/executor/cmd_navigation_native_test.go b/mdl/executor/cmd_navigation_native_test.go index 5866c5a012..8f1c6e7816 100644 --- a/mdl/executor/cmd_navigation_native_test.go +++ b/mdl/executor/cmd_navigation_native_test.go @@ -38,11 +38,11 @@ func runNav(t *testing.T, mb *mock.MockBackend, script string) (string, error) { return buf.String(), err } -// ako/mxcli#980: the native writer applies home pages and sync only, so a menu -// block (the bottom bar), login / not-found page or on-sync-error on a native -// profile was dropped while exec reported "updated". It is refused now. +// ako/mxcli#980: the native writer applies home pages, sync and the bottom bar +// only, so a login / not-found page or on-sync-error on a native profile was +// dropped while exec reported "updated". It is refused now. func TestNativeProfile_RefusesWhatItsWriterCannotApply(t *testing.T) { - for _, clause := range []string{"{ menu item 'X' ( OnClick: show page M.P ) }", "login page M.Login", "not found page M.NF", "on sync error continue"} { + for _, clause := range []string{"login page M.Login", "not found page M.NF", "on sync error continue"} { wrote := false mb := nativeNav() mb.UpdateNavigationProfileFunc = func(model.ID, string, types.NavigationProfileSpec) error { wrote = true; return nil } @@ -51,16 +51,19 @@ func TestNativeProfile_RefusesWhatItsWriterCannotApply(t *testing.T) { t.Errorf("%q: err=%v wrote=%v, want a refusal and no write", clause, err, wrote) } } - // CONTROL: home and sync are what the native writer applies. + // CONTROL: home, sync and the bottom bar are what the native writer applies. var got types.NavigationProfileSpec mb := nativeNav() mb.UpdateNavigationProfileFunc = func(_ model.ID, _ string, spec types.NavigationProfileSpec) error { got = spec; return nil } - if _, err := runNav(t, mb, "create or modify navigation NativePhone home nanoflow M.Home_NF sync ( sync M.Order all; );"); err != nil { + if _, err := runNav(t, mb, "create or modify navigation NativePhone home nanoflow M.Home_NF sync ( sync M.Order all; ) { menu item 'X' ( OnClick: show page M.P ) };"); err != nil { t.Fatal(err) } if !got.HasSync || len(got.HomePages) != 1 || got.HomePages[0].IsPage { t.Errorf("spec = %+v", got) } + if !got.HasMenu || len(got.MenuItems) != 1 || got.MenuItems[0].Caption != "X" { + t.Errorf("bottom bar not passed to the writer: %+v", got.MenuItems) + } } // `home nanoflow` is a native profile's; on a web profile it is refused, and @@ -77,7 +80,7 @@ func TestNavigationHomeNanoflow(t *testing.T) { } // Describe of a native profile names its nanoflow home `home nanoflow` and -// lists the bottom bar as comments, so its own output re-runs. +// emits the bottom bar as the profile's { } block, so its own output re-runs. func TestDescribeNativeProfile_ReRuns(t *testing.T) { mb := nativeNav() ctx, buf := newMockCtx(t, withBackend(mb)) @@ -86,8 +89,8 @@ func TestDescribeNativeProfile_ReRuns(t *testing.T) { if !strings.Contains(out, "home nanoflow M.Home_NF") || strings.Contains(out, "home microflow") { t.Errorf("native home:\n%s", out) } - if !strings.Contains(out, "-- menu item 'Reports' ( OnClick: show page M.Reports )") { - t.Errorf("bottom bar not listed as comments:\n%s", out) + if !strings.Contains(out, "{\n menu item 'Reports' ( OnClick: show page M.Reports )\n};") { + t.Errorf("bottom bar not emitted as a { } block:\n%s", out) } mb.UpdateNavigationProfileFunc = func(model.ID, string, types.NavigationProfileSpec) error { return nil } if _, err := runNav(t, mb, out); err != nil { diff --git a/mdl/executor/cmd_pages_describe_output.go b/mdl/executor/cmd_pages_describe_output.go index 8ad3693098..a8b5f3d8d3 100644 --- a/mdl/executor/cmd_pages_describe_output.go +++ b/mdl/executor/cmd_pages_describe_output.go @@ -1033,6 +1033,16 @@ func outputWidgetMDLV3(ctx *ExecContext, w rawWidget, indent int) { } } else { header := fmt.Sprintf("%s %s", widgetType, mdlIdent(w.Name)) + // A widget with no branch of its own is named the way the + // generic branch names it — its definition's keyword where that + // round-trips, else the id form. widgetType is the id's last + // segment, which names the web widget for a native one + // (`badge`) or no widget at all (`activityindicator`), so a + // native widget left at its defaults re-ran as the web widget + // or was refused. + if !isKnownCustomWidgetType(widgetType) && w.WidgetID != "" { + header = pluggableWidgetHeader(ctx.GetWidgetRegistry(), w.WidgetID, w.Name) + } props := []string{} if w.Caption != "" { props = append(props, fmt.Sprintf("Label: %s", mdlQuote(ctx, w.Caption))) diff --git a/mdl/executor/cmd_pages_describe_pluggable.go b/mdl/executor/cmd_pages_describe_pluggable.go index 3937e295e5..eb56e08201 100644 --- a/mdl/executor/cmd_pages_describe_pluggable.go +++ b/mdl/executor/cmd_pages_describe_pluggable.go @@ -130,12 +130,17 @@ func extractCustomWidgetType(ctx *ExecContext, w map[string]any) string { case "com.mendix.widget.web.image.Image": return "image" default: - // Extract last part of widget ID and uppercase it + // The last part of the widget ID, lowercased. It routes describe, + // so it must not name a dedicated branch: those were written for + // the web widgets matched above, and another widget ending in the + // same segment — the native Gallery and Image — was described as + // the web one and rebuilt as it on re-run. parts := strings.Split(widgetID, ".") - if len(parts) > 0 { - return strings.ToLower(parts[len(parts)-1]) + seg := strings.ToLower(parts[len(parts)-1]) + if isKnownCustomWidgetType(seg) { + return "customwidget" } - return strings.ToLower(widgetID) + return seg } } return "" diff --git a/mdl/executor/describe_native_widget_keyword_test.go b/mdl/executor/describe_native_widget_keyword_test.go new file mode 100644 index 0000000000..b5269b27c8 --- /dev/null +++ b/mdl/executor/describe_native_widget_keyword_test.go @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "bytes" + "strings" + "testing" +) + +// A native mobile widget is described under the keyword `widget init` gave it +// (`nativegallery`, `nativeactivityindicator`, …), or — with no definition to +// resolve against — the `pluggablewidget ''` form. Never under the last +// segment of its id. +// +// Measured on PedApp (11.13.0) with Native Mobile Resources 12.6.0 installed: +// a native widget with no setting away from its default took the bare branch +// of describe, which printed the id's last segment. Three of those segments +// are WEB keywords — `gallery`, `badge`, `image` — so re-running the +// description rebuilt the page with the web widget in place of the native one, +// and `check` passed it. Seven more (`activityindicator`, `qrcode`, …) named no +// widget at all and were refused (MDL-WIDGET25). `gallery` and `image` were +// worse still: they are matched on that segment to the WEB widget's dedicated +// branch, so a native gallery with a data source was described as the web one +// too. +func TestDescribeNativeWidget_UsesItsOwnKeyword(t *testing.T) { + registry := LoadWidgetRegistry("") + if registry == nil { + t.Fatal("no registry — the embedded definitions must load, or this test proves nothing") + } + natives := map[string]string{ + "com.mendix.widget.native.gallery.Gallery": "nativegallery", + "com.mendix.widget.native.badge.Badge": "nativebadge", + "com.mendix.widget.native.image.Image": "nativeimage", + "com.mendix.widget.native.activityindicator.ActivityIndicator": "nativeactivityindicator", + "com.mendix.widget.native.qrcode.QRCode": "nativeqrcode", + "com.mendix.widget.native.repeater.Repeater": "nativerepeater", + } + for id, kw := range natives { + def := &WidgetDefinition{WidgetID: id, MDLName: strings.ToUpper(kw), WidgetKind: "pluggable"} + registry.byWidgetID[id] = def + registry.byMDLName[strings.ToUpper(kw)] = def + } + + for id, kw := range natives { + t.Run(kw, func(t *testing.T) { + got := describeBareCustomWidget(t, registry, id, "w1") + if want := kw + " w1"; !strings.HasPrefix(got, want) { + t.Errorf("described as %q, want %q — the keyword that builds %s", got, want, id) + } + }) + } +} + +// Without a project the registry holds only the embedded (web) definitions, so +// a native widget has no keyword to resolve to: the id form is the one that +// builds it again. The last segment would name the web widget or nothing. +func TestDescribeNativeWidget_NoDefinitionUsesTheIDForm(t *testing.T) { + registry := LoadWidgetRegistry("") + for _, id := range []string{ + "com.mendix.widget.native.gallery.Gallery", + "com.mendix.widget.native.badge.Badge", + "com.mendix.widget.native.signature.Signature", + } { + got := describeBareCustomWidget(t, registry, id, "w1") + if want := "pluggablewidget '" + id + "' w1"; !strings.HasPrefix(got, want) { + t.Errorf("described as %q, want %q", got, want) + } + } +} + +// The control: the web widgets keep their keyword — gallery and image through +// their dedicated branches, the badge through the definition `widget init` +// writes for it (without one, it takes the id form, as it does when it has +// settings). +func TestDescribeWebWidget_KeepsItsKeyword(t *testing.T) { + registry := LoadWidgetRegistry("") + badge := &WidgetDefinition{WidgetID: "com.mendix.widget.custom.badge.Badge", MDLName: "BADGE", WidgetKind: "pluggable"} + registry.byWidgetID[badge.WidgetID] = badge + registry.byMDLName["BADGE"] = badge + for id, kw := range map[string]string{ + "com.mendix.widget.web.gallery.Gallery": "gallery", + "com.mendix.widget.web.image.Image": "image", + "com.mendix.widget.custom.badge.Badge": "badge", + } { + got := describeBareCustomWidget(t, registry, id, "w1") + if want := kw + " w1"; !strings.HasPrefix(got, want) { + t.Errorf("%s described as %q, want %q", id, got, want) + } + } +} + +// extractCustomWidgetType picks the dedicated describe branch. Only the web +// widget a branch was written for may land in it. +func TestExtractCustomWidgetType_NativeIDIsNotTheWebWidget(t *testing.T) { + for _, id := range []string{ + "com.mendix.widget.native.gallery.Gallery", + "com.mendix.widget.native.image.Image", + "com.acme.widgets.combobox.Combobox", + } { + got := extractCustomWidgetType(nil, map[string]any{"Type": map[string]any{"WidgetId": id}}) + if isKnownCustomWidgetType(got) { + t.Errorf("%s routed to the dedicated %q branch, which describes a different widget", id, got) + } + } + // Control: the web gallery is still routed to its branch. + if got := extractCustomWidgetType(nil, map[string]any{"Type": map[string]any{ + "WidgetId": "com.mendix.widget.web.gallery.Gallery"}}); got != "gallery" { + t.Errorf("web gallery routed to %q, want gallery", got) + } +} + +// describeBareCustomWidget describes a stored pluggable widget that holds no +// setting away from its default. +func describeBareCustomWidget(t *testing.T, registry *WidgetRegistry, widgetID, name string) string { + t.Helper() + stored := map[string]any{ + "$Type": "CustomWidgets$CustomWidget", + "Name": name, + "Type": map[string]any{ + "WidgetId": widgetID, + "ObjectType": map[string]any{"PropertyTypes": []any{int32(3)}}, + }, + "Object": map[string]any{"Properties": []any{int32(3)}}, + } + var buf bytes.Buffer + ctx := (&Executor{}).newExecContext(nil) + ctx.Output = &buf + ctx.widgetRegistry, ctx.widgetRegistryLoaded = registry, true + raws := parseRawWidget(ctx, stored) + if len(raws) != 1 { + t.Fatalf("parsed %d widgets, want 1", len(raws)) + } + outputWidgetMDLV3(ctx, raws[0], 0) + return strings.TrimSpace(buf.String()) +} diff --git a/mdl/executor/editorconfig_extract.go b/mdl/executor/editorconfig_extract.go index 28e910141f..b96da3476d 100644 --- a/mdl/executor/editorconfig_extract.go +++ b/mdl/executor/editorconfig_extract.go @@ -161,6 +161,18 @@ func extractVisibilityRulesFromJS(js string) ([]types.WidgetVisibilityRule, edit stats.SkippedComplex++ continue } + // A list computed by a switch (the native Image's image source). + if lifted, ok := iifeSwitchHideRules(js, callStart, args, consts); ok { + stats.Recognized++ + for _, r := range lifted { + sig := "\x00" + r.PropertyKey + "\x00" + r.HiddenWhen.PropertyKey + r.HiddenWhen.Operator + r.HiddenWhen.Value + if !seen[sig] { + seen[sig] = true + rules = append(rules, r) + } + } + continue + } listKey, keys, condKeys, ok := hideTargetKeys(args, consts) if !ok || (len(keys) == 0 && len(condKeys) == 0) { stats.SkippedComplex++ diff --git a/mdl/executor/editorconfig_iife_switch.go b/mdl/executor/editorconfig_iife_switch.go new file mode 100644 index 0000000000..74ea476a8e --- /dev/null +++ b/mdl/executor/editorconfig_iife_switch.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "regexp" + "strings" + + "github.com/mendixlabs/mxcli/mdl/types" +) + +// A hide call whose list is computed by a switch in an immediately-invoked +// function — the native Image's (Native Mobile Resources): +// +// return x.hidePropertiesIn(t, v, function(s){switch(s){ +// case "image": return L.filter(function(p){return "imageObject" !== p}); +// case "imageUrl": return L.filter(function(p){return "imageUrl" !== p}); +// default: return L }}(v.datasource)) +// +// Each case hides the whole list L but one member, and the default hides all +// of it. So a member is hidden unless the switched property holds one of the +// cases that keeps it: `notin` over those cases. +// +// Only that exact shape is read, and only at a function's own statement level +// with nothing guarding it. Anything else — a default other than L, a case +// keeping more than one member, a guard before the call — is left unread, +// which degrades to "not hidden" as every unread hide does. +var ( + iifeSwitchRE = regexp.MustCompile(`^function\(([\w$]+)\)\{switch\(([\w$]+)\)\{(.*)\}\}\(([\w$]+\.[\w$]+)\)$`) + iifeCaseRE = regexp.MustCompile(`^case"([^"]*)":return ([\w$]+)\.filter\(function\(([\w$]+)\)\{return(?:"([^"]*)"!==([\w$]+)|([\w$]+)!=="([^"]*)")\}\)$`) + iifeDefRE = regexp.MustCompile(`^default:return ([\w$]+)$`) + unguardedRE = regexp.MustCompile(`return\s*(?:[\w$]+\.)?$`) +) + +func iifeSwitchHideRules(js string, callStart int, args string, consts map[string][]string) ([]types.WidgetVisibilityRule, bool) { + parts := splitTopLevelCommas(args) + if len(parts) != 3 { + return nil, false + } + m := iifeSwitchRE.FindStringSubmatch(strings.TrimSpace(parts[2])) + if m == nil || m[1] != m[2] { + return nil, false + } + // Unguarded: `return [receiver.]hide…(` opening a function's statement. + loc := unguardedRE.FindStringIndex(js[:callStart]) + if loc == nil || !atFunctionStatementLevel(js, loc[0]) { + return nil, false + } + key, scope, ok := resolveRef(m[4], enclosingAliases(js, callStart), "") + if !ok || scope != "" { + return nil, false + } + + list, keeps := "", map[string][]string{} // member -> case values keeping it + sawDefault := false + for _, arm := range strings.Split(m[3], ";") { + if d := iifeDefRE.FindStringSubmatch(arm); d != nil { + if sawDefault || (list != "" && d[1] != list) { + return nil, false + } + list, sawDefault = d[1], true + continue + } + c := iifeCaseRE.FindStringSubmatch(arm) + if c == nil { + return nil, false + } + param, kept, ref := c[3], c[4], c[5] + if kept == "" { + kept, ref = c[7], c[6] + } + if ref != param || (list != "" && c[2] != list) { + return nil, false + } + list = c[2] + keeps[kept] = append(keeps[kept], c[1]) + } + members, known := consts[list] + if !sawDefault || !known { + return nil, false + } + inList := map[string]bool{} + for _, k := range members { + inList[k] = true + } + for k := range keeps { + if !inList[k] { + return nil, false // a case keeps something the list does not hold + } + } + var rules []types.WidgetVisibilityRule + for _, k := range members { + rules = append(rules, types.WidgetVisibilityRule{ + PropertyKey: k, + HiddenWhen: &types.WidgetVisibilityCondition{PropertyKey: key, Operator: "notin", Value: strings.Join(keeps[k], ",")}, + }) + } + return rules, true +} diff --git a/mdl/executor/editorconfig_iife_switch_test.go b/mdl/executor/editorconfig_iife_switch_test.go new file mode 100644 index 0000000000..2eba69cc80 --- /dev/null +++ b/mdl/executor/editorconfig_iife_switch_test.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/types" +) + +// The native Image (Native Mobile Resources 12.6.0) hides the image-source +// properties it is not using with a hide call whose list is computed by a +// switch, inside an immediately-invoked function: +// +// hidePropertiesIn(t, v, function(s){switch(s){ +// case "image": return L.filter(p => "imageObject" !== p); +// case "imageUrl": return L.filter(p => "imageUrl" !== p); +// case "icon": return L.filter(p => "imageIcon" !== p); +// default: return L }}(v.datasource)) +// +// The extractor read no list there and skipped the call, so `imageUrl` — a +// text template, hidden under the default source `image` — was written with +// a template where mx update-widgets writes none: CE0463 on every native +// image mxcli created (mx check 11.13.0). +// +// The source below is the widget's own getProperties, minified as shipped, +// cut after the call that matters. +const nativeImageGetProperties = `var dataSourceProperties=["imageObject","imageUrl","imageIcon"];` + + `exports.getProperties=function(values,defaultProperties){var _values$imageIcon,_values$imageIcon2;` + + `return distExports.hidePropertiesIn(defaultProperties,values,function(sourceProperty){switch(sourceProperty){` + + `case"image":return dataSourceProperties.filter(function(prop){return"imageObject"!==prop});` + + `case"imageUrl":return dataSourceProperties.filter(function(prop){return"imageUrl"!==prop});` + + `case"icon":return dataSourceProperties.filter(function(prop){return"imageIcon"!==prop});` + + `default:return dataSourceProperties}}(values.datasource)),` + + `"image"!==values.datasource&&distExports.hidePropertyIn(defaultProperties,values,"defaultImageDynamic")}` + +func TestExtractVisibility_SwitchComputedHideList(t *testing.T) { + rules, _ := extractVisibilityRulesFromJS(nativeImageGetProperties) + hidden := func(key string, values map[string]string) bool { + for _, r := range rules { + if r.PropertyKey != key || r.ListPropertyKey != "" { + continue + } + fires, _ := r.Fires(func(c types.WidgetVisibilityCondition) (string, bool) { + v, ok := values[c.PropertyKey] + return v, ok + }) + if fires { + return true + } + } + return false + } + for _, tc := range []struct { + source string + visible string + hidden []string + }{ + {"image", "imageObject", []string{"imageUrl", "imageIcon"}}, + {"imageUrl", "imageUrl", []string{"imageObject", "imageIcon"}}, + {"icon", "imageIcon", []string{"imageObject", "imageUrl"}}, + } { + values := map[string]string{"datasource": tc.source} + if hidden(tc.visible, values) { + t.Errorf("datasource=%s: %s is the property the source uses, but a rule hides it", tc.source, tc.visible) + } + for _, k := range tc.hidden { + if !hidden(k, values) { + t.Errorf("datasource=%s: %s is hidden by the editor, but no rule says so (rules: %+v)", tc.source, k, rules) + } + } + } + // Control: the plain guarded hide beside it is still read. + if !hidden("defaultImageDynamic", map[string]string{"datasource": "icon"}) { + t.Error("the guarded hidePropertyIn next to the switch is no longer read") + } +} + +// A computed list whose shape is not the one above is not guessed at: a +// default that is not the full list, or a case that keeps two members, could +// hide a property the editor shows. +func TestExtractVisibility_SwitchComputedHideList_OtherShapesNotLifted(t *testing.T) { + for name, js := range map[string]string{ + "default is not the list": `var L=["a","b"];exports.getProperties=function(v,t){return x.hidePropertiesIn(t,v,function(s){switch(s){` + + `case"x":return L.filter(function(p){return"a"!==p});default:return[]}}(v.mode))}`, + "under a guard": `var L=["a","b"];exports.getProperties=function(v,t){return v.on&&x.hidePropertiesIn(t,v,function(s){switch(s){` + + `case"x":return L.filter(function(p){return"a"!==p});default:return L}}(v.mode))}`, + } { + rules, _ := extractVisibilityRulesFromJS(js) + for _, r := range rules { + if r.PropertyKey == "a" || r.PropertyKey == "b" { + t.Errorf("%s: lifted %+v", name, r) + } + } + } +} diff --git a/mdl/executor/native_editable_own_property_test.go b/mdl/executor/native_editable_own_property_test.go new file mode 100644 index 0000000000..f119ed6db9 --- /dev/null +++ b/mdl/executor/native_editable_own_property_test.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/visitor" +) + +// The native Slider, Range slider, Rating and Toggle buttons declare a property +// of their own keyed `editable` — an enumeration, `default` | `never` — and not +// the Editability system property. exec writes `editable:` to that property +// (measured on PedApp 11.13.0 with Native Mobile Resources 12.6.0: the +// CustomWidget's own Editable stays Always), and describe prints it back as +// `editable: 'default'`. check read the name as the core Editable and refused +// the value: "`Editable: default` is not an Editable value [MDL-WIDGET19]" — so +// a native page with a slider could not be described and re-run. +// +// The value is the widget's own enumeration, judged against the keys its +// package declares, as a PDS Button's own `buttonStyle` is (ako/mxcli#2180). +func TestCheckNativeOwnEditable_JudgedByTheWidgetsOwnEnumeration(t *testing.T) { + def := &WidgetDefinition{ + WidgetID: "com.mendix.widget.native.slider.Slider", + MDLName: "nativeslider", + WidgetKind: "pluggable", + PropertyMappings: []PropertyMapping{ + {PropertyKey: "valueAttribute", Source: "Attribute", Operation: "attribute"}, + {PropertyKey: "editable", Value: "default", Operation: "primitive"}, + }, + enumKeys: map[string][]string{"editable": {"default", "never"}}, + } + reg := &WidgetRegistry{ + byMDLName: map[string]*WidgetDefinition{"NATIVESLIDER": def}, + byWidgetID: map[string]*WidgetDefinition{def.WidgetID: def}, + } + + for _, value := range []string{"'default'", "'never'", "never"} { + got := checkRules(t, reg, "nativeslider s1 (editable: "+value+")") + if hasNativeRule(got, "MDL-WIDGET19") { + t.Errorf("editable: %s is the native slider's own enumeration key, but check said %v", value, got) + } + } + // A key the widget does not declare is still refused — by its own list. + got := checkRules(t, reg, "nativeslider s1 (editable: 'sometimes')") + if hasNativeRule(got, "MDL-WIDGET19") || !hasNativeRule(got, widgetEnumRefused.Code) { + t.Errorf("editable: 'sometimes' on a nativeslider: want %s naming its own keys, got %v", widgetEnumRefused.Code, got) + } + // Control: a core input keeps MDL-WIDGET19. + got = checkRules(t, reg, "textbox tb (Attribute: Name, Editable: 'default')") + if !hasNativeRule(got, "MDL-WIDGET19") { + t.Errorf("a textbox with `Editable: default` must keep MDL-WIDGET19, got %v", got) + } +} + +// checkRules runs the widget checks over one widget and returns "RULE: message" +// for each violation. +func checkRules(t *testing.T, reg *WidgetRegistry, widget string) []string { + t.Helper() + prog, errs := visitor.Build("create page M.P (Title: 'P', Layout: Atlas_Core.NativePhone_Default) {\n " + widget + "\n};") + if len(errs) > 0 { + t.Fatalf("parse %q: %v", widget, errs[0]) + } + stmt, ok := prog.Statements[0].(*ast.CreatePageStmtV3) + if !ok { + t.Fatalf("parsed %T, want a page", prog.Statements[0]) + } + var out []string + for _, v := range validateWidgetTree(stmt.Widgets, reg, "page M.P") { + out = append(out, v.RuleID+": "+v.Message) + } + return out +} + +func hasNativeRule(got []string, rule string) bool { + for _, g := range got { + if strings.HasPrefix(g, rule) { + return true + } + } + return false +} diff --git a/mdl/executor/pluggable_own_core_name.go b/mdl/executor/pluggable_own_core_name.go index 82fa7df0ff..972b6d7314 100644 --- a/mdl/executor/pluggable_own_core_name.go +++ b/mdl/executor/pluggable_own_core_name.go @@ -23,21 +23,7 @@ import ( // Icon-typed `icon`, as on the Star rating) is in KnownProperties, and the core // reading stays, as before. func defOwnsCoreName(def *WidgetDefinition, name string) bool { - if def == nil || !pages.PluggableKeyShadowsCoreName(name) { - return false - } - sets := [][]PropertyMapping{def.PropertyMappings} - for _, m := range def.Modes { - sets = append(sets, m.PropertyMappings) - } - for _, set := range sets { - for _, m := range set { - if strings.EqualFold(m.PropertyKey, name) { - return true - } - } - } - return false + return pages.PluggableKeyShadowsCoreName(name) && defDeclaresOwnKey(def, name) } // templateOwnsCoreName is defOwnsCoreName asked of the template being built: @@ -55,3 +41,27 @@ func templateOwnsCoreName(propertyTypeIDs map[string]pages.PropertyTypeIDEntry, } return false } + +// defDeclaresOwnKey reports whether def maps a property key of its own spelled +// key, in any case — in its top-level mappings or any mode's. Unlike +// defOwnsCoreName it does not ask whether the name shadows a core property in +// general: `editable` does not (a CustomWidget stores its own Editable), but on +// a widget declaring an `editable` enumeration and no Editability system +// property, `editable:` is that enumeration. +func defDeclaresOwnKey(def *WidgetDefinition, key string) bool { + if def == nil { + return false + } + sets := [][]PropertyMapping{def.PropertyMappings} + for _, m := range def.Modes { + sets = append(sets, m.PropertyMappings) + } + for _, set := range sets { + for _, m := range set { + if strings.EqualFold(m.PropertyKey, key) { + return true + } + } + } + return false +} diff --git a/mdl/executor/validate_design_properties.go b/mdl/executor/validate_design_properties.go index e5dcd73b99..44f2cb20f9 100644 --- a/mdl/executor/validate_design_properties.go +++ b/mdl/executor/validate_design_properties.go @@ -77,8 +77,20 @@ func ValidateDesignProperties(prog *ast.Program, projectPath string, project fun // nativeLayoutResolver answers whether a layout, by qualified name, is native: // one the script creates with a native layout type, or one the project holds. -// The project is read once, on the first question. +// The project is read once, on the first question. A layout it cannot resolve +// is answered web. func nativeLayoutResolver(prog *ast.Program, project func() backend.FullBackend) func(string) bool { + resolve := layoutPlatformResolver(prog, project) + return func(qn string) bool { + native, _ := resolve(qn) + return native + } +} + +// layoutPlatformResolver is nativeLayoutResolver that also says whether it +// knows: known is false for a layout neither the script nor the project holds, +// for a caller that must not guess. +func layoutPlatformResolver(prog *ast.Program, project func() backend.FullBackend) func(string) (native, known bool) { native := map[string]bool{} for _, stmt := range prog.Statements { if s, ok := stmt.(*ast.CreateLayoutStmt); ok { @@ -88,25 +100,25 @@ func nativeLayoutResolver(prog *ast.Program, project func() backend.FullBackend) } } loaded := project == nil - return func(qn string) bool { + return func(qn string) (bool, bool) { if n, ok := native[qn]; ok { - return n + return n, true } if loaded { - return false + return false, false } loaded = true b := project() if b == nil { - return false + return false, false } layouts, err := b.ListLayouts() if err != nil { - return false + return false, false } h, err := NewContainerHierarchyFromBackend(b) if err != nil { - return false + return false, false } for _, l := range layouts { name := h.GetModuleName(h.FindModuleID(l.ContainerID)) + "." + l.Name @@ -114,7 +126,8 @@ func nativeLayoutResolver(prog *ast.Program, project func() backend.FullBackend) native[name] = l.Native } } - return native[qn] + n, ok := native[qn] + return n, ok } } diff --git a/mdl/executor/validate_program.go b/mdl/executor/validate_program.go index 6df059a4e4..1d1f51eda9 100644 --- a/mdl/executor/validate_program.go +++ b/mdl/executor/validate_program.go @@ -261,6 +261,11 @@ func ValidateProgram(prog *ast.Program, projectPath string) []linter.Violation { // can say which layouts are native. violations = append(violations, ValidatePageLayoutGrid(prog, projectNativeLayouts(project))...) + // A pluggable widget whose package declares the other platform than its + // page's — a web combobox on a native page, a native slider on a web one + // (MDL-WIDGET55). Judged only where both platforms are known. + violations = append(violations, ValidateWidgetPlatforms(prog, projectPath, project)...) + // A widget data source constraint whose one-hop comparand is the wrong type // (MDL-XPATH02) or names its association unqualified (MDL-XPATH01) — // CE0161 at build time (mendixlabs/mxcli#1466). The script's declarations diff --git a/mdl/executor/validate_widget_platform.go b/mdl/executor/validate_widget_platform.go new file mode 100644 index 0000000000..29d1cd7566 --- /dev/null +++ b/mdl/executor/validate_widget_platform.go @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/backend" + "github.com/mendixlabs/mxcli/mdl/linter" + mwidgets "github.com/mendixlabs/mxcli/modelsdk/widgets" + "github.com/mendixlabs/mxcli/modelsdk/widgets/mpk" +) + +// widgetPlatformRule warns about a pluggable widget on a page of the other +// platform. +const widgetPlatformRule = "MDL-WIDGET55" + +// ValidateWidgetPlatforms warns (MDL-WIDGET55) about a pluggable widget whose +// package declares a platform other than its page's: a web widget +// (`combobox`, `datagrid`, `image`, …) on a native page, or a native one +// (`nativeslider`, `nativegallery`, …) on a web page. The client of the other +// platform does not render it. +// +// Measured on PedApp (11.13.0) with Native Mobile Resources 12.6.0: both +// directions passed check and exec. It is a warning, not an error: what +// mxbuild reports for either is not measured. +// +// A page is judged only when its layout's platform is known — created by the +// script, or held by the project — and a widget only when its platform is: +// from its embedded template, or the project's installed package. +func ValidateWidgetPlatforms(prog *ast.Program, projectPath string, project func() backend.FullBackend) []linter.Violation { + return validateWidgetPlatforms(prog, LoadWidgetRegistry(projectPath), projectPath, project) +} + +func validateWidgetPlatforms(prog *ast.Program, registry *WidgetRegistry, projectPath string, project func() backend.FullBackend) []linter.Violation { + if registry == nil { + return nil + } + layoutPlatform := layoutPlatformResolver(prog, project) + platforms := map[string]string{} + platformOf := func(widgetID string) string { + p, ok := platforms[widgetID] + if !ok { + p = pluggableWidgetPlatform(widgetID, projectPath) + platforms[widgetID] = p + } + return p + } + + var out []linter.Violation + for _, stmt := range prog.Statements { + page, ok := stmt.(*ast.CreatePageStmtV3) + if !ok || page.Layout == "" { + continue + } + native, known := layoutPlatform(page.Layout) + if !known { + continue + } + pagePlatform, otherPlatform := "Web", "Native" + if native { + pagePlatform, otherPlatform = "Native", "Web" + } + forEachWidget(page, func(w *ast.WidgetV3, where string) { + def := lookupWidgetDef(w, registry) + if def == nil { + return + } + if !strings.EqualFold(platformOf(def.WidgetID), otherPlatform) { + return + } + out = append(out, linter.Violation{ + RuleID: widgetPlatformRule, + Severity: linter.SeverityWarning, + Message: fmt.Sprintf("page %s: `%s %s` is a %s widget (%s) on a %s page, which the %s client does not render", + page.Name.String(), strings.ToLower(w.Type), w.Name, strings.ToLower(otherPlatform), def.WidgetID, + strings.ToLower(pagePlatform), strings.ToLower(pagePlatform)), + Suggestion: platformSuggestion(native), + }) + }) + } + return out +} + +func platformSuggestion(nativePage bool) string { + if nativePage { + return "use the native widget instead (`widget init -p app.mpr` lists the installed `native…` keywords; " + + "`staticimage` / `dynamicimage` for an image), or put the widget on a web page" + } + return "use the web widget instead, or put the widget on a native page" +} + +// pluggableWidgetPlatform is the platform a pluggable widget's package +// declares — Web, Native or All — read from its embedded template, else the +// project's installed .mpk; "" when neither knows the widget. +func pluggableWidgetPlatform(widgetID, projectPath string) string { + if tmpl, err := mwidgets.GetTemplate(widgetID); err == nil && tmpl != nil { + if p, ok := tmpl.Type["SupportedPlatform"].(string); ok && p != "" { + return p + } + return "Web" // an absent supportedPlatform is Web + } + if projectPath == "" { + return "" + } + mpkPath, err := mpk.FindMPK(filepath.Dir(projectPath), widgetID) + if err != nil || mpkPath == "" { + return "" + } + def, err := mpk.ParseMPKForWidget(mpkPath, widgetID) + if err != nil || def == nil { + return "" + } + return def.SupportedPlatform +} diff --git a/mdl/executor/validate_widget_platform_test.go b/mdl/executor/validate_widget_platform_test.go new file mode 100644 index 0000000000..641443f347 --- /dev/null +++ b/mdl/executor/validate_widget_platform_test.go @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "archive/zip" + "io" + "os" + "path/filepath" + "sort" + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/visitor" + "github.com/mendixlabs/mxcli/modelsdk/widgets/mpk" +) + +// A pluggable widget package declares the platform it renders on +// (supportedPlatform: Web, Native or All; absent means Web). check never +// compared it with the page's: measured on PedApp (11.13.0) with Native Mobile +// Resources 12.6.0, `combobox` and `datagrid` on a NativePhone page and +// `nativeslider` / `nativegallery` on an Atlas_Default page all passed check +// and exec. A web widget on a native page is a widget the native client does +// not render, and the reverse the same for the browser. +const nativeSliderXML = ` + + Slider + + + + Value + + + + +` + +// writeNativeWidgetProject writes a project directory holding the native +// slider's package and returns the .mpr path. +func writeNativeWidgetProject(t *testing.T) string { + t.Helper() + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "widgets"), 0o755); err != nil { + t.Fatal(err) + } + f, err := os.Create(filepath.Join(dir, "widgets", "com.mendix.widget.native.Slider.mpk")) + if err != nil { + t.Fatal(err) + } + zw := zip.NewWriter(f) + for entry, body := range map[string]string{ + "package.xml": ``, + "Slider.xml": nativeSliderXML, + } { + w, err := zw.Create(entry) + if err != nil { + t.Fatal(err) + } + if _, err := io.WriteString(w, body); err != nil { + t.Fatal(err) + } + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + mpk.ClearCache() + t.Cleanup(mpk.ClearCache) + return filepath.Join(dir, "App.mpr") +} + +func platformRegistry() *WidgetRegistry { + reg := LoadWidgetRegistry("") + def := &WidgetDefinition{WidgetID: "com.mendix.widget.native.slider.Slider", MDLName: "nativeslider", WidgetKind: "pluggable", + PropertyMappings: []PropertyMapping{{PropertyKey: "valueAttribute", Source: "Attribute", Operation: "attribute"}}} + reg.byMDLName["NATIVESLIDER"] = def + reg.byWidgetID[def.WidgetID] = def + return reg +} + +func platformViolations(t *testing.T, mprPath, src string) []string { + t.Helper() + prog, errs := visitor.Build(src) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs[0]) + } + var got []string + for _, v := range validateWidgetPlatforms(prog, platformRegistry(), mprPath, nil) { + if v.RuleID != widgetPlatformRule { + t.Errorf("rule %s, want %s", v.RuleID, widgetPlatformRule) + } + got = append(got, v.Message) + } + sort.Strings(got) + return got +} + +func TestWidgetPlatform_WebWidgetOnNativePage(t *testing.T) { + mpr := writeNativeWidgetProject(t) + got := platformViolations(t, mpr, `create layout M.NL (LayoutType: Default) { placeholder Main }; +create page M.P (Title: 'N', Layout: M.NL) { + container c { + combobox cb1 + } + image img1 (Image: 'M.Images.logo') + nativeslider s1 +};`) + joined := strings.Join(got, "\n") + if len(got) != 2 || !strings.Contains(joined, "cb1") || !strings.Contains(joined, "img1") { + t.Fatalf("want the web combobox (nested in a container) and the web image reported, got:\n%s", joined) + } + if strings.Contains(joined, "s1") { + t.Errorf("the native slider belongs on a native page:\n%s", joined) + } +} + +func TestWidgetPlatform_NativeWidgetOnWebPage(t *testing.T) { + mpr := writeNativeWidgetProject(t) + got := platformViolations(t, mpr, `create layout M.WL (LayoutType: Responsive) { placeholder Main }; +create page M.P (Title: 'W', Layout: M.WL) { + nativeslider s1 + combobox cb1 +};`) + joined := strings.Join(got, "\n") + if len(got) != 1 || !strings.Contains(joined, "s1") { + t.Fatalf("want only the native slider reported, got:\n%s", joined) + } +} + +// A layout whose platform nothing can tell — neither the script nor a project — +// is not judged: guessing web would report every native widget on a native page. +func TestWidgetPlatform_UnknownLayoutIsNotJudged(t *testing.T) { + mpr := writeNativeWidgetProject(t) + got := platformViolations(t, mpr, `create page M.P (Title: 'X', Layout: Atlas_Core.NativePhone_Default) { + nativeslider s1 + combobox cb1 +};`) + if len(got) != 0 { + t.Fatalf("a page on an unresolved layout must not be judged, got:\n%s", strings.Join(got, "\n")) + } +} diff --git a/mdl/executor/validate_widget_required.go b/mdl/executor/validate_widget_required.go new file mode 100644 index 0000000000..9e9cbe2722 --- /dev/null +++ b/mdl/executor/validate_widget_required.go @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/linter" + "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/modelsdk/widgets/mpk" +) + +// widgetRequiredRule warns about a required pluggable-widget property left unset. +const widgetRequiredRule = "MDL-WIDGET56" + +// validateWidgetRequired warns (MDL-WIDGET56) about a property the widget's +// package marks required that the script leaves unset: mxbuild fails the build +// with CE0642 ("Property 'X' is required"), or CE4899 for a text template. +// Measured with Native Mobile Resources 12.6.0 on mx check 11.13.0: 29 of the +// 39 native widgets placed bare passed check and exec, and failed there. +// +// Set means a value, a filled slot, or at least one list item. A property with +// a usable default needs nothing — an enumeration, a boolean or number, an +// expression or string with a defaultValue, a text template with shipped +// translations — and neither does one the widget's editorConfig hides under +// the configuration, which mx does not require. +// +// Needs the installed package (the project); a warning, because the hidden +// rules are lifted from editorConfig.js and an unread one could leave a +// hidden property looking required. +func validateWidgetRequired(w *ast.WidgetV3, registry *WidgetRegistry, locationPrefix string) []linter.Violation { + def := lookupWidgetDef(w, registry) + if def == nil { + return nil + } + props := requiredTopLevelProps(registryProjectPath(registry), def.WidgetID) + if len(props) == 0 { + return nil + } + values, explicit := widgetValueMap(w, def) + rules := visibilityRulesFor(def, registry) + slots, lists := filledSlotsAndLists(w, def) + + var out []linter.Violation + for _, p := range props { + if propertyHasDefault(p) { + continue + } + key := strings.ToLower(p.Key) + switch { + case p.Type == "widgets" && slots[key]: + continue + case p.Type == "object" && lists[key]: + continue + case explicit[key]: + continue + } + if hiddenByConfiguration(rules, p.Key, values) { + continue + } + code := "CE0642" + if p.Type == "textTemplate" { + code = "CE4899" + } + out = append(out, linter.Violation{ + RuleID: widgetRequiredRule, + Severity: linter.SeverityWarning, + Message: fmt.Sprintf("%s: %s: `%s` (%s) is required and not set — mxbuild fails the build with %s", + locationPrefix, widgetLabel(w.Name, def.MDLName), p.Key, p.Caption, code), + Suggestion: requiredSuggestion(p, def), + }) + } + return out +} + +func requiredSuggestion(p mpk.PropertyDef, def *WidgetDefinition) string { + switch p.Type { + case "widgets": + if kw := childSlotKeyword(def, strings.ToLower(p.Key)); kw != "" { + return fmt.Sprintf("add a `%s { … }` block with at least one widget", kw) + } + case "object": + for _, ol := range def.ObjectLists { + if strings.EqualFold(ol.PropertyKey, p.Key) { + return fmt.Sprintf("add at least one `%s` item", strings.ToLower(ol.MDLContainer)) + } + } + } + return fmt.Sprintf("set `%s:`", p.Key) +} + +// requiredTopLevelProps returns the widget's required, non-system top-level +// properties as its installed package declares them; nil without one. +func requiredTopLevelProps(projectPath, widgetID string) []mpk.PropertyDef { + if projectPath == "" || widgetID == "" { + return nil + } + mpkPath, err := mpk.FindMPK(filepath.Dir(projectPath), widgetID) + if err != nil || mpkPath == "" { + return nil + } + wd, err := mpk.ParseMPKForWidget(mpkPath, widgetID) + if err != nil || wd == nil { + return nil + } + var out []mpk.PropertyDef + for _, p := range wd.Properties { + if p.Required && !p.IsSystem { + out = append(out, p) + } + } + return out +} + +// propertyHasDefault reports whether a required property is satisfied without +// the script naming it. +func propertyHasDefault(p mpk.PropertyDef) bool { + switch p.Type { + case "boolean", "integer", "decimal", "enumeration": + return true + case "expression", "string": + return p.DefaultValue != "" + case "textTemplate": + return len(p.Translations) > 0 + case "attribute", "association", "datasource", "widgets", "object", "image", "file", "icon": + return false + } + // action, selection and any other kind: not measured as required-when-unset. + return true +} + +// hiddenByConfiguration reports whether a top-level visibility rule determinably +// hides key under values. +func hiddenByConfiguration(rules []types.WidgetVisibilityRule, key string, values map[string]string) bool { + for _, r := range rules { + if r.Nested() || r.HiddenWhen == nil || !strings.EqualFold(r.PropertyKey, key) { + continue + } + fires, determinable := r.Fires(func(c types.WidgetVisibilityCondition) (string, bool) { + v, ok := values[strings.ToLower(c.PropertyKey)] + return v, ok + }) + if determinable && fires { + return true + } + } + return false +} + +// filledSlotsAndLists reports which widgets slots hold a widget and which +// object lists hold an item, routed the way the engine routes children +// (applyChildSlots, applyObjectLists): a container keyword, `container +// `, or loose children into the default slot. +func filledSlotsAndLists(w *ast.WidgetV3, def *WidgetDefinition) (slots, lists map[string]bool) { + slots, lists = map[string]bool{}, map[string]bool{} + slotByKeyword := map[string]string{} + all := append([]ChildSlotMapping(nil), def.ChildSlots...) + for _, m := range def.Modes { + all = append(all, m.ChildSlots...) + } + for _, s := range all { + slotByKeyword[strings.ToLower(s.MDLContainer)] = strings.ToLower(s.PropertyKey) + } + listByKeyword := map[string]string{} + for _, ol := range def.ObjectLists { + listByKeyword[strings.ToLower(ol.MDLContainer)] = strings.ToLower(ol.PropertyKey) + } + loose := false + for _, c := range w.Children { + if c == nil { + continue + } + t := strings.ToLower(c.Type) + if key, ok := listByKeyword[t]; ok { + lists[key] = true + continue + } + key, ok := slotByKeyword[t] + if !ok && t == "container" { + key, ok = slotByKeyword[strings.ToLower(c.Name)] + } + if ok { + if len(c.Children) > 0 { + slots[key] = true + } + continue + } + loose = true + } + if key, ok := slotByKeyword[defaultSlotContainer]; ok && loose { + slots[key] = true + } + return slots, lists +} diff --git a/mdl/executor/validate_widget_required_test.go b/mdl/executor/validate_widget_required_test.go new file mode 100644 index 0000000000..2386a54775 --- /dev/null +++ b/mdl/executor/validate_widget_required_test.go @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "archive/zip" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/mdl/visitor" + mmpk "github.com/mendixlabs/mxcli/modelsdk/widgets/mpk" + "github.com/mendixlabs/mxcli/sdk/widgets/mpk" +) + +// A pluggable widget property the package marks required, left unset, fails +// the build with CE0642 ("Property 'X' is required") or, for a text template, +// CE4899. check said nothing: measured with Native Mobile Resources 12.6.0 on +// mx check 11.13.0, 29 of the 39 native widgets placed bare passed check and +// exec and failed mx check — a gallery with no data source, a slider with no +// attribute, a repeater with no content. +// +// What counts as set: a value, a filled slot, at least one list item. What +// needs nothing: a value with a usable default (an enumeration, a boolean, an +// expression with a defaultValue, a text template with shipped translations), +// and a property the widget's editorConfig hides under the configuration — +// mx does not require what the editor does not show. +const requiredWidgetXML = ` + + Req + + + + Data source + Value attribute + + Content + Items + Label + + Title + Hint + Hint + Minimum + + Mode + PlainURL + URL attribute + + Optional + + + + +` + +func requiredWidgetRegistry(t *testing.T) (*WidgetRegistry, *WidgetDefinition) { + t.Helper() + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "widgets"), 0o755); err != nil { + t.Fatal(err) + } + mpkPath := filepath.Join(dir, "widgets", "Req.mpk") + f, err := os.Create(mpkPath) + if err != nil { + t.Fatal(err) + } + zw := zip.NewWriter(f) + for entry, body := range map[string]string{ + "package.xml": ``, + "Req.xml": requiredWidgetXML, + } { + w, err := zw.Create(entry) + if err != nil { + t.Fatal(err) + } + if _, err := io.WriteString(w, body); err != nil { + t.Fatal(err) + } + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + mpk.ClearCache() + mmpk.ClearCache() + t.Cleanup(func() { mpk.ClearCache(); mmpk.ClearCache() }) + + m, err := mpk.ParseMPK(mpkPath) + if err != nil { + t.Fatal(err) + } + def := GenerateDefJSON(m, "reqwidget") + // The editor hides urlAttribute unless mode is "url". + def.PropertyVisibility = []types.WidgetVisibilityRule{{ + PropertyKey: "urlAttribute", + HiddenWhen: &types.WidgetVisibilityCondition{PropertyKey: "mode", Operator: "ne", Value: "url"}, + }} + reg := &WidgetRegistry{ + byMDLName: map[string]*WidgetDefinition{"REQWIDGET": def}, + byWidgetID: map[string]*WidgetDefinition{def.WidgetID: def}, + projectPath: filepath.Join(dir, "App.mpr"), + } + return reg, def +} + +func requiredReported(t *testing.T, reg *WidgetRegistry, widget string) []string { + t.Helper() + prog, errs := visitor.Build("create page M.P (Title: 'P', Layout: M.L) {\n" + widget + "\n};") + if len(errs) > 0 { + t.Fatalf("parse: %v\n%s", errs[0], widget) + } + var got []string + for _, v := range validateWidgetTree(prog.Statements[0].(*ast.CreatePageStmtV3).Widgets, reg, "page M.P") { + if v.RuleID != widgetRequiredRule { + continue + } + // "page M.P: widget `r1` (reqwidget): `key` (Caption) is required …" + parts := strings.Split(v.Message, "`") + if len(parts) < 4 { + t.Fatalf("message shape: %s", v.Message) + } + got = append(got, parts[3]) + } + sort.Strings(got) + return got +} + +func TestWidgetRequired_UnsetRequiredPropertiesReported(t *testing.T) { + reg, _ := requiredWidgetRegistry(t) + got := strings.Join(requiredReported(t, reg, "reqwidget r1"), ",") + if want := "content,ds,items,title,valueAttribute"; got != want { + t.Errorf("reported %s, want %s — a default, a translation, an enumeration, a hidden and an optional property need nothing", got, want) + } +} + +func TestWidgetRequired_SetPropertiesNotReported(t *testing.T) { + reg, def := requiredWidgetRegistry(t) + if len(def.ObjectLists) != 1 || len(def.ChildSlots) != 1 { + t.Fatalf("definition: %d lists, %d slots — the test widget's shape changed", len(def.ObjectLists), len(def.ChildSlots)) + } + widget := fmt.Sprintf(`reqwidget r1 (ds: database from M.E, valueAttribute: Score, title: 'T') { + %s { dynamictext t1 (Content: 'x') } + %s i1 (itemLabel: 'a') +}`, def.ChildSlots[0].MDLContainer, def.ObjectLists[0].MDLContainer) + if got := requiredReported(t, reg, widget); len(got) != 0 { + t.Errorf("reported %v for a widget that sets every required property:\n%s", got, widget) + } +} + +// A property the configuration shows again is required again. +func TestWidgetRequired_ShownByConfigurationIsRequired(t *testing.T) { + reg, _ := requiredWidgetRegistry(t) + got := requiredReported(t, reg, "reqwidget r1 (mode: url)") + if !strings.Contains(strings.Join(got, ","), "urlAttribute") { + t.Errorf("mode: url shows urlAttribute, so it is required; reported %v", got) + } +} diff --git a/mdl/executor/validate_widgets.go b/mdl/executor/validate_widgets.go index 82d3885063..e34fd160ad 100644 --- a/mdl/executor/validate_widgets.go +++ b/mdl/executor/validate_widgets.go @@ -285,6 +285,9 @@ func validateWidgetTreeIn(widgets []*ast.WidgetV3, registry *WidgetRegistry, loc out = append(out, validatePluggableTemplateParams(w, locationPrefix)...) } out = append(out, validateWidgetVisibility(w, registry, locationPrefix)...) + // A required property the package declares, left unset: CE0642 / + // CE4899 at build time (MDL-WIDGET56). + out = append(out, validateWidgetRequired(w, registry, locationPrefix)...) // #1519: several attributes for a widget with one attribute slot — the // drop-down filter. exec refuses it; so does check. if m, attrs, over := singleAttributeOverflow(lookupWidgetDef(w, registry), w); over { @@ -1539,7 +1542,7 @@ func violation18(locationPrefix string, w *ast.WidgetV3, msg string) linter.Viol // // The grammar fix removes the known trigger. This rule is the general guard: the // next function name promoted to a lexer token fails loudly here instead. -func validateConsumableConditional(w *ast.WidgetV3, locationPrefix string) []linter.Violation { +func validateConsumableConditional(w *ast.WidgetV3, def *WidgetDefinition, locationPrefix string) []linter.Violation { var out []linter.Violation for _, p := range []struct{ plain, routed string }{ {"Visible", "VisibleIf"}, @@ -1558,7 +1561,14 @@ func validateConsumableConditional(w *ast.WidgetV3, locationPrefix string) []lin // Visible takes any string as its condition; Editable takes an enum // word, a boolean or a condition, and refuses what is none of them // here, because the writer has nowhere to put it. - if p.plain == "Editable" { + // + // Not on a pluggable widget declaring an `editable` key of its own + // (the native Slider, Range slider, Rating and Toggle buttons: + // `default` | `never`, and no Editability system property). exec + // writes the value there, and validatePluggableEnumValues judges + // it against the keys the package declares, as for a PDS Button's + // own buttonStyle (ako/mxcli#2180). + if p.plain == "Editable" && !defDeclaresOwnKey(def, "editable") { if problem := editableValueProblem(w); problem != "" { out = append(out, linter.Violation{ RuleID: "MDL-WIDGET19", @@ -1635,7 +1645,7 @@ func validateStaticWidgetOf(w *ast.WidgetV3, def *WidgetDefinition, locationPref out = append(out, *v) } - out = append(out, validateConsumableConditional(w, locationPrefix)...) + out = append(out, validateConsumableConditional(w, def, locationPrefix)...) // A DataView cannot use a database data source — a data view shows one object, // so Mendix offers only Context / Microflow / Nanoflow / Listen sources. diff --git a/mdl/types/navigation_profile_kind.go b/mdl/types/navigation_profile_kind.go index 890810195f..67ff505c47 100644 --- a/mdl/types/navigation_profile_kind.go +++ b/mdl/types/navigation_profile_kind.go @@ -14,10 +14,12 @@ import "strings" // changes is what the platform then demands of every page the profile reaches — // see the CE6206 warning MDL-OFFLINE01 raises. // -// The native profiles (Navigation$NativeNavigationProfile, a different $Type) -// and the Hybrid kinds are deliberately absent: no reference document was -// available for either, and a profile assembled from a guess is the failure mode -// that builds clean and then will not open in Studio Pro. +// The native profile (Navigation$NativeNavigationProfile, a different $Type) is +// deliberately absent from THIS table — see nativeProfileKinds below for its own +// table and the reason it is kept separate. The Hybrid kinds (web and native +// alike) are absent from both: no reference document is available for Hybrid at +// all, and a profile assembled from a guess is the failure mode that builds +// clean and then will not open in Studio Pro. var webProfileKinds = map[string]string{ "responsive": "Responsive", "phone": "Phone", @@ -53,3 +55,31 @@ func IsOfflineProfileKind(kind string) bool { func WebProfileKindNames() []string { return []string{"Responsive", "Phone", "Tablet", "ResponsiveOffline", "PhoneOffline", "TabletOffline"} } + +// nativeProfileKinds are the Navigation$NativeNavigationProfile names a NATIVE +// profile can take. Kept apart from webProfileKinds rather than merged into one +// table: a web profile is identified by its Kind property, a native profile has +// no Kind at all and is identified purely by $Type + Name — a lookup that +// returned a "kind" for both would make it easy to hand a native name to the web +// builder (or vice versa) and get a document with the wrong shape for its $Type. +// +// Only NativePhone is here. Hybrid is a different $Type again and, like the web +// Hybrid kinds, has no reference document to pin its shape against — see the +// doc comment on webProfileKinds. +var nativeProfileKinds = map[string]string{ + "nativephone": "NativePhone", +} + +// CanonicalNativeProfileKind maps a user-written profile name to the Name Mendix +// stores for a native profile, reporting whether it is one mxcli can create. It +// is the native counterpart of CanonicalProfileKind, not a branch inside it, for +// the reason given on nativeProfileKinds. +func CanonicalNativeProfileKind(name string) (string, bool) { + k, ok := nativeProfileKinds[strings.ToLower(strings.TrimSpace(name))] + return k, ok +} + +// NativeProfileKindNames lists the creatable native kinds for error messages. +func NativeProfileKindNames() []string { + return []string{"NativePhone"} +} diff --git a/modelsdk/widgets/augment.go b/modelsdk/widgets/augment.go index 744efe86fa..a49cc0905b 100644 --- a/modelsdk/widgets/augment.go +++ b/modelsdk/widgets/augment.go @@ -676,11 +676,16 @@ func reconcileEnumValues(node any, byKey map[string][]mpk.EnumValue) { func buildEnumValuesArray(opts []mpk.EnumValue) []any { arr := []any{float64(2)} for _, o := range opts { + // The caption as the package writes it: Mendix stores it verbatim. + caption := o.RawCaption + if caption == "" { + caption = o.Caption + } arr = append(arr, map[string]any{ "$ID": placeholderID(), "$Type": "CustomWidgets$WidgetEnumerationValue", "_Key": o.Key, - "Caption": o.Caption, + "Caption": caption, }) } return arr @@ -852,6 +857,7 @@ func createDefaultValueType(vtID string, bsonType string, p mpk.PropertyDef) map "$Type": "CustomWidgets$WidgetValueType", "ActionVariables": buildActionVariablesArray(p.ActionVariables), "AllowNonPersistableEntities": false, + "AllowUpload": p.AllowUpload, "AllowedTypes": allowedTypes, "AssociationTypes": []any{float64(1)}, "DataSourceProperty": "", @@ -865,7 +871,7 @@ func createDefaultValueType(vtID string, bsonType string, p mpk.PropertyDef) map "IsPath": "No", "Multiline": false, "ObjectType": nil, - "OnChangeProperty": "", + "OnChangeProperty": p.OnChange, "ParameterIsList": false, "PathType": "None", "Required": p.Required, @@ -1352,6 +1358,9 @@ func syncDefinitionAttrs(propTypes []any, props []mpk.PropertyDef) { if _, ok := target["OnChangeProperty"]; ok { target["OnChangeProperty"] = p.OnChange } + if _, ok := target["AllowUpload"]; ok { + target["AllowUpload"] = p.AllowUpload + } }) } diff --git a/modelsdk/widgets/mpk/mpk.go b/modelsdk/widgets/mpk/mpk.go index 2137f59b07..f74ed66f66 100644 --- a/modelsdk/widgets/mpk/mpk.go +++ b/modelsdk/widgets/mpk/mpk.go @@ -28,7 +28,11 @@ type PropertyDef struct { // OnChange names the sibling action property Studio Pro runs when this // property changes. Part of the widget DEFINITION, so a stale value makes // Mendix report CE0463 "definition of this widget has changed" (#716). - OnChange string + OnChange string + // AllowUpload is an image/file property's allowUpload="true": part of the + // widget DEFINITION (ValueType.AllowUpload), CE0463 when it differs + // (Native Mobile Resources 12.6.0's Signature). + AllowUpload bool DefaultValue string // for enumeration/boolean/integer types // DefaultType is the KIND of the default — `defaultType` in the widget XML, // e.g. an action defaulting to a nanoflow call ("CallNanoflow") or a @@ -76,7 +80,12 @@ type ActionVariable struct { // EnumValue is one option of an enumeration-typed widget property. type EnumValue struct { Key string - Caption string + Caption string // trimmed, for display + // RawCaption is the caption as the package writes it. Mendix stores that + // text verbatim — a multi-line element keeps its trailing newline and + // indentation — and a trimmed copy in the definition is CE0463 (Native + // Mobile Resources 12.6.0's Maps). + RawCaption string } // Translation is one localized caption/template string of a widget property. @@ -236,6 +245,7 @@ type xmlProperty struct { DefaultType string `xml:"defaultType,attr"` Required string `xml:"required,attr"` OnChange string `xml:"onChange,attr"` + AllowUpload string `xml:"allowUpload,attr"` IsList string `xml:"isList,attr"` Multiline string `xml:"multiline,attr"` DataSource string `xml:"dataSource,attr"` @@ -447,7 +457,7 @@ func walkPropertyGroup(pg xmlPropGroup, parentCategory string, def *WidgetDefini } var enumValues []EnumValue for _, ev := range p.EnumValues { - enumValues = append(enumValues, EnumValue{Key: ev.Key, Caption: strings.TrimSpace(ev.Caption)}) + enumValues = append(enumValues, EnumValue{Key: ev.Key, Caption: strings.TrimSpace(ev.Caption), RawCaption: ev.Caption}) } prop := PropertyDef{ Key: p.Key, @@ -462,6 +472,7 @@ func walkPropertyGroup(pg xmlPropGroup, parentCategory string, def *WidgetDefini // caused within-key CE0463 drift on augment-added keys (issue #600). Required: p.Required != "false", OnChange: p.OnChange, + AllowUpload: p.AllowUpload == "true", DefaultValue: p.DefaultValue, DefaultType: p.DefaultType, IsList: p.IsList == "true", @@ -540,7 +551,7 @@ func collectNestedProperties(pg xmlPropGroup, parent *PropertyDef, parentCategor } var enumValues []EnumValue for _, ev := range p.EnumValues { - enumValues = append(enumValues, EnumValue{Key: ev.Key, Caption: strings.TrimSpace(ev.Caption)}) + enumValues = append(enumValues, EnumValue{Key: ev.Key, Caption: strings.TrimSpace(ev.Caption), RawCaption: ev.Caption}) } child := PropertyDef{ Key: p.Key, @@ -555,6 +566,7 @@ func collectNestedProperties(pg xmlPropGroup, parent *PropertyDef, parentCategor // caused within-key CE0463 drift on augment-added keys (issue #600). Required: p.Required != "false", OnChange: p.OnChange, + AllowUpload: p.AllowUpload == "true", DefaultValue: p.DefaultValue, DefaultType: p.DefaultType, IsList: p.IsList == "true", diff --git a/modelsdk/widgets/mpk/native_attrs_test.go b/modelsdk/widgets/mpk/native_attrs_test.go new file mode 100644 index 0000000000..01077dc12b --- /dev/null +++ b/modelsdk/widgets/mpk/native_attrs_test.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 + +package mpk + +import "testing" + +// `allowUpload` is read from an image/file property, and an enumeration +// option's caption is kept as written: Mendix stores it verbatim, and a +// trimmed copy is CE0463 (Native Mobile Resources 12.6.0's Maps). The trimmed +// caption stays for display. +func TestParse_ReadsAllowUploadAndRawEnumCaption(t *testing.T) { + const widgetXML = ` + + W + + + + Image + + + Plain + + + Location + + Based on address + Based on latitude and longitude + + + + + +` + + def := parseWidgetXML(t, widgetXML) + byKey := map[string]PropertyDef{} + for _, p := range def.Properties { + byKey[p.Key] = p + } + if !byKey["imageSource"].AllowUpload { + t.Error("imageSource: allowUpload=\"true\" not read") + } + if byKey["plainImage"].AllowUpload { + t.Error("control: plainImage declares no allowUpload") + } + var latlng EnumValue + for _, ev := range byKey["locationType"].EnumValues { + if ev.Key == "latlng" { + latlng = ev + } + } + if want := "Based on latitude and longitude\n "; latlng.RawCaption != want { + t.Errorf("RawCaption = %q, want %q", latlng.RawCaption, want) + } + if latlng.Caption != "Based on latitude and longitude" { + t.Errorf("Caption = %q, want the trimmed text for display", latlng.Caption) + } +} diff --git a/modelsdk/widgets/native_definition_attrs_test.go b/modelsdk/widgets/native_definition_attrs_test.go new file mode 100644 index 0000000000..1176735a93 --- /dev/null +++ b/modelsdk/widgets/native_definition_attrs_test.go @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 + +package widgets + +import ( + "testing" + + "github.com/mendixlabs/mxcli/modelsdk/widgets/mpk" +) + +// Three properties of the definition mxcli generated from a package differed +// from what mx update-widgets writes, each one CE0463 on every instance +// (mx check 11.13.0, Native Mobile Resources 12.6.0): +// +// Signature imageSource type="image" allowUpload="true" AllowUpload false, want true +// Bottom sheet triggerAttribute onChange="triggerAttributeChange" OnChangeProperty "", want the key +// Maps markers/… Based on latitude and longitude +// caption trimmed, want it verbatim +// +// The parser already read onChange; the generator wrote "" regardless. +// allowUpload was not read at all. And the parser trimmed an option's caption, +// which Mendix stores as written — trailing newline and indentation included. +func TestGenerateFromMPK_DefinitionAttrsAsDeclared(t *testing.T) { + ResetPlaceholderCounter() + const latlng = "Based on latitude and longitude\n " + def := &mpk.WidgetDefinition{ + ID: "com.example.W", Name: "W", Version: "1.0.0", + Properties: []mpk.PropertyDef{ + {Key: "imageSource", Type: "image", Required: true, AllowUpload: true}, + {Key: "plainImage", Type: "image"}, + {Key: "triggerAttribute", Type: "attribute", OnChange: "triggerAttributeChange", AllowedTypes: []string{"Boolean"}}, + {Key: "triggerAttributeChange", Type: "action"}, + {Key: "locationType", Type: "enumeration", DefaultValue: "address", EnumValues: []mpk.EnumValue{ + {Key: "address", Caption: "Based on address", RawCaption: "Based on address"}, + {Key: "latlng", Caption: "Based on latitude and longitude", RawCaption: latlng}, + }}, + }, + } + vts := valueTypesByKey(t, GenerateFromMPK(def)) + + if got := vts["imageSource"]["AllowUpload"]; got != true { + t.Errorf("imageSource AllowUpload = %v, want true (allowUpload=\"true\")", got) + } + if got := vts["plainImage"]["AllowUpload"]; got != false { + t.Errorf("control: plainImage AllowUpload = %v, want false", got) + } + if got := vts["triggerAttribute"]["OnChangeProperty"]; got != "triggerAttributeChange" { + t.Errorf("triggerAttribute OnChangeProperty = %q, want triggerAttributeChange", got) + } + if got := vts["triggerAttributeChange"]["OnChangeProperty"]; got != "" { + t.Errorf("control: an action's OnChangeProperty = %q, want empty", got) + } + enum, _ := vts["locationType"]["EnumerationValues"].([]any) + captions := map[string]any{} + for _, e := range enum { + if m, ok := e.(map[string]any); ok { + captions[m["_Key"].(string)] = m["Caption"] + } + } + if captions["latlng"] != latlng { + t.Errorf("latlng caption = %q, want it as written in the package, %q", captions["latlng"], latlng) + } + if captions["address"] != "Based on address" { + t.Errorf("control: address caption = %q", captions["address"]) + } +} + +func valueTypesByKey(t *testing.T, tmpl *WidgetTemplate) map[string]map[string]any { + t.Helper() + pts := tmpl.Type["ObjectType"].(map[string]any)["PropertyTypes"].([]any) + out := map[string]map[string]any{} + for _, pt := range pts[1:] { + m := pt.(map[string]any) + if vt, ok := m["ValueType"].(map[string]any); ok { + out[m["PropertyKey"].(string)] = vt + } + } + return out +}