From 9fd7578dc77393879376689207a1b6cfce4a3514 Mon Sep 17 00:00:00 2001 From: Niels Laute Date: Sat, 21 Nov 2026 00:57:20 +0100 Subject: [PATCH 01/14] docs(reference): generate the full API reference from XML docs Rewrite the reference generator (AssemblyModel, ReferencePlanner, ReferenceRenderer) so it covers every public type, hook, factory and modifier, grouped by category. Regenerates docs/guide/reference (287 pages). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/_pipeline/reference-map.yaml | 986 +++++++++++- .../reference/accessibility/A11yContext.md | 93 ++ .../reference/accessibility/A11yDiagnostic.md | 95 ++ .../accessibility/A11yFixSuggestion.md | 47 + .../accessibility/AccessibilityScanner.md | 44 + .../accessibility/SemanticDescription.md | 70 + .../reference/accessibility/SemanticPanel.md | 99 ++ .../SemanticPanelAutomationPeer.md | 77 + docs/guide/reference/accessibility/index.md | 17 + .../reference/animation/AnimationConfig.md | 42 + .../reference/animation/AnimationScope.md | 61 + docs/guide/reference/animation/Animations.md | 59 + .../reference/animation/CompositorProvider.md | 33 + .../reference/animation/StaggerConfig.md | 42 + docs/guide/reference/animation/curves.md | 289 ++++ docs/guide/reference/animation/enums.md | 47 + docs/guide/reference/animation/implicit.md | 157 ++ docs/guide/reference/animation/index.md | 22 + .../reference/animation/interaction-states.md | 220 +++ docs/guide/reference/animation/keyframes.md | 216 +++ docs/guide/reference/animation/scroll.md | 189 +++ docs/guide/reference/animation/transitions.md | 360 +++++ .../guide/reference/components/AppContexts.md | 37 + docs/guide/reference/components/Callbacks.md | 101 ++ .../guide/reference/components/Component-1.md | 46 + docs/guide/reference/components/Component.md | 152 ++ docs/guide/reference/components/Context.md | 34 + .../guide/reference/components/ContextBase.md | 19 + .../reference/components/ElementFactory.md | 57 + .../reference/components/IReactorKeyed.md | 33 + docs/guide/reference/components/Observable.md | 76 + docs/guide/reference/components/Optional.md | 197 +++ docs/guide/reference/components/Ref.md | 33 + .../reference/components/RenderContext.md | 151 ++ .../reference/components/SourceLocation.md | 83 + docs/guide/reference/components/index.md | 26 + .../reference/components/render-errors.md | 142 ++ .../controls/PropertyGridComponent.md | 27 + .../controls/PropertyGridDefaults.md | 73 + .../reference/controls/collection-items.md | 161 ++ docs/guide/reference/controls/icons.md | 192 +++ docs/guide/reference/controls/index.md | 21 + docs/guide/reference/controls/masked-input.md | 490 ++++++ docs/guide/reference/controls/menu-items.md | 539 +++++++ .../reference/controls/navigation-items.md | 267 ++++ .../controls/property-grid-attributes.md | 211 +++ .../controls/property-grid-templates.md | 625 ++++++++ docs/guide/reference/controls/rich-text.md | 399 +++++ docs/guide/reference/controls/virtual-list.md | 196 +++ .../data/FocusRevalidationService.md | 109 ++ docs/guide/reference/data/IDataSource.md | 58 + docs/guide/reference/data/IKeyedDataSource.md | 39 + .../reference/data/IMutableDataSource.md | 53 + .../reference/data/IObservableDataSource.md | 19 + docs/guide/reference/data/ListDataSource.md | 113 ++ .../data/ObservableListDataSource.md | 44 + docs/guide/reference/data/async-values.md | 304 ++++ .../guide/reference/data/column-attributes.md | 139 ++ docs/guide/reference/data/descriptors.md | 454 ++++++ docs/guide/reference/data/enums.md | 28 + docs/guide/reference/data/index.md | 23 + docs/guide/reference/data/paging.md | 610 +++++++ docs/guide/reference/data/query-cache.md | 242 +++ .../reference/diagnostics/ReactorEvent.md | 108 ++ .../reference/diagnostics/ReactorSourceMap.md | 53 + .../ReactorSourceTransparentAttribute.md | 35 + .../reference/diagnostics/ReactorTrace.md | 98 ++ docs/guide/reference/diagnostics/devtools.md | 373 +++++ docs/guide/reference/diagnostics/index.md | 16 + docs/guide/reference/diagnostics/snapshots.md | 751 +++++++++ docs/guide/reference/elements/Element.md | 213 +++ docs/guide/reference/elements/buttons.md | 165 ++ docs/guide/reference/elements/collections.md | 658 ++++++++ docs/guide/reference/elements/composition.md | 196 +++ .../reference/elements/dialogs-and-flyouts.md | 130 ++ docs/guide/reference/elements/forms.md | 96 ++ docs/guide/reference/elements/index.md | 32 + docs/guide/reference/elements/input.md | 504 ++++++ docs/guide/reference/elements/interop.md | 91 ++ docs/guide/reference/elements/layout.md | 322 ++++ docs/guide/reference/elements/media.md | 131 ++ .../reference/elements/menus-and-commands.md | 114 ++ docs/guide/reference/elements/navigation.md | 254 +++ docs/guide/reference/elements/shapes.md | 115 ++ .../reference/elements/status-and-info.md | 98 ++ docs/guide/reference/elements/text.md | 80 + .../extensibility/ControlDescriptor.md | 469 ++++++ .../extensibility/ControlRegistry.md | 111 ++ .../extensibility/DescriptorHandler.md | 125 ++ .../reference/extensibility/ElementPool.md | 75 + .../extensibility/IDecoratorElementHandler.md | 84 + .../extensibility/IElementHandler.md | 119 ++ .../reference/extensibility/PathDataParser.md | 23 + .../reference/extensibility/PoolPolicy.md | 43 + .../reference/extensibility/PropEntry.md | 116 ++ .../extensibility/ReactorBinding-1.md | 271 ++++ .../reference/extensibility/ReactorBinding.md | 75 + .../extensibility/ReactorFeatureFlags.md | 67 + .../reference/extensibility/Reconciler.md | 456 ++++++ .../extensibility/children-strategies.md | 691 ++++++++ .../extensibility/descriptor-delegates.md | 61 + docs/guide/reference/extensibility/index.md | 28 + .../extensibility/lifecycle-contexts.md | 372 +++++ docs/guide/reference/factories/buttons.md | 211 +++ docs/guide/reference/factories/collections.md | 344 ++++ docs/guide/reference/factories/composition.md | 290 ++++ .../factories/dialogs-and-flyouts.md | 85 + docs/guide/reference/factories/forms.md | 111 ++ docs/guide/reference/factories/index.md | 26 + docs/guide/reference/factories/input.md | 398 +++++ docs/guide/reference/factories/interop.md | 71 + docs/guide/reference/factories/layout.md | 423 +++++ docs/guide/reference/factories/media.md | 164 ++ .../reference/factories/menus-and-commands.md | 280 ++++ docs/guide/reference/factories/navigation.md | 255 +++ docs/guide/reference/factories/shapes.md | 71 + .../reference/factories/status-and-info.md | 86 + docs/guide/reference/factories/text.md | 304 ++++ docs/guide/reference/hooks/Announce.md | 45 - docs/guide/reference/hooks/AnnounceHandle.md | 15 - .../reference/hooks/AnnounceRegionElement.md | 12 - docs/guide/reference/hooks/AnyLoading.md | 12 - docs/guide/reference/hooks/CacheKey.md | 15 - docs/guide/reference/hooks/CacheTime.md | 12 - docs/guide/reference/hooks/Changed.md | 12 - docs/guide/reference/hooks/Clear.md | 12 - .../hooks/ComponentUseMemoCellsExtensions.md | 19 - docs/guide/reference/hooks/Count.md | 12 - .../reference/hooks/CursorFromPageIndex.md | 15 - docs/guide/reference/hooks/Customize.md | 12 - docs/guide/reference/hooks/Descriptor.md | 12 - docs/guide/reference/hooks/Error.md | 12 - docs/guide/reference/hooks/Fields.md | 12 - docs/guide/reference/hooks/Focus.md | 31 - docs/guide/reference/hooks/FocusAttached.md | 12 - docs/guide/reference/hooks/FocusExtensions.md | 13 - docs/guide/reference/hooks/FocusField.md | 12 - docs/guide/reference/hooks/FocusFirst.md | 13 - docs/guide/reference/hooks/FocusManager.md | 13 - docs/guide/reference/hooks/FocusMeta.md | 12 - docs/guide/reference/hooks/FocusNext.md | 13 - docs/guide/reference/hooks/FocusPrevious.md | 12 - docs/guide/reference/hooks/FocusTrap.md | 13 - .../hooks/FocusTrapElementExtensions.md | 13 - docs/guide/reference/hooks/FocusTrapHandle.md | 14 - docs/guide/reference/hooks/GetFocus.md | 12 - docs/guide/reference/hooks/IHookDispatcher.md | 19 - .../reference/hooks/InfiniteHookState.md | 13 - docs/guide/reference/hooks/IsActive.md | 12 - docs/guide/reference/hooks/IsFirstField.md | 12 - docs/guide/reference/hooks/IsLastField.md | 12 - docs/guide/reference/hooks/IsPending.md | 12 - docs/guide/reference/hooks/LastResult.md | 12 - docs/guide/reference/hooks/Mutation.md | 31 - .../reference/hooks/MutationHookState.md | 13 - docs/guide/reference/hooks/MutationOptions.md | 31 - docs/guide/reference/hooks/NotifyPending.md | 12 - docs/guide/reference/hooks/Pending.md | 216 ++- .../guide/reference/hooks/PendingComponent.md | 22 - docs/guide/reference/hooks/PendingFactory.md | 13 - docs/guide/reference/hooks/PendingProps.md | 12 - docs/guide/reference/hooks/PendingScope.md | 37 - docs/guide/reference/hooks/Post.md | 12 - docs/guide/reference/hooks/RefetchOnMount.md | 12 - .../reference/hooks/RefetchOnWindowFocus.md | 12 - docs/guide/reference/hooks/Region.md | 13 - docs/guide/reference/hooks/Register.md | 34 - docs/guide/reference/hooks/Reset.md | 13 - .../reference/hooks/ResourceHookState.md | 13 - docs/guide/reference/hooks/ResourceOptions.md | 26 - docs/guide/reference/hooks/RetryCount.md | 12 - docs/guide/reference/hooks/RunAsync.md | 31 - docs/guide/reference/hooks/SetControl.md | 12 - docs/guide/reference/hooks/SetLoading.md | 14 - .../guide/reference/hooks/SetSubmitHandler.md | 12 - docs/guide/reference/hooks/StaleTime.md | 12 - docs/guide/reference/hooks/Unregister.md | 12 - docs/guide/reference/hooks/UseAnnounce.md | 47 +- .../reference/hooks/UseAnnounceExtensions.md | 12 - docs/guide/reference/hooks/UseBreakpoint.md | 60 +- docs/guide/reference/hooks/UseCallback.md | 114 +- .../hooks/UseChildValidationContext.md | 19 + docs/guide/reference/hooks/UseClosingGuard.md | 27 +- docs/guide/reference/hooks/UseCollection.md | 24 +- docs/guide/reference/hooks/UseColorScheme.md | 32 +- docs/guide/reference/hooks/UseCommand.md | 69 +- docs/guide/reference/hooks/UseCommandState.md | 16 - docs/guide/reference/hooks/UseContext.md | 26 +- docs/guide/reference/hooks/UseDataSource.md | 84 + docs/guide/reference/hooks/UseDevtools.md | 26 +- docs/guide/reference/hooks/UseDisplays.md | 17 +- docs/guide/reference/hooks/UseDpi.md | 19 +- docs/guide/reference/hooks/UseEffect.md | 215 ++- docs/guide/reference/hooks/UseElementFocus.md | 50 +- .../hooks/UseElementFocusExtensions.md | 16 - docs/guide/reference/hooks/UseElementRef.md | 42 +- .../hooks/UseElementRefExtensions.md | 28 - .../guide/reference/hooks/UseExternalStore.md | 44 +- docs/guide/reference/hooks/UseFocus.md | 35 +- .../reference/hooks/UseFocusExtensions.md | 12 - docs/guide/reference/hooks/UseFocusTrap.md | 57 +- .../reference/hooks/UseFocusTrapExtensions.md | 12 - docs/guide/reference/hooks/UseHighContrast.md | 24 +- .../reference/hooks/UseHighContrastScheme.md | 23 +- .../reference/hooks/UseInfiniteResource.md | 76 +- .../hooks/UseInfiniteResourceExtensions.md | 17 - docs/guide/reference/hooks/UseIntl.md | 20 +- docs/guide/reference/hooks/UseIsActive.md | 19 +- docs/guide/reference/hooks/UseIsCovered.md | 18 +- docs/guide/reference/hooks/UseIsDarkTheme.md | 20 +- docs/guide/reference/hooks/UseMemo.md | 113 +- docs/guide/reference/hooks/UseMemoCells.md | 80 +- .../reference/hooks/UseMemoCellsByIndex.md | 101 +- .../reference/hooks/UseMemoCellsByKey.md | 70 +- .../reference/hooks/UseMemoCellsExtensions.md | 45 - docs/guide/reference/hooks/UseMutation.md | 75 +- .../reference/hooks/UseMutationExtensions.md | 17 - docs/guide/reference/hooks/UseNavigation.md | 55 +- .../reference/hooks/UseNavigationLifecycle.md | 30 +- docs/guide/reference/hooks/UseObservable.md | 25 +- .../reference/hooks/UseObservableProperty.md | 26 +- .../reference/hooks/UseObservableTree.md | 26 +- docs/guide/reference/hooks/UseOpenWindow.md | 51 +- docs/guide/reference/hooks/UsePersisted.md | 82 +- .../guide/reference/hooks/UseReducedMotion.md | 31 +- docs/guide/reference/hooks/UseReducer.md | 70 +- docs/guide/reference/hooks/UseRef.md | 24 +- docs/guide/reference/hooks/UseResource.md | 101 +- .../reference/hooks/UseResourceExtensions.md | 17 - docs/guide/reference/hooks/UseState.md | 36 +- .../reference/hooks/UseStateSetterByIndex.md | 13 - .../reference/hooks/UseSystemBackButton.md | 25 +- docs/guide/reference/hooks/UseTrayIcon.md | 37 +- .../reference/hooks/UseValidationContext.md | 23 + docs/guide/reference/hooks/UseWindow.md | 21 +- .../reference/hooks/UseWindowAspectRatio.md | 24 +- .../reference/hooks/UseWindowDragMove.md | 28 +- .../reference/hooks/UseWindowPosition.md | 18 +- docs/guide/reference/hooks/UseWindowSize.md | 53 +- docs/guide/reference/hooks/UseWindowState.md | 19 +- .../hooks/WindowsDispatcherHookDispatcher.md | 13 - docs/guide/reference/hooks/focus-helpers.md | 218 +++ docs/guide/reference/hooks/hook-types.md | 348 ++++ docs/guide/reference/hooks/index.md | 164 +- docs/guide/reference/hosting/ReactorApp.md | 381 +++++ .../reference/hosting/ReactorAppContext.md | 25 + .../reference/hosting/ReactorApplication.md | 105 ++ docs/guide/reference/hosting/ReactorHost.md | 138 ++ .../reference/hosting/ReactorHostControl.md | 179 +++ docs/guide/reference/hosting/ReactorWindow.md | 459 ++++++ docs/guide/reference/hosting/RenderStats.md | 103 ++ .../hosting/UIThreadOnlyAttribute.md | 25 + docs/guide/reference/hosting/WindowIcon.md | 142 ++ docs/guide/reference/hosting/WindowKey.md | 87 + docs/guide/reference/hosting/WindowSpec.md | 384 +++++ docs/guide/reference/hosting/displays.md | 122 ++ docs/guide/reference/hosting/file-pickers.md | 364 +++++ docs/guide/reference/hosting/index.md | 32 + docs/guide/reference/hosting/launch.md | 146 ++ docs/guide/reference/hosting/persistence.md | 614 ++++++++ docs/guide/reference/hosting/taskbar.md | 521 ++++++ docs/guide/reference/hosting/tray-icon.md | 220 +++ docs/guide/reference/hosting/window-events.md | 193 +++ .../guide/reference/hosting/window-options.md | 268 ++++ docs/guide/reference/hosting/xaml-interop.md | 107 ++ docs/guide/reference/index.md | 24 + docs/guide/reference/input/Command-1.md | 119 ++ docs/guide/reference/input/Command.md | 129 ++ docs/guide/reference/input/CommandInterop.md | 52 + docs/guide/reference/input/FocusManager.md | 43 + docs/guide/reference/input/StandardCommand.md | 253 +++ docs/guide/reference/input/drag-and-drop.md | 803 ++++++++++ docs/guide/reference/input/element-refs.md | 117 ++ docs/guide/reference/input/gestures.md | 586 +++++++ docs/guide/reference/input/index.md | 18 + docs/guide/reference/layout/GridSize.md | 157 ++ .../reference/layout/GridSizeExtensions.md | 45 + docs/guide/reference/layout/attached.md | 448 ++++++ docs/guide/reference/layout/flex-enums.md | 614 ++++++++ docs/guide/reference/layout/index.md | 14 + .../localization/DateFormatOptions.md | 25 + .../localization/IStringResourceProvider.md | 29 + .../reference/localization/IntlAccessor.md | 200 +++ .../reference/localization/IntlContexts.md | 21 + .../reference/localization/MessageCache.md | 75 + .../reference/localization/MessageKey.md | 42 + .../localization/NumberFormatOptions.md | 37 + .../reference/localization/PseudoLocalizer.md | 41 + .../localization/ReswResourceProvider.md | 52 + .../guide/reference/localization/RtlHelper.md | 27 + docs/guide/reference/localization/enums.md | 59 + docs/guide/reference/localization/index.md | 21 + .../modifiers/AccessibilityModifiers.md | 163 ++ .../reference/modifiers/ElementExtensions.md | 429 +++++ .../reference/modifiers/ElementExtras.md | 157 ++ .../reference/modifiers/ElementModifiers.md | 579 +++++++ .../reference/modifiers/LayoutModifiers.md | 159 ++ .../reference/modifiers/VisualModifiers.md | 105 ++ .../reference/modifiers/accessibility.md | 390 +++++ docs/guide/reference/modifiers/animation.md | 331 ++++ docs/guide/reference/modifiers/appearance.md | 375 +++++ docs/guide/reference/modifiers/buttons.md | 232 +++ docs/guide/reference/modifiers/collections.md | 190 +++ .../modifiers/dialogs-and-flyouts.md | 250 +++ .../reference/modifiers/focus-and-keyboard.md | 312 ++++ docs/guide/reference/modifiers/forms.md | 48 + docs/guide/reference/modifiers/index.md | 55 + .../reference/modifiers/input-and-events.md | 665 ++++++++ docs/guide/reference/modifiers/input.md | 1402 +++++++++++++++++ docs/guide/reference/modifiers/interop.md | 79 + .../reference/modifiers/layout-and-spacing.md | 570 +++++++ docs/guide/reference/modifiers/layout.md | 329 ++++ docs/guide/reference/modifiers/lifecycle.md | 178 +++ docs/guide/reference/modifiers/media.md | 165 ++ .../reference/modifiers/native-properties.md | 109 ++ docs/guide/reference/modifiers/navigation.md | 1158 ++++++++++++++ docs/guide/reference/modifiers/shapes.md | 201 +++ .../reference/modifiers/shared-controls.md | 291 ++++ .../reference/modifiers/status-and-info.md | 147 ++ .../modifiers/tooltips-and-flyouts.md | 117 ++ docs/guide/reference/modifiers/typography.md | 550 +++++++ docs/guide/reference/modifiers/validation.md | 176 +++ .../guide/reference/navigation/DeepLinkMap.md | 50 + .../reference/navigation/DeepLinkResult.md | 29 + .../reference/navigation/NavigateOptions.md | 45 + .../navigation/NavigationEventArgs.md | 56 + .../reference/navigation/NavigationHandle.md | 188 +++ .../reference/navigation/NavigationState.md | 57 + docs/guide/reference/navigation/RouteArgs.md | 93 ++ .../guide/reference/navigation/diagnostics.md | 254 +++ docs/guide/reference/navigation/enums.md | 43 + docs/guide/reference/navigation/index.md | 21 + docs/guide/reference/navigation/lifecycle.md | 153 ++ .../guide/reference/navigation/transitions.md | 353 +++++ .../guide/reference/theming/BackdropChoice.md | 65 + docs/guide/reference/theming/BrushHelper.md | 27 + .../reference/theming/ResourceBuilder.md | 200 +++ .../reference/theming/ResourceOverrides.md | 42 + docs/guide/reference/theming/Theme.md | 265 ++++ docs/guide/reference/theming/ThemeRef.md | 52 + docs/guide/reference/theming/ThemeResource.md | 78 + docs/guide/reference/theming/enums.md | 50 + docs/guide/reference/theming/index.md | 18 + .../reference/validation/ErrorBubbling.md | 59 + .../reference/validation/ErrorStyling.md | 78 + .../reference/validation/FormFieldHelpers.md | 89 ++ .../reference/validation/IAsyncValidator.md | 29 + docs/guide/reference/validation/IValidator.md | 28 + docs/guide/reference/validation/Validate.md | 175 ++ .../validation/ValidateExtensions.md | 48 + .../reference/validation/ValidationContext.md | 375 +++++ .../validation/ValidationContexts.md | 21 + .../reference/validation/ValidationMessage.md | 64 + .../validation/ValidationReconciler.md | 181 +++ .../reference/validation/ValidationRuleDsl.md | 38 + docs/guide/reference/validation/attached.md | 128 ++ docs/guide/reference/validation/enums.md | 62 + docs/guide/reference/validation/index.md | 24 + .../ReferenceGenOverloadTests.cs | 456 +++--- .../ReferenceGenTests.cs | 905 +++++++++-- .../ReferenceLinkInjectorTests.cs | 230 +-- tools/Reactor.DocPipeline/CompileCommand.cs | 201 ++- .../ReferenceGen/AssemblyModel.cs | 1378 ++++++++++++++++ .../ReferenceGen/CrefResolver.cs | 287 ---- .../ReferenceGen/CrefSignature.cs | 2 +- .../ReferenceGen/DocMarkdown.cs | 348 ++++ .../ReferenceGen/MemberRouter.cs | 89 -- .../ReferenceGen/ReferenceGenerator.cs | 387 ++--- .../ReferenceGen/ReferencePlanner.cs | 562 +++++++ .../ReferenceGen/ReferenceRenderer.cs | 1391 ++++++++++++++++ .../ReferenceGen/ReferenceWriter.cs | 265 ---- .../Reactor.DocPipeline/ReferenceGen/Slug.cs | 131 ++ .../ReferenceGen/XmlDocReader.cs | 20 +- .../ReferenceLinkInjector.cs | 256 +-- tools/Reactor.DocPipeline/ReferenceMap.cs | 192 ++- .../Reactor.DocPipeline/YamlStaticContext.cs | 4 + 376 files changed, 50624 insertions(+), 3952 deletions(-) create mode 100644 docs/guide/reference/accessibility/A11yContext.md create mode 100644 docs/guide/reference/accessibility/A11yDiagnostic.md create mode 100644 docs/guide/reference/accessibility/A11yFixSuggestion.md create mode 100644 docs/guide/reference/accessibility/AccessibilityScanner.md create mode 100644 docs/guide/reference/accessibility/SemanticDescription.md create mode 100644 docs/guide/reference/accessibility/SemanticPanel.md create mode 100644 docs/guide/reference/accessibility/SemanticPanelAutomationPeer.md create mode 100644 docs/guide/reference/accessibility/index.md create mode 100644 docs/guide/reference/animation/AnimationConfig.md create mode 100644 docs/guide/reference/animation/AnimationScope.md create mode 100644 docs/guide/reference/animation/Animations.md create mode 100644 docs/guide/reference/animation/CompositorProvider.md create mode 100644 docs/guide/reference/animation/StaggerConfig.md create mode 100644 docs/guide/reference/animation/curves.md create mode 100644 docs/guide/reference/animation/enums.md create mode 100644 docs/guide/reference/animation/implicit.md create mode 100644 docs/guide/reference/animation/index.md create mode 100644 docs/guide/reference/animation/interaction-states.md create mode 100644 docs/guide/reference/animation/keyframes.md create mode 100644 docs/guide/reference/animation/scroll.md create mode 100644 docs/guide/reference/animation/transitions.md create mode 100644 docs/guide/reference/components/AppContexts.md create mode 100644 docs/guide/reference/components/Callbacks.md create mode 100644 docs/guide/reference/components/Component-1.md create mode 100644 docs/guide/reference/components/Component.md create mode 100644 docs/guide/reference/components/Context.md create mode 100644 docs/guide/reference/components/ContextBase.md create mode 100644 docs/guide/reference/components/ElementFactory.md create mode 100644 docs/guide/reference/components/IReactorKeyed.md create mode 100644 docs/guide/reference/components/Observable.md create mode 100644 docs/guide/reference/components/Optional.md create mode 100644 docs/guide/reference/components/Ref.md create mode 100644 docs/guide/reference/components/RenderContext.md create mode 100644 docs/guide/reference/components/SourceLocation.md create mode 100644 docs/guide/reference/components/index.md create mode 100644 docs/guide/reference/components/render-errors.md create mode 100644 docs/guide/reference/controls/PropertyGridComponent.md create mode 100644 docs/guide/reference/controls/PropertyGridDefaults.md create mode 100644 docs/guide/reference/controls/collection-items.md create mode 100644 docs/guide/reference/controls/icons.md create mode 100644 docs/guide/reference/controls/index.md create mode 100644 docs/guide/reference/controls/masked-input.md create mode 100644 docs/guide/reference/controls/menu-items.md create mode 100644 docs/guide/reference/controls/navigation-items.md create mode 100644 docs/guide/reference/controls/property-grid-attributes.md create mode 100644 docs/guide/reference/controls/property-grid-templates.md create mode 100644 docs/guide/reference/controls/rich-text.md create mode 100644 docs/guide/reference/controls/virtual-list.md create mode 100644 docs/guide/reference/data/FocusRevalidationService.md create mode 100644 docs/guide/reference/data/IDataSource.md create mode 100644 docs/guide/reference/data/IKeyedDataSource.md create mode 100644 docs/guide/reference/data/IMutableDataSource.md create mode 100644 docs/guide/reference/data/IObservableDataSource.md create mode 100644 docs/guide/reference/data/ListDataSource.md create mode 100644 docs/guide/reference/data/ObservableListDataSource.md create mode 100644 docs/guide/reference/data/async-values.md create mode 100644 docs/guide/reference/data/column-attributes.md create mode 100644 docs/guide/reference/data/descriptors.md create mode 100644 docs/guide/reference/data/enums.md create mode 100644 docs/guide/reference/data/index.md create mode 100644 docs/guide/reference/data/paging.md create mode 100644 docs/guide/reference/data/query-cache.md create mode 100644 docs/guide/reference/diagnostics/ReactorEvent.md create mode 100644 docs/guide/reference/diagnostics/ReactorSourceMap.md create mode 100644 docs/guide/reference/diagnostics/ReactorSourceTransparentAttribute.md create mode 100644 docs/guide/reference/diagnostics/ReactorTrace.md create mode 100644 docs/guide/reference/diagnostics/devtools.md create mode 100644 docs/guide/reference/diagnostics/index.md create mode 100644 docs/guide/reference/diagnostics/snapshots.md create mode 100644 docs/guide/reference/elements/Element.md create mode 100644 docs/guide/reference/elements/buttons.md create mode 100644 docs/guide/reference/elements/collections.md create mode 100644 docs/guide/reference/elements/composition.md create mode 100644 docs/guide/reference/elements/dialogs-and-flyouts.md create mode 100644 docs/guide/reference/elements/forms.md create mode 100644 docs/guide/reference/elements/index.md create mode 100644 docs/guide/reference/elements/input.md create mode 100644 docs/guide/reference/elements/interop.md create mode 100644 docs/guide/reference/elements/layout.md create mode 100644 docs/guide/reference/elements/media.md create mode 100644 docs/guide/reference/elements/menus-and-commands.md create mode 100644 docs/guide/reference/elements/navigation.md create mode 100644 docs/guide/reference/elements/shapes.md create mode 100644 docs/guide/reference/elements/status-and-info.md create mode 100644 docs/guide/reference/elements/text.md create mode 100644 docs/guide/reference/extensibility/ControlDescriptor.md create mode 100644 docs/guide/reference/extensibility/ControlRegistry.md create mode 100644 docs/guide/reference/extensibility/DescriptorHandler.md create mode 100644 docs/guide/reference/extensibility/ElementPool.md create mode 100644 docs/guide/reference/extensibility/IDecoratorElementHandler.md create mode 100644 docs/guide/reference/extensibility/IElementHandler.md create mode 100644 docs/guide/reference/extensibility/PathDataParser.md create mode 100644 docs/guide/reference/extensibility/PoolPolicy.md create mode 100644 docs/guide/reference/extensibility/PropEntry.md create mode 100644 docs/guide/reference/extensibility/ReactorBinding-1.md create mode 100644 docs/guide/reference/extensibility/ReactorBinding.md create mode 100644 docs/guide/reference/extensibility/ReactorFeatureFlags.md create mode 100644 docs/guide/reference/extensibility/Reconciler.md create mode 100644 docs/guide/reference/extensibility/children-strategies.md create mode 100644 docs/guide/reference/extensibility/descriptor-delegates.md create mode 100644 docs/guide/reference/extensibility/index.md create mode 100644 docs/guide/reference/extensibility/lifecycle-contexts.md create mode 100644 docs/guide/reference/factories/buttons.md create mode 100644 docs/guide/reference/factories/collections.md create mode 100644 docs/guide/reference/factories/composition.md create mode 100644 docs/guide/reference/factories/dialogs-and-flyouts.md create mode 100644 docs/guide/reference/factories/forms.md create mode 100644 docs/guide/reference/factories/index.md create mode 100644 docs/guide/reference/factories/input.md create mode 100644 docs/guide/reference/factories/interop.md create mode 100644 docs/guide/reference/factories/layout.md create mode 100644 docs/guide/reference/factories/media.md create mode 100644 docs/guide/reference/factories/menus-and-commands.md create mode 100644 docs/guide/reference/factories/navigation.md create mode 100644 docs/guide/reference/factories/shapes.md create mode 100644 docs/guide/reference/factories/status-and-info.md create mode 100644 docs/guide/reference/factories/text.md delete mode 100644 docs/guide/reference/hooks/Announce.md delete mode 100644 docs/guide/reference/hooks/AnnounceHandle.md delete mode 100644 docs/guide/reference/hooks/AnnounceRegionElement.md delete mode 100644 docs/guide/reference/hooks/AnyLoading.md delete mode 100644 docs/guide/reference/hooks/CacheKey.md delete mode 100644 docs/guide/reference/hooks/CacheTime.md delete mode 100644 docs/guide/reference/hooks/Changed.md delete mode 100644 docs/guide/reference/hooks/Clear.md delete mode 100644 docs/guide/reference/hooks/ComponentUseMemoCellsExtensions.md delete mode 100644 docs/guide/reference/hooks/Count.md delete mode 100644 docs/guide/reference/hooks/CursorFromPageIndex.md delete mode 100644 docs/guide/reference/hooks/Customize.md delete mode 100644 docs/guide/reference/hooks/Descriptor.md delete mode 100644 docs/guide/reference/hooks/Error.md delete mode 100644 docs/guide/reference/hooks/Fields.md delete mode 100644 docs/guide/reference/hooks/Focus.md delete mode 100644 docs/guide/reference/hooks/FocusAttached.md delete mode 100644 docs/guide/reference/hooks/FocusExtensions.md delete mode 100644 docs/guide/reference/hooks/FocusField.md delete mode 100644 docs/guide/reference/hooks/FocusFirst.md delete mode 100644 docs/guide/reference/hooks/FocusManager.md delete mode 100644 docs/guide/reference/hooks/FocusMeta.md delete mode 100644 docs/guide/reference/hooks/FocusNext.md delete mode 100644 docs/guide/reference/hooks/FocusPrevious.md delete mode 100644 docs/guide/reference/hooks/FocusTrap.md delete mode 100644 docs/guide/reference/hooks/FocusTrapElementExtensions.md delete mode 100644 docs/guide/reference/hooks/FocusTrapHandle.md delete mode 100644 docs/guide/reference/hooks/GetFocus.md delete mode 100644 docs/guide/reference/hooks/IHookDispatcher.md delete mode 100644 docs/guide/reference/hooks/InfiniteHookState.md delete mode 100644 docs/guide/reference/hooks/IsActive.md delete mode 100644 docs/guide/reference/hooks/IsFirstField.md delete mode 100644 docs/guide/reference/hooks/IsLastField.md delete mode 100644 docs/guide/reference/hooks/IsPending.md delete mode 100644 docs/guide/reference/hooks/LastResult.md delete mode 100644 docs/guide/reference/hooks/Mutation.md delete mode 100644 docs/guide/reference/hooks/MutationHookState.md delete mode 100644 docs/guide/reference/hooks/MutationOptions.md delete mode 100644 docs/guide/reference/hooks/NotifyPending.md delete mode 100644 docs/guide/reference/hooks/PendingComponent.md delete mode 100644 docs/guide/reference/hooks/PendingFactory.md delete mode 100644 docs/guide/reference/hooks/PendingProps.md delete mode 100644 docs/guide/reference/hooks/PendingScope.md delete mode 100644 docs/guide/reference/hooks/Post.md delete mode 100644 docs/guide/reference/hooks/RefetchOnMount.md delete mode 100644 docs/guide/reference/hooks/RefetchOnWindowFocus.md delete mode 100644 docs/guide/reference/hooks/Region.md delete mode 100644 docs/guide/reference/hooks/Register.md delete mode 100644 docs/guide/reference/hooks/Reset.md delete mode 100644 docs/guide/reference/hooks/ResourceHookState.md delete mode 100644 docs/guide/reference/hooks/ResourceOptions.md delete mode 100644 docs/guide/reference/hooks/RetryCount.md delete mode 100644 docs/guide/reference/hooks/RunAsync.md delete mode 100644 docs/guide/reference/hooks/SetControl.md delete mode 100644 docs/guide/reference/hooks/SetLoading.md delete mode 100644 docs/guide/reference/hooks/SetSubmitHandler.md delete mode 100644 docs/guide/reference/hooks/StaleTime.md delete mode 100644 docs/guide/reference/hooks/Unregister.md delete mode 100644 docs/guide/reference/hooks/UseAnnounceExtensions.md create mode 100644 docs/guide/reference/hooks/UseChildValidationContext.md delete mode 100644 docs/guide/reference/hooks/UseCommandState.md create mode 100644 docs/guide/reference/hooks/UseDataSource.md delete mode 100644 docs/guide/reference/hooks/UseElementFocusExtensions.md delete mode 100644 docs/guide/reference/hooks/UseElementRefExtensions.md delete mode 100644 docs/guide/reference/hooks/UseFocusExtensions.md delete mode 100644 docs/guide/reference/hooks/UseFocusTrapExtensions.md delete mode 100644 docs/guide/reference/hooks/UseInfiniteResourceExtensions.md delete mode 100644 docs/guide/reference/hooks/UseMemoCellsExtensions.md delete mode 100644 docs/guide/reference/hooks/UseMutationExtensions.md delete mode 100644 docs/guide/reference/hooks/UseResourceExtensions.md delete mode 100644 docs/guide/reference/hooks/UseStateSetterByIndex.md create mode 100644 docs/guide/reference/hooks/UseValidationContext.md delete mode 100644 docs/guide/reference/hooks/WindowsDispatcherHookDispatcher.md create mode 100644 docs/guide/reference/hooks/focus-helpers.md create mode 100644 docs/guide/reference/hooks/hook-types.md create mode 100644 docs/guide/reference/hosting/ReactorApp.md create mode 100644 docs/guide/reference/hosting/ReactorAppContext.md create mode 100644 docs/guide/reference/hosting/ReactorApplication.md create mode 100644 docs/guide/reference/hosting/ReactorHost.md create mode 100644 docs/guide/reference/hosting/ReactorHostControl.md create mode 100644 docs/guide/reference/hosting/ReactorWindow.md create mode 100644 docs/guide/reference/hosting/RenderStats.md create mode 100644 docs/guide/reference/hosting/UIThreadOnlyAttribute.md create mode 100644 docs/guide/reference/hosting/WindowIcon.md create mode 100644 docs/guide/reference/hosting/WindowKey.md create mode 100644 docs/guide/reference/hosting/WindowSpec.md create mode 100644 docs/guide/reference/hosting/displays.md create mode 100644 docs/guide/reference/hosting/file-pickers.md create mode 100644 docs/guide/reference/hosting/index.md create mode 100644 docs/guide/reference/hosting/launch.md create mode 100644 docs/guide/reference/hosting/persistence.md create mode 100644 docs/guide/reference/hosting/taskbar.md create mode 100644 docs/guide/reference/hosting/tray-icon.md create mode 100644 docs/guide/reference/hosting/window-events.md create mode 100644 docs/guide/reference/hosting/window-options.md create mode 100644 docs/guide/reference/hosting/xaml-interop.md create mode 100644 docs/guide/reference/index.md create mode 100644 docs/guide/reference/input/Command-1.md create mode 100644 docs/guide/reference/input/Command.md create mode 100644 docs/guide/reference/input/CommandInterop.md create mode 100644 docs/guide/reference/input/FocusManager.md create mode 100644 docs/guide/reference/input/StandardCommand.md create mode 100644 docs/guide/reference/input/drag-and-drop.md create mode 100644 docs/guide/reference/input/element-refs.md create mode 100644 docs/guide/reference/input/gestures.md create mode 100644 docs/guide/reference/input/index.md create mode 100644 docs/guide/reference/layout/GridSize.md create mode 100644 docs/guide/reference/layout/GridSizeExtensions.md create mode 100644 docs/guide/reference/layout/attached.md create mode 100644 docs/guide/reference/layout/flex-enums.md create mode 100644 docs/guide/reference/layout/index.md create mode 100644 docs/guide/reference/localization/DateFormatOptions.md create mode 100644 docs/guide/reference/localization/IStringResourceProvider.md create mode 100644 docs/guide/reference/localization/IntlAccessor.md create mode 100644 docs/guide/reference/localization/IntlContexts.md create mode 100644 docs/guide/reference/localization/MessageCache.md create mode 100644 docs/guide/reference/localization/MessageKey.md create mode 100644 docs/guide/reference/localization/NumberFormatOptions.md create mode 100644 docs/guide/reference/localization/PseudoLocalizer.md create mode 100644 docs/guide/reference/localization/ReswResourceProvider.md create mode 100644 docs/guide/reference/localization/RtlHelper.md create mode 100644 docs/guide/reference/localization/enums.md create mode 100644 docs/guide/reference/localization/index.md create mode 100644 docs/guide/reference/modifiers/AccessibilityModifiers.md create mode 100644 docs/guide/reference/modifiers/ElementExtensions.md create mode 100644 docs/guide/reference/modifiers/ElementExtras.md create mode 100644 docs/guide/reference/modifiers/ElementModifiers.md create mode 100644 docs/guide/reference/modifiers/LayoutModifiers.md create mode 100644 docs/guide/reference/modifiers/VisualModifiers.md create mode 100644 docs/guide/reference/modifiers/accessibility.md create mode 100644 docs/guide/reference/modifiers/animation.md create mode 100644 docs/guide/reference/modifiers/appearance.md create mode 100644 docs/guide/reference/modifiers/buttons.md create mode 100644 docs/guide/reference/modifiers/collections.md create mode 100644 docs/guide/reference/modifiers/dialogs-and-flyouts.md create mode 100644 docs/guide/reference/modifiers/focus-and-keyboard.md create mode 100644 docs/guide/reference/modifiers/forms.md create mode 100644 docs/guide/reference/modifiers/index.md create mode 100644 docs/guide/reference/modifiers/input-and-events.md create mode 100644 docs/guide/reference/modifiers/input.md create mode 100644 docs/guide/reference/modifiers/interop.md create mode 100644 docs/guide/reference/modifiers/layout-and-spacing.md create mode 100644 docs/guide/reference/modifiers/layout.md create mode 100644 docs/guide/reference/modifiers/lifecycle.md create mode 100644 docs/guide/reference/modifiers/media.md create mode 100644 docs/guide/reference/modifiers/native-properties.md create mode 100644 docs/guide/reference/modifiers/navigation.md create mode 100644 docs/guide/reference/modifiers/shapes.md create mode 100644 docs/guide/reference/modifiers/shared-controls.md create mode 100644 docs/guide/reference/modifiers/status-and-info.md create mode 100644 docs/guide/reference/modifiers/tooltips-and-flyouts.md create mode 100644 docs/guide/reference/modifiers/typography.md create mode 100644 docs/guide/reference/modifiers/validation.md create mode 100644 docs/guide/reference/navigation/DeepLinkMap.md create mode 100644 docs/guide/reference/navigation/DeepLinkResult.md create mode 100644 docs/guide/reference/navigation/NavigateOptions.md create mode 100644 docs/guide/reference/navigation/NavigationEventArgs.md create mode 100644 docs/guide/reference/navigation/NavigationHandle.md create mode 100644 docs/guide/reference/navigation/NavigationState.md create mode 100644 docs/guide/reference/navigation/RouteArgs.md create mode 100644 docs/guide/reference/navigation/diagnostics.md create mode 100644 docs/guide/reference/navigation/enums.md create mode 100644 docs/guide/reference/navigation/index.md create mode 100644 docs/guide/reference/navigation/lifecycle.md create mode 100644 docs/guide/reference/navigation/transitions.md create mode 100644 docs/guide/reference/theming/BackdropChoice.md create mode 100644 docs/guide/reference/theming/BrushHelper.md create mode 100644 docs/guide/reference/theming/ResourceBuilder.md create mode 100644 docs/guide/reference/theming/ResourceOverrides.md create mode 100644 docs/guide/reference/theming/Theme.md create mode 100644 docs/guide/reference/theming/ThemeRef.md create mode 100644 docs/guide/reference/theming/ThemeResource.md create mode 100644 docs/guide/reference/theming/enums.md create mode 100644 docs/guide/reference/theming/index.md create mode 100644 docs/guide/reference/validation/ErrorBubbling.md create mode 100644 docs/guide/reference/validation/ErrorStyling.md create mode 100644 docs/guide/reference/validation/FormFieldHelpers.md create mode 100644 docs/guide/reference/validation/IAsyncValidator.md create mode 100644 docs/guide/reference/validation/IValidator.md create mode 100644 docs/guide/reference/validation/Validate.md create mode 100644 docs/guide/reference/validation/ValidateExtensions.md create mode 100644 docs/guide/reference/validation/ValidationContext.md create mode 100644 docs/guide/reference/validation/ValidationContexts.md create mode 100644 docs/guide/reference/validation/ValidationMessage.md create mode 100644 docs/guide/reference/validation/ValidationReconciler.md create mode 100644 docs/guide/reference/validation/ValidationRuleDsl.md create mode 100644 docs/guide/reference/validation/attached.md create mode 100644 docs/guide/reference/validation/enums.md create mode 100644 docs/guide/reference/validation/index.md create mode 100644 tools/Reactor.DocPipeline/ReferenceGen/AssemblyModel.cs delete mode 100644 tools/Reactor.DocPipeline/ReferenceGen/CrefResolver.cs create mode 100644 tools/Reactor.DocPipeline/ReferenceGen/DocMarkdown.cs delete mode 100644 tools/Reactor.DocPipeline/ReferenceGen/MemberRouter.cs create mode 100644 tools/Reactor.DocPipeline/ReferenceGen/ReferencePlanner.cs create mode 100644 tools/Reactor.DocPipeline/ReferenceGen/ReferenceRenderer.cs delete mode 100644 tools/Reactor.DocPipeline/ReferenceGen/ReferenceWriter.cs create mode 100644 tools/Reactor.DocPipeline/ReferenceGen/Slug.cs diff --git a/docs/_pipeline/reference-map.yaml b/docs/_pipeline/reference-map.yaml index 79f896c2bc..6d114a03af 100644 --- a/docs/_pipeline/reference-map.yaml +++ b/docs/_pipeline/reference-map.yaml @@ -1,35 +1,975 @@ -# Reference map for spec 041 §10.4.1 — XML-doc → MD reference generation. +# Reference map for spec 041 §10.4: how the API reference is laid out. # -# Maps each canonical cref (T:, M:, P:, F:, E: prefix) to (category, -# guide-pages). Two ordered passes: +# Phase 5.7 of `compile` reads Microsoft.UI.Reactor.dll and +# Microsoft.UI.Reactor.xml and writes the pages under docs/guide/reference/. +# This file decides where each public type and member goes. # -# 1. overrides — exact cref match wins, then prefix match (most-specific -# prefix wins). Use this to pin individual members to a non-default -# category or to redirect a member to a specific conceptual page. -# 2. defaults — namespace-prefix glob, most-specific wins. Catches -# everything not explicitly pinned. +# categories One folder per category, each with a generated index.md. +# `layout` picks the page shape: +# types one page per type (groups collect small types) +# hooks one page per Use* hook, plus type pages +# elements one page per area of element records +# factories one page per area of Factories methods +# modifiers one page per area of fluent modifiers +# `groups` with `match` put several small types on one page. +# `groups` with `hooks` only make sections on the hooks index. +# areas Control areas shared by the elements, factories and +# modifiers categories. `elements` match an element record +# name without its `Element` suffix. `factories` match factory +# methods that do not return an element of the area. +# modifier-areas +# Areas for modifiers, matched by method name. A modifier no +# area matches goes to the page of the control area it +# extends, then to the area that has no `match` list. +# defaults Type name globs to category (most specific wins). Member +# globs only add guide pages ("Learn more" links). +# overrides Checked before defaults. A `category` here also wins over +# the "element records go to elements" rule. # -# Unmatched members produce REACTOR_DOC_REGISTRY_W001 at build time and -# fall through with no category/guide-pages. +# Globs: `*` matches any run of characters. A glob is anchored at both ends +# unless it starts or ends with `*`. Rules match the cref without its +# `T:`/`M:` prefix. Use the category `excluded` to keep a type out. +# Guide pages are template ids from docs/_pipeline/templates/. + +element-base: "Microsoft.UI.Reactor.Core.Element" + +categories: + - id: hooks + title: Hooks + layout: hooks + summary: "State, effects, context and the other hooks a component calls from Render." + intro: >- + Hooks are how Reactor components subscribe to state, schedule effects, and + reach into the framework's lifecycle from a function-shaped `Render` body. + Call them on the `RenderContext` (or from a `Component`), always in the same + order, and never inside a condition or a loop. + guide-pages: [hooks, effects, rules-of-reactor] + groups: + - id: state + title: State + summary: "Hooks that keep values between renders." + hooks: ["UseState*", "UseReducer", "UseRef", "UseCollection", "UseExternalStore", "UseObservable*", "UsePersisted"] + - id: effects-and-memo + title: Effects and memoization + summary: "Hooks that run side effects or cache values between renders." + hooks: ["UseEffect", "UseMemo*", "UseCallback"] + - id: context + title: Context + summary: "Hooks that read values provided higher in the tree." + hooks: ["UseContext", "UseIntl"] + - id: data + title: Data and commands + summary: "Hooks that load data, run mutations and expose commands." + hooks: ["UseResource", "UseInfiniteResource", "UseMutation", "UseDataSource", "UseCommand*"] + - id: forms + title: Forms and validation + summary: "Hooks that connect a component to a validation context." + hooks: ["Use*ValidationContext"] + - id: windows + title: Windows and display + summary: "Hooks that read or change the window, the display and the tray icon." + hooks: ["UseWindow*", "UseOpenWindow", "UseClosingGuard", "UseIsActive", "UseIsCovered", "UseDisplays", "UseDpi", "UseBreakpoint", "UseTrayIcon"] + - id: theme-and-accessibility + title: Theme and accessibility + summary: "Hooks that follow the system theme and accessibility settings." + hooks: ["UseColorScheme", "UseIsDarkTheme", "UseHighContrast*", "UseReducedMotion", "UseAnnounce"] + - id: focus + title: Focus and element refs + summary: "Hooks that move focus or reach a mounted control." + hooks: ["UseFocus*", "UseElementFocus", "UseElementRef"] + - id: navigation + title: Navigation + summary: "Hooks for page navigation and the system back button." + hooks: ["UseNavigation*", "UseSystemBackButton"] + - id: tools + title: Developer tools + summary: "Hooks for the Reactor developer tools." + hooks: ["UseDevtools"] + - id: hook-types + title: Hook results and options + summary: "Small types that hooks return or take as options." + match: ["AnnounceHandle", "FocusTrapHandle", "Mutation", "MutationOptions", "ResourceOptions", "IHookDispatcher"] + - id: pending + title: Pending + summary: "The Pending element that shows a fallback while resources below it load." + match: ["Pending*"] + - id: focus-helpers + title: Focus helpers + summary: "The focus manager and the modifiers that the UseFocus hooks work with." + match: ["Microsoft.UI.Reactor.Hooks.Focus*"] + + - id: components + title: Components + summary: "Component base classes, the render context, refs, context and error types." + intro: >- + A component is a class whose `Render` method returns an element tree. These + types are the building blocks every component uses. + guide-pages: [components, thinking-in-reactor, context] + groups: + - id: render-errors + title: Render errors + summary: "Types that describe an error thrown while a component renders." + match: ["RenderError*", "HookOrderException"] + + - id: elements + title: Elements + layout: elements + summary: "The immutable element records that describe each control." + intro: >- + Every control in Reactor is described by an element record. Factory methods + create them and modifiers return changed copies. The reconciler turns them + into real WinUI controls. + guide-pages: [controls, reconciliation] + + - id: factories + title: Factories + layout: factories + summary: "The DSL factory methods that create element records." + intro: >- + Add `using static Microsoft.UI.Reactor.Factories;` and call these methods to + build an element tree, for example `VStack(TextBlock("Hello"), Button("OK", onClick))`. + guide-pages: [controls, layout, cheat-sheet] + + - id: modifiers + title: Modifiers + layout: modifiers + summary: "Fluent extension methods that change layout, appearance, input and behavior." + intro: >- + Modifiers are extension methods on element records. Each one returns a + changed copy of the element, so you can chain them: + `TextBlock("Hi").Margin(8).Bold()`. + guide-pages: [modifier-system, styling] + + - id: hosting + title: Hosting and windows + summary: "Start the app, open windows and integrate with the Windows shell." + intro: >- + `ReactorApp` starts the app and opens its first window. The other types here + describe windows, the tray icon, the taskbar and the ways to host Reactor + inside an existing WinUI app. + guide-pages: [windows, windowing-advanced, desktop-integration] + groups: + - id: window-events + title: Window events + summary: "Event arguments raised by a Reactor window." + match: ["Window*EventArgs", "WindowCloseReason"] + - id: window-options + title: Window options + summary: "Enums that describe the style, size and position of a window." + match: ["WindowCornerStyle", "WindowEmbedStyle", "WindowLevel", "WindowResizeMode", "WindowSizeToContent", + "WindowStartPosition", "WindowState", "WindowStyle", "WindowTitleBar*", "WindowIconKind", "AspectRatioBasis", + "PresenterKind", "ShutdownPolicy"] + - id: taskbar + title: Taskbar and jump lists + summary: "Types for the taskbar button, its progress, overlay, thumbnail buttons and jump list." + match: ["Taskbar*", "JumpList*", "ThumbnailToolbarButton"] + - id: tray-icon + title: Tray icon + summary: "Types for an icon in the notification area." + match: ["ReactorTrayIcon", "TrayIconSpec"] + - id: displays + title: Displays + summary: "Information about the connected displays." + match: ["DisplayInfo", "ReactorDisplay"] + - id: launch + title: Launch and activation + summary: "How the app was started, and requests to embed it." + match: ["LaunchActivation", "LaunchKind", "EmbedRequest"] + - id: file-pickers + title: File pickers + summary: "Options for the open file, save file and folder pickers." + match: ["*PickerOptions", "FileTypeChoice"] + - id: persistence + title: Persistence + summary: "Stores and scopes that save window placement and persisted state." + match: ["Microsoft.UI.Reactor.Hosting.Persistence.*", "*PersistedScope", "IPersistedStateScope"] + - id: xaml-interop + title: XAML interop + summary: "Helpers for hosting Reactor inside an existing XAML app." + match: ["PageHelper", "XamlInterop"] + + - id: theming + title: Theming + summary: "Theme tokens, theme resources, brushes and window backdrops." + guide-pages: [theming-tokens, styling] + + - id: layout + title: Layout + summary: "The flex panel, grid sizes and the attached layout records." + guide-pages: [layout, flex-layout] + groups: + - id: attached + title: Attached layout properties + summary: "Records that hold the attached properties set by the layout modifiers." + match: ["CanvasAttached", "FlexAttached", "GridAttached", "RelativePanelAttached", "WrapGridAttached", "GridDefinition"] + - id: flex-enums + title: Flex enums + summary: "Enums that control the flex layout." + match: ["Flex*"] + + - id: input + title: Input and commands + summary: "Commands, element refs, focus, drag and drop, and gestures." + guide-pages: [input-and-gestures, commanding] + groups: + - id: drag-and-drop + title: Drag and drop + summary: "Types for dragging data out of and dropping it onto elements." + match: ["Drag*", "DropTargetConfig"] + - id: gestures + title: Gestures + summary: "Gesture events and their options." + match: ["*Gesture", "*GestureConfig", "GesturePhase", "PanAxis"] + - id: element-refs + title: Element refs + summary: "Refs to mounted controls." + match: ["ElementRef", "TypedElementRef"] + + - id: data + title: Data + summary: "Async values, resources, the query cache and data sources." + guide-pages: [data-system, async-resources] + groups: + - id: async-values + title: Async values + summary: "The value a resource hook returns while it loads, after it loads and after it fails." + match: ["AsyncValue", "LoadState"] + - id: query-cache + title: Query cache + summary: "The process-wide cache that resource hooks share." + match: ["QueryCache", "CacheEntry"] + - id: paging + title: Paging + summary: "Types for infinite and paged resources." + match: ["InfiniteResource*", "Page", "DataPage*", "CacheBlock", "BlockStatus"] + - id: descriptors + title: Sort and filter descriptors + summary: "Requests, sort, filter and field descriptors that data sources receive." + match: ["DataRequest", "SortDescriptor", "FilterDescriptor", "FieldDescriptor", "RowKey", "SortDirection", "FilterOperator"] + - id: column-attributes + title: Column attributes + summary: "Attributes that change how a property shows as a column." + match: ["Column*Attribute", "Not*Attribute", "PinPosition"] + + - id: navigation + title: Navigation + summary: "Navigation state, routes, lifecycle contexts and page transitions." + guide-pages: [navigation] + groups: + - id: transitions + title: Navigation transitions + summary: "Transitions that play when the navigation host changes pages." + match: ["*Transition", "SlideDirection"] + - id: lifecycle + title: Navigation lifecycle + summary: "Contexts passed to the navigation lifecycle callbacks." + match: ["Navigat*Context"] + - id: diagnostics + title: Navigation diagnostics + summary: "Diagnostic events raised by the navigation system." + match: ["*DiagnosticEvent", "NavigationDiagnostics"] + + - id: animation + title: Animation + summary: "Transitions, curves, keyframes, interaction states and scroll-linked animation." + guide-pages: [animation] + groups: + - id: transitions + title: Transitions + summary: "Enter and exit transitions for elements." + match: ["Microsoft.UI.Reactor.Animation.*Transition", "Edge"] + - id: curves + title: Curves and easing + summary: "Curves that shape the timing of an animation." + match: ["*Curve", "Easing"] + - id: keyframes + title: Keyframes + summary: "Types for keyframe animations." + match: ["Keyframe*"] + - id: interaction-states + title: Interaction states + summary: "Animations that follow pointer over, pressed and focus states." + match: ["InteractionState*"] + - id: scroll + title: Scroll-linked animation + summary: "Animations driven by the scroll position." + match: ["Scroll*"] + - id: implicit + title: Implicit and theme transitions + summary: "Transitions WinUI runs when a property or a child collection changes." + match: ["ImplicitTransitions", "ThemeTransitions", "LayoutAnimationConfig"] + + - id: accessibility + title: Accessibility + summary: "The accessibility scanner, its diagnostics and semantic panels." + guide-pages: [accessibility] + + - id: localization + title: Localization + summary: "Message keys, string resources, number and date formatting, and right-to-left helpers." + guide-pages: [localization] + + - id: controls + title: Controls + summary: "Item data records and support types for the property grid, masked input and virtual lists." + guide-pages: [controls, collections] + groups: + - id: icons + title: Icon data + summary: "Records that describe an icon." + match: ["*IconData"] + - id: menu-items + title: Menu and command bar items + summary: "Records that describe menu, menu bar, command bar and keyboard accelerator items." + match: ["AppBar*", "Menu*Data", "MenuFlyoutItemBase", "*MenuFlyoutItemData", "KeyboardAcceleratorData"] + - id: navigation-items + title: Navigation items + summary: "Records that describe items of navigation controls." + match: ["BreadcrumbBarItemData", "NavigationViewItemData", "PivotItemData", "SelectorBarItemData", "TabViewItemData"] + - id: collection-items + title: Collection items + summary: "Records and enums for tree, swipe and items view content." + match: ["TreeViewNodeData", "SwipeItemData", "ItemsViewLayoutKind", "TemplatedControlKind"] + - id: rich-text + title: Rich text + summary: "Inline records for rich text blocks." + match: ["RichText*"] + - id: property-grid-attributes + title: Property grid attributes + summary: "Attributes that change how the property grid shows a property." + match: ["Property*Attribute"] + - id: property-grid-templates + title: Property grid templates + summary: "Delegates and metadata the property grid uses to build its rows." + match: ["*Template", "ArrayTypeMetadata", "TypeMetadata", "EditorTier", "Editors", "CellRenderers", "ReflectionTypeMetadataProvider", "TypeRegistry"] + - id: masked-input + title: Masked input + summary: "The mask engine and formatters behind MaskedTextBox." + match: ["Mask*", "*Formatter*", "FormatResult"] + - id: virtual-list + title: Virtual list + summary: "Support types for the virtual list." + match: ["VirtualList*", "SearchManager", "SearchState"] + + - id: validation + title: Validation + summary: "Validators, validation contexts and error styling for forms." + guide-pages: [forms] + groups: + - id: attached + title: Attached validation state + summary: "Records that hold the validation state stored on an element." + match: ["*Attached"] + + - id: diagnostics + title: Diagnostics + summary: "Tracing, source maps, component snapshots and developer tools hosting." + guide-pages: [diagnostics, devtools] + groups: + - id: snapshots + title: Diagnostic snapshots + summary: "Snapshots of the component tree that the diagnostics API returns." + match: ["Microsoft.UI.Reactor.Core.Diagnostics.*"] + - id: devtools + title: Developer tools hosting + summary: "Types the developer tools use to start inside an app." + match: ["Microsoft.UI.Reactor.Hosting.Devtools.*"] + + - id: extensibility + title: Extensibility + summary: "The control protocol, control descriptors, the reconciler and element pooling." + intro: >- + Use these types to add your own controls to Reactor or to change how built-in + controls are created and updated. + guide-pages: [extending-reactor-controls, control-reconciler-protocol, element-pool] + groups: + - id: children-strategies + title: Children strategies + summary: "Records that tell the reconciler how a control holds its children." + match: ["ChildrenStrategy", "None", "Panel", "SingleContent", "NamedSlot*", "PreMountedItems", "ItemsHost*", "TabItemsHost", + "TemplatedItems*", "TreeChildren", "Imperative", "AttachedPropWriter"] + - id: lifecycle-contexts + title: Handler contexts + summary: "Contexts passed to an element handler when it mounts, updates or unmounts a control." + match: ["MountContext", "UpdateContext", "UnmountContext", "V1UnmountDisposition"] + - id: descriptor-delegates + title: Descriptor callbacks + summary: "Delegates and attributes used by control descriptors." + match: ["*Callback", "OneWayBridgedSetter", "NoClearValueAttribute"] + + - id: excluded + title: Excluded + +areas: + - id: layout + title: Layout + summary: "Panels, stacks, grids, scrolling and other containers." + elements: ["Border", "Canvas", "Flex", "Grid", "RelativePanel", "Stack", "Viewbox", "WrapGrid", "ScrollView", "ScrollViewer", + "ParallaxView", "AnnotatedScrollBar", "Expander", "SplitView"] + factories: ["VStack", "HStack", "FlexRow", "FlexColumn", "UniformGrid", "InterspersedGrid", "Card", "Thick"] + guide-pages: [layout, flex-layout] + - id: text + title: Text + summary: "Text blocks, rich text and the typography factories." + elements: ["TextBlock", "RichTextBlock", "RichText*"] + factories: ["Body*", "Caption", "Display", "Heading", "SubHeading", "Subtitle", "Title*", "Paragraph", "Run", "Hyperlink", "InlineUI"] + guide-pages: [text-and-media] + - id: buttons + title: Buttons + summary: "Buttons, toggle buttons, split buttons and hyperlink buttons." + elements: ["Button", "DropDownButton", "HyperlinkButton", "RepeatButton", "SplitButton", "ToggleButton", "ToggleSplitButton"] + guide-pages: [controls, commanding] + - id: input + title: Input + summary: "Text boxes, check boxes, combo boxes, sliders, pickers and other input controls." + elements: ["TextBox", "PasswordBox", "NumberBox", "AutoSuggestBox", "AutoSuggest", "RichEditBox", "MaskedTextBox", "CheckBox", + "RadioButton", "RadioButtons", "ComboBox", "Slider", "ToggleSwitch", "RatingControl", "ColorPicker", + "CalendarDatePicker", "CalendarView", "DatePicker", "TimePicker"] + guide-pages: [controls, forms] + - id: collections + title: Collections + summary: "Lists, grids, trees, flip views and virtualized collections." + elements: ["ListView", "GridView", "ListBox", "FlipView", "TreeView", "ItemsRepeater", "ItemsView", "Templated*", "ItemContainer", + "Lazy*", "VirtualList", "SemanticZoom", "RefreshContainer", "SwipeControl"] + factories: ["TreeNode"] + guide-pages: [collections] + - id: navigation + title: Navigation + summary: "Navigation views, tabs, pivots, breadcrumbs and the title bar." + elements: ["NavigationView", "NavigationHost", "BreadcrumbBar", "Pivot", "SelectorBar", "TabView", "TitleBar", "Frame", "PipsPager"] + factories: ["Breadcrumb", "NavItem", "NavItemHeader", "PivotItem", "SelectorBarItem", "Tab"] + guide-pages: [navigation] + - id: menus-and-commands + title: Menus and commands + summary: "Menus, menu bars, command bars and keyboard accelerators." + elements: ["CommandBar", "CommandBarFlyout", "MenuBar", "MenuFlyout", "MenuFlyoutContent", "CommandHost", "AppBar*"] + factories: ["Accelerator", "AppBar*", "Menu", "MenuItem*", "MenuSeparator", "MenuSubItem", "RadioMenuItem", "ToggleMenuItem", "DevtoolsMenu"] + guide-pages: [commanding] + - id: dialogs-and-flyouts + title: Dialogs and flyouts + summary: "Content dialogs, flyouts, popups and teaching tips." + elements: ["ContentDialog", "ContentFlyout", "Flyout", "Popup", "TeachingTip"] + guide-pages: [dialogs-and-flyouts] + - id: media + title: Media and icons + summary: "Images, icons, animated visuals, media playback and person pictures." + elements: ["Image", "Icon", "AnimatedIcon", "AnimatedVisualPlayer", "MediaPlayerElement", "PersonPicture"] + factories: ["BitmapIcon", "FontIcon", "ImageIcon", "PathIcon", "SymbolIcon"] + guide-pages: [text-and-media] + - id: shapes + title: Shapes + summary: "Rectangles, ellipses, lines, paths and brushes." + elements: ["Rectangle", "Ellipse", "Line", "Path"] + factories: ["Path2D", "AcrylicBrush"] + guide-pages: [styling] + - id: status-and-info + title: Status and info + summary: "Info bars, badges and progress indicators." + elements: ["InfoBar", "InfoBadge", "Progress", "ProgressRing"] + guide-pages: [status-and-info] + - id: forms + title: Forms + summary: "Form fields, validation rules, validation visualizers and the property grid." + elements: ["FormField", "ValidationRule", "ValidationVisualizer", "PropertyGrid"] + guide-pages: [forms] + - id: composition + title: Composition + summary: "Components, memoization, error boundaries, conditionals and other structural elements." + elements: ["Component", "Memo", "KeyedMemo", "ErrorBoundary", "Empty", "Group", "Func", "Modified", "LocaleProvider", "Semantic"] + factories: ["If", "When", "ForEach", "Expr", "RenderEachTime", "Empty", "Group"] + guide-pages: [components, advanced] + - id: interop + title: Interop + summary: "Hosted XAML content, web views and maps." + elements: ["XamlHost", "XamlPage", "WebView2", "MapControl"] + guide-pages: [xaml-developers] + +modifier-areas: + - id: layout-and-spacing + title: Layout and spacing + summary: "Size, margin, padding, alignment and the attached layout properties." + match: ["Margin*", "Padding*", "FlexPadding", "Width", "Height", "MinWidth", "MinHeight", "MaxWidth", "MaxHeight", "Size", + "HAlign", "VAlign", "HorizontalAlignment", "VerticalAlignment", "HorizontalContentAlignment", "VerticalContentAlignment", + "Center", "CenterAt", "Grid", "Canvas", "Flex", "RelativePanel", "WrapGrid*", "Visible", "IsVisible"] + guide-pages: [layout, flex-layout] + - id: appearance + title: Appearance + summary: "Background, foreground, borders, corners, opacity, transforms, styles and theme." + match: ["Background", "Foreground", "BorderBrush", "BorderThickness", "BorderInlineStart", "CornerRadius", "Opacity", "WithBorder", + "Backdrop", "RequestedTheme", "ApplyStyle", "Resources", "Rotation", "Scale", "Translation", "CenterPoint"] + guide-pages: [styling, theming-tokens] + - id: typography + title: Typography + summary: "Fonts, text alignment, wrapping, trimming and other text formatting." + match: ["Font*", "CharacterSpacing", "LineHeight", "LineStackingStrategy", "TextDecorations", "TextAlignment", + "HorizontalTextAlignment", "TextWrapping", "TextTrimming", "TextIndent", "TextLineBounds", "TextReadingOrder", + "OpticalMarginAlignment", "Bold", "SemiBold", "MaxLines", "IsTextScaleFactorEnabled", "IsColorFontEnabled", + "UnderlineStyle", "Selectable", "IsTextSelectionEnabled", "SelectionHighlightColor", "FlowDirection", "Language"] + guide-pages: [text-and-media, styling] + - id: accessibility + title: Accessibility + summary: "Automation names, landmarks, live regions and other accessibility properties." + match: ["Accessibility*", "AutomationId", "AutomationName", "DescribedBy", "FlowsFrom", "FlowsTo", "FullDescription", + "HeadingLevel", "HelpText", "HierarchyLevel", "ItemStatus", "LabeledBy", "Landmark", "LiveRegion", "PositionInSet", + "Semantics"] + guide-pages: [accessibility] + - id: focus-and-keyboard + title: Focus and keyboard + summary: "Tab order, access keys, directional focus and focus traps." + match: ["AccessKey*", "OnAccessKeyDisplayRequested", "FocusMeta", "FocusTrap", "GetFocus", "IsTabStop", "TabIndex", + "TabNavigation", "XYFocus*", "SoundMode"] + guide-pages: [input-and-gestures, accessibility] + - id: input-and-events + title: Input and events + summary: "Pointer, keyboard, gesture and drag and drop events, and whether an element takes input." + match: ["OnPointer*", "OnKey*", "OnPreviewKey*", "OnCharacterReceived", "OnTapped", "OnDoubleTap*", "OnRightTapped", + "OnHolding", "OnLongPress", "OnPan", "OnPinch", "OnRotate", "OnDrag*", "OnDrop", "OnGotFocus", "OnLostFocus", + "Drag", "DraggableWhen", "IsDragRegion", "IsEnabled", "Disabled", "IsHitTestVisible"] + guide-pages: [input-and-gestures] + - id: lifecycle + title: Lifecycle and identity + summary: "Keys, refs, mount and unmount callbacks, size changes and context values." + match: ["WithKey", "Ref", "OnMount*", "OnUnmount*", "OnSizeChanged", "Provide"] + guide-pages: [components, context] + - id: animation + title: Animation + summary: "Transitions, keyframes, layout animations, interaction states and scroll-linked animation." + match: ["Animate", "ConnectedAnimation", "InteractionStates", "Keyframes", "*LayoutAnimation", "Stagger", "ScrollLinked", + "Transition", "*Transition", "*Transitions"] + guide-pages: [animation] + - id: tooltips-and-flyouts + title: Tooltips and flyouts + summary: "Tooltips, flyouts and context flyouts attached to any element." + match: ["ToolTip*", "WithToolTip", "WithFlyout", "WithContextFlyout"] + guide-pages: [dialogs-and-flyouts] + - id: validation + title: Validation + summary: "Validators, required fields and error styling." + match: ["Validate*", "Required", "ShowErrors", "WithErrorStyling", "OnError", "OnWarning", "GetValidation", "Immediate"] + guide-pages: [forms] + - id: native-properties + title: Native properties + summary: "The Set modifier, which changes the real WinUI control directly." + match: ["Set"] + guide-pages: [modifier-system, xaml-developers] + - id: shared-controls + title: Shared controls + summary: "Modifiers that several kinds of controls share, such as headers, placeholders and selection events." + guide-pages: [controls] defaults: + # ── Hooks ────────────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Hooks.*" + category: hooks + guide-pages: [hooks] - match: "Microsoft.UI.Reactor.Core.RenderContext.Use*" category: hooks - guide-pages: [hooks, effects] - - match: "Microsoft.UI.Reactor.Hooks.*" + guide-pages: [hooks] + - match: "Microsoft.UI.Reactor.Core.Component*.Use*" category: hooks - guide-pages: [hooks, effects] - - match: "Microsoft.UI.Reactor.Factories.*" + guide-pages: [hooks] + + # ── Components ───────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Core.Component" + category: components + guide-pages: [components] + - match: "Microsoft.UI.Reactor.Core.Component`1" + category: components + guide-pages: [components] + - match: "Microsoft.UI.Reactor.Core.RenderContext" + category: components + guide-pages: [components, hooks] + - match: "Microsoft.UI.Reactor.Core.Context`1" + category: components + guide-pages: [context] + - match: "Microsoft.UI.Reactor.Core.ContextBase" + category: components + guide-pages: [context] + - match: "Microsoft.UI.Reactor.Core.ContextExtensions" + category: components + guide-pages: [context] + - match: "Microsoft.UI.Reactor.Core.AppContexts" + category: components + guide-pages: [context] + - match: "Microsoft.UI.Reactor.Core.Ref`1" + category: components + guide-pages: [hooks] + - match: "Microsoft.UI.Reactor.Core.Observable`1" + category: components + guide-pages: [reactivity-model] + - match: "Microsoft.UI.Reactor.Core.Callbacks`1" + category: components + - match: "Microsoft.UI.Reactor.Core.ElementFactory`1" + category: components + - match: "Microsoft.UI.Reactor.Core.IReactorKeyed" + category: components + guide-pages: [collections] + - match: "Microsoft.UI.Reactor.Core.SourceLocation" + category: components + guide-pages: [source-mapping] + - match: "Microsoft.UI.Reactor.Core.HookOrderException" + category: components + guide-pages: [rules-of-reactor] + - match: "Microsoft.UI.Reactor.Core.RenderError*" + category: components + guide-pages: [advanced] + - match: "Microsoft.UI.Reactor.Optional`1" + category: components + + # ── Elements ─────────────────────────────────────────────────────────── + # Element records are found by their base type; this rule only places + # the base record itself. + - match: "Microsoft.UI.Reactor.Core.Element" + category: elements + guide-pages: [reconciliation] + + # ── Factories and modifiers ──────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Factories" + category: factories + - match: "Microsoft.UI.Reactor.*Dsl" category: factories - guide-pages: [layout, forms, collections] - - match: "Microsoft.UI.Reactor.Charting.*" - category: charting - guide-pages: [charting] + - match: "Microsoft.UI.Reactor.ElementExtensions" + category: modifiers + - match: "Microsoft.UI.Reactor.CanvasExtensions" + category: modifiers + - match: "Microsoft.UI.Reactor.FlexExtensions" + category: modifiers + - match: "Microsoft.UI.Reactor.GridExtensions" + category: modifiers + - match: "Microsoft.UI.Reactor.RelativePanelExtensions" + category: modifiers + - match: "Microsoft.UI.Reactor.Core.ElementModifiers" + category: modifiers + guide-pages: [modifier-system] + - match: "Microsoft.UI.Reactor.Core.LayoutModifiers" + category: modifiers + guide-pages: [modifier-system] + - match: "Microsoft.UI.Reactor.Core.VisualModifiers" + category: modifiers + guide-pages: [modifier-system] + - match: "Microsoft.UI.Reactor.Core.AccessibilityModifiers" + category: modifiers + guide-pages: [modifier-system, accessibility] + - match: "Microsoft.UI.Reactor.Core.ElementExtras" + category: modifiers + guide-pages: [modifier-system] -overrides: - - cref: "M:Microsoft.UI.Reactor.Factories.DataGrid``1" + # ── Hosting and windows ──────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Hosting.*" + category: hosting + guide-pages: [xaml-developers] + - match: "Microsoft.UI.Reactor.Hosting.Persistence.*" + category: hosting + guide-pages: [persistence] + - match: "Microsoft.UI.Reactor.Reactor*" + category: hosting + guide-pages: [windows] + - match: "Microsoft.UI.Reactor.Window*" + category: hosting + guide-pages: [windows, windowing-advanced] + - match: "Microsoft.UI.Reactor.Taskbar*" + category: hosting + guide-pages: [desktop-integration] + - match: "Microsoft.UI.Reactor.JumpList*" + category: hosting + guide-pages: [desktop-integration] + - match: "Microsoft.UI.Reactor.ThumbnailToolbarButton" + category: hosting + guide-pages: [desktop-integration] + - match: "Microsoft.UI.Reactor.TrayIconSpec" + category: hosting + guide-pages: [desktop-integration] + - match: "Microsoft.UI.Reactor.Launch*" + category: hosting + guide-pages: [desktop-integration] + - match: "Microsoft.UI.Reactor.DisplayInfo" + category: hosting + guide-pages: [windowing-advanced] + - match: "Microsoft.UI.Reactor.EmbedRequest" + category: hosting + guide-pages: [windowing-advanced] + - match: "Microsoft.UI.Reactor.PresenterKind" + category: hosting + - match: "Microsoft.UI.Reactor.ShutdownPolicy" + category: hosting + - match: "Microsoft.UI.Reactor.AspectRatioBasis" + category: hosting + - match: "Microsoft.UI.Reactor.Core.*FilePickerOptions" + category: hosting + guide-pages: [desktop-integration] + - match: "Microsoft.UI.Reactor.Core.FolderPickerOptions" + category: hosting + guide-pages: [desktop-integration] + - match: "Microsoft.UI.Reactor.Core.FileTypeChoice" + category: hosting + guide-pages: [desktop-integration] + - match: "Microsoft.UI.Reactor.Core.*PersistedScope" + category: hosting + guide-pages: [persistence] + - match: "Microsoft.UI.Reactor.Core.IPersistedStateScope" + category: hosting + guide-pages: [persistence] + + # ── Theming ──────────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Core.Theme" + category: theming + guide-pages: [theming-tokens] + - match: "Microsoft.UI.Reactor.Core.ThemeRef" + category: theming + guide-pages: [theming-tokens] + - match: "Microsoft.UI.Reactor.Core.ColorScheme" + category: theming + - match: "Microsoft.UI.Reactor.Core.Backdrop*" + category: theming + guide-pages: [styling] + - match: "Microsoft.UI.Reactor.ThemeResource" + category: theming + guide-pages: [theming-tokens] + - match: "Microsoft.UI.Reactor.BrushHelper" + category: theming + guide-pages: [styling] + - match: "Microsoft.UI.Reactor.BackdropExtensions" + category: theming + guide-pages: [styling] + - match: "Microsoft.UI.Reactor.Elements.*" + category: theming + guide-pages: [styling] + + # ── Layout ───────────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Layout.*" + category: layout + guide-pages: [flex-layout] + - match: "Microsoft.UI.Reactor.GridSize*" + category: layout + guide-pages: [layout] + - match: "Microsoft.UI.Reactor.Core.*Attached" + category: layout + guide-pages: [layout] + - match: "Microsoft.UI.Reactor.Core.GridDefinition" + category: layout + guide-pages: [layout] + + # ── Input and commands ───────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Input.*" + category: input + guide-pages: [input-and-gestures] + - match: "Microsoft.UI.Reactor.Core.DragAttached" + category: input + guide-pages: [input-and-gestures] + - match: "Microsoft.UI.Reactor.Core.Command*" + category: input + guide-pages: [commanding] + - match: "Microsoft.UI.Reactor.Core.StandardCommand" + category: input + guide-pages: [commanding] + - match: "Microsoft.UI.Reactor.Core.FocusRevalidationService" + category: data + guide-pages: [async-resources] + + # ── Data ─────────────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Data.*" + category: data guide-pages: [data-system] - - cref: "T:Microsoft.UI.Reactor.ErrorBoundary" + - match: "Microsoft.UI.Reactor.Core.AsyncValue`1*" + category: data + guide-pages: [async-resources] + - match: "Microsoft.UI.Reactor.Core.LoadState*" + category: data + guide-pages: [async-resources] + - match: "Microsoft.UI.Reactor.Core.InfiniteResource*" + category: data + guide-pages: [async-resources] + - match: "Microsoft.UI.Reactor.Core.Page`2" + category: data + guide-pages: [async-resources] + - match: "Microsoft.UI.Reactor.Core.QueryCache" + category: data + guide-pages: [async-resources] + - match: "Microsoft.UI.Reactor.Core.CacheEntry`1" + category: data + guide-pages: [async-resources] + + # ── Navigation ───────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Navigation.*" + category: navigation + guide-pages: [navigation] + + # ── Animation ────────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Animation.*" + category: animation + guide-pages: [animation] + - match: "Microsoft.UI.Reactor.Core.Animation*" + category: animation + guide-pages: [animation] + - match: "Microsoft.UI.Reactor.Core.ImplicitTransitions" + category: animation + guide-pages: [animation] + - match: "Microsoft.UI.Reactor.Core.ThemeTransitions" + category: animation + guide-pages: [animation] + - match: "Microsoft.UI.Reactor.Core.LayoutAnimationConfig" + category: animation + guide-pages: [animation] + + # ── Accessibility ────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Accessibility.*" + category: accessibility + guide-pages: [accessibility] + - match: "Microsoft.UI.Reactor.Core.A11y*" + category: accessibility + guide-pages: [accessibility] + - match: "Microsoft.UI.Reactor.Core.AccessibilityScanner" + category: accessibility + guide-pages: [accessibility] + - match: "Microsoft.UI.Reactor.Core.SemanticDescription" + category: accessibility + guide-pages: [accessibility] + + # ── Localization ─────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Localization.*" + category: localization + guide-pages: [localization] + + # ── Controls ─────────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Controls.*" + category: controls + guide-pages: [controls] + - match: "Microsoft.UI.Reactor.Core.*Data" + category: controls + guide-pages: [controls] + - match: "Microsoft.UI.Reactor.Core.*ItemBase" + category: controls + guide-pages: [commanding] + - match: "Microsoft.UI.Reactor.Core.RichText*" + category: controls + guide-pages: [text-and-media] + - match: "Microsoft.UI.Reactor.Core.ItemsViewLayoutKind" + category: controls + guide-pages: [collections] + - match: "Microsoft.UI.Reactor.Core.TemplatedControlKind" + category: controls + guide-pages: [collections] + + # ── Validation ───────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Controls.Validation.*" + category: validation + guide-pages: [forms] + + # ── Diagnostics ──────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Diagnostics.*" + category: diagnostics + guide-pages: [diagnostics] + - match: "Microsoft.UI.Reactor.Core.Diagnostics.*" + category: diagnostics + guide-pages: [diagnostics] + - match: "Microsoft.UI.Reactor.Hosting.Devtools.*" + category: diagnostics + guide-pages: [devtools] + + # ── Extensibility ────────────────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Core.V1Protocol.*" + category: extensibility + guide-pages: [extending-reactor-controls, control-reconciler-protocol] + - match: "Microsoft.UI.Reactor.Core.Reconciler" + category: extensibility + guide-pages: [reconciliation] + - match: "Microsoft.UI.Reactor.Core.ElementPool" + category: extensibility + guide-pages: [element-pool] + - match: "Microsoft.UI.Reactor.Core.PoolPolicy`1" + category: extensibility + guide-pages: [element-pool] + - match: "Microsoft.UI.Reactor.Core.ReactorBinding" + category: extensibility + guide-pages: [extending-reactor-controls] + - match: "Microsoft.UI.Reactor.Core.ReactorFeatureFlags" + category: extensibility + - match: "Microsoft.UI.Reactor.Core.PathDataParser" + category: extensibility + + # ── Not part of the reference ────────────────────────────────────────── + - match: "Microsoft.UI.Reactor.Core.Internal.*" + category: excluded + - match: "Microsoft.UI.Reactor.Reactor_XamlTypeInfo.*" + category: excluded + +overrides: + # Hook pages get "Learn more" links from the member rules below. An + # override replaces the default guide pages, so each one lists `hooks`. + - match: "*.UseState*" + guide-pages: [hooks] + - match: "*.UseReducer*" + guide-pages: [hooks] + - match: "*.UseEffect*" + guide-pages: [effects, effects-scheduling, hooks] + - match: "*.UseMemo*" + guide-pages: [hooks, performance] + - match: "*.UseCallback*" + guide-pages: [hooks, performance] + - match: "*.UseContext*" + guide-pages: [context, hooks] + - match: "*.UseResource*" + guide-pages: [async-resources, effects, hooks] + - match: "*.UseInfiniteResource*" + guide-pages: [async-resources, hooks] + - match: "*.UseMutation*" + guide-pages: [async-resources, hooks] + - match: "*.UseDataSource*" + guide-pages: [data-system, hooks] + - match: "*.UseCommand*" + guide-pages: [commanding, hooks] + - match: "*.UsePersisted*" + guide-pages: [persistence, hooks] + - match: "*.UseObservable*" + guide-pages: [reactivity-model, hooks] + - match: "*.UseExternalStore*" + guide-pages: [reactivity-model, hooks] + - match: "*.UseNavigation*" + guide-pages: [navigation, hooks] + - match: "*.UseSystemBackButton*" + guide-pages: [navigation, hooks] + - match: "*.UseFocus*" + guide-pages: [input-and-gestures, accessibility, hooks] + - match: "*.UseElementFocus*" + guide-pages: [input-and-gestures, hooks] + - match: "*.UseElementRef*" + guide-pages: [input-and-gestures, hooks] + - match: "*.UseAnnounce*" + guide-pages: [accessibility, hooks] + - match: "*.UseHighContrast*" + guide-pages: [accessibility, theming-tokens, hooks] + - match: "*.UseReducedMotion*" + guide-pages: [accessibility, animation, hooks] + - match: "*.UseColorScheme*" + guide-pages: [theming-tokens, hooks] + - match: "*.UseIsDarkTheme*" + guide-pages: [theming-tokens, hooks] + - match: "*.UseIntl*" + guide-pages: [localization, hooks] + - match: "*.UseWindow*" + guide-pages: [windows, windowing-advanced, hooks] + - match: "*.UseOpenWindow*" + guide-pages: [windows, hooks] + - match: "*.UseClosingGuard*" + guide-pages: [windows, hooks] + - match: "*.UseIsActive*" + guide-pages: [windows, hooks] + - match: "*.UseIsCovered*" + guide-pages: [windowing-advanced, hooks] + - match: "*.UseDisplays*" + guide-pages: [windowing-advanced, hooks] + - match: "*.UseDpi*" + guide-pages: [windowing-advanced, hooks] + - match: "*.UseBreakpoint*" + guide-pages: [layout, hooks] + - match: "*.UseTrayIcon*" + guide-pages: [desktop-integration, hooks] + - match: "*.UseDevtools*" + guide-pages: [devtools, hooks] + - match: "*.Use*ValidationContext*" + guide-pages: [forms, hooks] + - match: "*.UseCollection*" + guide-pages: [collections, hooks] + + - cref: "T:Microsoft.UI.Reactor.Core.ErrorBoundaryElement" guide-pages: [advanced] - - match: "Microsoft.UI.Reactor.Factories.*Chart*" - guide-pages: [charting] diff --git a/docs/guide/reference/accessibility/A11yContext.md b/docs/guide/reference/accessibility/A11yContext.md new file mode 100644 index 0000000000..c766e8c124 --- /dev/null +++ b/docs/guide/reference/accessibility/A11yContext.md @@ -0,0 +1,93 @@ +# A11yContext + +Rich contextual information harvested from the element tree during the scan. An AI agent uses this to generate semantically correct accessible names without needing to re-read the source code. + +```csharp +public record A11yContext +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Accessibility](../../accessibility.md) + +## Constructors + +### `A11yContext` + +```csharp +public A11yContext() +``` + +## Properties + +### `ChildContent` + +String description of the child content (e.g., "SymbolIcon(Symbol.Delete)"). + +```csharp +public string? ChildContent // get, init +``` + +### `ChildText` + +Text content of the first TextBlockElement child, if any. + +```csharp +public string? ChildText // get, init +``` + +### `ChildTypes` + +Type names of immediate children. + +```csharp +public string[]? ChildTypes // get, init +``` + +### `Header` + +Header property value (for TextBoxElement etc.). + +```csharp +public string? Header // get, init +``` + +### `NearestHeading` + +Text and level of the nearest heading above this element. + +```csharp +public string? NearestHeading // get, init +``` + +### `NearestLandmark` + +Nearest landmark type name (e.g., "Navigation", "Main"). + +```csharp +public string? NearestLandmark // get, init +``` + +### `ParentAutomationName` + +AutomationName of the nearest ancestor that has one. + +```csharp +public string? ParentAutomationName // get, init +``` + +### `PlaceholderText` + +Placeholder text (for TextBoxElement etc.). + +```csharp +public string? PlaceholderText // get, init +``` + +### `SiblingTexts` + +Text labels of sibling elements at the same level. + +```csharp +public string[]? SiblingTexts // get, init +``` diff --git a/docs/guide/reference/accessibility/A11yDiagnostic.md b/docs/guide/reference/accessibility/A11yDiagnostic.md new file mode 100644 index 0000000000..eb9cbebaf7 --- /dev/null +++ b/docs/guide/reference/accessibility/A11yDiagnostic.md @@ -0,0 +1,95 @@ +# A11yDiagnostic + +A single accessibility diagnostic finding from the scanner. Each finding maps to a specific WCAG 2.1 criterion and includes rich contextual information so an AI agent can generate intelligent fixes from the JSON export alone. + +```csharp +public record A11yDiagnostic +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Accessibility](../../accessibility.md) + +## Constructors + +### `A11yDiagnostic` + +```csharp +public A11yDiagnostic() +``` + +> **Obsolete.** Constructors of types with required members are not supported in this version of your compiler. + +## Properties + +### `AutomationId` + +AutomationId if set on the element, null otherwise. + +```csharp +public string? AutomationId // get, init +``` + +### `ComponentType` + +The component type name wrapping this element, if known. + +```csharp +public string? ComponentType // get, init +``` + +### `Context` + +Contextual clues from the surrounding element tree. + +```csharp +public A11yContext Context // get, init +``` + +### `ElementType` + +The C# record type name of the element (e.g., "ButtonElement"). + +```csharp +public string ElementType // get, init +``` + +### `Fix` + +What modifier to add and a suggested value. + +```csharp +public A11yFixSuggestion Fix // get, init +``` + +### `Id` + +Diagnostic ID (e.g., "A11Y_001"). + +```csharp +public string Id // get, init +``` + +### `Message` + +Human-readable description of the issue. + +```csharp +public string Message // get, init +``` + +### `Severity` + +"warning" or "info". + +```csharp +public string Severity // get, init +``` + +### `WcagCriterion` + +WCAG 2.1 success criterion (e.g., "1.1.1"). + +```csharp +public string WcagCriterion // get, init +``` diff --git a/docs/guide/reference/accessibility/A11yFixSuggestion.md b/docs/guide/reference/accessibility/A11yFixSuggestion.md new file mode 100644 index 0000000000..db345b20ad --- /dev/null +++ b/docs/guide/reference/accessibility/A11yFixSuggestion.md @@ -0,0 +1,47 @@ +# A11yFixSuggestion + +Tells an AI agent exactly which modifier to add and what value to use. + +```csharp +public record A11yFixSuggestion +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Accessibility](../../accessibility.md) + +## Constructors + +### `A11yFixSuggestion` + +```csharp +public A11yFixSuggestion() +``` + +> **Obsolete.** Constructors of types with required members are not supported in this version of your compiler. + +## Properties + +### `CodeSnippet` + +Example code snippet (e.g., ".AutomationName(\\"...\\")"). + +```csharp +public string? CodeSnippet // get, init +``` + +### `Modifier` + +The Reactor modifier method name (e.g., "AutomationName"). + +```csharp +public string Modifier // get, init +``` + +### `SuggestedValue` + +A suggested value, or null if the agent must infer from context. + +```csharp +public string? SuggestedValue // get, init +``` diff --git a/docs/guide/reference/accessibility/AccessibilityScanner.md b/docs/guide/reference/accessibility/AccessibilityScanner.md new file mode 100644 index 0000000000..4099d28acb --- /dev/null +++ b/docs/guide/reference/accessibility/AccessibilityScanner.md @@ -0,0 +1,44 @@ +# AccessibilityScanner + +Post-reconciliation accessibility scanner that walks the Reactor virtual element tree and produces structured diagnostics. Intended for DEBUG builds only — call via `ReactorHostControl.EnableAccessibilityDiagnostics`. + +The scanner produces AI-agent-friendly JSON output: each diagnostic includes rich contextual clues (sibling texts, parent names, child content) so an AI agent can generate semantically correct fixes in a single pass without re-reading source code. + +```csharp +public static class AccessibilityScanner +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Accessibility](../../accessibility.md) + +## Methods + +### `ExportJson` + +Exports diagnostics as structured JSON to the specified file path. + +```csharp +public static void ExportJson(List diagnostics, string filePath) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `diagnostics` | `List` | | +| `filePath` | `string` | | + +### `Scan` + +Scans the virtual element tree for accessibility issues. Returns a list of diagnostics, each with rich context for AI-agent consumption. + +```csharp +public static List Scan(Element root) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `root` | [`Element`](../elements/Element.md) | | diff --git a/docs/guide/reference/accessibility/SemanticDescription.md b/docs/guide/reference/accessibility/SemanticDescription.md new file mode 100644 index 0000000000..7fcacd81b4 --- /dev/null +++ b/docs/guide/reference/accessibility/SemanticDescription.md @@ -0,0 +1,70 @@ +# SemanticDescription + +Describes the semantic role, value, and range of a composite component for assistive technology. Used with the .Semantics() modifier. + +```csharp +public record SemanticDescription(string? Role = null, string? Value = null, double? RangeMin = null, double? RangeMax = null, double? RangeValue = null, bool IsReadOnly = true) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Accessibility](../../accessibility.md) + +## Constructors + +### `SemanticDescription` + +Describes the semantic role, value, and range of a composite component for assistive technology. Used with the .Semantics() modifier. + +```csharp +public SemanticDescription(string? Role = null, string? Value = null, double? RangeMin = null, double? RangeMax = null, double? RangeValue = null, bool IsReadOnly = true) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Role` | `string?` | `null` | | +| `Value` | `string?` | `null` | | +| `RangeMin` | `double?` | `null` | | +| `RangeMax` | `double?` | `null` | | +| `RangeValue` | `double?` | `null` | | +| `IsReadOnly` | `bool` | `true` | | + +## Properties + +### `IsReadOnly` + +```csharp +public bool IsReadOnly // get, init +``` + +### `RangeMax` + +```csharp +public double? RangeMax // get, init +``` + +### `RangeMin` + +```csharp +public double? RangeMin // get, init +``` + +### `RangeValue` + +```csharp +public double? RangeValue // get, init +``` + +### `Role` + +```csharp +public string? Role // get, init +``` + +### `Value` + +```csharp +public string? Value // get, init +``` diff --git a/docs/guide/reference/accessibility/SemanticPanel.md b/docs/guide/reference/accessibility/SemanticPanel.md new file mode 100644 index 0000000000..8e76e58ae1 --- /dev/null +++ b/docs/guide/reference/accessibility/SemanticPanel.md @@ -0,0 +1,99 @@ +# SemanticPanel + +A lightweight WinUI Panel that provides custom automation semantics for composite Reactor components. Wraps a single child and overrides OnCreateAutomationPeer() to expose a custom role, value, and range to screen readers. + +This solves the fundamental limitation where Reactor components (C# records) cannot override OnCreateAutomationPeer() on WinUI Controls. + +Usage from Reactor DSL: StarRating(value: 3, max: 5) .Semantics(role: "slider", value: "3 of 5 stars", rangeValue: 3, rangeMin: 0, rangeMax: 5) + +```csharp +public sealed class SemanticPanel : Panel +``` + +Namespace: `Microsoft.UI.Reactor.Accessibility`. Inherits from [`Panel`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.panel). + +**Learn more:** [Accessibility](../../accessibility.md) + +## Constructors + +### `SemanticPanel` + +```csharp +public SemanticPanel() +``` + +## Properties + +### `IsReadOnly` + +```csharp +public bool IsReadOnly // get, set +``` + +### `RangeMaximum` + +```csharp +public double RangeMaximum // get, set +``` + +### `RangeMinimum` + +```csharp +public double RangeMinimum // get, set +``` + +### `RangeValue` + +```csharp +public double RangeValue // get, set +``` + +### `SemanticRole` + +```csharp +public string? SemanticRole // get, set +``` + +### `SemanticValue` + +```csharp +public string? SemanticValue // get, set +``` + +## Fields + +### `IsReadOnlyProperty` + +```csharp +public static readonly DependencyProperty IsReadOnlyProperty +``` + +### `RangeMaximumProperty` + +```csharp +public static readonly DependencyProperty RangeMaximumProperty +``` + +### `RangeMinimumProperty` + +```csharp +public static readonly DependencyProperty RangeMinimumProperty +``` + +### `RangeValueProperty` + +```csharp +public static readonly DependencyProperty RangeValueProperty +``` + +### `SemanticRoleProperty` + +```csharp +public static readonly DependencyProperty SemanticRoleProperty +``` + +### `SemanticValueProperty` + +```csharp +public static readonly DependencyProperty SemanticValueProperty +``` diff --git a/docs/guide/reference/accessibility/SemanticPanelAutomationPeer.md b/docs/guide/reference/accessibility/SemanticPanelAutomationPeer.md new file mode 100644 index 0000000000..6f93531cc9 --- /dev/null +++ b/docs/guide/reference/accessibility/SemanticPanelAutomationPeer.md @@ -0,0 +1,77 @@ +# SemanticPanelAutomationPeer + +Custom AutomationPeer for SemanticPanel. Implements IRangeValueProvider and IValueProvider so screen readers can read the composite component's semantic role, value, and range. Analogous to SwiftUI's .accessibilityRepresentation \{\} and Compose's Modifier.semantics \{ role = Role.Slider \}. + +```csharp +public sealed class SemanticPanelAutomationPeer : FrameworkElementAutomationPeer, IRangeValueProvider, IValueProvider +``` + +Namespace: `Microsoft.UI.Reactor.Accessibility`. Inherits from [`FrameworkElementAutomationPeer`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.automation.peers.frameworkelementautomationpeer). + +**Learn more:** [Accessibility](../../accessibility.md) + +## Constructors + +### `SemanticPanelAutomationPeer` + +```csharp +public SemanticPanelAutomationPeer(SemanticPanel owner) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `owner` | [`SemanticPanel`](SemanticPanel.md) | | + +## Properties + +### `IsReadOnly` + +```csharp +public bool IsReadOnly // get +``` + +### `LargeChange` + +```csharp +public double LargeChange // get +``` + +### `Maximum` + +```csharp +public double Maximum // get +``` + +### `Minimum` + +```csharp +public double Minimum // get +``` + +### `SmallChange` + +```csharp +public double SmallChange // get +``` + +### `Value` + +```csharp +public double Value // get +``` + +## Methods + +### `SetValue` + +```csharp +public void SetValue(double value) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `value` | `double` | | diff --git a/docs/guide/reference/accessibility/index.md b/docs/guide/reference/accessibility/index.md new file mode 100644 index 0000000000..a1493dd28b --- /dev/null +++ b/docs/guide/reference/accessibility/index.md @@ -0,0 +1,17 @@ +# Accessibility + +The accessibility scanner, its diagnostics and semantic panels. + +**Learn more:** [Accessibility](../../accessibility.md) + +## Types + +| Type | Description | +| --- | --- | +| [`A11yContext`](A11yContext.md) | Rich contextual information harvested from the element tree during the scan. | +| [`A11yDiagnostic`](A11yDiagnostic.md) | A single accessibility diagnostic finding from the scanner. | +| [`A11yFixSuggestion`](A11yFixSuggestion.md) | Tells an AI agent exactly which modifier to add and what value to use. | +| [`AccessibilityScanner`](AccessibilityScanner.md) | Post-reconciliation accessibility scanner that walks the Reactor virtual element tree and produces structured diagnostics. | +| [`SemanticDescription`](SemanticDescription.md) | Describes the semantic role, value, and range of a composite component for assistive technology. | +| [`SemanticPanel`](SemanticPanel.md) | A lightweight WinUI Panel that provides custom automation semantics for composite Reactor components. | +| [`SemanticPanelAutomationPeer`](SemanticPanelAutomationPeer.md) | Custom AutomationPeer for SemanticPanel. | diff --git a/docs/guide/reference/animation/AnimationConfig.md b/docs/guide/reference/animation/AnimationConfig.md new file mode 100644 index 0000000000..8d1426bcd9 --- /dev/null +++ b/docs/guide/reference/animation/AnimationConfig.md @@ -0,0 +1,42 @@ +# AnimationConfig + +Configuration for the .Animate() modifier — declaration-site implicit animation on compositor Visual properties. Stored on the Element base record. + +```csharp +public record AnimationConfig(Curve Curve, AnimateProperty Properties = AnimateProperty.All) +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +**Learn more:** [Animation](../../animation.md) + +## Constructors + +### `AnimationConfig` + +Configuration for the .Animate() modifier — declaration-site implicit animation on compositor Visual properties. Stored on the Element base record. + +```csharp +public AnimationConfig(Curve Curve, AnimateProperty Properties = AnimateProperty.All) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Curve` | [`Curve`](curves.md#curve) | | | +| `Properties` | [`AnimateProperty`](enums.md#animateproperty) | `AnimateProperty.All` | | + +## Properties + +### `Curve` + +```csharp +public Curve Curve // get, init +``` + +### `Properties` + +```csharp +public AnimateProperty Properties // get, init +``` diff --git a/docs/guide/reference/animation/AnimationScope.md b/docs/guide/reference/animation/AnimationScope.md new file mode 100644 index 0000000000..45ffd89088 --- /dev/null +++ b/docs/guide/reference/animation/AnimationScope.md @@ -0,0 +1,61 @@ +# AnimationScope + +Provides ambient animation context via \[ThreadStatic\] fields. When a curve is active, property changes in the reconciler's ApplyModifiers route through compositor animations instead of direct property assignment. + +```csharp +public static class AnimationScope +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +**Learn more:** [Animation](../../animation.md) + +## Properties + +### `Current` + +Gets the current ambient animation curve, or null if none. + +```csharp +public static Curve? Current // get +``` + +### `HasScope` + +Returns true if inside a WithAnimation scope (even if curve is null for explicit suppression). + +```csharp +public static bool HasScope // get +``` + +## Methods + +### `WithAnimation` + +Runs the action with the given curve as the ambient animation. Property changes in the reconciler will animate using this curve. Nesting is supported: inner scopes override outer ones, restoring correctly in finally. Pass null to explicitly suppress animation (e.g., inside an outer animated scope). + +```csharp +public static void WithAnimation(Curve? curve, Action action) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `curve` | [`Curve?`](curves.md#curve) | | +| `action` | `Action` | | + +### `WithAnimationAsync` + +Async variant: runs the action with ambient animation, then returns a Task that completes when all compositor animations started during the scope finish. Uses CompositionScopedBatch for completion tracking. + +```csharp +public static Task WithAnimationAsync(Curve? curve, Action action) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `curve` | [`Curve?`](curves.md#curve) | | +| `action` | `Action` | | diff --git a/docs/guide/reference/animation/Animations.md b/docs/guide/reference/animation/Animations.md new file mode 100644 index 0000000000..e694d5f5ba --- /dev/null +++ b/docs/guide/reference/animation/Animations.md @@ -0,0 +1,59 @@ +# Animations + +Transactional animation entry points — the SwiftUI `withAnimation { … }` analog. See spec 042 §6. + +```csharp +public static class Animations +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Animation](../../animation.md) + +## Remarks + +`Animate(...)` pushes an `AmbientAnimation` onto an [`AsyncLocal`](https://learn.microsoft.com/dotnet/api/system.threading.asynclocal-1) stack for the duration of the supplied action. State setters from `UseState` / `UseReducer` invoked inside the block snapshot the ambient synchronously so the resulting render observes the same intent even when the rerender hops a dispatcher. The reconciler consumes the snapshot when applying `KeyedListDiff` ops and `ChildReconciler` mount / move / unmount, configuring per-container animations to match. + +`Animate` does **not** animate arbitrary property changes (color, size) on surviving leaves — that remains the job of per-element modifiers such as `OpacityTransition`. Scoping the transaction to keyed structural changes keeps the SwiftUI "withAnimation only animates layout-shape ops" contract intact. (spec 042 §6, scope discipline) + +Named `Animations` (plural) instead of `Animation` to avoid collision with the existing `Microsoft.UI.Reactor.Animation` sub-namespace, which houses per-element animation modifiers. + +## Methods + +### `Animate` + +#### `Animate(AnimationKind, Action)` + +Wrap a state mutation in an ambient animation transaction. + +```csharp +public static void Animate(AnimationKind kind, Action action) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `kind` | [`AnimationKind`](enums.md#animationkind) | The animation kind that should apply to any container insert / move / remove ops produced by state setters invoked from `action`. Passing [`AnimationKind.None`](enums.md#values_1) is meaningful: it explicitly suppresses any \*outer\* `Animate` for the scope of the inner block (nested calls stack like `using`). | +| `action` | `Action` | State mutation. Typically calls `setItems(...)` from a hook. | + +**Example** + +```csharp +Animate(AnimationKind.Spring, () => setItems([..items, x])); +``` + +#### `Animate(AnimationKind, Func)` + +Wrap a value-producing state mutation in an ambient animation transaction. Returns the value produced by `func`. + +```csharp +public static T Animate(AnimationKind kind, Func func) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `kind` | [`AnimationKind`](enums.md#animationkind) | | +| `func` | `Func` | | diff --git a/docs/guide/reference/animation/CompositorProvider.md b/docs/guide/reference/animation/CompositorProvider.md new file mode 100644 index 0000000000..8c7ca9b669 --- /dev/null +++ b/docs/guide/reference/animation/CompositorProvider.md @@ -0,0 +1,33 @@ +# CompositorProvider + +Static accessor for the current Compositor instance. + +```csharp +public static class CompositorProvider +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +**Learn more:** [Animation](../../animation.md) + +## Properties + +### `Current` + +```csharp +public static Compositor? Current // get, set +``` + +## Methods + +### `EnsureCompositor` + +```csharp +public static Compositor EnsureCompositor(UIElement element) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `element` | `UIElement` | | diff --git a/docs/guide/reference/animation/StaggerConfig.md b/docs/guide/reference/animation/StaggerConfig.md new file mode 100644 index 0000000000..4e8672f717 --- /dev/null +++ b/docs/guide/reference/animation/StaggerConfig.md @@ -0,0 +1,42 @@ +# StaggerConfig + +Stagger configuration for container children animations. + +```csharp +public record StaggerConfig(TimeSpan Delay, Curve? Curve = null) +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +**Learn more:** [Animation](../../animation.md) + +## Constructors + +### `StaggerConfig` + +Stagger configuration for container children animations. + +```csharp +public StaggerConfig(TimeSpan Delay, Curve? Curve = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Delay` | `TimeSpan` | | | +| `Curve` | [`Curve?`](curves.md#curve) | `null` | | + +## Properties + +### `Curve` + +```csharp +public Curve? Curve // get, init +``` + +### `Delay` + +```csharp +public TimeSpan Delay // get, init +``` diff --git a/docs/guide/reference/animation/curves.md b/docs/guide/reference/animation/curves.md new file mode 100644 index 0000000000..e160829e04 --- /dev/null +++ b/docs/guide/reference/animation/curves.md @@ -0,0 +1,289 @@ +# Curves and easing + +Curves that shape the timing of an animation. + +**Learn more:** [Animation](../../animation.md) + +## `Curve` + +Describes the timing/physics of an animation. Immutable, shareable, zero-allocation. Maps to either a CompositionEasingFunction or a SpringAnimation at the compositor layer. + +```csharp +public abstract record Curve +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `Curve` + +```csharp +protected Curve() +``` + +### Methods + +#### `Ease` + +Cubic-bezier eased animation over a fixed duration. + +```csharp +public static Curve Ease(int durationMs, Easing easing = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `durationMs` | `int` | | | +| `easing` | [`Easing`](#easing_1) | `default` | | + +#### `Linear` + +Constant-speed animation over a fixed duration. + +```csharp +public static Curve Linear(int durationMs) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `durationMs` | `int` | | + +#### `Spring` + +Spring natural motion. DampingRatio 0=undamped, 1=critically damped. + +```csharp +public static Curve Spring(float dampingRatio = 0.800000011920929f, float period = 0.05000000074505806f) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `dampingRatio` | `float` | `0.800000011920929f` | | +| `period` | `float` | `0.05000000074505806f` | | + +## `EaseCurve` + +```csharp +public sealed record EaseCurve(TimeSpan Duration, Easing Easing) : Curve +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. Inherits from [`Curve`](#curve). + +### Constructors + +#### `EaseCurve` + +```csharp +public EaseCurve(TimeSpan Duration, Easing Easing) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Duration` | `TimeSpan` | | +| `Easing` | [`Easing`](#easing_1) | | + +### Properties + +#### `Duration` + +```csharp +public TimeSpan Duration // get, init +``` + +#### `Easing` + +```csharp +public Easing Easing // get, init +``` + +## `Easing` + +Cubic bezier easing definition. Presets match WinUI/Fluent Design motion guidelines. + +```csharp +public readonly record struct Easing(float X1, float Y1, float X2, float Y2) +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `Easing` + +Cubic bezier easing definition. Presets match WinUI/Fluent Design motion guidelines. + +```csharp +public Easing(float X1, float Y1, float X2, float Y2) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `X1` | `float` | | +| `Y1` | `float` | | +| `X2` | `float` | | +| `Y2` | `float` | | + +### Properties + +#### `X1` + +```csharp +public float X1 // get, init +``` + +#### `X2` + +```csharp +public float X2 // get, init +``` + +#### `Y1` + +```csharp +public float Y1 // get, init +``` + +#### `Y2` + +```csharp +public float Y2 // get, init +``` + +### Methods + +#### `CubicBezier` + +```csharp +public static Easing CubicBezier(float x1, float y1, float x2, float y2) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `x1` | `float` | | +| `y1` | `float` | | +| `x2` | `float` | | +| `y2` | `float` | | + +### Fields + +#### `Accelerate` + +```csharp +public static readonly Easing Accelerate +``` + +#### `Decelerate` + +```csharp +public static readonly Easing Decelerate +``` + +#### `EaseIn` + +```csharp +public static readonly Easing EaseIn +``` + +#### `EaseInOut` + +```csharp +public static readonly Easing EaseInOut +``` + +#### `EaseOut` + +```csharp +public static readonly Easing EaseOut +``` + +#### `Linear` + +```csharp +public static readonly Easing Linear +``` + +#### `Standard` + +```csharp +public static readonly Easing Standard +``` + +## `LinearCurve` + +```csharp +public sealed record LinearCurve(TimeSpan Duration) : Curve +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. Inherits from [`Curve`](#curve). + +### Constructors + +#### `LinearCurve` + +```csharp +public LinearCurve(TimeSpan Duration) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Duration` | `TimeSpan` | | + +### Properties + +#### `Duration` + +```csharp +public TimeSpan Duration // get, init +``` + +## `SpringCurve` + +```csharp +public sealed record SpringCurve(float DampingRatio, float Period) : Curve +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. Inherits from [`Curve`](#curve). + +### Constructors + +#### `SpringCurve` + +```csharp +public SpringCurve(float DampingRatio, float Period) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `DampingRatio` | `float` | | +| `Period` | `float` | | + +### Properties + +#### `DampingRatio` + +```csharp +public float DampingRatio // get, init +``` + +#### `Period` + +```csharp +public float Period // get, init +``` diff --git a/docs/guide/reference/animation/enums.md b/docs/guide/reference/animation/enums.md new file mode 100644 index 0000000000..a289e621ec --- /dev/null +++ b/docs/guide/reference/animation/enums.md @@ -0,0 +1,47 @@ +# Enums + +The enumerations in this category. + +**Learn more:** [Animation](../../animation.md) + +## `AnimateProperty` + +Flags enum specifying which compositor properties should have implicit animations applied via the .Animate() modifier. + +```csharp +public enum AnimateProperty +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `Opacity` | `1` | | +| `Offset` | `2` | | +| `Scale` | `4` | | +| `Rotation` | `8` | | +| `CenterPoint` | `16` | | +| `All` | `31` | | + +## `AnimationKind` + +Animation kinds that an ambient `Animations.Animate(...)` transaction can carry through a state-setter into the resulting diff. See spec 042 §6. + +```csharp +public enum AnimationKind +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `None` | `0` | No animation; container changes apply instantly. | +| `Default` | `1` | Framework default — currently matches [`AnimationKind.EaseOut`](#values_1). | +| `Spring` | `2` | Critically-damped spring; expressive on insert/remove. | +| `EaseIn` | `3` | Standard quadratic ease-in. | +| `EaseOut` | `4` | Standard quadratic ease-out (matches WinUI `RepositionThemeTransition`). | +| `EaseInOut` | `5` | Standard ease-in-out. | diff --git a/docs/guide/reference/animation/implicit.md b/docs/guide/reference/animation/implicit.md new file mode 100644 index 0000000000..dc0830fc6a --- /dev/null +++ b/docs/guide/reference/animation/implicit.md @@ -0,0 +1,157 @@ +# Implicit and theme transitions + +Transitions WinUI runs when a property or a child collection changes. + +**Learn more:** [Animation](../../animation.md) + +## `ImplicitTransitions` + +Declarative implicit transition configuration for a UIElement. Each property maps to a WinUI implicit transition property on UIElement/Panel. Null means "don't set this transition". + +```csharp +public record ImplicitTransitions +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `ImplicitTransitions` + +```csharp +public ImplicitTransitions() +``` + +### Properties + +#### `Background` + +```csharp +public BrushTransition? Background // get, init +``` + +#### `Opacity` + +```csharp +public ScalarTransition? Opacity // get, init +``` + +#### `Rotation` + +```csharp +public ScalarTransition? Rotation // get, init +``` + +#### `Scale` + +```csharp +public Vector3Transition? Scale // get, init +``` + +#### `Translation` + +```csharp +public Vector3Transition? Translation // get, init +``` + +## `LayoutAnimationConfig` + +Configuration for Composition-layer layout animations. When applied to an element, the reconciler sets up implicit animations on the element's Visual so that layout-driven Offset (position) and optionally Size changes animate smoothly. Runs entirely on the Composition thread — zero managed-code involvement during animation. + +Limitations: - Hit-testing uses the final layout position, not the animated visual position. - Elements must have stable keys (.WithKey()) for the reconciler to match them across reorders. - Size animation is cosmetic: content does not re-layout during the Size animation. - Only handles position changes for persistent elements; use theme transitions for enter/exit. + +```csharp +public record LayoutAnimationConfig +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `LayoutAnimationConfig` + +```csharp +public LayoutAnimationConfig() +``` + +### Properties + +#### `AnimateOffset` + +Animate Offset (position) changes. Default: true. + +```csharp +public bool AnimateOffset // get, init +``` + +#### `AnimateSize` + +Animate Size changes. Default: false (content won't re-layout during animation). + +```csharp +public bool AnimateSize // get, init +``` + +#### `DampingRatio` + +Spring damping ratio (0..1). Only used when UseSpring is true. Default: 0.6. + +```csharp +public float DampingRatio // get, init +``` + +#### `Duration` + +Duration of the layout animation. Default: 300ms. + +```csharp +public TimeSpan Duration // get, init +``` + +#### `Period` + +Spring period in seconds. Only used when UseSpring is true. Default: 0.08. + +```csharp +public float Period // get, init +``` + +#### `UseSpring` + +When true, use a spring natural motion animation instead of linear keyframes. + +```csharp +public bool UseSpring // get, init +``` + +## `ThemeTransitions` + +Declarative theme transition configuration. Children applies to Panel.ChildrenTransitions / Border.ChildTransitions / ContentControl.ContentTransitions. ItemContainer applies to ItemsControl.ItemContainerTransitions. The reconciler picks the correct property based on control type. + +```csharp +public record ThemeTransitions +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `ThemeTransitions` + +```csharp +public ThemeTransitions() +``` + +### Properties + +#### `Children` + +```csharp +public Transition[]? Children // get, init +``` + +#### `ItemContainer` + +```csharp +public Transition[]? ItemContainer // get, init +``` diff --git a/docs/guide/reference/animation/index.md b/docs/guide/reference/animation/index.md new file mode 100644 index 0000000000..624c64315a --- /dev/null +++ b/docs/guide/reference/animation/index.md @@ -0,0 +1,22 @@ +# Animation + +Transitions, curves, keyframes, interaction states and scroll-linked animation. + +**Learn more:** [Animation](../../animation.md) + +## Types + +| Type | Description | +| --- | --- | +| [Curves and easing](curves.md) | Curves that shape the timing of an animation. | +| [Enums](enums.md) | The enumerations in this category. | +| [Implicit and theme transitions](implicit.md) | Transitions WinUI runs when a property or a child collection changes. | +| [Interaction states](interaction-states.md) | Animations that follow pointer over, pressed and focus states. | +| [Keyframes](keyframes.md) | Types for keyframe animations. | +| [Scroll-linked animation](scroll.md) | Animations driven by the scroll position. | +| [Transitions](transitions.md) | Enter and exit transitions for elements. | +| [`AnimationConfig`](AnimationConfig.md) | Configuration for the .Animate() modifier — declaration-site implicit animation on compositor Visual properties. | +| [`Animations`](Animations.md) | Transactional animation entry points — the SwiftUI `withAnimation { … }` analog. | +| [`AnimationScope`](AnimationScope.md) | Provides ambient animation context via \[ThreadStatic\] fields. | +| [`CompositorProvider`](CompositorProvider.md) | Static accessor for the current Compositor instance. | +| [`StaggerConfig`](StaggerConfig.md) | Stagger configuration for container children animations. | diff --git a/docs/guide/reference/animation/interaction-states.md b/docs/guide/reference/animation/interaction-states.md new file mode 100644 index 0000000000..b3b971266a --- /dev/null +++ b/docs/guide/reference/animation/interaction-states.md @@ -0,0 +1,220 @@ +# Interaction states + +Animations that follow pointer over, pressed and focus states. + +**Learn more:** [Animation](../../animation.md) + +## `InteractionStateValues` + +Values for a single interaction state (PointerOver, Pressed, Focused). Only visual/brush properties — no layout properties (Width, Margin, etc.). The record IS the boundary: adding a field is a deliberate API decision. + +```csharp +public record InteractionStateValues(float? Opacity = null, float? Scale = null, Vector3? ScaleV = null, Vector3? Translation = null, float? Rotation = null, Brush? Background = null, Brush? Foreground = null, Brush? BorderBrush = null) +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `InteractionStateValues` + +Values for a single interaction state (PointerOver, Pressed, Focused). Only visual/brush properties — no layout properties (Width, Margin, etc.). The record IS the boundary: adding a field is a deliberate API decision. + +```csharp +public InteractionStateValues(float? Opacity = null, float? Scale = null, Vector3? ScaleV = null, Vector3? Translation = null, float? Rotation = null, Brush? Background = null, Brush? Foreground = null, Brush? BorderBrush = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Opacity` | `float?` | `null` | | +| `Scale` | `float?` | `null` | | +| `ScaleV` | `Vector3?` | `null` | | +| `Translation` | `Vector3?` | `null` | | +| `Rotation` | `float?` | `null` | | +| `Background` | `Brush?` | `null` | | +| `Foreground` | `Brush?` | `null` | | +| `BorderBrush` | `Brush?` | `null` | | + +### Properties + +#### `Background` + +```csharp +public Brush? Background // get, init +``` + +#### `BorderBrush` + +```csharp +public Brush? BorderBrush // get, init +``` + +#### `Foreground` + +```csharp +public Brush? Foreground // get, init +``` + +#### `Opacity` + +```csharp +public float? Opacity // get, init +``` + +#### `Rotation` + +```csharp +public float? Rotation // get, init +``` + +#### `Scale` + +```csharp +public float? Scale // get, init +``` + +#### `ScaleV` + +```csharp +public Vector3? ScaleV // get, init +``` + +#### `Translation` + +```csharp +public Vector3? Translation // get, init +``` + +## `InteractionStatesBuilder` + +Builder for constructing InteractionStatesConfig fluently. + +```csharp +public class InteractionStatesBuilder +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `InteractionStatesBuilder` + +```csharp +public InteractionStatesBuilder() +``` + +### Methods + +#### `Focused` + +```csharp +public InteractionStatesBuilder Focused(float? opacity = null, float? scale = null, Vector3? scaleV = null, Vector3? translation = null, float? rotation = null, Brush? background = null, Brush? foreground = null, Brush? borderBrush = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `opacity` | `float?` | `null` | | +| `scale` | `float?` | `null` | | +| `scaleV` | `Vector3?` | `null` | | +| `translation` | `Vector3?` | `null` | | +| `rotation` | `float?` | `null` | | +| `background` | `Brush?` | `null` | | +| `foreground` | `Brush?` | `null` | | +| `borderBrush` | `Brush?` | `null` | | + +#### `PointerOver` + +```csharp +public InteractionStatesBuilder PointerOver(float? opacity = null, float? scale = null, Vector3? scaleV = null, Vector3? translation = null, float? rotation = null, Brush? background = null, Brush? foreground = null, Brush? borderBrush = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `opacity` | `float?` | `null` | | +| `scale` | `float?` | `null` | | +| `scaleV` | `Vector3?` | `null` | | +| `translation` | `Vector3?` | `null` | | +| `rotation` | `float?` | `null` | | +| `background` | `Brush?` | `null` | | +| `foreground` | `Brush?` | `null` | | +| `borderBrush` | `Brush?` | `null` | | + +#### `Pressed` + +```csharp +public InteractionStatesBuilder Pressed(float? opacity = null, float? scale = null, Vector3? scaleV = null, Vector3? translation = null, float? rotation = null, Brush? background = null, Brush? foreground = null, Brush? borderBrush = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `opacity` | `float?` | `null` | | +| `scale` | `float?` | `null` | | +| `scaleV` | `Vector3?` | `null` | | +| `translation` | `Vector3?` | `null` | | +| `rotation` | `float?` | `null` | | +| `background` | `Brush?` | `null` | | +| `foreground` | `Brush?` | `null` | | +| `borderBrush` | `Brush?` | `null` | | + +## `InteractionStatesConfig` + +Configuration for the .InteractionStates() modifier. Defines visual state values for PointerOver, Pressed, and Focused states, plus an optional animation curve for state transitions. + +```csharp +public record InteractionStatesConfig(InteractionStateValues? PointerOver = null, InteractionStateValues? Pressed = null, InteractionStateValues? Focused = null, Curve? Curve = null) +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `InteractionStatesConfig` + +Configuration for the .InteractionStates() modifier. Defines visual state values for PointerOver, Pressed, and Focused states, plus an optional animation curve for state transitions. + +```csharp +public InteractionStatesConfig(InteractionStateValues? PointerOver = null, InteractionStateValues? Pressed = null, InteractionStateValues? Focused = null, Curve? Curve = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `PointerOver` | [`InteractionStateValues?`](#interactionstatevalues) | `null` | | +| `Pressed` | [`InteractionStateValues?`](#interactionstatevalues) | `null` | | +| `Focused` | [`InteractionStateValues?`](#interactionstatevalues) | `null` | | +| `Curve` | [`Curve?`](curves.md#curve) | `null` | | + +### Properties + +#### `Curve` + +```csharp +public Curve? Curve // get, init +``` + +#### `Focused` + +```csharp +public InteractionStateValues? Focused // get, init +``` + +#### `PointerOver` + +```csharp +public InteractionStateValues? PointerOver // get, init +``` + +#### `Pressed` + +```csharp +public InteractionStateValues? Pressed // get, init +``` diff --git a/docs/guide/reference/animation/keyframes.md b/docs/guide/reference/animation/keyframes.md new file mode 100644 index 0000000000..178110511b --- /dev/null +++ b/docs/guide/reference/animation/keyframes.md @@ -0,0 +1,216 @@ +# Keyframes + +Types for keyframe animations. + +**Learn more:** [Animation](../../animation.md) + +## `KeyframeAnimationDef` + +Immutable definition of a keyframe animation, built by the fluent builder. + +```csharp +public record KeyframeAnimationDef +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `KeyframeAnimationDef` + +```csharp +public KeyframeAnimationDef() +``` + +### Properties + +#### `Duration` + +```csharp +public TimeSpan Duration // get, init +``` + +#### `Keyframes` + +```csharp +public KeyframeDef[] Keyframes // get, init +``` + +#### `Loop` + +```csharp +public bool Loop // get, init +``` + +## `KeyframeBuilder` + +Fluent builder for constructing keyframe animation definitions. + +```csharp +public class KeyframeBuilder +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `KeyframeBuilder` + +```csharp +public KeyframeBuilder() +``` + +### Methods + +#### `At` + +```csharp +public KeyframeBuilder At(float progress, float? opacity = null, Vector3? scale = null, Vector3? translation = null, float? rotation = null, Easing? easing = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `progress` | `float` | | | +| `opacity` | `float?` | `null` | | +| `scale` | `Vector3?` | `null` | | +| `translation` | `Vector3?` | `null` | | +| `rotation` | `float?` | `null` | | +| `easing` | `Easing?` | `null` | | + +#### `Build` + +```csharp +public KeyframeAnimationDef Build() +``` + +#### `Duration` + +```csharp +public KeyframeBuilder Duration(int ms) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ms` | `int` | | + +#### `Loop` + +```csharp +public KeyframeBuilder Loop() +``` + +## `KeyframeDef` + +A single keyframe in a keyframe animation. + +```csharp +public record KeyframeDef(float Progress) +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `KeyframeDef` + +A single keyframe in a keyframe animation. + +```csharp +public KeyframeDef(float Progress) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Progress` | `float` | | + +### Properties + +#### `Easing` + +```csharp +public Easing? Easing // get, init +``` + +#### `Opacity` + +```csharp +public float? Opacity // get, init +``` + +#### `Progress` + +```csharp +public float Progress // get, init +``` + +#### `Rotation` + +```csharp +public float? Rotation // get, init +``` + +#### `Scale` + +```csharp +public Vector3? Scale // get, init +``` + +#### `Translation` + +```csharp +public Vector3? Translation // get, init +``` + +## `KeyframeEntry` + +A named keyframe animation entry stored on the Element. + +```csharp +public record KeyframeEntry(string Name, object? Trigger, KeyframeAnimationDef Definition) +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `KeyframeEntry` + +A named keyframe animation entry stored on the Element. + +```csharp +public KeyframeEntry(string Name, object? Trigger, KeyframeAnimationDef Definition) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Name` | `string` | | +| `Trigger` | `object?` | | +| `Definition` | [`KeyframeAnimationDef`](#keyframeanimationdef) | | + +### Properties + +#### `Definition` + +```csharp +public KeyframeAnimationDef Definition // get, init +``` + +#### `Name` + +```csharp +public string Name // get, init +``` + +#### `Trigger` + +```csharp +public object? Trigger // get, init +``` diff --git a/docs/guide/reference/animation/scroll.md b/docs/guide/reference/animation/scroll.md new file mode 100644 index 0000000000..bf9e10ecef --- /dev/null +++ b/docs/guide/reference/animation/scroll.md @@ -0,0 +1,189 @@ +# Scroll-linked animation + +Animations driven by the scroll position. + +**Learn more:** [Animation](../../animation.md) + +## `ScrollAnimationBuilder` + +Fluent builder for constructing scroll-linked expression animations. + +```csharp +public class ScrollAnimationBuilder +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `ScrollAnimationBuilder` + +```csharp +public ScrollAnimationBuilder() +``` + +### Methods + +#### `Build` + +```csharp +public ScrollExpression[] Build() +``` + +#### `Expression` + +Custom expression for advanced scenarios. + +```csharp +public ScrollAnimationBuilder Expression(string property, string expression) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `property` | `string` | | +| `expression` | `string` | | + +#### `FadeIn` + +Fade in as scroll position increases from startOffset to endOffset. + +```csharp +public ScrollAnimationBuilder FadeIn(float startOffset, float endOffset) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `startOffset` | `float` | | +| `endOffset` | `float` | | + +#### `FadeOut` + +Fade out as scroll position increases from startOffset to endOffset. + +```csharp +public ScrollAnimationBuilder FadeOut(float startOffset, float endOffset) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `startOffset` | `float` | | +| `endOffset` | `float` | | + +#### `Parallax` + +Parallax effect: element translates at a fraction of scroll speed. + +```csharp +public ScrollAnimationBuilder Parallax(float factor) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `factor` | `float` | | + +#### `ScaleRange` + +Scale range: uniform scale interpolates between from and to as scroll moves from scrollStart to scrollEnd. + +```csharp +public ScrollAnimationBuilder ScaleRange(float scrollStart, float scrollEnd, float from, float to) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `scrollStart` | `float` | | +| `scrollEnd` | `float` | | +| `from` | `float` | | +| `to` | `float` | | + +## `ScrollAnimationConfig` + +Configuration for scroll-linked expression animations. + +```csharp +public record ScrollAnimationConfig(ScrollViewer ScrollViewer, ScrollExpression[] Expressions) +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `ScrollAnimationConfig` + +Configuration for scroll-linked expression animations. + +```csharp +public ScrollAnimationConfig(ScrollViewer ScrollViewer, ScrollExpression[] Expressions) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ScrollViewer` | `ScrollViewer` | | +| `Expressions` | [`ScrollExpression[]`](#scrollexpression) | | + +### Properties + +#### `Expressions` + +```csharp +public ScrollExpression[] Expressions // get, init +``` + +#### `ScrollViewer` + +```csharp +public ScrollViewer ScrollViewer // get, init +``` + +## `ScrollExpression` + +A single scroll-linked expression animation binding. + +```csharp +public record ScrollExpression(string Property, string Expression) +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `ScrollExpression` + +A single scroll-linked expression animation binding. + +```csharp +public ScrollExpression(string Property, string Expression) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Property` | `string` | | +| `Expression` | `string` | | + +### Properties + +#### `Expression` + +```csharp +public string Expression // get, init +``` + +#### `Property` + +```csharp +public string Property // get, init +``` diff --git a/docs/guide/reference/animation/transitions.md b/docs/guide/reference/animation/transitions.md new file mode 100644 index 0000000000..e93b810e04 --- /dev/null +++ b/docs/guide/reference/animation/transitions.md @@ -0,0 +1,360 @@ +# Transitions + +Enter and exit transitions for elements. + +**Learn more:** [Animation](../../animation.md) + +## `AsymmetricTransition` + +```csharp +public sealed record AsymmetricTransition : Transition +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. Inherits from [`Transition`](#transition_1). + +### Constructors + +#### `AsymmetricTransition` + +```csharp +public AsymmetricTransition(Transition enter, Transition exit) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `enter` | [`Transition`](#transition_1) | | +| `exit` | [`Transition`](#transition_1) | | + +### Properties + +#### `EnterTransition` + +```csharp +public Transition EnterTransition // get, init +``` + +#### `ExitTransition` + +```csharp +public Transition ExitTransition // get, init +``` + +## `CombinedTransition` + +```csharp +public sealed record CombinedTransition(Transition First, Transition Second) : Transition +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. Inherits from [`Transition`](#transition_1). + +### Constructors + +#### `CombinedTransition` + +```csharp +public CombinedTransition(Transition First, Transition Second) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `First` | [`Transition`](#transition_1) | | +| `Second` | [`Transition`](#transition_1) | | + +### Properties + +#### `First` + +```csharp +public Transition First // get, init +``` + +#### `Second` + +```csharp +public Transition Second // get, init +``` + +## `DirectionalTransition` + +```csharp +public sealed record DirectionalTransition : Transition +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. Inherits from [`Transition`](#transition_1). + +### Constructors + +#### `DirectionalTransition` + +```csharp +public DirectionalTransition(Transition? enter, Transition? exit) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `enter` | [`Transition?`](#transition_1) | | +| `exit` | [`Transition?`](#transition_1) | | + +### Properties + +#### `EnterTransition` + +```csharp +public Transition? EnterTransition // get, init +``` + +#### `ExitTransition` + +```csharp +public Transition? ExitTransition // get, init +``` + +## `Edge` + +Edge enum for slide direction. + +```csharp +public enum Edge +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `Left` | `0` | | +| `Top` | `1` | | +| `Right` | `2` | | +| `Bottom` | `3` | | + +## `ElementTransition` + +Stores transition configuration on an Element. Includes the transition definition and an optional curve override (default: 300ms Decelerate). + +```csharp +public record ElementTransition(Transition Transition, Curve? Curve = null) +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `ElementTransition` + +Stores transition configuration on an Element. Includes the transition definition and an optional curve override (default: 300ms Decelerate). + +```csharp +public ElementTransition(Transition Transition, Curve? Curve = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Transition` | [`Transition`](#transition_1) | | | +| `Curve` | [`Curve?`](curves.md#curve) | `null` | | + +### Properties + +#### `Curve` + +```csharp +public Curve? Curve // get, init +``` + +#### `Transition` + +```csharp +public Transition Transition // get, init +``` + +## `FadeTransition` + +```csharp +public sealed record FadeTransition : Transition +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. Inherits from [`Transition`](#transition_1). + +### Constructors + +#### `FadeTransition` + +```csharp +public FadeTransition() +``` + +## `ScaleTransition` + +```csharp +public sealed record ScaleTransition(float From) : Transition +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. Inherits from [`Transition`](#transition_1). + +### Constructors + +#### `ScaleTransition` + +```csharp +public ScaleTransition(float From) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `From` | `float` | | + +### Properties + +#### `From` + +```csharp +public float From // get, init +``` + +## `SlideTransition` + +```csharp +public sealed record SlideTransition(Edge Edge) : Transition +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. Inherits from [`Transition`](#transition_1). + +### Constructors + +#### `SlideTransition` + +```csharp +public SlideTransition(Edge Edge) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Edge` | [`Edge`](#edge) | | + +### Properties + +#### `Edge` + +```csharp +public Edge Edge // get, init +``` + +## `Transition` + +Describes enter/exit transitions for conditional rendering. Transitions are composable: Fade + Slide(Bottom) plays both in parallel. Asymmetric: MakeEnter(Fade) | MakeExit(Scale) uses different animations for enter/exit. + +```csharp +public abstract record Transition +``` + +Namespace: `Microsoft.UI.Reactor.Animation`. + +### Constructors + +#### `Transition` + +```csharp +protected Transition() +``` + +### Methods + +#### `Enter` + +```csharp +public static Transition Enter(Transition enter) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `enter` | [`Transition`](#transition_1) | | + +#### `Exit` + +```csharp +public static Transition Exit(Transition exit) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `exit` | [`Transition`](#transition_1) | | + +#### `Scale` + +```csharp +public static Transition Scale(float from = 0.8500000238418579f) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `from` | `float` | `0.8500000238418579f` | | + +#### `Slide` + +```csharp +public static Transition Slide(Edge edge = Edge.Bottom) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `edge` | [`Edge`](#edge) | `Edge.Bottom` | | + +### Fields + +#### `Fade` + +```csharp +public static readonly Transition Fade +``` + +### Operators + +#### `op_Addition` + +Combine two transitions to play in parallel (e.g., Fade + Slide). + +```csharp +public static Transition operator +(Transition a, Transition b) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `a` | [`Transition`](#transition_1) | | +| `b` | [`Transition`](#transition_1) | | + +#### `op_BitwiseOr` + +Asymmetric: left side is enter, right side is exit. + +```csharp +public static Transition operator |(Transition enter, Transition exit) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `enter` | [`Transition`](#transition_1) | | +| `exit` | [`Transition`](#transition_1) | | diff --git a/docs/guide/reference/components/AppContexts.md b/docs/guide/reference/components/AppContexts.md new file mode 100644 index 0000000000..119c4c2cee --- /dev/null +++ b/docs/guide/reference/components/AppContexts.md @@ -0,0 +1,37 @@ +# AppContexts + +Static context registrations shared across the Reactor core. Install the cache via `ReactorHost` bootstrap (or override per test). + +```csharp +public static class AppContexts +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Context](../../context.md) + +## Fields + +### `FocusRevalidation` + +Ambient [`FocusRevalidationService`](../data/FocusRevalidationService.md) bound to the root [`AppContexts.QueryCache`](#querycache). Hooks that opt in via `ResourceOptions.RefetchOnWindowFocus = true` enroll themselves so the service can invalidate their cache entry on window activation / resume. + +```csharp +public static readonly Context FocusRevalidation +``` + +### `PendingScope` + +Nearest ancestor [`PendingScope`](../hooks/pending.md#pendingscope), or `null` at the root. The `Pending` element provides a fresh scope to its subtree; hooks that participate in Pending-style bubble-up read this via `UseContext`. + +```csharp +public static readonly Context PendingScope +``` + +### `QueryCache` + +The ambient [`QueryCache`](../data/query-cache.md#querycache). The default value is a fresh cache instance installed at app root; tests can provide their own. + +```csharp +public static readonly Context QueryCache +``` diff --git a/docs/guide/reference/components/Callbacks.md b/docs/guide/reference/components/Callbacks.md new file mode 100644 index 0000000000..65e9d691eb --- /dev/null +++ b/docs/guide/reference/components/Callbacks.md @@ -0,0 +1,101 @@ +# Callbacks\ + +An opt-in, always-equal wrapper for the delegate (callback) portion of a component's props, so callback identity never forces a re-render. + +```csharp +public sealed record Callbacks(T Value) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +## Remarks + +[`Component`](Component-1.md) memoizes against `!Equals(oldProps, newProps)` in its `ShouldUpdate` method. For `record` props that is a field-by-field compare, and `Action`/`Func` delegate fields compare by *reference*. A parent typically passes a freshly-allocated delegate (a lambda or local function) on every render, so a child's props compare unequal and the child re-renders even though no observable data changed. + +Historically apps worked around this by hand-writing `Equals`/`GetHashCode` on every props record, listing only the data fields — ~10 lines each, with a silent stale-UI bug if you forgot a field. Wrap the callbacks in [`Callbacks`](Callbacks.md) instead: its [`Callbacks.Equals`](Callbacks.md) is constant `true` and [`Callbacks.GetHashCode`](Callbacks.md) is constant `0`, so the outer record's auto-generated equality treats the callbacks slot as always-equal — data fields still drive the memo decision, callbacks never do. + +```csharp +public sealed record StepCardCallbacks( + Action OnPromptChanged, + Action OnRun); + +public sealed record StepCardProps( + StepModel Step, + bool IsGenerating, + Callbacks Cb); // ← no manual Equals needed +``` + +**Stale-delegate guarantee.** "Always-equal for diffing" must not mean "stale delegate at invoke". When the reconciler skips a child's re-render because the data is unchanged, it still refreshes the child's [`Component.Props`](Component-1.md#props) with the latest props (see `Reconciler.ReconcileComponent`). So a handler that reads `Props.Cb.Value.OnRun` *live* at event time always invokes the *current* delegate, never the memoized one. Read callbacks off `Props` at dispatch time — do not capture `Props.Cb.Value.OnRun` into a local at render time. + +## Type parameters + +| Name | Description | +| --- | --- | +| `T` | The payload carrying the callbacks. Usually a small record (or a single delegate) holding only `Action`/`Func` delegate members. | + +## Constructors + +### `Callbacks` + +An opt-in, always-equal wrapper for the delegate (callback) portion of a component's props, so callback identity never forces a re-render. + +```csharp +public Callbacks(T Value) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Value` | `T` | The wrapped callbacks payload. Read it live at dispatch time. | + +**Type parameters** + +| Name | Description | +| --- | --- | +| `T` | The payload carrying the callbacks. Usually a small record (or a single delegate) holding only `Action`/`Func` delegate members. | + +**Remarks** + +[`Component`](Component-1.md) memoizes against `!Equals(oldProps, newProps)` in its `ShouldUpdate` method. For `record` props that is a field-by-field compare, and `Action`/`Func` delegate fields compare by *reference*. A parent typically passes a freshly-allocated delegate (a lambda or local function) on every render, so a child's props compare unequal and the child re-renders even though no observable data changed. + +Historically apps worked around this by hand-writing `Equals`/`GetHashCode` on every props record, listing only the data fields — ~10 lines each, with a silent stale-UI bug if you forgot a field. Wrap the callbacks in [`Callbacks`](Callbacks.md) instead: its [`Callbacks.Equals`](Callbacks.md) is constant `true` and [`Callbacks.GetHashCode`](Callbacks.md) is constant `0`, so the outer record's auto-generated equality treats the callbacks slot as always-equal — data fields still drive the memo decision, callbacks never do. + +```csharp +public sealed record StepCardCallbacks( + Action OnPromptChanged, + Action OnRun); + +public sealed record StepCardProps( + StepModel Step, + bool IsGenerating, + Callbacks Cb); // ← no manual Equals needed +``` + +**Stale-delegate guarantee.** "Always-equal for diffing" must not mean "stale delegate at invoke". When the reconciler skips a child's re-render because the data is unchanged, it still refreshes the child's [`Component.Props`](Component-1.md#props) with the latest props (see `Reconciler.ReconcileComponent`). So a handler that reads `Props.Cb.Value.OnRun` *live* at event time always invokes the *current* delegate, never the memoized one. Read callbacks off `Props` at dispatch time — do not capture `Props.Cb.Value.OnRun` into a local at render time. + +## Properties + +### `Value` + +The wrapped callbacks payload. Read it live at dispatch time. + +```csharp +public T Value // get, init +``` + +## Operators + +### `op_Implicit` + +Wraps a callbacks payload so it can be assigned directly to a [`Callbacks`](Callbacks.md) props field without calling the constructor — the payload type is inferred from the target field, so authors just write `new StepProps(step, new StepCallbacks(...))`. + +```csharp +public static implicit operator Callbacks(T value) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `value` | `T` | | diff --git a/docs/guide/reference/components/Component-1.md b/docs/guide/reference/components/Component-1.md new file mode 100644 index 0000000000..8f175698ae --- /dev/null +++ b/docs/guide/reference/components/Component-1.md @@ -0,0 +1,46 @@ +# Component\ + +Base class for components that receive typed props (e.g., navigation parameters). Props are set by the host before rendering. + +```csharp +public abstract class Component : Component +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Component`](Component.md). + +**Learn more:** [Components](../../components.md) + +## Constructors + +### `Component` + +```csharp +protected Component() +``` + +## Properties + +### `Props` + +The typed props passed to this component by its parent or host. + +```csharp +public TProps Props // get +``` + +## Methods + +### `ShouldUpdate` + +Controls whether this component should re-render when its parent re-renders with new props. Default: structural equality via record Equals — record props get auto-comparison for free; class props need an Equals override. Override for custom comparison logic. + +```csharp +protected virtual bool ShouldUpdate(TProps? oldProps, TProps? newProps) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `oldProps` | `TProps?` | | +| `newProps` | `TProps?` | | diff --git a/docs/guide/reference/components/Component.md b/docs/guide/reference/components/Component.md new file mode 100644 index 0000000000..c247766d68 --- /dev/null +++ b/docs/guide/reference/components/Component.md @@ -0,0 +1,152 @@ +# Component + +Base class for stateful components (like React class components, but using hooks). Components hold a RenderContext that tracks their hook state across re-renders. + +```csharp +public abstract class Component +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Components](../../components.md) + +## Constructors + +### `Component` + +```csharp +protected Component() +``` + +## Methods + +### `PickFileAsync` + +Opens a single-file picker owned by this component's window. Not a hook: call from a UI-thread event handler. + +```csharp +protected Task PickFileAsync(FilePickerOptions options) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `options` | [`FilePickerOptions`](../hosting/file-pickers.md#filepickeroptions) | | + +### `PickFolderAsync` + +Opens a single-folder picker owned by this component's window. Not a hook: call from a UI-thread event handler. + +```csharp +protected Task PickFolderAsync(FolderPickerOptions options) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `options` | [`FolderPickerOptions`](../hosting/file-pickers.md#folderpickeroptions) | | + +### `PickMultipleFilesAsync` + +Opens a multiple-file picker owned by this component's window. Not a hook: call from a UI-thread event handler. + +```csharp +protected Task> PickMultipleFilesAsync(FilePickerOptions options) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `options` | [`FilePickerOptions`](../hosting/file-pickers.md#filepickeroptions) | | + +### `PickMultipleFoldersAsync` + +Opens a multiple-folder picker owned by this component's window. Not a hook: call from a UI-thread event handler. + +```csharp +protected Task> PickMultipleFoldersAsync(FolderPickerOptions options) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `options` | [`FolderPickerOptions`](../hosting/file-pickers.md#folderpickeroptions) | | + +### `PickSaveFileAsync` + +Opens a save-file picker owned by this component's window. Not a hook: call from a UI-thread event handler. + +```csharp +protected Task PickSaveFileAsync(SaveFilePickerOptions options) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `options` | [`SaveFilePickerOptions`](../hosting/file-pickers.md#savefilepickeroptions) | | + +### `Render` + +Override to describe the UI. Use UseState, UseEffect, etc. from the context. Must call hooks in the same order every render. + +```csharp +public abstract Element Render() +``` + +### `ShouldUpdate` + +Controls whether this propless component should re-render when its parent re-renders. Default: false — propless components only re-render from their own state changes or context changes. Override and return true to always re-render when the parent re-renders. + +```csharp +protected virtual bool ShouldUpdate() +``` + +## Hooks + +- [`UseAnnounce`](../hooks/UseAnnounce.md) +- [`UseBreakpoint`](../hooks/UseBreakpoint.md) +- [`UseCallback`](../hooks/UseCallback.md) +- [`UseClosingGuard`](../hooks/UseClosingGuard.md) +- [`UseCollection`](../hooks/UseCollection.md) +- [`UseColorScheme`](../hooks/UseColorScheme.md) +- [`UseCommand`](../hooks/UseCommand.md) +- [`UseContext`](../hooks/UseContext.md) +- [`UseDataSource`](../hooks/UseDataSource.md) +- [`UseDisplays`](../hooks/UseDisplays.md) +- [`UseDpi`](../hooks/UseDpi.md) +- [`UseEffect`](../hooks/UseEffect.md) +- [`UseExternalStore`](../hooks/UseExternalStore.md) +- [`UseHighContrast`](../hooks/UseHighContrast.md) +- [`UseHighContrastScheme`](../hooks/UseHighContrastScheme.md) +- [`UseInfiniteResource`](../hooks/UseInfiniteResource.md) +- [`UseIntl`](../hooks/UseIntl.md) +- [`UseIsActive`](../hooks/UseIsActive.md) +- [`UseIsCovered`](../hooks/UseIsCovered.md) +- [`UseIsDarkTheme`](../hooks/UseIsDarkTheme.md) +- [`UseMemo`](../hooks/UseMemo.md) +- [`UseMutation`](../hooks/UseMutation.md) +- [`UseNavigation`](../hooks/UseNavigation.md) +- [`UseNavigationLifecycle`](../hooks/UseNavigationLifecycle.md) +- [`UseObservable`](../hooks/UseObservable.md) +- [`UseObservableProperty`](../hooks/UseObservableProperty.md) +- [`UseObservableTree`](../hooks/UseObservableTree.md) +- [`UseOpenWindow`](../hooks/UseOpenWindow.md) +- [`UsePersisted`](../hooks/UsePersisted.md) +- [`UseReducedMotion`](../hooks/UseReducedMotion.md) +- [`UseReducer`](../hooks/UseReducer.md) +- [`UseRef`](../hooks/UseRef.md) +- [`UseResource`](../hooks/UseResource.md) +- [`UseState`](../hooks/UseState.md) +- [`UseSystemBackButton`](../hooks/UseSystemBackButton.md) +- [`UseTrayIcon`](../hooks/UseTrayIcon.md) +- [`UseWindow`](../hooks/UseWindow.md) +- [`UseWindowAspectRatio`](../hooks/UseWindowAspectRatio.md) +- [`UseWindowDragMove`](../hooks/UseWindowDragMove.md) +- [`UseWindowPosition`](../hooks/UseWindowPosition.md) +- [`UseWindowSize`](../hooks/UseWindowSize.md) +- [`UseWindowState`](../hooks/UseWindowState.md) diff --git a/docs/guide/reference/components/Context.md b/docs/guide/reference/components/Context.md new file mode 100644 index 0000000000..4cf4973677 --- /dev/null +++ b/docs/guide/reference/components/Context.md @@ -0,0 +1,34 @@ +# Context\ + +A typed, named context that can be provided to a subtree and consumed by any descendant. Define as a static field. Provide via .Provide() modifier. Consume via UseContext() hook. + +```csharp +public sealed class Context : ContextBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`ContextBase`](ContextBase.md). + +**Learn more:** [Context](../../context.md) + +## Constructors + +### `Context` + +```csharp +public Context(T defaultValue, string? name = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `defaultValue` | `T` | | | +| `name` | `string?` | `null` | | + +## Properties + +### `DefaultValue` + +```csharp +public T DefaultValue // get +``` diff --git a/docs/guide/reference/components/ContextBase.md b/docs/guide/reference/components/ContextBase.md new file mode 100644 index 0000000000..5cea89eea6 --- /dev/null +++ b/docs/guide/reference/components/ContextBase.md @@ -0,0 +1,19 @@ +# ContextBase + +Non-generic base for type-erased storage in the context scope stack. + +```csharp +public abstract class ContextBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Context](../../context.md) + +## Constructors + +### `ContextBase` + +```csharp +protected ContextBase() +``` diff --git a/docs/guide/reference/components/ElementFactory.md b/docs/guide/reference/components/ElementFactory.md new file mode 100644 index 0000000000..f451581d80 --- /dev/null +++ b/docs/guide/reference/components/ElementFactory.md @@ -0,0 +1,57 @@ +# ElementFactory\ + +Bridges WinUI's ItemsRepeater/IElementFactory to Reactor's Reconciler. GetElement calls the view builder then mounts; RecycleElement unmounts. + +```csharp +public sealed class ElementFactory : IElementFactory +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +## Remarks + +Spec 042 Phase 1: [`ElementFactory._mountedElements`](ElementFactory.md) is keyed by the stable identity string from `ReactorRow`, not by realized index. Insert-at-0 used to shift every entry's effective index by one — that broke [`ElementFactory.RefreshRealizedItems`](ElementFactory.md)'s lookup contract because the dictionary's int keys no longer matched the repeater's new positions. Keying by string makes the mapping reorder-stable. + +## Constructors + +### `ElementFactory` + +```csharp +public ElementFactory(IReadOnlyList items, Func viewBuilder, Reconciler reconciler, Action requestRerender, ElementPool? pool = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `items` | `IReadOnlyList` | | | +| `viewBuilder` | `Func` | | | +| `reconciler` | [`Reconciler`](../extensibility/Reconciler.md) | | | +| `requestRerender` | `Action` | | | +| `pool` | [`ElementPool?`](../extensibility/ElementPool.md) | `null` | | + +## Methods + +### `GetElement` + +```csharp +public UIElement GetElement(ElementFactoryGetArgs args) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `args` | `ElementFactoryGetArgs` | | + +### `RecycleElement` + +```csharp +public void RecycleElement(ElementFactoryRecycleArgs args) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `args` | `ElementFactoryRecycleArgs` | | diff --git a/docs/guide/reference/components/IReactorKeyed.md b/docs/guide/reference/components/IReactorKeyed.md new file mode 100644 index 0000000000..8649a48aff --- /dev/null +++ b/docs/guide/reference/components/IReactorKeyed.md @@ -0,0 +1,33 @@ +# IReactorKeyed + +Identity-on-data convention for items rendered into Reactor collection elements ([`TemplatedListElementBase`](../elements/collections.md#templatedlistelementbase) and [`LazyStackElementBase`](../elements/collections.md#lazystackelementbase)) and into hand-built keyed children (`FlexColumn(items.Select(... .WithKey(item)))`). + +```csharp +public interface IReactorKeyed +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Collections](../../collections.md) + +## Remarks + +When a data type implements [`IReactorKeyed`](IReactorKeyed.md), collection elements default their `KeySelector` to `t => t.Key` and a `WithKey(this T el, TKey item) where T: Element where TKey: IReactorKeyed` overload becomes available (the open `T` preserves the element's concrete type through the fluent chain). Explicit `KeySelector` and `WithKey(string)` continue to work for types you do not own. + +The returned [`IReactorKeyed.Key`](#key) value must be: + +- **Stable** across re-renders for the lifetime of the item — using a value that changes (e.g. row index) defeats keyed reconciliation and produces the same visual churn as having no key. +- **Unique** within the containing list — duplicate keys trigger a bulk-replace bailout and a one-shot diagnostic. +- **Non-null** — a null key is treated as a developer bug and bails out the diff for the affected list. + +See spec 042 §3 (the unified identity model) and §5 (identity-on-data convention) for the design rationale. + +## Properties + +### `Key` + +Stable, unique, non-null identifier for this item within the list it belongs to. Read at every reconcile pass; must be cheap to compute (ideally a field read, not a derived value). + +```csharp +public abstract string Key // get +``` diff --git a/docs/guide/reference/components/Observable.md b/docs/guide/reference/components/Observable.md new file mode 100644 index 0000000000..15067b245c --- /dev/null +++ b/docs/guide/reference/components/Observable.md @@ -0,0 +1,76 @@ +# Observable\ + +A single-value cell that raises [`INotifyPropertyChanged.PropertyChanged`](https://learn.microsoft.com/dotnet/api/system.componentmodel.inotifypropertychanged.propertychanged) when [`Observable.Value`](#value) is assigned a different value. Exists to let developers declare small pieces of global app state (dev flags, light/dark mode, currently-signed-in user, etc.) in one line without hand-writing an INotifyPropertyChanged class. + +Pairs with `RenderContext.UseObservable`, which subscribes the current component and re-renders on change: + +```csharp +public static readonly Observable DebugUI = new(false); +// ... +var on = ctx.UseObservable(DebugUI).Value; +``` + +For richer state (multiple related properties, computed properties, XAML binding interop), authoring a plain INPC class is still the recommended path — [`Observable`](Observable.md) is deliberately minimal and is not a replacement for that. + +```csharp +public sealed class Observable : INotifyPropertyChanged +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Reactivity Model](../../reactivity-model.md) + +## Constructors + +### `Observable` + +```csharp +public Observable() +public Observable(T initial) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `initial` | `T` | | + +## Properties + +### `Value` + +```csharp +public T Value // get, set +``` + +## Methods + +### `ToString` + +Returns a string that represents this object. + +```csharp +public override string ToString() +``` + +## Events + +### `PropertyChanged` + +```csharp +public event PropertyChangedEventHandler? PropertyChanged +``` + +## Operators + +### `op_Implicit` + +```csharp +public static implicit operator T(Observable cell) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `cell` | [`Observable`](Observable.md) | | diff --git a/docs/guide/reference/components/Optional.md b/docs/guide/reference/components/Optional.md new file mode 100644 index 0000000000..ff2f3fbf4f --- /dev/null +++ b/docs/guide/reference/components/Optional.md @@ -0,0 +1,197 @@ +# Optional\ + +Represents either an explicit value or an unset state. + +```csharp +public readonly struct Optional +``` + +Namespace: `Microsoft.UI.Reactor`. + +## Type parameters + +| Name | Description | +| --- | --- | +| `T` | The type of value stored when the optional has a value. | + +## Properties + +### `HasValue` + +Gets a value indicating whether this optional contains an explicit value. + +```csharp +public bool HasValue // get +``` + +### `Unset` + +Gets the unset value. Equivalent to `default(Optional)`. + +```csharp +public static Optional Unset // get +``` + +### `Value` + +Gets the stored value when [`Optional.HasValue`](#hasvalue) is true. + +```csharp +public T Value // get +``` + +**Exceptions** + +| Exception | Condition | +| --- | --- | +| [`InvalidOperationException`](https://learn.microsoft.com/dotnet/api/system.invalidoperationexception) | Thrown when this optional is unset. | + +## Methods + +### `Equals` + +#### `Equals(Optional)` + +Determines whether this optional and another optional represent the same state and value. + +```csharp +public bool Equals(Optional other) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `other` | [`Optional`](Optional.md) | The optional to compare with this optional. | + +**Returns:** `true` when both optionals are unset or both contain equal values; otherwise `false`. + +#### `Equals(object?)` + +Determines whether this optional and another object represent the same state and value. + +```csharp +public override bool Equals(object? obj) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `obj` | `object?` | The object to compare with this optional. | + +**Returns:** `true` when `obj` is an equal optional; otherwise `false`. + +### `GetHashCode` + +Returns the hash code for this optional. + +```csharp +public override int GetHashCode() +``` + +**Returns:** A hash code that distinguishes unset from an explicit default value. + +### `GetValueOrDefault` + +#### `GetValueOrDefault()` + +Gets the stored value, or `default` when this optional is unset. + +```csharp +public T GetValueOrDefault() +``` + +**Returns:** The stored value when set; otherwise `default`. + +#### `GetValueOrDefault(T)` + +Gets the stored value, or the supplied fallback when this optional is unset. + +```csharp +public T GetValueOrDefault(T fallback) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `fallback` | `T` | The value to return when this optional is unset. | + +**Returns:** The stored value when set; otherwise `fallback`. + +### `Of` + +Creates an optional that contains an explicit value. + +```csharp +public static Optional Of(T value) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `value` | `T` | The value to store. For reference types, `null` is an explicit value. | + +**Returns:** An optional containing `value`. + +### `ToString` + +Returns a string representation of this optional. + +```csharp +public override string ToString() +``` + +**Returns:** `Unset` when unset; otherwise the stored value's string representation or `null`. + +## Operators + +### `op_Equality` + +Determines whether two optionals represent the same state and value. + +```csharp +public static bool operator ==(Optional left, Optional right) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `left` | [`Optional`](Optional.md) | The left optional. | +| `right` | [`Optional`](Optional.md) | The right optional. | + +**Returns:** `true` when the optionals are equal; otherwise `false`. + +### `op_Implicit` + +Converts a value to an optional that explicitly contains that value. For reference-type optionals, `with { Background = null }` becomes `Optional.Of(null)`, not [`Optional.Unset`](#unset); use [`Optional.Unset`](#unset) to express the unset state. + +```csharp +public static implicit operator Optional(T value) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `value` | `T` | The value to store. For reference types, `null` is an explicit value. | + +### `op_Inequality` + +Determines whether two optionals represent different states or values. + +```csharp +public static bool operator !=(Optional left, Optional right) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `left` | [`Optional`](Optional.md) | The left optional. | +| `right` | [`Optional`](Optional.md) | The right optional. | + +**Returns:** `true` when the optionals are not equal; otherwise `false`. diff --git a/docs/guide/reference/components/Ref.md b/docs/guide/reference/components/Ref.md new file mode 100644 index 0000000000..3f26478017 --- /dev/null +++ b/docs/guide/reference/components/Ref.md @@ -0,0 +1,33 @@ +# Ref\ + +A mutable reference that persists across renders (like React's useRef). + +```csharp +public class Ref +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Hooks](../../hooks.md) + +## Constructors + +### `Ref` + +```csharp +public Ref(T initial) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `initial` | `T` | | + +## Properties + +### `Current` + +```csharp +public T Current // get, set +``` diff --git a/docs/guide/reference/components/RenderContext.md b/docs/guide/reference/components/RenderContext.md new file mode 100644 index 0000000000..36abbd753d --- /dev/null +++ b/docs/guide/reference/components/RenderContext.md @@ -0,0 +1,151 @@ +# RenderContext + +Passed to function components and provides access to hooks. Each component instance gets its own RenderContext which tracks hook call order. + +```csharp +public sealed class RenderContext +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Components](../../components.md), [Hooks](../../hooks.md) + +## Constructors + +### `RenderContext` + +```csharp +public RenderContext() +``` + +## Methods + +### `PickFileAsync` + +Opens a single-file picker owned by this component's window. + +```csharp +public Task PickFileAsync(FilePickerOptions options) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `options` | [`FilePickerOptions`](../hosting/file-pickers.md#filepickeroptions) | | + +**Remarks** + +Not a hook: call from a UI-thread event handler, not during Render. The owner is the window whose host renders this component (for ReactorHostControl, the window it is loaded in). Throws [`InvalidOperationException`](https://learn.microsoft.com/dotnet/api/system.invalidoperationexception) once the component unmounts, its window closes or its host is disposed, or while its ReactorHostControl is not loaded. Cancellation returns null. + +### `PickFolderAsync` + +Opens a single-folder picker owned by this component's window. + +```csharp +public Task PickFolderAsync(FolderPickerOptions options) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `options` | [`FolderPickerOptions`](../hosting/file-pickers.md#folderpickeroptions) | | + +**Remarks** + +Not a hook: call from a UI-thread event handler, not during Render. The owner is the window whose host renders this component (for ReactorHostControl, the window it is loaded in). Throws [`InvalidOperationException`](https://learn.microsoft.com/dotnet/api/system.invalidoperationexception) once the component unmounts, its window closes or its host is disposed, or while its ReactorHostControl is not loaded. Cancellation returns null. + +### `PickMultipleFilesAsync` + +Opens a multiple-file picker owned by this component's window. + +```csharp +public Task> PickMultipleFilesAsync(FilePickerOptions options) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `options` | [`FilePickerOptions`](../hosting/file-pickers.md#filepickeroptions) | | + +**Remarks** + +Not a hook: call from a UI-thread event handler, not during Render. The owner is the window whose host renders this component (for ReactorHostControl, the window it is loaded in). Throws [`InvalidOperationException`](https://learn.microsoft.com/dotnet/api/system.invalidoperationexception) once the component unmounts, its window closes or its host is disposed, or while its ReactorHostControl is not loaded. Cancellation returns an empty list. + +### `PickMultipleFoldersAsync` + +Opens a multiple-folder picker owned by this component's window. + +```csharp +public Task> PickMultipleFoldersAsync(FolderPickerOptions options) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `options` | [`FolderPickerOptions`](../hosting/file-pickers.md#folderpickeroptions) | | + +**Remarks** + +Not a hook: call from a UI-thread event handler, not during Render. The owner is the window whose host renders this component (for ReactorHostControl, the window it is loaded in). Throws [`InvalidOperationException`](https://learn.microsoft.com/dotnet/api/system.invalidoperationexception) once the component unmounts, its window closes or its host is disposed, or while its ReactorHostControl is not loaded. Cancellation returns an empty list. + +### `PickSaveFileAsync` + +Opens a save-file picker owned by this component's window. + +```csharp +public Task PickSaveFileAsync(SaveFilePickerOptions options) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `options` | [`SaveFilePickerOptions`](../hosting/file-pickers.md#savefilepickeroptions) | | + +**Remarks** + +Not a hook: call from a UI-thread event handler, not during Render. The owner is the window whose host renders this component (for ReactorHostControl, the window it is loaded in). Throws [`InvalidOperationException`](https://learn.microsoft.com/dotnet/api/system.invalidoperationexception) once the component unmounts, its window closes or its host is disposed, or while its ReactorHostControl is not loaded. Cancellation returns null. Selecting a target does not create or write the file; that is the caller's responsibility. + +## Hooks + +- [`UseBreakpoint`](../hooks/UseBreakpoint.md) +- [`UseCallback`](../hooks/UseCallback.md) +- [`UseClosingGuard`](../hooks/UseClosingGuard.md) +- [`UseCollection`](../hooks/UseCollection.md) +- [`UseColorScheme`](../hooks/UseColorScheme.md) +- [`UseCommand`](../hooks/UseCommand.md) +- [`UseContext`](../hooks/UseContext.md) +- [`UseDisplays`](../hooks/UseDisplays.md) +- [`UseDpi`](../hooks/UseDpi.md) +- [`UseEffect`](../hooks/UseEffect.md) +- [`UseExternalStore`](../hooks/UseExternalStore.md) +- [`UseHighContrast`](../hooks/UseHighContrast.md) +- [`UseHighContrastScheme`](../hooks/UseHighContrastScheme.md) +- [`UseIntl`](../hooks/UseIntl.md) +- [`UseIsActive`](../hooks/UseIsActive.md) +- [`UseIsCovered`](../hooks/UseIsCovered.md) +- [`UseIsDarkTheme`](../hooks/UseIsDarkTheme.md) +- [`UseMemo`](../hooks/UseMemo.md) +- [`UseNavigation`](../hooks/UseNavigation.md) +- [`UseNavigationLifecycle`](../hooks/UseNavigationLifecycle.md) +- [`UseObservable`](../hooks/UseObservable.md) +- [`UseObservableProperty`](../hooks/UseObservableProperty.md) +- [`UseObservableTree`](../hooks/UseObservableTree.md) +- [`UseOpenWindow`](../hooks/UseOpenWindow.md) +- [`UsePersisted`](../hooks/UsePersisted.md) +- [`UseReducedMotion`](../hooks/UseReducedMotion.md) +- [`UseReducer`](../hooks/UseReducer.md) +- [`UseRef`](../hooks/UseRef.md) +- [`UseState`](../hooks/UseState.md) +- [`UseSystemBackButton`](../hooks/UseSystemBackButton.md) +- [`UseTrayIcon`](../hooks/UseTrayIcon.md) +- [`UseWindow`](../hooks/UseWindow.md) +- [`UseWindowAspectRatio`](../hooks/UseWindowAspectRatio.md) +- [`UseWindowDragMove`](../hooks/UseWindowDragMove.md) +- [`UseWindowPosition`](../hooks/UseWindowPosition.md) +- [`UseWindowSize`](../hooks/UseWindowSize.md) +- [`UseWindowState`](../hooks/UseWindowState.md) diff --git a/docs/guide/reference/components/SourceLocation.md b/docs/guide/reference/components/SourceLocation.md new file mode 100644 index 0000000000..b6fbf24fbe --- /dev/null +++ b/docs/guide/reference/components/SourceLocation.md @@ -0,0 +1,83 @@ +# SourceLocation + +Spec 010 — the C# source location that produced an [`Element`](../elements/Element.md). + +[`SourceLocation.ToString`](SourceLocation.md) / [`SourceLocation.ToShortString`](#toshortstring) keep their `file:line` forms; read [`SourceLocation.ColumnNumber`](#columnnumber) directly. + +```csharp +public readonly record struct SourceLocation(string FilePath, int LineNumber, int ColumnNumber) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Source Mapping](../../source-mapping.md) + +## Constructors + +### `SourceLocation` + +Spec 010 — the C# source location that produced an [`Element`](../elements/Element.md). + +[`SourceLocation.ToString`](SourceLocation.md) / [`SourceLocation.ToShortString`](#toshortstring) keep their `file:line` forms; read [`SourceLocation.ColumnNumber`](#columnnumber) directly. + +```csharp +public SourceLocation(string FilePath, int LineNumber, int ColumnNumber) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `FilePath` | `string` | Absolute path of the source file at compile time. Under a deterministic build (`DeterministicSourcePaths`, which this repo enables when `CI=true`) this is the *mapped* path — e.g. `/_/src/Reactor/Elements/Dsl.cs` — not a local disk path. | +| `LineNumber` | `int` | 1-based line number of the DSL call site. | +| `ColumnNumber` | `int` | 1-based column of the DSL call site on `LineNumber`, or `0` when the provider did not record one. The source-map generator reports the first character of the invoked method's name — the `B` of `Button` in `Row(Button("a"), Button("b"))`, the `T` of `TextBlock` in `Factories.TextBlock("x")` — which is what tells several factory calls on one line apart. In the rare layout where the name and its `(` sit on different lines, [`SourceLocation.LineNumber`](#linenumber) follows the paren (matching `[CallerLineNumber]`), so the column is the paren's too and the pair always names a position on the reported line. For an element stamped in argument position (a `string` converted to an element) it is the first character of the argument expression. Counted in UTF-16 code units with a tab counting as one, the convention Roslyn diagnostics and VS Code's `file:line:column` links use. | + +## Properties + +### `ColumnNumber` + +1-based column of the DSL call site on `LineNumber`, or `0` when the provider did not record one. + +The source-map generator reports the first character of the invoked method's name — the `B` of `Button` in `Row(Button("a"), Button("b"))`, the `T` of `TextBlock` in `Factories.TextBlock("x")` — which is what tells several factory calls on one line apart. In the rare layout where the name and its `(` sit on different lines, [`SourceLocation.LineNumber`](#linenumber) follows the paren (matching `[CallerLineNumber]`), so the column is the paren's too and the pair always names a position on the reported line. For an element stamped in argument position (a `string` converted to an element) it is the first character of the argument expression. + +Counted in UTF-16 code units with a tab counting as one, the convention Roslyn diagnostics and VS Code's `file:line:column` links use. + +```csharp +public int ColumnNumber // get, init +``` + +### `DeclaredName` + +The identifier the element created at this call site was assigned to, as the source-map generator saw it — `title` for `var title = TextBlock("x").Bold()`, a field or property name for an initializer, the member name for an expression-bodied member or local function. `null` for an element written inline (an argument, a collection element), for a build without source mapping, or after a hot-reload edit moved the call. + +Not stored on the location: it is looked up in the generator's static table, so it costs nothing per element and does not take part in equality. + +```csharp +public string? DeclaredName // get +``` + +### `FilePath` + +Absolute path of the source file at compile time. Under a deterministic build (`DeterministicSourcePaths`, which this repo enables when `CI=true`) this is the *mapped* path — e.g. `/_/src/Reactor/Elements/Dsl.cs` — not a local disk path. + +```csharp +public string FilePath // get, init +``` + +### `LineNumber` + +1-based line number of the DSL call site. + +```csharp +public int LineNumber // get, init +``` + +## Methods + +### `ToShortString` + +Short display form: filename + line only (`MainPage.cs:34`). + +```csharp +public string ToShortString() +``` diff --git a/docs/guide/reference/components/index.md b/docs/guide/reference/components/index.md new file mode 100644 index 0000000000..8fe07865f3 --- /dev/null +++ b/docs/guide/reference/components/index.md @@ -0,0 +1,26 @@ +# Components + +Component base classes, the render context, refs, context and error types. + +A component is a class whose `Render` method returns an element tree. These types are the building blocks every component uses. + +**Learn more:** [Components](../../components.md), [Thinking in Reactor](../../thinking-in-reactor.md), [Context](../../context.md) + +## Types + +| Type | Description | +| --- | --- | +| [Render errors](render-errors.md) | Types that describe an error thrown while a component renders. | +| [`AppContexts`](AppContexts.md) | Static context registrations shared across the Reactor core. | +| [`Callbacks`](Callbacks.md) | An opt-in, always-equal wrapper for the delegate (callback) portion of a component's props, so callback identity never forces a re-render. | +| [`Component`](Component.md) | Base class for stateful components (like React class components, but using hooks). | +| [`Component`](Component-1.md) | Base class for components that receive typed props (e.g., navigation parameters). | +| [`Context`](Context.md) | A typed, named context that can be provided to a subtree and consumed by any descendant. | +| [`ContextBase`](ContextBase.md) | Non-generic base for type-erased storage in the context scope stack. | +| [`ElementFactory`](ElementFactory.md) | Bridges WinUI's ItemsRepeater/IElementFactory to Reactor's Reconciler. | +| [`IReactorKeyed`](IReactorKeyed.md) | Identity-on-data convention for items rendered into Reactor collection elements (`TemplatedListElementBase` and `LazyStackElementBase`) and into hand-built keyed children (`FlexColumn(items.Select(... .WithKey(item)))`). | +| [`Observable`](Observable.md) | A single-value cell that raises `INotifyPropertyChanged.PropertyChanged` when `Observable.Value` is assigned a different value. | +| [`Optional`](Optional.md) | Represents either an explicit value or an unset state. | +| [`Ref`](Ref.md) | A mutable reference that persists across renders (like React's useRef). | +| [`RenderContext`](RenderContext.md) | Passed to function components and provides access to hooks. | +| [`SourceLocation`](SourceLocation.md) | Spec 010 — the C# source location that produced an `Element`. | diff --git a/docs/guide/reference/components/render-errors.md b/docs/guide/reference/components/render-errors.md new file mode 100644 index 0000000000..ffee02a332 --- /dev/null +++ b/docs/guide/reference/components/render-errors.md @@ -0,0 +1,142 @@ +# Render errors + +Types that describe an error thrown while a component renders. + +**Learn more:** [Rules of Reactor](../../rules-of-reactor.md), [Advanced Patterns](../../advanced.md) + +## `HookOrderException` + +Thrown when a component's hook call sequence diverges from the previous render's sequence — either a hook is called at a different index, or the hook type at a given index doesn't match what was previously declared. + +In normal operation this is a programming bug (hooks must be called in the same order every render). During Hot Reload, however, an edit that reorders or changes hook types is the \*expected\* outcome of the user editing their code — so the host catches this exception, runs cleanups on the surviving RenderContext, resets its hook state, and re-renders. State is lost (we cannot reliably re-key surviving hook values to a shape that may have changed), but the app keeps running rather than hard-failing the dev loop. + +Derives from [`InvalidOperationException`](https://learn.microsoft.com/dotnet/api/system.invalidoperationexception) so existing \`catch (InvalidOperationException)\` handlers around component render continue to work; the host's render catch sniffs the more specific type to gate the hot-reload recovery path. + +```csharp +public sealed class HookOrderException : InvalidOperationException +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`InvalidOperationException`](https://learn.microsoft.com/dotnet/api/system.invalidoperationexception). + +### Constructors + +#### `HookOrderException` + +```csharp +public HookOrderException(string message) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `message` | `string` | | + +## `RenderError` + +A render-time exception Reactor caught, handed to a [`RenderErrorHandler`](#rendererrorhandler). + +```csharp +public sealed class RenderError +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Properties + +#### `ComponentName` + +The failing component's type name, when known. + +```csharp +public string? ComponentName // get +``` + +#### `Exception` + +The exception Reactor caught. + +```csharp +public Exception Exception // get +``` + +#### `IsHostLevel` + +Where the failure sits. For a displayable error: `true` when the returned element replaces the host's whole content (root render, reconcile, root effects); `false` when it replaces only the failing component's slot in the tree. For [`RenderErrorSource.Cleanup`](#values), where no element is shown: `true` for a cleanup registered by the host's root component, `false` for one registered by a child component. + +```csharp +public bool IsHostLevel // get +``` + +#### `IsPropagationRequested` + +Whether [`RenderError.Propagate`](#propagate) has been called. + +```csharp +public bool IsPropagationRequested // get +``` + +#### `Source` + +Which part of the render pass threw. + +```csharp +public RenderErrorSource Source // get +``` + +### Methods + +#### `Propagate` + +Show no fallback and route the exception to the app's unhandled-exception path instead: [`ReactorApp.AppLogger`](../hosting/ReactorApp.md#applogger) and [`ReactorApplication.OnUnhandledException`](../hosting/ReactorApplication.md#onunhandledexception). The handler's return value is ignored. Has no effect if the handler throws afterwards. + +```csharp +public void Propagate() +``` + +**Remarks** + +When [`ReactorApplication.OnUnhandledException`](../hosting/ReactorApplication.md#onunhandledexception) returns `true`, nothing is shown where the failure happened and the app keeps running. Otherwise the exception is rethrown (stack preserved) out of whatever ran the render: + +- Re-renders, and every render of a [`ReactorHostControl`](../hosting/ReactorHostControl.md), run from a `DispatcherQueue` callback. WinUI ends the process for an exception that escapes one, without raising `Application.UnhandledException` or `AppDomain.UnhandledException` (microsoft/microsoft-ui-xaml#8940). The [`ReactorApplication.OnUnhandledException`](../hosting/ReactorApplication.md#onunhandledexception) call Reactor makes first is therefore the only managed hook the app gets, and returning `false` (or not setting it) ends the process. +- The first render of a [`ReactorHost`](../hosting/ReactorHost.md) runs synchronously inside `Mount` / `ReactorApp.OpenWindow`, so there the exception is thrown to that caller. + +[`ReactorApplication.OnUnhandledException`](../hosting/ReactorApplication.md#onunhandledexception) is static and is called even when the app's `Application` is not a [`ReactorApplication`](../hosting/ReactorApplication.md) — for example a XAML app that hosts Reactor content in [`ReactorHostControl`](../hosting/ReactorHostControl.md). For such an app it is the only way to observe a propagated render error. + +## `RenderErrorHandler` + +Replaces Reactor's built-in render-error fallback. Called on the UI thread with the exception Reactor caught. + +```csharp +public delegate Element? RenderErrorHandler(RenderError error) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Remarks + +Set it app-wide with [`ReactorApp.DefaultRenderErrorHandler`](../hosting/ReactorApp.md#defaultrendererrorhandler), per window with [`WindowSpec.RenderErrorHandler`](../hosting/WindowSpec.md#rendererrorhandler), or per host with [`ReactorHost.RenderErrorHandler`](../hosting/ReactorHost.md#rendererrorhandler) / [`ReactorHostControl.RenderErrorHandler`](../hosting/ReactorHostControl.md#rendererrorhandler). A host's own handler wins; otherwise the app-wide default is used. Exceptions caught by an `ErrorBoundary` are handled by that boundary and never reach this handler. + +Failure is closed, not open: if the handler throws, or the element it returns throws while rendering, Reactor shows a neutral "Something went wrong." message without exception details, and does not call the handler again for that failure. + +The handler can run many times for the same fault. Reactor does not latch a failing component: every later render retries it (that retry is how recovery works), and if it throws again the handler is called again — once per re-render of a failing child, and once per host render for a host-level failure. De-duplicate side effects such as telemetry or logging, for example by remembering the exceptions already recorded. + +## `RenderErrorSource` + +Where a render error handled by a [`RenderErrorHandler`](#rendererrorhandler) came from. + +```csharp +public enum RenderErrorSource +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `RootRender` | `0` | The host's root component `Render()` or root render function threw. | +| `ComponentRender` | `1` | A child component's `Render()` threw (in-tree placeholder). | +| `Reconcile` | `2` | The commit phase threw: reconciling the element tree into native controls (mount/update/unmount), installing the result in the host, or a host callback run after the render pass such as `OnRenderComplete`. | +| `Effects` | `3` | An effect body, or an effect cleanup run while flushing effects, threw. | +| `Cleanup` | `4` | An effect cleanup threw while the host was being disposed (window closed, host control disposed). Nothing can be displayed at that point, so the handler's return value is ignored; it is a report-only notification. Remaining cleanups still run. | diff --git a/docs/guide/reference/controls/PropertyGridComponent.md b/docs/guide/reference/controls/PropertyGridComponent.md new file mode 100644 index 0000000000..551ef59063 --- /dev/null +++ b/docs/guide/reference/controls/PropertyGridComponent.md @@ -0,0 +1,27 @@ +# PropertyGridComponent + +The core PropertyGrid component. Uses FlexColumn layout with FlexRow per property row. Category headers and property expand/collapse use a single shared state dictionary. + +```csharp +public class PropertyGridComponent +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +**Learn more:** [Controls](../../controls.md) + +## Constructors + +### `PropertyGridComponent` + +```csharp +public PropertyGridComponent() +``` + +## Methods + +### `Render` + +```csharp +public override Element Render() +``` diff --git a/docs/guide/reference/controls/PropertyGridDefaults.md b/docs/guide/reference/controls/PropertyGridDefaults.md new file mode 100644 index 0000000000..9b19d6fc63 --- /dev/null +++ b/docs/guide/reference/controls/PropertyGridDefaults.md @@ -0,0 +1,73 @@ +# PropertyGridDefaults + +Default rendering templates for PropertyGrid — compact Windows 11 layout. Uses FlexRow per property row: fixed 160px label, grow-1 editor. + +```csharp +public static class PropertyGridDefaults +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +**Learn more:** [Controls](../../controls.md) + +## Methods + +### `ArrayItemTemplate` + +```csharp +public static Element ArrayItemTemplate(int index, string summary, bool isExpanded, Action onExpandedChanged, Action? onMoveUp, Action? onMoveDown, Action? onRemove) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `index` | `int` | | +| `summary` | `string` | | +| `isExpanded` | `bool` | | +| `onExpandedChanged` | `Action` | | +| `onMoveUp` | `Action?` | | +| `onMoveDown` | `Action?` | | +| `onRemove` | `Action?` | | + +### `ArrayToolbarTemplate` + +```csharp +public static Element ArrayToolbarTemplate(string propertyName, int count, Func? onAdd) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `propertyName` | `string` | | +| `count` | `int` | | +| `onAdd` | `Func?` | | + +### `PropertyLabelTemplate` + +```csharp +public static Element PropertyLabelTemplate(FieldDescriptor descriptor, int indentLevel) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `descriptor` | [`FieldDescriptor`](../data/descriptors.md#fielddescriptor) | | +| `indentLevel` | `int` | | + +### `PropertyRowTemplate` + +```csharp +public static Element PropertyRowTemplate(FieldDescriptor descriptor, Element label, Element editor, int indentLevel) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `descriptor` | [`FieldDescriptor`](../data/descriptors.md#fielddescriptor) | | +| `label` | [`Element`](../elements/Element.md) | | +| `editor` | [`Element`](../elements/Element.md) | | +| `indentLevel` | `int` | | diff --git a/docs/guide/reference/controls/collection-items.md b/docs/guide/reference/controls/collection-items.md new file mode 100644 index 0000000000..d12c6338d5 --- /dev/null +++ b/docs/guide/reference/controls/collection-items.md @@ -0,0 +1,161 @@ +# Collection items + +Records and enums for tree, swipe and items view content. + +**Learn more:** [Collections](../../collections.md), [Controls](../../controls.md) + +## `ItemsViewLayoutKind` + +```csharp +public enum ItemsViewLayoutKind +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `StackLayout` | `0` | | +| `LinedFlowLayout` | `1` | | +| `UniformGridLayout` | `2` | | + +## `SwipeItemData` + +```csharp +public record SwipeItemData(string Text, Action? OnInvoked = null, IconSource? IconSource = null, Brush? Background = null, Brush? Foreground = null, SwipeBehaviorOnInvoked BehaviorOnInvoked = default) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `SwipeItemData` + +```csharp +public SwipeItemData(string Text, Action? OnInvoked = null, IconSource? IconSource = null, Brush? Background = null, Brush? Foreground = null, SwipeBehaviorOnInvoked BehaviorOnInvoked = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Text` | `string` | | | +| `OnInvoked` | `Action?` | `null` | | +| `IconSource` | `IconSource?` | `null` | | +| `Background` | `Brush?` | `null` | | +| `Foreground` | `Brush?` | `null` | | +| `BehaviorOnInvoked` | `SwipeBehaviorOnInvoked` | `default` | | + +### Properties + +#### `Background` + +```csharp +public Brush? Background // get, init +``` + +#### `BehaviorOnInvoked` + +```csharp +public SwipeBehaviorOnInvoked BehaviorOnInvoked // get, init +``` + +#### `Foreground` + +```csharp +public Brush? Foreground // get, init +``` + +#### `IconSource` + +```csharp +public IconSource? IconSource // get, init +``` + +#### `OnInvoked` + +```csharp +public Action? OnInvoked // get, init +``` + +#### `Text` + +```csharp +public string Text // get, init +``` + +## `TemplatedControlKind` + +Which WinUI control type a templated list element targets. + +```csharp +public enum TemplatedControlKind +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `ListView` | `0` | | +| `GridView` | `1` | | +| `FlipView` | `2` | | + +## `TreeViewNodeData` + +```csharp +public record TreeViewNodeData(string Content, TreeViewNodeData[]? Children = null) : IBindableCustomPropertyImplementation +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `TreeViewNodeData` + +```csharp +public TreeViewNodeData(string Content, TreeViewNodeData[]? Children = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Content` | `string` | | | +| `Children` | [`TreeViewNodeData[]?`](#treeviewnodedata) | `null` | | + +### Properties + +#### `Children` + +```csharp +public TreeViewNodeData[]? Children // get, init +``` + +#### `Content` + +```csharp +public string Content // get, init +``` + +#### `ContentElement` + +Optional Reactor element to render as the node's visual content. When null, a TextBlock showing Content is rendered. + +```csharp +public Element? ContentElement // get, init +``` + +> **Obsolete.** Use the typed UI.TreeView\(items, keySelector, childrenSelector, viewBuilder) overload (the hierarchical peer of ListView\); a pre-built Element cannot be hosted in a node-mode TreeViewNode. See issue #447. + +**Remarks** + +Deprecated. WinUI's node-mode `TreeView` stringifies node content and cannot host a pre-built `UIElement`, so rich per-node visuals must come from a template (a `data → Element` function), never an element instance. Use the typed, data-driven `UI.TreeView(items, keySelector, childrenSelector, viewBuilder)` — the hierarchical peer of `ListView` — instead. The legacy path stays functional for back-compat but renders blank under virtualization recycling. + +#### `IsExpanded` + +```csharp +public bool IsExpanded // get, init +``` diff --git a/docs/guide/reference/controls/icons.md b/docs/guide/reference/controls/icons.md new file mode 100644 index 0000000000..90dd546c53 --- /dev/null +++ b/docs/guide/reference/controls/icons.md @@ -0,0 +1,192 @@ +# Icon data + +Records that describe an icon. + +**Learn more:** [Controls](../../controls.md) + +## `BitmapIconData` + +```csharp +public record BitmapIconData(Uri Source, bool ShowAsMonochrome = true) : IconData +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`IconData`](#icondata). + +### Constructors + +#### `BitmapIconData` + +```csharp +public BitmapIconData(Uri Source, bool ShowAsMonochrome = true) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Source` | `Uri` | | | +| `ShowAsMonochrome` | `bool` | `true` | | + +### Properties + +#### `ShowAsMonochrome` + +```csharp +public bool ShowAsMonochrome // get, init +``` + +#### `Source` + +```csharp +public Uri Source // get, init +``` + +## `FontIconData` + +```csharp +public record FontIconData(string Glyph, string? FontFamily = null, double? FontSize = null) : IconData +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`IconData`](#icondata). + +### Constructors + +#### `FontIconData` + +```csharp +public FontIconData(string Glyph, string? FontFamily = null, double? FontSize = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Glyph` | `string` | | | +| `FontFamily` | `string?` | `null` | | +| `FontSize` | `double?` | `null` | | + +### Properties + +#### `FontFamily` + +```csharp +public string? FontFamily // get, init +``` + +#### `FontSize` + +```csharp +public double? FontSize // get, init +``` + +#### `Glyph` + +```csharp +public string Glyph // get, init +``` + +## `IconData` + +```csharp +public abstract record IconData +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `IconData` + +```csharp +protected IconData() +``` + +## `ImageIconData` + +```csharp +public record ImageIconData(Uri Source) : IconData +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`IconData`](#icondata). + +### Constructors + +#### `ImageIconData` + +```csharp +public ImageIconData(Uri Source) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Source` | `Uri` | | + +### Properties + +#### `Source` + +```csharp +public Uri Source // get, init +``` + +## `PathIconData` + +```csharp +public record PathIconData(string Data) : IconData +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`IconData`](#icondata). + +### Constructors + +#### `PathIconData` + +```csharp +public PathIconData(string Data) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Data` | `string` | | + +### Properties + +#### `Data` + +```csharp +public string Data // get, init +``` + +## `SymbolIconData` + +```csharp +public record SymbolIconData(string Symbol) : IconData +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`IconData`](#icondata). + +### Constructors + +#### `SymbolIconData` + +```csharp +public SymbolIconData(string Symbol) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Symbol` | `string` | | + +### Properties + +#### `Symbol` + +```csharp +public string Symbol // get, init +``` diff --git a/docs/guide/reference/controls/index.md b/docs/guide/reference/controls/index.md new file mode 100644 index 0000000000..e339a28f16 --- /dev/null +++ b/docs/guide/reference/controls/index.md @@ -0,0 +1,21 @@ +# Controls + +Item data records and support types for the property grid, masked input and virtual lists. + +**Learn more:** [Controls](../../controls.md), [Collections](../../collections.md) + +## Types + +| Type | Description | +| --- | --- | +| [Collection items](collection-items.md) | Records and enums for tree, swipe and items view content. | +| [Icon data](icons.md) | Records that describe an icon. | +| [Masked input](masked-input.md) | The mask engine and formatters behind MaskedTextBox. | +| [Menu and command bar items](menu-items.md) | Records that describe menu, menu bar, command bar and keyboard accelerator items. | +| [Navigation items](navigation-items.md) | Records that describe items of navigation controls. | +| [Property grid attributes](property-grid-attributes.md) | Attributes that change how the property grid shows a property. | +| [Property grid templates](property-grid-templates.md) | Delegates and metadata the property grid uses to build its rows. | +| [Rich text](rich-text.md) | Inline records for rich text blocks. | +| [Virtual list](virtual-list.md) | Support types for the virtual list. | +| [`PropertyGridComponent`](PropertyGridComponent.md) | The core PropertyGrid component. | +| [`PropertyGridDefaults`](PropertyGridDefaults.md) | Default rendering templates for PropertyGrid — compact Windows 11 layout. | diff --git a/docs/guide/reference/controls/masked-input.md b/docs/guide/reference/controls/masked-input.md new file mode 100644 index 0000000000..1e67cf28cc --- /dev/null +++ b/docs/guide/reference/controls/masked-input.md @@ -0,0 +1,490 @@ +# Masked input + +The mask engine and formatters behind MaskedTextBox. + +**Learn more:** [Controls](../../controls.md) + +## `FormatResult` + +Result returned by an [`InputFormatter`](#inputformatter): the transformed output text paired with the adjusted cursor position. + +```csharp +public readonly record struct FormatResult(string Output, int CursorPos) +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Constructors + +#### `FormatResult` + +Result returned by an [`InputFormatter`](#inputformatter): the transformed output text paired with the adjusted cursor position. + +```csharp +public FormatResult(string Output, int CursorPos) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Output` | `string` | The transformed output text. | +| `CursorPos` | `int` | The cursor position in the output. | + +### Properties + +#### `CursorPos` + +The cursor position in the output. + +```csharp +public int CursorPos // get, init +``` + +#### `Output` + +The transformed output text. + +```csharp +public string Output // get, init +``` + +## `FormatterPipeline` + +Chains multiple formatters into a pipeline. + +```csharp +public sealed class FormatterPipeline +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Constructors + +#### `FormatterPipeline` + +```csharp +public FormatterPipeline(params InputFormatter[] formatters) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `formatters` | [`InputFormatter[]`](#inputformatter) | | + +### Methods + +#### `Format` + +Runs all formatters in sequence. + +```csharp +public FormatResult Format(string input, int cursorPos) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `input` | `string` | | +| `cursorPos` | `int` | | + +#### `Parse` + +Parses a formatted value through all formatters in reverse order. + +```csharp +public string Parse(string formatted) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `formatted` | `string` | | + +## `InputFormatter` + +Base class for input formatters that transform text as the user types. + +```csharp +public abstract class InputFormatter +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Constructors + +#### `InputFormatter` + +```csharp +protected InputFormatter() +``` + +### Properties + +#### `LowerCase` + +Force lowercase. + +```csharp +public static InputFormatter LowerCase // get +``` + +#### `PhoneUS` + +US phone format: (555) 123-4567 + +```csharp +public static InputFormatter PhoneUS // get +``` + +#### `TitleCase` + +Title case (first letter of each word uppercase). + +```csharp +public static InputFormatter TitleCase // get +``` + +#### `TrimWhitespace` + +Trim leading and trailing whitespace. + +```csharp +public static InputFormatter TrimWhitespace // get +``` + +#### `UpperCase` + +Force uppercase. + +```csharp +public static InputFormatter UpperCase // get +``` + +### Methods + +#### `AllowOnly` + +Only allow characters matching the regex. + +```csharp +public static InputFormatter AllowOnly(string regex) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `regex` | `string` | | + +#### `Currency` + +Currency format: $1,234.56 + +```csharp +public static InputFormatter Currency(string symbol = "$") +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `symbol` | `string` | `"$"` | | + +#### `Custom` + +Custom formatter with format and parse functions. + +```csharp +public static InputFormatter Custom(Func format, Func parse) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `format` | `Func` | | +| `parse` | `Func` | | + +#### `DenyOnly` + +Remove characters matching the regex. + +```csharp +public static InputFormatter DenyOnly(string regex) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `regex` | `string` | | + +#### `Format` + +Formats the input and adjusts cursor position. + +```csharp +public abstract FormatResult Format(string input, int cursorPos) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `input` | `string` | | +| `cursorPos` | `int` | | + +#### `MaxLength` + +Truncate at n characters. + +```csharp +public static InputFormatter MaxLength(int n) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `n` | `int` | | + +#### `Parse` + +Parses a formatted value back to a raw model value. Default implementation returns the formatted value as-is. + +```csharp +public virtual string Parse(string formatted) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `formatted` | `string` | | + +#### `PhoneIntl` + +International phone with configurable country code. + +```csharp +public static InputFormatter PhoneIntl(string countryCode = "+1") +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `countryCode` | `string` | `"+1"` | | + +## `MaskEngine` + +Engine that parses mask patterns and applies them to input strings. + +Mask tokens: 0 = required digit 9 = optional digit A = required letter a = optional letter \* = required alphanumeric All others = literal (auto-insert) + +```csharp +public sealed class MaskEngine +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Constructors + +#### `MaskEngine` + +```csharp +public MaskEngine(string mask) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `mask` | `string` | | + +### Properties + +#### `Length` + +Number of tokens in the mask. + +```csharp +public int Length // get +``` + +#### `Mask` + +The original mask pattern. + +```csharp +public string Mask // get +``` + +### Methods + +#### `Apply` + +Applies the mask to raw input, producing a formatted output. Literal characters are auto-inserted at the correct positions. + +```csharp +public string Apply(string input, char placeholder = '_') +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `input` | `string` | | | +| `placeholder` | `char` | `'_'` | | + +#### `GetRawValue` + +Extracts the raw value from a formatted string by stripping literals and placeholders. + +```csharp +public string GetRawValue(string formatted, char placeholder = '_') +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `formatted` | `string` | | | +| `placeholder` | `char` | `'_'` | | + +#### `IsComplete` + +Returns true if all required slots are filled. + +```csharp +public bool IsComplete(string formatted, char placeholder = '_') +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `formatted` | `string` | | | +| `placeholder` | `char` | `'_'` | | + +#### `IsLiteral` + +Returns true if the position is a literal position. + +```csharp +public bool IsLiteral(int position) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `position` | `int` | | + +#### `NextInputPosition` + +Finds the next non-literal position at or after the given position. + +```csharp +public int NextInputPosition(int position) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `position` | `int` | | + +#### `PreviousInputPosition` + +Finds the previous non-literal position at or before the given position. + +```csharp +public int PreviousInputPosition(int position) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `position` | `int` | | + +## `MaskPreset` + +Common mask presets for standard formats. + +```csharp +public static class MaskPreset +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Fields + +#### `CreditCard` + +Credit card: 0000 0000 0000 0000 + +```csharp +public const string CreditCard = "0000 0000 0000 0000" +``` + +#### `Date` + +Date: 00/00/0000 + +```csharp +public const string Date = "00/00/0000" +``` + +#### `IPv4` + +IPv4: 099.099.099.099 + +```csharp +public const string IPv4 = "099.099.099.099" +``` + +#### `PhoneUS` + +US phone: (000) 000-0000 + +```csharp +public const string PhoneUS = "(000) 000-0000" +``` + +#### `SSN` + +SSN: 000-00-0000 + +```csharp +public const string SSN = "000-00-0000" +``` + +#### `Time` + +Time: 00:00 + +```csharp +public const string Time = "00:00" +``` + +#### `ZipCode` + +ZIP code: 00000 + +```csharp +public const string ZipCode = "00000" +``` + +#### `ZipCodePlus4` + +ZIP+4: 00000-0000 + +```csharp +public const string ZipCodePlus4 = "00000-0000" +``` diff --git a/docs/guide/reference/controls/menu-items.md b/docs/guide/reference/controls/menu-items.md new file mode 100644 index 0000000000..64dc0e6e47 --- /dev/null +++ b/docs/guide/reference/controls/menu-items.md @@ -0,0 +1,539 @@ +# Menu and command bar items + +Records that describe menu, menu bar, command bar and keyboard accelerator items. + +**Learn more:** [Controls](../../controls.md), [Commanding](../../commanding.md) + +## `AppBarButtonData` + +```csharp +public record AppBarButtonData(string Label, Action? OnClick = null, string? Icon = null) : AppBarItemBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`AppBarItemBase`](#appbaritembase). + +### Constructors + +#### `AppBarButtonData` + +```csharp +public AppBarButtonData(string Label, Action? OnClick = null, string? Icon = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Label` | `string` | | | +| `OnClick` | `Action?` | `null` | | +| `Icon` | `string?` | `null` | | + +### Properties + +#### `AccessKey` + +```csharp +public string? AccessKey // get, init +``` + +#### `Description` + +```csharp +public string? Description // get, init +``` + +#### `Icon` + +```csharp +public string? Icon // get, init +``` + +#### `IconElement` + +```csharp +public IconData? IconElement // get, init +``` + +#### `IsEnabled` + +```csharp +public bool IsEnabled // get, init +``` + +#### `KeyboardAccelerators` + +```csharp +public KeyboardAcceleratorData[]? KeyboardAccelerators // get, init +``` + +#### `Label` + +```csharp +public string Label // get, init +``` + +#### `OnClick` + +```csharp +public Action? OnClick // get, init +``` + +## `AppBarItemBase` + +```csharp +public abstract record AppBarItemBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `AppBarItemBase` + +```csharp +protected AppBarItemBase() +``` + +### Properties + +#### `CallSite` + +Where this command was created in C#, stamped by the source map on the `AppBarButton(…)` / `AppBarToggleButton(…)` / `AppBarSeparator()` factory call (the same mechanism as [`Element.CallSite`](../elements/Element.md#callsite)). The realized command publishes it for inspectors. Not part of equality, like [`Element.CallSite`](../elements/Element.md#callsite). + +```csharp +public SourceLocation? CallSite // get, init +``` + +## `AppBarSeparatorData` + +```csharp +public record AppBarSeparatorData : AppBarItemBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`AppBarItemBase`](#appbaritembase). + +### Constructors + +#### `AppBarSeparatorData` + +```csharp +public AppBarSeparatorData() +``` + +## `AppBarToggleButtonData` + +```csharp +public record AppBarToggleButtonData(string Label, bool IsChecked = false, Action? OnIsCheckedChanged = null, string? Icon = null) : AppBarItemBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`AppBarItemBase`](#appbaritembase). + +### Constructors + +#### `AppBarToggleButtonData` + +```csharp +public AppBarToggleButtonData(string Label, bool IsChecked = false, Action? OnIsCheckedChanged = null, string? Icon = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Label` | `string` | | | +| `IsChecked` | `bool` | `false` | | +| `OnIsCheckedChanged` | `Action?` | `null` | | +| `Icon` | `string?` | `null` | | + +### Properties + +#### `Icon` + +```csharp +public string? Icon // get, init +``` + +#### `IconElement` + +```csharp +public IconData? IconElement // get, init +``` + +#### `IsChecked` + +```csharp +public bool IsChecked // get, init +``` + +#### `Label` + +```csharp +public string Label // get, init +``` + +#### `OnIsCheckedChanged` + +```csharp +public Action? OnIsCheckedChanged // get, init +``` + +## `KeyboardAcceleratorData` + +```csharp +public record KeyboardAcceleratorData(VirtualKey Key, VirtualKeyModifiers Modifiers = default) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `KeyboardAcceleratorData` + +```csharp +public KeyboardAcceleratorData(VirtualKey Key, VirtualKeyModifiers Modifiers = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Key` | `VirtualKey` | | | +| `Modifiers` | `VirtualKeyModifiers` | `default` | | + +### Properties + +#### `Key` + +```csharp +public VirtualKey Key // get, init +``` + +#### `Modifiers` + +```csharp +public VirtualKeyModifiers Modifiers // get, init +``` + +## `MenuBarItemData` + +```csharp +public record MenuBarItemData(string Title, MenuFlyoutItemBase[] Items) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `MenuBarItemData` + +```csharp +public MenuBarItemData(string Title, MenuFlyoutItemBase[] Items) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Title` | `string` | | +| `Items` | [`MenuFlyoutItemBase[]`](#menuflyoutitembase) | | + +### Properties + +#### `Items` + +```csharp +public MenuFlyoutItemBase[] Items // get, init +``` + +#### `Title` + +```csharp +public string Title // get, init +``` + +## `MenuFlyoutItemBase` + +```csharp +public abstract record MenuFlyoutItemBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `MenuFlyoutItemBase` + +```csharp +protected MenuFlyoutItemBase() +``` + +### Properties + +#### `CallSite` + +Where this item was created in C#, stamped by the source map on the `MenuItem(…)` / `ToggleMenuItem(…)` / … factory call (the same mechanism as [`Element.CallSite`](../elements/Element.md#callsite)). The realized menu item publishes it for inspectors. Not part of equality, like [`Element.CallSite`](../elements/Element.md#callsite). + +```csharp +public SourceLocation? CallSite // get, init +``` + +## `MenuFlyoutItemData` + +```csharp +public record MenuFlyoutItemData(string Text, Action? OnClick = null, string? Icon = null) : MenuFlyoutItemBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`MenuFlyoutItemBase`](#menuflyoutitembase). + +### Constructors + +#### `MenuFlyoutItemData` + +```csharp +public MenuFlyoutItemData(string Text, Action? OnClick = null, string? Icon = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Text` | `string` | | | +| `OnClick` | `Action?` | `null` | | +| `Icon` | `string?` | `null` | | + +### Properties + +#### `AccessKey` + +```csharp +public string? AccessKey // get, init +``` + +#### `Description` + +```csharp +public string? Description // get, init +``` + +#### `Icon` + +```csharp +public string? Icon // get, init +``` + +#### `IconElement` + +```csharp +public IconData? IconElement // get, init +``` + +#### `IsEnabled` + +```csharp +public bool IsEnabled // get, init +``` + +#### `KeyboardAccelerators` + +```csharp +public KeyboardAcceleratorData[]? KeyboardAccelerators // get, init +``` + +#### `OnClick` + +```csharp +public Action? OnClick // get, init +``` + +#### `Text` + +```csharp +public string Text // get, init +``` + +## `MenuFlyoutSeparatorData` + +```csharp +public record MenuFlyoutSeparatorData : MenuFlyoutItemBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`MenuFlyoutItemBase`](#menuflyoutitembase). + +### Constructors + +#### `MenuFlyoutSeparatorData` + +```csharp +public MenuFlyoutSeparatorData() +``` + +## `MenuFlyoutSubItemData` + +```csharp +public record MenuFlyoutSubItemData(string Text, MenuFlyoutItemBase[] Items, string? Icon = null) : MenuFlyoutItemBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`MenuFlyoutItemBase`](#menuflyoutitembase). + +### Constructors + +#### `MenuFlyoutSubItemData` + +```csharp +public MenuFlyoutSubItemData(string Text, MenuFlyoutItemBase[] Items, string? Icon = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Text` | `string` | | | +| `Items` | [`MenuFlyoutItemBase[]`](#menuflyoutitembase) | | | +| `Icon` | `string?` | `null` | | + +### Properties + +#### `Icon` + +```csharp +public string? Icon // get, init +``` + +#### `IconElement` + +```csharp +public IconData? IconElement // get, init +``` + +#### `Items` + +```csharp +public MenuFlyoutItemBase[] Items // get, init +``` + +#### `Text` + +```csharp +public string Text // get, init +``` + +## `RadioMenuFlyoutItemData` + +```csharp +public record RadioMenuFlyoutItemData(string Text, string GroupName, bool IsChecked = false, Action? OnClick = null, string? Icon = null) : MenuFlyoutItemBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`MenuFlyoutItemBase`](#menuflyoutitembase). + +### Constructors + +#### `RadioMenuFlyoutItemData` + +```csharp +public RadioMenuFlyoutItemData(string Text, string GroupName, bool IsChecked = false, Action? OnClick = null, string? Icon = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Text` | `string` | | | +| `GroupName` | `string` | | | +| `IsChecked` | `bool` | `false` | | +| `OnClick` | `Action?` | `null` | | +| `Icon` | `string?` | `null` | | + +### Properties + +#### `GroupName` + +```csharp +public string GroupName // get, init +``` + +#### `Icon` + +```csharp +public string? Icon // get, init +``` + +#### `IconElement` + +```csharp +public IconData? IconElement // get, init +``` + +#### `IsChecked` + +```csharp +public bool IsChecked // get, init +``` + +#### `OnClick` + +```csharp +public Action? OnClick // get, init +``` + +#### `Text` + +```csharp +public string Text // get, init +``` + +## `ToggleMenuFlyoutItemData` + +```csharp +public record ToggleMenuFlyoutItemData(string Text, bool IsChecked = false, Action? OnIsCheckedChanged = null, string? Icon = null) : MenuFlyoutItemBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`MenuFlyoutItemBase`](#menuflyoutitembase). + +### Constructors + +#### `ToggleMenuFlyoutItemData` + +```csharp +public ToggleMenuFlyoutItemData(string Text, bool IsChecked = false, Action? OnIsCheckedChanged = null, string? Icon = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Text` | `string` | | | +| `IsChecked` | `bool` | `false` | | +| `OnIsCheckedChanged` | `Action?` | `null` | | +| `Icon` | `string?` | `null` | | + +### Properties + +#### `Icon` + +```csharp +public string? Icon // get, init +``` + +#### `IconElement` + +```csharp +public IconData? IconElement // get, init +``` + +#### `IsChecked` + +```csharp +public bool IsChecked // get, init +``` + +#### `OnIsCheckedChanged` + +```csharp +public Action? OnIsCheckedChanged // get, init +``` + +#### `Text` + +```csharp +public string Text // get, init +``` diff --git a/docs/guide/reference/controls/navigation-items.md b/docs/guide/reference/controls/navigation-items.md new file mode 100644 index 0000000000..2a0c1d3b36 --- /dev/null +++ b/docs/guide/reference/controls/navigation-items.md @@ -0,0 +1,267 @@ +# Navigation items + +Records that describe items of navigation controls. + +**Learn more:** [Controls](../../controls.md) + +## `BreadcrumbBarItemData` + +```csharp +public record BreadcrumbBarItemData(string Label, object? Tag = null) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `BreadcrumbBarItemData` + +```csharp +public BreadcrumbBarItemData(string Label, object? Tag = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Label` | `string` | | | +| `Tag` | `object?` | `null` | | + +### Properties + +#### `Label` + +```csharp +public string Label // get, init +``` + +#### `Tag` + +```csharp +public object? Tag // get, init +``` + +## `NavigationViewItemData` + +```csharp +public record NavigationViewItemData(string Content, string? Icon = null, string? Tag = null) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `NavigationViewItemData` + +```csharp +public NavigationViewItemData(string Content, string? Icon = null, string? Tag = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Content` | `string` | | | +| `Icon` | `string?` | `null` | | +| `Tag` | `string?` | `null` | | + +### Properties + +#### `Children` + +```csharp +public NavigationViewItemData[]? Children // get, init +``` + +#### `Content` + +```csharp +public string Content // get, init +``` + +#### `Icon` + +```csharp +public string? Icon // get, init +``` + +#### `IconElement` + +```csharp +public IconData? IconElement // get, init +``` + +#### `IsHeader` + +```csharp +public bool IsHeader // get, init +``` + +#### `Tag` + +```csharp +public string? Tag // get, init +``` + +## `PivotItemData` + +```csharp +public record PivotItemData(string Header, Element Content) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `PivotItemData` + +```csharp +public PivotItemData(string Header, Element Content) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Header` | `string` | | +| `Content` | [`Element`](../elements/Element.md) | | + +### Properties + +#### `Content` + +```csharp +public Element Content // get, init +``` + +#### `Header` + +```csharp +public string Header // get, init +``` + +## `SelectorBarItemData` + +```csharp +public record SelectorBarItemData(string Text, string? Icon = null) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `SelectorBarItemData` + +```csharp +public SelectorBarItemData(string Text, string? Icon = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Text` | `string` | | | +| `Icon` | `string?` | `null` | | + +### Properties + +#### `Icon` + +```csharp +public string? Icon // get, init +``` + +#### `Text` + +```csharp +public string Text // get, init +``` + +## `TabViewItemData` + +```csharp +public record TabViewItemData(string Header, Element Content) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `TabViewItemData` + +```csharp +public TabViewItemData(string Header, Element Content) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Header` | `string` | | +| `Content` | [`Element`](../elements/Element.md) | | + +### Properties + +#### `Content` + +```csharp +public Element Content // get, init +``` + +#### `Header` + +```csharp +public string Header // get, init +``` + +#### `Icon` + +```csharp +public string? Icon // get, init +``` + +#### `IsClosable` + +```csharp +public bool IsClosable // get, init +``` + +#### `IsPinnable` + +Spec 045 §2.2 — when true, the reconciler renders a small "pin" affordance in the tab header chrome alongside the close X. Used by the docking pipeline for ToolWindow tabs whose CanAutoHide=true. + +```csharp +public bool IsPinnable // get, init +``` + +#### `IsPinned` + +Indicates whether the pin button should render as already-pinned (glyph ) or unpinned (). Only consulted when IsPinnable is true. + +```csharp +public bool IsPinned // get, init +``` + +#### `OnPinRequested` + +Invoked when the user clicks the pin button. Caller is responsible for routing through the docking model (DockHostModel.PinToSide / Hide). + +```csharp +public Action? OnPinRequested // get, init +``` + +#### `PinAutomationId` + +Stable AutomationId for the pin button. Selftests address the per-tab pin via this id. + +```csharp +public string? PinAutomationId // get, init +``` + +#### `PinAutomationName` + +Tooltip + AT name applied to the pin button when IsPinnable is true. Caller supplies the localized string. + +```csharp +public string? PinAutomationName // get, init +``` diff --git a/docs/guide/reference/controls/property-grid-attributes.md b/docs/guide/reference/controls/property-grid-attributes.md new file mode 100644 index 0000000000..392d4da5a7 --- /dev/null +++ b/docs/guide/reference/controls/property-grid-attributes.md @@ -0,0 +1,211 @@ +# Property grid attributes + +Attributes that change how the property grid shows a property. + +**Learn more:** [Controls](../../controls.md) + +## `PropertyCategoryAttribute` + +Assigns a property to a named category group in the PropertyGrid. + +```csharp +public class PropertyCategoryAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Constructors + +#### `PropertyCategoryAttribute` + +Assigns a property to a named category group in the PropertyGrid. + +```csharp +public PropertyCategoryAttribute(string name) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `name` | `string` | | + +### Properties + +#### `Name` + +```csharp +public string Name // get +``` + +## `PropertyDescriptionAttribute` + +Provides tooltip/help text for a property in the PropertyGrid. + +```csharp +public class PropertyDescriptionAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Constructors + +#### `PropertyDescriptionAttribute` + +Provides tooltip/help text for a property in the PropertyGrid. + +```csharp +public PropertyDescriptionAttribute(string text) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `text` | `string` | | + +### Properties + +#### `Text` + +```csharp +public string Text // get +``` + +## `PropertyDisplayNameAttribute` + +Overrides the display name for a property in the PropertyGrid. + +```csharp +public class PropertyDisplayNameAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Constructors + +#### `PropertyDisplayNameAttribute` + +Overrides the display name for a property in the PropertyGrid. + +```csharp +public PropertyDisplayNameAttribute(string name) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `name` | `string` | | + +### Properties + +#### `Name` + +```csharp +public string Name // get +``` + +## `PropertyEditorAttribute` + +Applied to a type to specify a custom editor for all properties of that type. The referenced type must have a static method: static Element CreateEditor(object value, Action\ onChange) + +```csharp +public class PropertyEditorAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Constructors + +#### `PropertyEditorAttribute` + +Applied to a type to specify a custom editor for all properties of that type. The referenced type must have a static method: static Element CreateEditor(object value, Action\ onChange) + +```csharp +public PropertyEditorAttribute(Type editorType) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `editorType` | `Type` | | + +### Properties + +#### `EditorType` + +```csharp +public Type EditorType // get +``` + +## `PropertyHiddenAttribute` + +Marks a property as hidden from the PropertyGrid. + +```csharp +public class PropertyHiddenAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Constructors + +#### `PropertyHiddenAttribute` + +```csharp +public PropertyHiddenAttribute() +``` + +## `PropertyOrderAttribute` + +Explicitly controls declaration order when the default MetadataToken ordering is insufficient (e.g., inherited properties). + +```csharp +public class PropertyOrderAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Constructors + +#### `PropertyOrderAttribute` + +Explicitly controls declaration order when the default MetadataToken ordering is insufficient (e.g., inherited properties). + +```csharp +public PropertyOrderAttribute(int order) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `order` | `int` | | + +### Properties + +#### `Order` + +```csharp +public int Order // get +``` + +## `PropertyReadOnlyAttribute` + +Marks a property as read-only in the PropertyGrid, even if it has a public setter. + +```csharp +public class PropertyReadOnlyAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Constructors + +#### `PropertyReadOnlyAttribute` + +```csharp +public PropertyReadOnlyAttribute() +``` diff --git a/docs/guide/reference/controls/property-grid-templates.md b/docs/guide/reference/controls/property-grid-templates.md new file mode 100644 index 0000000000..6c97b3a6a3 --- /dev/null +++ b/docs/guide/reference/controls/property-grid-templates.md @@ -0,0 +1,625 @@ +# Property grid templates + +Delegates and metadata the property grid uses to build its rows. + +**Learn more:** [Controls](../../controls.md) + +## `ArrayItemTemplate` + +```csharp +public delegate Element ArrayItemTemplate(int index, string summary, bool isExpanded, Action onExpandedChanged, Action? onMoveUp, Action? onMoveDown, Action? onRemove) +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +## `ArrayToolbarTemplate` + +```csharp +public delegate Element ArrayToolbarTemplate(string propertyName, int count, Func? onAdd) +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +## `ArrayTypeMetadata` + +Extended metadata for array/list types. + +```csharp +public record ArrayTypeMetadata : TypeMetadata +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`TypeMetadata`](#typemetadata). + +### Constructors + +#### `ArrayTypeMetadata` + +```csharp +public ArrayTypeMetadata() +``` + +### Properties + +#### `CreateElement` + +Factory to create a new element for "Add" operations. Null means add is disabled. + +```csharp +public Func>? CreateElement // get, init +``` + +## `CategoryTemplate` + +```csharp +public delegate Element CategoryTemplate(string name, bool isExpanded, Action onExpandedChanged, Element[] children) +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +## `CellRenderers` + +Catalog of read-mode cell renderers for DataGrid (and anywhere else that needs a "display this value" factory). Each method returns a `Func` matching [`FieldDescriptor.CellRenderer`](../data/descriptors.md#cellrenderer). + +Paired with [`Editors`](#editors) — the convention is that a specialized column uses the matching pair (e.g. `CellRenderers.Date` + `Editors.DateTime`). + +```csharp +public static class CellRenderers +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Methods + +#### `CheckMark` + +```csharp +public static Func CheckMark() +``` + +#### `ColorSwatch` + +```csharp +public static Func ColorSwatch() +``` + +#### `Date` + +```csharp +public static Func Date(string format = "d") +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `format` | `string` | `"d"` | | + +#### `Enum` + +```csharp +public static Func Enum() +``` + +#### `Hyperlink` + +```csharp +public static Func Hyperlink(string? displayTextFormat = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `displayTextFormat` | `string?` | `null` | | + +#### `Number` + +```csharp +public static Func Number(string? format = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `format` | `string?` | `null` | | + +#### `Text` + +```csharp +public static Func Text(string? format = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `format` | `string?` | `null` | | + +#### `Time` + +```csharp +public static Func Time(string format = "t") +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `format` | `string` | `"t"` | | + +#### `ToggleIndicator` + +```csharp +public static Func ToggleIndicator() +``` + +## `EditorTier` + +Specifies which editor tier to resolve. + +```csharp +public enum EditorTier +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `Standard` | `0` | Standard editor for PropertyGrid/FormField. | +| `Compact` | `1` | Compact editor for grid inline cells. | +| `Full` | `2` | Full editor for expanded/flyout editing. | + +## `Editors` + +Catalog of inline editor factories for DataGrid and PropertyGrid. Each method returns a `Func, Element>` matching the [`FieldDescriptor.Editor`](../data/descriptors.md#editor) contract: takes the current cell value and an onChange callback, returns the editor Element. + +Use these via: + +- `FieldDescriptor`'s `Editor` slot directly, or +- A typed column factory like `NumberColumn` (thin wrappers over this catalog), or +- `TypeRegistry` registration for metadata-driven discovery. + +```csharp +public static class Editors +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Methods + +#### `CheckBox` + +```csharp +public static Func, Element> CheckBox() +``` + +#### `Color` + +```csharp +public static Func, Element> Color() +``` + +#### `ColorCompact` + +```csharp +public static Func, Element> ColorCompact() +``` + +#### `Combo` + +```csharp +public static Func, Element> Combo(IReadOnlyList choices) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `choices` | `IReadOnlyList` | | + +#### `Date` + +```csharp +public static Func, Element> Date() +``` + +#### `DateOffset` + +```csharp +public static Func, Element> DateOffset() +``` + +#### `DateOnly` + +```csharp +public static Func, Element> DateOnly() +``` + +#### `Decimal` + +```csharp +public static Func, Element> Decimal(decimal? min = null, decimal? max = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `min` | `decimal?` | `null` | | +| `max` | `decimal?` | `null` | | + +#### `Double` + +```csharp +public static Func, Element> Double(double? min = null, double? max = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `min` | `double?` | `null` | | +| `max` | `double?` | `null` | | + +#### `EnumCombo` + +```csharp +public static Func, Element> EnumCombo(Type enumType) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `enumType` | `Type` | | + +#### `Float` + +```csharp +public static Func, Element> Float(float? min = null, float? max = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `min` | `float?` | `null` | | +| `max` | `float?` | `null` | | + +#### `Int` + +```csharp +public static Func, Element> Int(int? min = null, int? max = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `min` | `int?` | `null` | | +| `max` | `int?` | `null` | | + +#### `Long` + +```csharp +public static Func, Element> Long(long? min = null, long? max = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `min` | `long?` | `null` | | +| `max` | `long?` | `null` | | + +#### `Number` + +```csharp +public static Func, Element> Number(Type numberType, double? min = null, double? max = null, double smallChange = 1) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `numberType` | `Type` | | | +| `min` | `double?` | `null` | | +| `max` | `double?` | `null` | | +| `smallChange` | `double` | `1` | | + +#### `Text` + +```csharp +public static Func, Element> Text(string? placeholderText = null, int? maxLength = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `placeholderText` | `string?` | `null` | | +| `maxLength` | `int?` | `null` | | + +#### `TimeOfDay` + +```csharp +public static Func, Element> TimeOfDay() +``` + +#### `TimeOnlyEditor` + +```csharp +public static Func, Element> TimeOnlyEditor() +``` + +#### `TimeSpanEditor` + +```csharp +public static Func, Element> TimeSpanEditor() +``` + +#### `Toggle` + +```csharp +public static Func, Element> Toggle(string? onContent = null, string? offContent = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `onContent` | `string?` | `null` | | +| `offContent` | `string?` | `null` | | + +#### `Uri` + +```csharp +public static Func, Element> Uri() +``` + +## `PropertyLabelTemplate` + +```csharp +public delegate Element PropertyLabelTemplate(FieldDescriptor descriptor, int indentLevel) +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +## `PropertyRowTemplate` + +```csharp +public delegate Element PropertyRowTemplate(FieldDescriptor descriptor, Element label, Element editor, int indentLevel) +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +## `ReflectionTypeMetadataProvider` + +Generates TypeMetadata for CLR types by reflecting over public instance properties and reading attributes. Used as the default fallback by TypeRegistry. + +```csharp +public static class ReflectionTypeMetadataProvider +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Methods + +#### `CreateDescriptor` + +Generates a FieldDescriptor for a single PropertyInfo (unbound — for registry use). + +```csharp +public static FieldDescriptor CreateDescriptor(PropertyInfo property, int defaultOrder) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `property` | `PropertyInfo` | | +| `defaultOrder` | `int` | | + +#### `CreateMetadata` + +Generates TypeMetadata for a CLR type by reflecting over its public instance properties and reading attributes. + +```csharp +public static TypeMetadata CreateMetadata(Type type) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `type` | `Type` | | + +## `TypeMetadata` + +Describes how to edit values of a given type in the PropertyGrid. A type either has an Editor (leaf/atomic) or a Decomposition (composite), or both (e.g., a Color has a hex editor AND can expand to R/G/B). + +```csharp +public record TypeMetadata +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Constructors + +#### `TypeMetadata` + +```csharp +public TypeMetadata() +``` + +### Properties + +#### `CompactEditor` + +Compact editor variant for grid inline cells. Falls back to Editor when null. + +```csharp +public Func, Element>? CompactEditor // get, init +``` + +#### `Compose` + +Reconstructs a value from its decomposed parts. Required for immutable types that have a Decompose. For mutable types where Decompose returns descriptors with working setters, this is null. + +```csharp +public Func, object>? Compose // get, init +``` + +#### `Decompose` + +Breaks a value into named sub-properties for recursive editing. Null if this type is atomic (edited only via Editor). + +```csharp +public Func>? Decompose // get, init +``` + +#### `DisplayName` + +Display name for the type (used in array item headers, etc.). Falls back to Type.Name if null. + +```csharp +public string? DisplayName // get, init +``` + +#### `Editor` + +Creates an editor Element for a value of this type. Null if this type is only editable through decomposition. + +```csharp +public Func, Element>? Editor // get, init +``` + +#### `FullEditor` + +Full editor variant for expanded/flyout editing. Null when no expanded editing is available. + +```csharp +public Func, Element>? FullEditor // get, init +``` + +## `TypeRegistry` + +Maps CLR types to TypeMetadata for the PropertyGrid. Provides a fluent Register API and a Resolve method with built-in fallbacks. + +```csharp +public class TypeRegistry +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Constructors + +#### `TypeRegistry` + +```csharp +public TypeRegistry() +``` + +### Methods + +#### `GetCellRenderer` + +Try to get a cell renderer for a type. Falls back to built-in defaults for common primitive/date/uri/color types so `AutoColumns` picks up sensible display renderers without requiring explicit registration. + +```csharp +public Func? GetCellRenderer(Type type) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `type` | `Type` | | + +#### `GetFormatter` + +Try to get a registered formatter for a type. + +```csharp +public Func? GetFormatter(Type type) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `type` | `Type` | | + +#### `Register` + +Register metadata for a type. + +```csharp +public TypeRegistry Register(TypeMetadata metadata) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `metadata` | [`TypeMetadata`](#typemetadata) | | + +#### `RegisterCellRenderer` + +Register a custom cell renderer for grid display. + +```csharp +public TypeRegistry RegisterCellRenderer(Func renderer) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `renderer` | `Func` | | + +#### `RegisterFormatter` + +Register a custom value formatter for grid display. + +```csharp +public TypeRegistry RegisterFormatter(Func formatter) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `formatter` | `Func` | | + +#### `Resolve` + +Resolve metadata for a type. Falls back to built-in rules: 1. Exact match in registry 2. Enum — auto-generated ComboBox editor 3. CLR primitive — built-in editor 4. Collection/enumerable shapes — array editor 5. Record/class/struct — reflection-based decomposition + +```csharp +public TypeMetadata Resolve(Type type) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `type` | `Type` | | + +#### `ResolveEditor` + +Resolves the editor for a type using tiered resolution: For compact (grid): CompactEditor ?? Editor ?? built-in For standard (PropertyGrid/FormField): Editor ?? built-in For full (expand): FullEditor (null when not registered) + +```csharp +public Func, Element>? ResolveEditor(Type type, EditorTier tier) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `type` | `Type` | | +| `tier` | [`EditorTier`](#editortier) | | diff --git a/docs/guide/reference/controls/rich-text.md b/docs/guide/reference/controls/rich-text.md new file mode 100644 index 0000000000..75a1d6799e --- /dev/null +++ b/docs/guide/reference/controls/rich-text.md @@ -0,0 +1,399 @@ +# Rich text + +Inline records for rich text blocks. + +**Learn more:** [Text and Media](../../text-and-media.md) + +## `RichTextHyperlink` + +Inline hyperlink fragment inside a [`RichTextBlockElement`](../elements/text.md#richtextblockelement). + +**Two modes** (issue #479): + +- **Navigate mode** — when [`RichTextHyperlink.OnClick`](#onclick) is `null` the WinUI `Hyperlink` is mounted with [`RichTextHyperlink.NavigateUri`](#navigateuri) set and clicks open the URI via the platform launcher. +- **Click mode** — when [`RichTextHyperlink.OnClick`](#onclick) is non-null the delegate fires on click and the WinUI `NavigateUri` is left unset, so the platform does not navigate. Use this for clickable inline fragments (open a menu, enter edit mode, dispatch an action) without escaping to a hosted native subtree. + +```csharp +public record RichTextHyperlink(string Text, Uri NavigateUri) : RichTextInline +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`RichTextInline`](#richtextinline). + +### Constructors + +#### `RichTextHyperlink` + +Inline hyperlink fragment inside a [`RichTextBlockElement`](../elements/text.md#richtextblockelement). + +**Two modes** (issue #479): + +- **Navigate mode** — when [`RichTextHyperlink.OnClick`](#onclick) is `null` the WinUI `Hyperlink` is mounted with [`RichTextHyperlink.NavigateUri`](#navigateuri) set and clicks open the URI via the platform launcher. +- **Click mode** — when [`RichTextHyperlink.OnClick`](#onclick) is non-null the delegate fires on click and the WinUI `NavigateUri` is left unset, so the platform does not navigate. Use this for clickable inline fragments (open a menu, enter edit mode, dispatch an action) without escaping to a hosted native subtree. + +```csharp +public RichTextHyperlink(string Text, Uri NavigateUri) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Text` | `string` | | +| `NavigateUri` | `Uri` | | + +### Properties + +#### `IsTabStop` + +```csharp +public bool? IsTabStop // get, init +``` + +#### `NavigateUri` + +```csharp +public Uri NavigateUri // get, init +``` + +#### `OnClick` + +Optional click handler. When non-null, fires on every click and suppresses navigation (the underlying WinUI `Hyperlink` is mounted with no `NavigateUri`). When null, the inline behaves as a pure navigation link using [`RichTextHyperlink.NavigateUri`](#navigateuri). + +```csharp +public Action? OnClick // get, init +``` + +#### `TabIndex` + +```csharp +public int? TabIndex // get, init +``` + +#### `Text` + +```csharp +public string Text // get, init +``` + +#### `UnderlineStyle` + +```csharp +public UnderlineStyle? UnderlineStyle // get, init +``` + +## `RichTextInline` + +```csharp +public abstract record RichTextInline +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `RichTextInline` + +```csharp +protected RichTextInline() +``` + +### Properties + +#### `CharacterSpacing` + +```csharp +public int? CharacterSpacing // get, init +``` + +#### `FontFamily` + +```csharp +public string? FontFamily // get, init +``` + +#### `FontSize` + +```csharp +public double? FontSize // get, init +``` + +#### `FontStretch` + +```csharp +public FontStretch? FontStretch // get, init +``` + +#### `FontStyle` + +```csharp +public FontStyle? FontStyle // get, init +``` + +#### `FontWeight` + +```csharp +public FontWeight? FontWeight // get, init +``` + +#### `Foreground` + +```csharp +public Brush? Foreground // get, init +``` + +#### `IsTextScaleFactorEnabled` + +```csharp +public bool? IsTextScaleFactorEnabled // get, init +``` + +#### `Language` + +```csharp +public string? Language // get, init +``` + +#### `TextDecorations` + +```csharp +public TextDecorations? TextDecorations // get, init +``` + +## `RichTextInlineUIContainer` + +Mirrors WinUI's `Microsoft.UI.Xaml.Documents.InlineUIContainer` — an inline that embeds a UIElement inside a flowing [`RichTextBlockElement`](../elements/text.md#richtextblockelement). + +**Two embedding routes** (issue #480): + +- **Route A — Reactor element ([`RichTextInlineUIContainer.Child`](#child)):** the embedded UI is described declaratively as any other Reactor [`Element`](../elements/Element.md) (e.g. `Button("+", () => ...)`) and is mounted through the reconciler. The descriptor uses an incremental rich-text update path: re-renders of the owning `RichTextBlock` preserve the existing inline UIElement and reconcile the Reactor child via the standard child-reconciliation pipeline, so embedded interactive controls (sliders, buttons, etc.) keep their drag focus and component state across renders. A structural change to the surrounding paragraph tree (different paragraph count, mismatched inline shape) falls back to a full rebuild that tears down and remounts the child along with the rest of the block. +- **Route B — imperative native factory ([`RichTextInlineUIContainer.Factory`](#factory)):** the embedded UI is produced by a caller-supplied lambda returning a raw WinUI [`FrameworkElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.frameworkelement). Useful as an escape hatch for native controls that have no Reactor element counterpart. The factory is opaque to the reconciler, so the incremental path re-invokes it only when the delegate identity itself changes (capture-equal lambdas are treated as unchanged) — pass a stable delegate reference if you want the native UIElement to survive renders. + +Exactly one of [`RichTextInlineUIContainer.Child`](#child) / [`RichTextInlineUIContainer.Factory`](#factory) should be non-null. If both are null the inline expands to a zero-size empty container; if both are set, [`RichTextInlineUIContainer.Child`](#child) wins. + +```csharp +public record RichTextInlineUIContainer : RichTextInline +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`RichTextInline`](#richtextinline). + +### Constructors + +#### `RichTextInlineUIContainer` + +```csharp +public RichTextInlineUIContainer() +``` + +### Properties + +#### `Child` + +Reactor element to mount as the inline UI (Route A). + +```csharp +public Element? Child // get, init +``` + +#### `Factory` + +Imperative factory producing a native [`FrameworkElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.frameworkelement) (Route B). Invoked once per rebuild of the owning `RichTextBlock`. + +```csharp +public Func? Factory // get, init +``` + +## `RichTextLineBreak` + +```csharp +public record RichTextLineBreak : RichTextInline +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`RichTextInline`](#richtextinline). + +### Constructors + +#### `RichTextLineBreak` + +```csharp +public RichTextLineBreak() +``` + +## `RichTextParagraph` + +```csharp +public record RichTextParagraph(RichTextInline[] Inlines) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `RichTextParagraph` + +```csharp +public RichTextParagraph(RichTextInline[] Inlines) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Inlines` | [`RichTextInline[]`](#richtextinline) | | + +### Properties + +#### `CharacterSpacing` + +```csharp +public int? CharacterSpacing // get, init +``` + +#### `FontFamily` + +```csharp +public string? FontFamily // get, init +``` + +#### `FontSize` + +```csharp +public double? FontSize // get, init +``` + +#### `FontStretch` + +```csharp +public FontStretch? FontStretch // get, init +``` + +#### `FontStyle` + +```csharp +public FontStyle? FontStyle // get, init +``` + +#### `FontWeight` + +```csharp +public FontWeight? FontWeight // get, init +``` + +#### `Foreground` + +```csharp +public Brush? Foreground // get, init +``` + +#### `HorizontalTextAlignment` + +```csharp +public TextAlignment? HorizontalTextAlignment // get, init +``` + +#### `Inlines` + +```csharp +public RichTextInline[] Inlines // get, init +``` + +#### `IsTextScaleFactorEnabled` + +```csharp +public bool? IsTextScaleFactorEnabled // get, init +``` + +#### `Language` + +```csharp +public string? Language // get, init +``` + +#### `LineHeight` + +```csharp +public double? LineHeight // get, init +``` + +#### `LineStackingStrategy` + +```csharp +public LineStackingStrategy? LineStackingStrategy // get, init +``` + +#### `Margin` + +```csharp +public Thickness? Margin // get, init +``` + +#### `TextAlignment` + +```csharp +public TextAlignment? TextAlignment // get, init +``` + +#### `TextDecorations` + +```csharp +public TextDecorations? TextDecorations // get, init +``` + +#### `TextIndent` + +```csharp +public double? TextIndent // get, init +``` + +## `RichTextRun` + +```csharp +public record RichTextRun(string Text) : RichTextInline +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`RichTextInline`](#richtextinline). + +### Constructors + +#### `RichTextRun` + +```csharp +public RichTextRun(string Text) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Text` | `string` | | + +### Properties + +#### `FlowDirection` + +```csharp +public FlowDirection? FlowDirection // get, init +``` + +#### `IsBold` + +```csharp +public bool IsBold // get, init +``` + +#### `IsItalic` + +```csharp +public bool IsItalic // get, init +``` + +#### `IsStrikethrough` + +```csharp +public bool IsStrikethrough // get, init +``` + +#### `Text` + +```csharp +public string Text // get, init +``` diff --git a/docs/guide/reference/controls/virtual-list.md b/docs/guide/reference/controls/virtual-list.md new file mode 100644 index 0000000000..84b10d63c9 --- /dev/null +++ b/docs/guide/reference/controls/virtual-list.md @@ -0,0 +1,196 @@ +# Virtual list + +Support types for the virtual list. + +**Learn more:** [Controls](../../controls.md) + +## `SearchManager` + +Manages async search with debounce and cancellation for AutoSuggest. + +```csharp +public sealed class SearchManager : IDisposable +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Constructors + +#### `SearchManager` + +```csharp +public SearchManager(Func>> search, int debounceMs = 300) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `search` | `Func>>` | | | +| `debounceMs` | `int` | `300` | | + +### Properties + +#### `ErrorText` + +```csharp +public string? ErrorText // get +``` + +#### `Results` + +```csharp +public IReadOnlyList Results // get +``` + +#### `State` + +```csharp +public SearchState State // get +``` + +### Methods + +#### `Cancel` + +Cancels any in-flight search and resets state. + +```csharp +public void Cancel() +``` + +#### `Dispose` + +Releases the resources that this object holds. + +```csharp +public void Dispose() +``` + +#### `Search` + +Triggers a debounced search. Cancels any in-flight search. + +```csharp +public void Search(string query) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `query` | `string` | | + +### Events + +#### `StateChanged` + +Fired when state changes (for triggering re-renders). + +```csharp +public event Action? StateChanged +``` + +## `SearchState` + +State for the search operation: loading, results, error, or empty. + +```csharp +public enum SearchState +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `Idle` | `0` | | +| `Loading` | `1` | | +| `Results` | `2` | | +| `Empty` | `3` | | +| `Error` | `4` | | + +## `VirtualListComponent` + +Component that renders a virtualized list using WinUI's ItemsRepeater. Adapts the count-based VirtualListElement API to the ItemsRepeater infrastructure, supporting both fixed-height (O(1) offset) and variable-height modes. + +```csharp +public class VirtualListComponent +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Constructors + +#### `VirtualListComponent` + +```csharp +public VirtualListComponent() +``` + +### Methods + +#### `Render` + +```csharp +public override Element Render() +``` + +## `VirtualListRef` + +Imperative handle for VirtualList scroll operations. Obtained via the VirtualListElement.Ref callback. + +```csharp +public sealed class VirtualListRef +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. + +### Properties + +#### `Repeater` + +The underlying ItemsRepeater, for advanced scenarios. + +```csharp +public ItemsRepeater? Repeater // get +``` + +#### `ScrollOffset` + +Gets the current vertical scroll offset. + +```csharp +public double ScrollOffset // get +``` + +### Methods + +#### `RestoreScrollOffset` + +Restores a previously saved scroll offset. + +```csharp +public void RestoreScrollOffset(double offset) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `offset` | `double` | | + +#### `ScrollToIndex` + +Programmatically scroll to bring the item at the given index into view. + +```csharp +public void ScrollToIndex(int index) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `index` | `int` | | diff --git a/docs/guide/reference/data/FocusRevalidationService.md b/docs/guide/reference/data/FocusRevalidationService.md new file mode 100644 index 0000000000..a66cb340f7 --- /dev/null +++ b/docs/guide/reference/data/FocusRevalidationService.md @@ -0,0 +1,109 @@ +# FocusRevalidationService + +Central service that invalidates stale [`QueryCache`](query-cache.md#querycache) entries when the app window is reactivated or resumed, so consumers that opted in via `ResourceOptions.RefetchOnWindowFocus = true` see fresh data after an Alt-Tab or resume. Disabled by default — see [`ReactorFeatureFlags.FocusRevalidation`](../extensibility/ReactorFeatureFlags.md#focusrevalidation). + +```csharp +public sealed class FocusRevalidationService +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Async Resources](../../async-resources.md) + +## Remarks + +**Per-resource enrollment.** Hooks that opt in call [`FocusRevalidationService.Enroll`](#enroll) with their cache key; the service tracks enrolled keys as a set and invalidates only those whose entry is past `StaleTime` at activation time. Non-enrolled keys are untouched. + +**Throttling.** A default 30-second window between activation-driven revalidation sweeps prevents Alt-Tab thrashing from refetching on every transient focus event. Adjustable via [`FocusRevalidationService.ThrottleWindow`](#throttlewindow). + +**Threading.** All members are thread-safe. Activation callbacks may fire on the UI thread or the dispatcher thread — the service does not marshal. Invalidation in turn fires `QueryCache.EntryChanged`, which the `UseResource` hook listens to and re-renders from. + +## Constructors + +### `FocusRevalidationService` + +```csharp +public FocusRevalidationService(QueryCache cache) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `cache` | [`QueryCache`](query-cache.md#querycache) | | + +## Properties + +### `EnrolledCount` + +Diagnostic: current number of keys enrolled for focus revalidation. + +```csharp +public int EnrolledCount // get +``` + +### `ThrottleWindow` + +Minimum time between activation-driven revalidation sweeps. Defaults to 30s. + +```csharp +public TimeSpan ThrottleWindow // get, set +``` + +### `UtcNow` + +Clock override for deterministic tests. + +```csharp +public Func UtcNow // get, set +``` + +## Methods + +### `Enroll` + +Enroll `key` in focus revalidation. Hooks call this when `ResourceOptions.RefetchOnWindowFocus = true`. Idempotent — re-enrolling the same key is a no-op. + +```csharp +public void Enroll(string key) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `key` | `string` | | + +### `RevalidateNow` + +Revalidate enrolled entries. Invalidates every enrolled key whose entry is past its `StaleTime`. Returns the keys that were invalidated. + +```csharp +public IReadOnlyList RevalidateNow() +``` + +**Remarks** + +Short-circuits if the last call fired within [`FocusRevalidationService.ThrottleWindow`](#throttlewindow) — returns an empty list without touching the cache. + +### `RevalidateNowForce` + +Forces a revalidation sweep, bypassing the throttle window. Diagnostic / test-only — production code paths should go through [`FocusRevalidationService.RevalidateNow`](#revalidatenow). + +```csharp +public IReadOnlyList RevalidateNowForce() +``` + +### `Unenroll` + +Remove `key` from the focus-revalidation set. Hooks call this on unmount or when their cache key changes. + +```csharp +public void Unenroll(string key) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `key` | `string` | | diff --git a/docs/guide/reference/data/IDataSource.md b/docs/guide/reference/data/IDataSource.md new file mode 100644 index 0000000000..f0c352d424 --- /dev/null +++ b/docs/guide/reference/data/IDataSource.md @@ -0,0 +1,58 @@ +# IDataSource\ + +A read-only data source that provides paged access to items. + +```csharp +public interface IDataSource +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +**Learn more:** [Data System](../../data-system.md) + +## Type parameters + +| Name | Description | +| --- | --- | +| `T` | The item type. | + +## Properties + +### `Capabilities` + +Declares what this data source can do server-side. + +```csharp +public abstract DataSourceCapabilities Capabilities // get +``` + +## Methods + +### `GetPageAsync` + +Fetches a page of data matching the request. + +```csharp +public Task> GetPageAsync(DataRequest request, CancellationToken cancellationToken = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `request` | [`DataRequest`](descriptors.md#datarequest) | | | +| `cancellationToken` | `CancellationToken` | `default` | | + +### `GetRowKey` + +Gets the stable key for an item. + +```csharp +public RowKey GetRowKey(T item) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `item` | `T` | | diff --git a/docs/guide/reference/data/IKeyedDataSource.md b/docs/guide/reference/data/IKeyedDataSource.md new file mode 100644 index 0000000000..6997c2eac6 --- /dev/null +++ b/docs/guide/reference/data/IKeyedDataSource.md @@ -0,0 +1,39 @@ +# IKeyedDataSource\ + +A data source that supports fetching individual items by key. + +```csharp +public interface IKeyedDataSource : IDataSource +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +**Learn more:** [Data System](../../data-system.md) + +## Methods + +### `GetByKeyAsync` + +```csharp +public Task GetByKeyAsync(RowKey key, CancellationToken cancellationToken = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `key` | [`RowKey`](descriptors.md#rowkey) | | | +| `cancellationToken` | `CancellationToken` | `default` | | + +### `GetByKeysAsync` + +```csharp +public Task> GetByKeysAsync(IEnumerable keys, CancellationToken cancellationToken = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `keys` | `IEnumerable` | | | +| `cancellationToken` | `CancellationToken` | `default` | | diff --git a/docs/guide/reference/data/IMutableDataSource.md b/docs/guide/reference/data/IMutableDataSource.md new file mode 100644 index 0000000000..b2b189c460 --- /dev/null +++ b/docs/guide/reference/data/IMutableDataSource.md @@ -0,0 +1,53 @@ +# IMutableDataSource\ + +A mutable data source that supports CRUD operations. + +```csharp +public interface IMutableDataSource : IDataSource +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +**Learn more:** [Data System](../../data-system.md) + +## Methods + +### `CreateAsync` + +```csharp +public Task CreateAsync(T item, CancellationToken cancellationToken = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `item` | `T` | | | +| `cancellationToken` | `CancellationToken` | `default` | | + +### `DeleteAsync` + +```csharp +public Task DeleteAsync(RowKey key, CancellationToken cancellationToken = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `key` | [`RowKey`](descriptors.md#rowkey) | | | +| `cancellationToken` | `CancellationToken` | `default` | | + +### `UpdateAsync` + +```csharp +public Task UpdateAsync(RowKey key, T item, CancellationToken cancellationToken = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `key` | [`RowKey`](descriptors.md#rowkey) | | | +| `item` | `T` | | | +| `cancellationToken` | `CancellationToken` | `default` | | diff --git a/docs/guide/reference/data/IObservableDataSource.md b/docs/guide/reference/data/IObservableDataSource.md new file mode 100644 index 0000000000..c9190c56f6 --- /dev/null +++ b/docs/guide/reference/data/IObservableDataSource.md @@ -0,0 +1,19 @@ +# IObservableDataSource\ + +A data source that fires events when data changes. + +```csharp +public interface IObservableDataSource : IDataSource +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +**Learn more:** [Data System](../../data-system.md) + +## Events + +### `DataChanged` + +```csharp +public event EventHandler? DataChanged +``` diff --git a/docs/guide/reference/data/ListDataSource.md b/docs/guide/reference/data/ListDataSource.md new file mode 100644 index 0000000000..d891305461 --- /dev/null +++ b/docs/guide/reference/data/ListDataSource.md @@ -0,0 +1,113 @@ +# ListDataSource\ + +In-memory data source backed by a list. Supports client-side sorting, filtering, text search, paging, and CRUD mutations. + +```csharp +public class ListDataSource : IDataSource, IMutableDataSource +``` + +Namespace: `Microsoft.UI.Reactor.Data.Providers`. + +**Learn more:** [Data System](../../data-system.md) + +## Constructors + +### `ListDataSource` + +For subclasses that manage their own item list. + +```csharp +public ListDataSource(IEnumerable items, Func getRowKey) +protected ListDataSource(List items, Func getRowKey, bool directReference) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `items` | `IEnumerable` or `List` | | +| `getRowKey` | `Func` | | +| `directReference` | `bool` | | + +## Properties + +### `Capabilities` + +```csharp +public DataSourceCapabilities Capabilities // get +``` + +### `Items` + +Direct access to the backing list for subclasses. + +```csharp +protected List Items // get +``` + +## Methods + +### `CreateAsync` + +```csharp +public Task CreateAsync(T item, CancellationToken cancellationToken = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `item` | `T` | | | +| `cancellationToken` | `CancellationToken` | `default` | | + +### `DeleteAsync` + +```csharp +public Task DeleteAsync(RowKey key, CancellationToken cancellationToken = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `key` | [`RowKey`](descriptors.md#rowkey) | | | +| `cancellationToken` | `CancellationToken` | `default` | | + +### `GetPageAsync` + +```csharp +public Task> GetPageAsync(DataRequest request, CancellationToken cancellationToken = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `request` | [`DataRequest`](descriptors.md#datarequest) | | | +| `cancellationToken` | `CancellationToken` | `default` | | + +### `GetRowKey` + +```csharp +public RowKey GetRowKey(T item) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `item` | `T` | | + +### `UpdateAsync` + +```csharp +public Task UpdateAsync(RowKey key, T item, CancellationToken cancellationToken = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `key` | [`RowKey`](descriptors.md#rowkey) | | | +| `item` | `T` | | | +| `cancellationToken` | `CancellationToken` | `default` | | diff --git a/docs/guide/reference/data/ObservableListDataSource.md b/docs/guide/reference/data/ObservableListDataSource.md new file mode 100644 index 0000000000..43ba3adbb8 --- /dev/null +++ b/docs/guide/reference/data/ObservableListDataSource.md @@ -0,0 +1,44 @@ +# ObservableListDataSource\ + +An observable data source that watches an ObservableCollection for changes and fires DataChanged when items are added, removed, or modified. The collection is the authoritative source — mutations go through the collection, not through the data source's CRUD methods. + +```csharp +public class ObservableListDataSource : IObservableDataSource, IDataSource, IDisposable +``` + +Namespace: `Microsoft.UI.Reactor.Data.Providers`. + +**Learn more:** [Data System](../../data-system.md) + +## Constructors + +### `ObservableListDataSource` + +```csharp +public ObservableListDataSource(ObservableCollection collection, Func getRowKey) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `collection` | `ObservableCollection` | | +| `getRowKey` | `Func` | | + +## Methods + +### `Dispose` + +Releases the resources that this object holds. + +```csharp +public void Dispose() +``` + +## Events + +### `DataChanged` + +```csharp +public event EventHandler? DataChanged +``` diff --git a/docs/guide/reference/data/async-values.md b/docs/guide/reference/data/async-values.md new file mode 100644 index 0000000000..6b68092344 --- /dev/null +++ b/docs/guide/reference/data/async-values.md @@ -0,0 +1,304 @@ +# Async values + +The value a resource hook returns while it loads, after it loads and after it fails. + +**Learn more:** [Async Resources](../../async-resources.md) + +## `AsyncValue` + +Algebraic data type representing the four observable states of an async fetch: [`AsyncValue.Loading`](#asyncvaluetloading), [`AsyncValue.Data`](#asyncvaluetdata), [`AsyncValue.Error`](#asyncvalueterror), and [`AsyncValue.Reloading`](#asyncvaluetreloading). Designed for exhaustive pattern matching with C# switch expressions: the hierarchy is `closed`, so a C# 15+ `switch` that handles all four cases needs no discard arm, and omitting a case is a CS8509 warning naming the missing case. + +```csharp +public abstract record AsyncValue +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Remarks + +See spec `docs/specs/020-async-resources-design.md` §5 for the design rationale and §6.2 for the transition rules driven by `UseResource`. + +### Type parameters + +| Name | Description | +| --- | --- | +| `T` | The value type produced by the fetcher. | + +### Constructors + +#### `AsyncValue` + +```csharp +protected AsyncValue() +``` + +### Methods + +#### `Match` + +Convenience match that renders the `loading` arm for [`AsyncValue.Reloading`](#asyncvaluetreloading) by default. Pass `reloading` explicitly to show stale content while a refresh is in progress (stale-while-revalidate). + +```csharp +public TResult Match(Func loading, Func loaded, Func error, Func? reloading = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `loading` | `Func` | | | +| `loaded` | `Func` | | | +| `error` | `Func` | | | +| `reloading` | `Func?` | `null` | | + +**Remarks** + +Omitting `reloading` means a refresh shows the loading UI, so authors don't have to duplicate the loading arm. Provide `reloading` to keep the previous value visible while revalidating. + +The success arm is named `loaded`. This is a source-breaking rename from the previous `data` parameter for named-argument callers; a back-compat overload is impossible because overloads cannot differ by parameter name alone. + +Allocates a delegate per arm at the call site; prefer a `switch` expression in per-row render paths (see spec §5.1). + +### `AsyncValue.Data` + +Fetch succeeded; `Value` is authoritative. Transitions to [`AsyncValue.Reloading`](#asyncvaluetreloading) when a refetch starts, or back to [`AsyncValue.Data`](#asyncvaluetdata) on cache hit within `StaleTime`. + +```csharp +public sealed record Data(T Value) +``` + +#### Constructors + +##### `Data` + +Fetch succeeded; `Value` is authoritative. Transitions to [`AsyncValue.Reloading`](#asyncvaluetreloading) when a refetch starts, or back to [`AsyncValue.Data`](#asyncvaluetdata) on cache hit within `StaleTime`. + +```csharp +public Data(T Value) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Value` | `T` | | + +#### Properties + +##### `Value` + +```csharp +public T Value // get, init +``` + +### `AsyncValue.Error` + +Fetch failed. Any prior data is discarded — `UseResource` does not retain stale values across a failure. If you need "last known good", wrap the fetcher. + +```csharp +public sealed record Error(Exception Exception) +``` + +#### Constructors + +##### `Error` + +Fetch failed. Any prior data is discarded — `UseResource` does not retain stale values across a failure. If you need "last known good", wrap the fetcher. + +```csharp +public Error(Exception Exception) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Exception` | `Exception` | | + +#### Properties + +##### `Exception` + +```csharp +public Exception Exception // get, init +``` + +### `AsyncValue.Loading` + +First fetch in flight; no prior data is available. Transitions to [`AsyncValue.Data`](#asyncvaluetdata) or [`AsyncValue.Error`](#asyncvalueterror). + +```csharp +public sealed record Loading +``` + +#### Constructors + +##### `Loading` + +```csharp +public Loading() +``` + +#### Fields + +##### `Instance` + +Singleton instance — [`AsyncValue.Loading`](#asyncvaluetloading) has no payload. + +```csharp +public static readonly AsyncValue.Loading Instance +``` + +### `AsyncValue.Reloading` + +Refetching with the previous value still observable (stale-while-revalidate). The `Previous` payload is intentionally non-nullable so call sites can render the stale tree without null-guards. Components may choose to dim, overlay a spinner, or render identically to [`AsyncValue.Data`](#asyncvaluetdata) — §5.1. + +```csharp +public sealed record Reloading(T Previous) +``` + +#### Constructors + +##### `Reloading` + +Refetching with the previous value still observable (stale-while-revalidate). The `Previous` payload is intentionally non-nullable so call sites can render the stale tree without null-guards. Components may choose to dim, overlay a spinner, or render identically to [`AsyncValue.Data`](#asyncvaluetdata) — §5.1. + +```csharp +public Reloading(T Previous) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Previous` | `T` | | + +#### Properties + +##### `Previous` + +```csharp +public T Previous // get, init +``` + +## `LoadState` + +The four discrete load states of an [`InfiniteResource`](paging.md#infiniteresourcetitem). Mirrors Android Paging 3's `LoadState`. The hierarchy is `closed`, so a C# 15+ `switch` over all four cases is exhaustive without a discard arm. + +```csharp +public abstract record LoadState +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `LoadState` + +```csharp +protected LoadState() +``` + +### `LoadState.EndOfList` + +Server reported `NextCursor == null` — no further pages. + +```csharp +public sealed record EndOfList : LoadState +``` + +#### Constructors + +##### `EndOfList` + +```csharp +public EndOfList() +``` + +#### Fields + +##### `Instance` + +```csharp +public static readonly LoadState.EndOfList Instance +``` + +### `LoadState.Error` + +Most recent fetch failed; call `Retry()` to retry the failed page. + +```csharp +public sealed record Error(Exception Exception) : LoadState +``` + +#### Constructors + +##### `Error` + +Most recent fetch failed; call `Retry()` to retry the failed page. + +```csharp +public Error(Exception Exception) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Exception` | `Exception` | | + +#### Properties + +##### `Exception` + +```csharp +public Exception Exception // get, init +``` + +### `LoadState.Idle` + +No fetch pending; `HasMore` determines whether more pages are available. + +```csharp +public sealed record Idle : LoadState +``` + +#### Constructors + +##### `Idle` + +```csharp +public Idle() +``` + +#### Fields + +##### `Instance` + +```csharp +public static readonly LoadState.Idle Instance +``` + +### `LoadState.Loading` + +A page fetch is in flight. + +```csharp +public sealed record Loading : LoadState +``` + +#### Constructors + +##### `Loading` + +```csharp +public Loading() +``` + +#### Fields + +##### `Instance` + +```csharp +public static readonly LoadState.Loading Instance +``` diff --git a/docs/guide/reference/data/column-attributes.md b/docs/guide/reference/data/column-attributes.md new file mode 100644 index 0000000000..0b6512eb0c --- /dev/null +++ b/docs/guide/reference/data/column-attributes.md @@ -0,0 +1,139 @@ +# Column attributes + +Attributes that change how a property shows as a column. + +**Learn more:** [Data System](../../data-system.md) + +## `ColumnPinAttribute` + +Pins a column to the left or right edge of a DataGrid. + +```csharp +public class ColumnPinAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Data`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Constructors + +#### `ColumnPinAttribute` + +Pins a column to the left or right edge of a DataGrid. + +```csharp +public ColumnPinAttribute(PinPosition position) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `position` | [`PinPosition`](#pinposition) | | + +### Properties + +#### `Position` + +```csharp +public PinPosition Position // get +``` + +## `ColumnWidthAttribute` + +Specifies the preferred column width for a property when displayed in a DataGrid. + +```csharp +public class ColumnWidthAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Data`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Constructors + +#### `ColumnWidthAttribute` + +Specifies the preferred column width for a property when displayed in a DataGrid. + +```csharp +public ColumnWidthAttribute(double width) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `width` | `double` | | + +### Properties + +#### `MaxWidth` + +```csharp +public double MaxWidth // get, set +``` + +#### `MinWidth` + +```csharp +public double MinWidth // get, set +``` + +#### `Width` + +```csharp +public double Width // get +``` + +## `NotFilterableAttribute` + +Marks a column as not filterable in a DataGrid. + +```csharp +public class NotFilterableAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Data`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Constructors + +#### `NotFilterableAttribute` + +```csharp +public NotFilterableAttribute() +``` + +## `NotSortableAttribute` + +Marks a column as not sortable in a DataGrid. + +```csharp +public class NotSortableAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Data`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Constructors + +#### `NotSortableAttribute` + +```csharp +public NotSortableAttribute() +``` + +## `PinPosition` + +Controls column pinning in data grids. + +```csharp +public enum PinPosition +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `None` | `0` | | +| `Left` | `1` | | +| `Right` | `2` | | diff --git a/docs/guide/reference/data/descriptors.md b/docs/guide/reference/data/descriptors.md new file mode 100644 index 0000000000..0d0c69ab70 --- /dev/null +++ b/docs/guide/reference/data/descriptors.md @@ -0,0 +1,454 @@ +# Sort and filter descriptors + +Requests, sort, filter and field descriptors that data sources receive. + +**Learn more:** [Data System](../../data-system.md) + +## `DataRequest` + +Describes a data fetch request with paging, sorting, filtering, and search. + +```csharp +public record DataRequest +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Constructors + +#### `DataRequest` + +```csharp +public DataRequest() +``` + +### Properties + +#### `ContinuationToken` + +Token for fetching the next page. Null for the first page. + +```csharp +public string? ContinuationToken // get, init +``` + +#### `Filters` + +Filter operations to apply (AND-ed together). + +```csharp +public IReadOnlyList? Filters // get, init +``` + +#### `PageSize` + +Number of items per page. Default 50. + +```csharp +public int PageSize // get, init +``` + +#### `SearchQuery` + +Free-text search query. + +```csharp +public string? SearchQuery // get, init +``` + +#### `Select` + +Fields to include in the result (projection). Null = all fields. + +```csharp +public IReadOnlyList? Select // get, init +``` + +#### `Sort` + +Sort operations to apply. + +```csharp +public IReadOnlyList? Sort // get, init +``` + +## `FieldDescriptor` + +Describes a single field within a decomposed type. Unified descriptor used by PropertyGrid, DataGrid, and FormField. + +```csharp +public record FieldDescriptor +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Constructors + +#### `FieldDescriptor` + +```csharp +public FieldDescriptor() +``` + +> **Obsolete.** Constructors of types with required members are not supported in this version of your compiler. + +### Properties + +#### `AsyncValidators` + +Asynchronous validators for this field. + +```csharp +public IReadOnlyList? AsyncValidators // get, init +``` + +#### `Category` + +Category for grouping. Null = default/uncategorized. + +```csharp +public string? Category // get, init +``` + +#### `CellRenderer` + +Custom cell renderer for grid display. + +```csharp +public Func? CellRenderer // get, init +``` + +#### `Description` + +Help text shown as tooltip or description. + +```csharp +public string? Description // get, init +``` + +#### `DisplayName` + +Display label shown in grids and form fields. + +```csharp +public string? DisplayName // get, init +``` + +#### `Editor` + +Custom editor factory for this specific field. Takes (value, onChange) and returns an Element. + +```csharp +public Func, Element>? Editor // get, init +``` + +#### `FieldType` + +The CLR type of this field's value. + +```csharp +public Type FieldType // get, init +``` + +#### `Filterable` + +Whether this column can be filtered. Default true. + +```csharp +public bool Filterable // get, init +``` + +#### `Flex` + +Flex grow factor for column sizing. + +```csharp +public double? Flex // get, init +``` + +#### `FormatValue` + +Custom value formatter for grid display. + +```csharp +public Func? FormatValue // get, init +``` + +#### `GetValue` + +Gets the current value from the owner object. + +```csharp +public Func GetValue // get, init +``` + +#### `IsReadOnly` + +Whether this field is read-only in editors. + +```csharp +public bool IsReadOnly // get, init +``` + +#### `MaxWidth` + +Maximum column width in pixels. + +```csharp +public double? MaxWidth // get, init +``` + +#### `MinWidth` + +Minimum column width in pixels. + +```csharp +public double? MinWidth // get, init +``` + +#### `Name` + +Field name (used as key in accessors and Compose dictionary). + +```csharp +public string Name // get, init +``` + +#### `Order` + +Declaration order for stable sorting. + +```csharp +public int Order // get, init +``` + +#### `Pin` + +Pin position for fixed columns. + +```csharp +public PinPosition Pin // get, init +``` + +#### `SetValue` + +Sets the value on the owner object and returns the (possibly new) owner. For mutable properties: mutates in place and returns the same reference. For immutable properties: constructs a new object and returns it. Null for truly read-only fields (no setter, no constructor match). + +```csharp +public Func? SetValue // get, init +``` + +#### `Sortable` + +Whether this column can be sorted. Default true. + +```csharp +public bool Sortable // get, init +``` + +#### `Validators` + +Synchronous validators for this field. + +```csharp +public IReadOnlyList? Validators // get, init +``` + +#### `Width` + +Preferred column width in pixels. + +```csharp +public double? Width // get, init +``` + +## `FilterDescriptor` + +Describes a filter operation on a field. + +```csharp +public record FilterDescriptor(string Field, FilterOperator Operator, object? Value = null, object? ValueTo = null) +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Constructors + +#### `FilterDescriptor` + +Describes a filter operation on a field. + +```csharp +public FilterDescriptor(string Field, FilterOperator Operator, object? Value = null, object? ValueTo = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Field` | `string` | | | +| `Operator` | [`FilterOperator`](#filteroperator) | | | +| `Value` | `object?` | `null` | | +| `ValueTo` | `object?` | `null` | | + +### Properties + +#### `Field` + +```csharp +public string Field // get, init +``` + +#### `Operator` + +```csharp +public FilterOperator Operator // get, init +``` + +#### `Value` + +```csharp +public object? Value // get, init +``` + +#### `ValueTo` + +```csharp +public object? ValueTo // get, init +``` + +## `FilterOperator` + +Filter operators for data queries. + +```csharp +public enum FilterOperator +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `Equals` | `0` | Returns whether this object equals another object. | +| `NotEquals` | `1` | | +| `Contains` | `2` | | +| `StartsWith` | `3` | | +| `EndsWith` | `4` | | +| `GreaterThan` | `5` | | +| `GreaterThanOrEqual` | `6` | | +| `LessThan` | `7` | | +| `LessThanOrEqual` | `8` | | +| `Between` | `9` | | +| `In` | `10` | | +| `IsNull` | `11` | | +| `IsNotNull` | `12` | | + +## `RowKey` + +A strongly-typed key for identifying rows in a data source. + +```csharp +public readonly record struct RowKey(string Value) +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Constructors + +#### `RowKey` + +A strongly-typed key for identifying rows in a data source. + +```csharp +public RowKey(string Value) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Value` | `string` | | + +### Properties + +#### `Value` + +```csharp +public string Value // get, init +``` + +### Operators + +#### `op_Implicit` + +```csharp +public static implicit operator RowKey(Guid value) +public static implicit operator RowKey(int value) +public static implicit operator RowKey(string value) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `value` | `Guid` or `int` or `string` | | + +## `SortDescriptor` + +Describes a sort operation on a field. + +```csharp +public record SortDescriptor(string Field, SortDirection Direction = SortDirection.Ascending) +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Constructors + +#### `SortDescriptor` + +Describes a sort operation on a field. + +```csharp +public SortDescriptor(string Field, SortDirection Direction = SortDirection.Ascending) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Field` | `string` | | | +| `Direction` | [`SortDirection`](#sortdirection) | `SortDirection.Ascending` | | + +### Properties + +#### `Direction` + +```csharp +public SortDirection Direction // get, init +``` + +#### `Field` + +```csharp +public string Field // get, init +``` + +## `SortDirection` + +Sort direction for data queries. + +```csharp +public enum SortDirection +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `Ascending` | `0` | | +| `Descending` | `1` | | diff --git a/docs/guide/reference/data/enums.md b/docs/guide/reference/data/enums.md new file mode 100644 index 0000000000..a1faa390a2 --- /dev/null +++ b/docs/guide/reference/data/enums.md @@ -0,0 +1,28 @@ +# Enums + +The enumerations in this category. + +**Learn more:** [Data System](../../data-system.md) + +## `DataSourceCapabilities` + +Capabilities flags for data sources. + +```csharp +public enum DataSourceCapabilities +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `None` | `0` | | +| `ServerSort` | `1` | | +| `ServerFilter` | `2` | | +| `ServerSearch` | `4` | | +| `ServerCount` | `8` | | +| `ServerSelect` | `16` | | +| `Mutate` | `32` | | +| `Refresh` | `64` | | diff --git a/docs/guide/reference/data/index.md b/docs/guide/reference/data/index.md new file mode 100644 index 0000000000..cc454e0aa3 --- /dev/null +++ b/docs/guide/reference/data/index.md @@ -0,0 +1,23 @@ +# Data + +Async values, resources, the query cache and data sources. + +**Learn more:** [Data System](../../data-system.md), [Async Resources](../../async-resources.md) + +## Types + +| Type | Description | +| --- | --- | +| [Async values](async-values.md) | The value a resource hook returns while it loads, after it loads and after it fails. | +| [Column attributes](column-attributes.md) | Attributes that change how a property shows as a column. | +| [Enums](enums.md) | The enumerations in this category. | +| [Paging](paging.md) | Types for infinite and paged resources. | +| [Query cache](query-cache.md) | The process-wide cache that resource hooks share. | +| [Sort and filter descriptors](descriptors.md) | Requests, sort, filter and field descriptors that data sources receive. | +| [`FocusRevalidationService`](FocusRevalidationService.md) | Central service that invalidates stale `QueryCache` entries when the app window is reactivated or resumed, so consumers that opted in via `ResourceOptions.RefetchOnWindowFocus = true` see fresh data after an Alt-Tab or resume. | +| [`IDataSource`](IDataSource.md) | A read-only data source that provides paged access to items. | +| [`IKeyedDataSource`](IKeyedDataSource.md) | A data source that supports fetching individual items by key. | +| [`IMutableDataSource`](IMutableDataSource.md) | A mutable data source that supports CRUD operations. | +| [`IObservableDataSource`](IObservableDataSource.md) | A data source that fires events when data changes. | +| [`ListDataSource`](ListDataSource.md) | In-memory data source backed by a list. | +| [`ObservableListDataSource`](ObservableListDataSource.md) | An observable data source that watches an ObservableCollection for changes and fires DataChanged when items are added, removed, or modified. | diff --git a/docs/guide/reference/data/paging.md b/docs/guide/reference/data/paging.md new file mode 100644 index 0000000000..bd7d1d1c40 --- /dev/null +++ b/docs/guide/reference/data/paging.md @@ -0,0 +1,610 @@ +# Paging + +Types for infinite and paged resources. + +**Learn more:** [Async Resources](../../async-resources.md), [Data System](../../data-system.md) + +## `BlockStatus` + +Status of a cached block. + +```csharp +public enum BlockStatus +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `Loading` | `0` | Block is currently being loaded from the data source. | +| `Loaded` | `1` | Block data is available. | +| `Failed` | `2` | Block load failed. | + +## `CacheBlock` + +A cached block of data from a paged data source. + +```csharp +public record CacheBlock(int BlockIndex, IReadOnlyList Items, BlockStatus Status, string? Error = null) +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Constructors + +#### `CacheBlock` + +A cached block of data from a paged data source. + +```csharp +public CacheBlock(int BlockIndex, IReadOnlyList Items, BlockStatus Status, string? Error = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `BlockIndex` | `int` | | | +| `Items` | `IReadOnlyList` | | | +| `Status` | [`BlockStatus`](#blockstatus) | | | +| `Error` | `string?` | `null` | | + +### Properties + +#### `BlockIndex` + +```csharp +public int BlockIndex // get, init +``` + +#### `Error` + +```csharp +public string? Error // get, init +``` + +#### `Items` + +```csharp +public IReadOnlyList Items // get, init +``` + +#### `Status` + +```csharp +public BlockStatus Status // get, init +``` + +### Methods + +#### `LoadingBlock` + +Empty loading placeholder block. + +```csharp +public static CacheBlock LoadingBlock(int index) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `index` | `int` | | + +## `DataPage` + +A page of data from a data source. + +```csharp +public record DataPage(IReadOnlyList Items, string? ContinuationToken = null, int? TotalCount = null) +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Type parameters + +| Name | Description | +| --- | --- | +| `T` | The item type. | + +### Constructors + +#### `DataPage` + +A page of data from a data source. + +```csharp +public DataPage(IReadOnlyList Items, string? ContinuationToken = null, int? TotalCount = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Items` | `IReadOnlyList` | | The items in this page. | +| `ContinuationToken` | `string?` | `null` | Token for fetching the next page. Null means this is the last page. | +| `TotalCount` | `int?` | `null` | Total number of items matching the current filters (if the source supports counting). Null if the source doesn't support server-side counting. | + +**Type parameters** + +| Name | Description | +| --- | --- | +| `T` | The item type. | + +### Properties + +#### `ContinuationToken` + +Token for fetching the next page. Null means this is the last page. + +```csharp +public string? ContinuationToken // get, init +``` + +#### `Items` + +The items in this page. + +```csharp +public IReadOnlyList Items // get, init +``` + +#### `TotalCount` + +Total number of items matching the current filters (if the source supports counting). Null if the source doesn't support server-side counting. + +```csharp +public int? TotalCount // get, init +``` + +## `DataPageCache` + +Caches pages of data from IDataSource, keyed by sort/filter state + page index. Evicts blocks outside the viewport via LRU when max capacity is reached. + +Follows a pull model (matching Compose Paging 3): accessing a row index that falls in an unloaded block triggers the fetch. The virtualizer tells the cache which blocks are needed; the cache returns immediately for loaded blocks and initiates async loads for missing ones. + +```csharp +public class DataPageCache +``` + +Namespace: `Microsoft.UI.Reactor.Data`. + +### Constructors + +#### `DataPageCache` + +Creates a new DataPageCache. + +```csharp +public DataPageCache(IDataSource source, int blockSize = 50, int maxBlocks = 20) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `source` | [`IDataSource`](IDataSource.md) | | The data source to cache. | +| `blockSize` | `int` | `50` | Number of items per block (page size). Default 50. | +| `maxBlocks` | `int` | `20` | Maximum number of blocks to keep in cache. Default 20. | + +### Properties + +#### `BlockSize` + +Number of items per block. + +```csharp +public int BlockSize // get +``` + +#### `CachedBlockCount` + +Number of blocks currently in the cache. + +```csharp +public int CachedBlockCount // get +``` + +#### `CurrentState` + +Gets the current sort/filter state. Changing this via [`DataPageCache.SetState`](#setstate) invalidates all cached blocks. + +```csharp +public DataRequest CurrentState // get +``` + +#### `MaxBlocks` + +Maximum number of blocks in cache before LRU eviction. + +```csharp +public int MaxBlocks // get +``` + +#### `TotalCount` + +Total known row count from the last data source response. + +```csharp +public int? TotalCount // get +``` + +### Methods + +#### `GetBlock` + +Get the block containing the given block index. Returns cached data immediately for loaded blocks, or initiates an async fetch for missing blocks and returns a loading placeholder. + +```csharp +public CacheBlock GetBlock(int blockIndex) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `blockIndex` | `int` | | + +#### `GetBlockAsync` + +Get the block containing the given block index asynchronously. If the block is cached, returns immediately. Otherwise waits for the fetch. + +```csharp +public ValueTask> GetBlockAsync(int blockIndex, CancellationToken cancellationToken = default) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `blockIndex` | `int` | | | +| `cancellationToken` | `CancellationToken` | `default` | | + +#### `GetBlockStatus` + +Get the status of a block. + +```csharp +public BlockStatus GetBlockStatus(int blockIndex) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `blockIndex` | `int` | | + +#### `GetItem` + +Get the item at a specific row index, or default if not loaded. Triggers an async fetch for missing blocks. + +```csharp +public T? GetItem(int rowIndex) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `rowIndex` | `int` | | + +#### `Invalidate` + +Invalidate all cached blocks (e.g., after sort/filter change). + +```csharp +public void Invalidate() +``` + +#### `IsLoaded` + +Check if a row index is loaded. + +```csharp +public bool IsLoaded(int rowIndex) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `rowIndex` | `int` | | + +#### `PeekItem` + +Read-only peek: returns the item if its block is already loaded, or default if not. Does NOT trigger a fetch for missing blocks. Safe to call during a render pass. + +```csharp +public T? PeekItem(int rowIndex) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `rowIndex` | `int` | | + +#### `RequestBlock` + +Request that a block be loaded if it isn't already cached or in-flight. The fetch is deferred via Task.Yield so it never runs synchronously in the caller's stack frame, but stays on the caller's thread (UI thread). Fires [`DataPageCache.BlockLoaded`](#blockloaded) on completion. + +```csharp +public void RequestBlock(int blockIndex) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `blockIndex` | `int` | | + +#### `SetState` + +Update the sort/filter state. Invalidates all cached blocks. + +```csharp +public void SetState(DataRequest state) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `state` | [`DataRequest`](descriptors.md#datarequest) | | + +### Events + +#### `BlockLoaded` + +Fires when a block finishes loading (success or failure). + +```csharp +public event Action? BlockLoaded +``` + +## `InfiniteResource` + +Pull-model paginated result view. Each call-site of `UseInfiniteResource` owns a single [`InfiniteResource`](#infiniteresourcetitem); virtualized controls call [`InfiniteResource.ItemAt`](#itemat) / [`InfiniteResource.EnsureRange`](#ensurerange) per row to drive fetches, and render `null` slots as placeholders. + +```csharp +public sealed class InfiniteResource +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Remarks + +All mutating methods are UI-thread-affined. Internally the implementation shares a lock for structural mutations (page table, cursor, load state). Callers should not enumerate [`InfiniteResource.Items`](#items_2) from a background thread. + +### Properties + +#### `EstimatedRemaining` + +Approximate number of items not yet loaded. 0 once [`InfiniteResource.HasMore`](#hasmore) is false. + +```csharp +public int EstimatedRemaining // get +``` + +#### `HasMore` + +True iff the server has not yet reported `NextCursor == null`. + +```csharp +public bool HasMore // get +``` + +#### `Items` + +Flat, virtualized view. Indices beyond loaded content are either null-placeholders (in-flight or about-to-fetch) or, past the known end, not returned. + +```csharp +public IReadOnlyList Items // get +``` + +#### `LoadState` + +Current load state — updated on every fetch lifecycle event. + +```csharp +public LoadState LoadState // get +``` + +#### `TotalCount` + +Total items as reported by the server, or null when unknown. + +```csharp +public int? TotalCount // get +``` + +### Methods + +#### `EnsureRange` + +Eagerly ensures every page covering `[firstIndex, lastIndex]` is loaded (or in-flight). Dedups against existing in-flight fetches. + +```csharp +public void EnsureRange(int firstIndex, int lastIndex) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `firstIndex` | `int` | | +| `lastIndex` | `int` | | + +#### `FetchNext` + +Fetches the next page using the last-known cursor. No-op if load-state is not [`LoadState.Idle`](async-values.md#loadstateidle) or if [`InfiniteResource.HasMore`](#hasmore) is false. + +```csharp +public void FetchNext() +``` + +#### `ItemAt` + +Returns the item at `index` or null when the slot is in-flight / unloaded. Triggers a coalesced fetch when the slot's page is not yet requested, unless the index is past the known end. + +```csharp +public TItem? ItemAt(int index) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `index` | `int` | | + +#### `Refresh` + +Invalidate all cached pages and refetch from page 1. Preserves the current [`InfiniteResource.TotalCount`](#totalcount_2) — consumers that want to snapshot scroll state should do so inside their [`LoadState.Loading`](async-values.md#loadstateloading) render. + +```csharp +public void Refresh() +``` + +#### `Retry` + +Retry the most recent failed page fetch. No-op if the current load-state is not [`LoadState.Error`](async-values.md#loadstateerror). + +```csharp +public void Retry() +``` + +## `InfiniteResourceOptions` + +Tuning for `UseInfiniteResource`. Defaults: 50 items per page, no LRU cap (keeps every loaded page), 5-minute `CacheTime`, 0 `StaleTime`. + +```csharp +public sealed record InfiniteResourceOptions(int PageSize = 50, int? MaxLoadedPages = null, TimeSpan? StaleTime = null, TimeSpan? CacheTime = null, string? CacheKeyPrefix = null) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `InfiniteResourceOptions` + +Tuning for `UseInfiniteResource`. Defaults: 50 items per page, no LRU cap (keeps every loaded page), 5-minute `CacheTime`, 0 `StaleTime`. + +```csharp +public InfiniteResourceOptions(int PageSize = 50, int? MaxLoadedPages = null, TimeSpan? StaleTime = null, TimeSpan? CacheTime = null, string? CacheKeyPrefix = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `PageSize` | `int` | `50` | Number of items per page. | +| `MaxLoadedPages` | `int?` | `null` | Maximum retained pages; null keeps all loaded pages. | +| `StaleTime` | `TimeSpan?` | `null` | Stale-time setting; null uses zero. | +| `CacheTime` | `TimeSpan?` | `null` | Retention after the last subscriber leaves; null uses five minutes. | +| `CacheKeyPrefix` | `string?` | `null` | Overrides the prefix for page cache keys; null uses a prefix unique to this hook. Page keys still include the dependency hash, initial page size, and page index. Changing deps cancels in-flight page requests, resets the page set, and loads the first page for the new deps, even if the prefix is unchanged. | + +### Properties + +#### `CacheKeyPrefix` + +Overrides the prefix for page cache keys; null uses a prefix unique to this hook. Page keys still include the dependency hash, initial page size, and page index. Changing deps cancels in-flight page requests, resets the page set, and loads the first page for the new deps, even if the prefix is unchanged. + +```csharp +public string? CacheKeyPrefix // get, init +``` + +#### `CacheTime` + +Retention after the last subscriber leaves; null uses five minutes. + +```csharp +public TimeSpan? CacheTime // get, init +``` + +#### `MaxLoadedPages` + +Maximum retained pages; null keeps all loaded pages. + +```csharp +public int? MaxLoadedPages // get, init +``` + +#### `PageSize` + +Number of items per page. + +```csharp +public int PageSize // get, init +``` + +#### `StaleTime` + +Stale-time setting; null uses zero. + +```csharp +public TimeSpan? StaleTime // get, init +``` + +### Fields + +#### `Default` + +```csharp +public static readonly InfiniteResourceOptions Default +``` + +## `Page` + +One page of paginated results, as returned by a `UseInfiniteResource` fetcher. + +```csharp +public sealed record Page(IReadOnlyList Items, TCursor? NextCursor, int? TotalCount = null) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `Page` + +One page of paginated results, as returned by a `UseInfiniteResource` fetcher. + +```csharp +public Page(IReadOnlyList Items, TCursor? NextCursor, int? TotalCount = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Items` | `IReadOnlyList` | | The page payload. | +| `NextCursor` | `TCursor?` | | Cursor for the next page; null signals the end of the list. | +| `TotalCount` | `int?` | `null` | Server-reported total (when known); enables stable virtualization. | + +### Properties + +#### `Items` + +The page payload. + +```csharp +public IReadOnlyList Items // get, init +``` + +#### `NextCursor` + +Cursor for the next page; null signals the end of the list. + +```csharp +public TCursor? NextCursor // get, init +``` + +#### `TotalCount` + +Server-reported total (when known); enables stable virtualization. + +```csharp +public int? TotalCount // get, init +``` diff --git a/docs/guide/reference/data/query-cache.md b/docs/guide/reference/data/query-cache.md new file mode 100644 index 0000000000..3f46236006 --- /dev/null +++ b/docs/guide/reference/data/query-cache.md @@ -0,0 +1,242 @@ +# Query cache + +The process-wide cache that resource hooks share. + +**Learn more:** [Async Resources](../../async-resources.md) + +## `CacheEntry` + +```csharp +public sealed record CacheEntry(T Value, DateTime FetchedAt, TimeSpan StaleTime, int SubscriberCount) +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Constructors + +#### `CacheEntry` + +```csharp +public CacheEntry(T Value, DateTime FetchedAt, TimeSpan StaleTime, int SubscriberCount) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Value` | `T` | | +| `FetchedAt` | `DateTime` | | +| `StaleTime` | `TimeSpan` | | +| `SubscriberCount` | `int` | | + +### Properties + +#### `FetchedAt` + +```csharp +public DateTime FetchedAt // get, init +``` + +#### `StaleTime` + +```csharp +public TimeSpan StaleTime // get, init +``` + +#### `SubscriberCount` + +```csharp +public int SubscriberCount // get, init +``` + +#### `Value` + +```csharp +public T Value // get, init +``` + +## `QueryCache` + +Process-wide query cache with TTL, ref-counted subscriptions, and pattern invalidation. Shared across components via [`Context`](../components/Context.md) — see [`AppContexts.QueryCache`](../components/AppContexts.md#querycache). + +```csharp +public sealed class QueryCache : IDisposable +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +### Remarks + +**Threading.** All public methods are safe to call from any thread. Slots are protected by a per-key lock; [`QueryCache.EntryChanged`](#entrychanged) fires either inline or on the configured [`QueryCache.DispatcherPost`](#dispatcherpost) callback (set by `ReactorHost` at bootstrap). Tests can leave it null to observe events inline. + +**Eviction.** A single shared timer (started lazily on first subscription) polls all slots every [`QueryCache.EvictionPollInterval`](#evictionpollinterval). Slots whose `SubscriberCount == 0` for longer than their `CacheTime` are evicted. Using one timer keeps the entry count's impact on system timers O(1). + +### Constructors + +#### `QueryCache` + +```csharp +public QueryCache() +``` + +### Properties + +#### `Count` + +Snapshot the current cache size. Diagnostic only — do not use for correctness. + +```csharp +public int Count // get +``` + +#### `DispatcherPost` + +Injected marshaller for [`QueryCache.EntryChanged`](#entrychanged). Null → fires inline. + +```csharp +public Action? DispatcherPost // get, set +``` + +#### `EvictionPollInterval` + +How often the eviction timer checks every slot for expiry. Default 1s. + +```csharp +public static TimeSpan EvictionPollInterval // get, set +``` + +#### `UtcNow` + +Clock override for deterministic tests. + +```csharp +public Func UtcNow // get, set +``` + +### Methods + +#### `Clear` + +Removes every entry. Subscribers are retained. Fires [`QueryCache.EntryChanged`](#entrychanged) once per key that actually held a value. + +```csharp +public void Clear() +``` + +#### `Dispose` + +Releases the resources that this object holds. + +```csharp +public void Dispose() +``` + +#### `EvictNow` + +Test / diagnostic hook: drive the eviction sweep explicitly rather than waiting for the background [`QueryCache.EvictionPollInterval`](#evictionpollinterval) timer. Returns the set of keys that were evicted on this pass. Safe to call from any thread. + +```csharp +public IReadOnlyList EvictNow() +``` + +**Remarks** + +Production code should not need this — subscribers keep entries alive and the shared timer evicts zero-subscriber entries past their `CacheTime`. It's exposed publicly so framerate / stress tests can make eviction deterministic. + +#### `Invalidate` + +Removes the entry (if any) for `key`. Subscribers are retained — the next [`QueryCache.Set`](#set) will see their count. Fires [`QueryCache.EntryChanged`](#entrychanged) if there was an entry to remove. + +```csharp +public void Invalidate(string key) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `key` | `string` | | + +#### `InvalidatePattern` + +Invalidates every key that starts with `keyPrefix`. O(n) in the number of cached keys — document the pattern prefix carefully if you store a lot of unrelated keys under one cache. + +```csharp +public void InvalidatePattern(string keyPrefix) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `keyPrefix` | `string` | | + +#### `Set` + +Stores or replaces the entry for `key`. Preserves any existing subscriber count on the slot. Fires [`QueryCache.EntryChanged`](#entrychanged). + +```csharp +public void Set(string key, T value, TimeSpan staleTime, TimeSpan cacheTime) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `key` | `string` | | +| `value` | `T` | | +| `staleTime` | `TimeSpan` | | +| `cacheTime` | `TimeSpan` | | + +#### `Subscribe` + +Increments the subscriber count on `key`. Cancels any pending eviction for the slot. Returns the new subscriber count. + +```csharp +public int Subscribe(string key) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `key` | `string` | | + +#### `TryGet` + +Retrieves the current entry for `key` if present and typed as `T`. Returns false on miss or on type-mismatch. Staleness is a caller-side decision — the entry's [`CacheEntry.FetchedAt`](#fetchedat) and [`CacheEntry.StaleTime`](#staletime) are both returned on a hit. + +```csharp +public bool TryGet(string key, out CacheEntry entry) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `key` | `string` | | +| `entry` | [`CacheEntry`](#cacheentryt) | | + +#### `Unsubscribe` + +Decrements the subscriber count. When it reaches zero, starts the eviction clock based on the slot's most recent [`QueryCache.Set`](#set) `cacheTime`. Throws [`InvalidOperationException`](https://learn.microsoft.com/dotnet/api/system.invalidoperationexception) if called on a slot that has no subscribers — this catches hook-logic bugs that would otherwise hide underflow forever. + +```csharp +public int Unsubscribe(string key) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `key` | `string` | | + +### Events + +#### `EntryChanged` + +Fires when an entry is added, replaced, invalidated, or evicted. + +```csharp +public event Action? EntryChanged +``` diff --git a/docs/guide/reference/diagnostics/ReactorEvent.md b/docs/guide/reference/diagnostics/ReactorEvent.md new file mode 100644 index 0000000000..bdd626f56d --- /dev/null +++ b/docs/guide/reference/diagnostics/ReactorEvent.md @@ -0,0 +1,108 @@ +# ReactorEvent + +A single event captured from the `Microsoft-UI-Reactor` [`EventSource`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventsource), delivered to subscribers of [`ReactorTrace.Subscribe`](ReactorTrace.md#subscribe). + +The payload arrays come from [`EventWrittenEventArgs.Payload`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventwritteneventargs.payload) and [`EventWrittenEventArgs.PayloadNames`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventwritteneventargs.payloadnames) directly — no reflection is involved, so this surface is AOT/trim-clean. + +PII discipline: every framework event has already stripped sensitive fields (no [`Exception.Message`](https://learn.microsoft.com/dotnet/api/system.exception.message), no window titles, no instantiated route paths). Subscribers should respect that policy in any downstream sink they forward to. + +```csharp +public readonly record struct ReactorEvent(int EventId, string EventName, EventLevel Level, EventKeywords Keywords, DateTime TimestampUtc, int ThreadId, IReadOnlyList Payload, IReadOnlyList PayloadNames) +``` + +Namespace: `Microsoft.UI.Reactor.Diagnostics`. + +**Learn more:** [Diagnostics](../../diagnostics.md) + +## Constructors + +### `ReactorEvent` + +A single event captured from the `Microsoft-UI-Reactor` [`EventSource`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventsource), delivered to subscribers of [`ReactorTrace.Subscribe`](ReactorTrace.md#subscribe). + +The payload arrays come from [`EventWrittenEventArgs.Payload`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventwritteneventargs.payload) and [`EventWrittenEventArgs.PayloadNames`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventwritteneventargs.payloadnames) directly — no reflection is involved, so this surface is AOT/trim-clean. + +PII discipline: every framework event has already stripped sensitive fields (no [`Exception.Message`](https://learn.microsoft.com/dotnet/api/system.exception.message), no window titles, no instantiated route paths). Subscribers should respect that policy in any downstream sink they forward to. + +```csharp +public ReactorEvent(int EventId, string EventName, EventLevel Level, EventKeywords Keywords, DateTime TimestampUtc, int ThreadId, IReadOnlyList Payload, IReadOnlyList PayloadNames) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `EventId` | `int` | Numeric event identifier (stable per event method; see the EventId allocation comment in `ReactorEventSource`). | +| `EventName` | `string` | The C# method name on `ReactorEventSource` that emitted this event (e.g. `"ReconcileStart"`, `"SwallowedError"`). | +| `Level` | `EventLevel` | Severity ([`EventLevel.Verbose`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventlevel.verbose) through [`EventLevel.Critical`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventlevel.critical)). | +| `Keywords` | `EventKeywords` | The bitwise keyword(s) the event was emitted under. ETW reserved bits in the high 4 bits may be set by the runtime; subscribers should mask against the keyword they care about rather than equality-test. | +| `TimestampUtc` | `DateTime` | UTC capture timestamp at delivery time. | +| `ThreadId` | `int` | Managed thread id of the emission thread. | +| `Payload` | `IReadOnlyList` | Positional payload values in the order declared by the event method's parameters. Always non-null but may be empty. | +| `PayloadNames` | `IReadOnlyList` | Parallel array of parameter names. Always non-null; same length as `Payload`. | + +## Properties + +### `EventId` + +Numeric event identifier (stable per event method; see the EventId allocation comment in `ReactorEventSource`). + +```csharp +public int EventId // get, init +``` + +### `EventName` + +The C# method name on `ReactorEventSource` that emitted this event (e.g. `"ReconcileStart"`, `"SwallowedError"`). + +```csharp +public string EventName // get, init +``` + +### `Keywords` + +The bitwise keyword(s) the event was emitted under. ETW reserved bits in the high 4 bits may be set by the runtime; subscribers should mask against the keyword they care about rather than equality-test. + +```csharp +public EventKeywords Keywords // get, init +``` + +### `Level` + +Severity ([`EventLevel.Verbose`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventlevel.verbose) through [`EventLevel.Critical`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventlevel.critical)). + +```csharp +public EventLevel Level // get, init +``` + +### `Payload` + +Positional payload values in the order declared by the event method's parameters. Always non-null but may be empty. + +```csharp +public IReadOnlyList Payload // get, init +``` + +### `PayloadNames` + +Parallel array of parameter names. Always non-null; same length as `Payload`. + +```csharp +public IReadOnlyList PayloadNames // get, init +``` + +### `ThreadId` + +Managed thread id of the emission thread. + +```csharp +public int ThreadId // get, init +``` + +### `TimestampUtc` + +UTC capture timestamp at delivery time. + +```csharp +public DateTime TimestampUtc // get, init +``` diff --git a/docs/guide/reference/diagnostics/ReactorSourceMap.md b/docs/guide/reference/diagnostics/ReactorSourceMap.md new file mode 100644 index 0000000000..7c2755e156 --- /dev/null +++ b/docs/guide/reference/diagnostics/ReactorSourceMap.md @@ -0,0 +1,53 @@ +# ReactorSourceMap + +Spec 010 — runtime switch and read path for Reactor source mapping. + +**Why a runtime flag at all.** Interceptors are baked in at compile time, so without a runtime gate every Debug build would pay the stamping cost whether or not anyone is inspecting. This flag is what the emitted interceptor checks before writing a location, so an un-inspected Debug session allocates nothing extra. + +**It does not change control tagging for leaves.** The reconciler attaches a `ReactorState` (the control → element back-pointer) only to controls that something will read back — callbacks, a key, extras, or reference modifiers (see `Reconciler.NeedsTag`), which is the allocation win PR #468 landed. `NeedsTag` has no arm for this flag on ordinary elements: a stamped element carries its `CallSite` in the `Extensions` bucket and so already satisfies the existing `Extensions is not null` test. Adding one would only tag *unstamped* elements, which have no location to return, while re-introducing the per-leaf allocation. Elements the generator does not reach (wrapper factories, bare-string children) therefore stay untagged and report no location rather than a wrong one. The one exception is component boundaries: while this flag is on, every component's Border wrapper is tagged so an inspector can find where each component starts — one allocation per component, never per leaf. + +**Who turns it on.** The devtools session switch. `ReactorApp` sets [`ReactorSourceMap.Enabled`](#enabled) when the process was launched with `--devtools app` / `--devtools run`, so a retail session never pays. It is public-settable so a host that embeds its own inspector (or a test) can opt in without going through the CLI. + +```csharp +public static class ReactorSourceMap +``` + +Namespace: `Microsoft.UI.Reactor.Diagnostics`. + +**Learn more:** [Diagnostics](../../diagnostics.md) + +## Properties + +### `Enabled` + +True when source mapping is active for this process. Read by every generated factory interceptor before it stamps, so it is an `int` + `Volatile` rather than a lock. + +```csharp +public static bool Enabled // get, set +``` + +## Methods + +### `GetSource` + +Resolves the DSL call site that produced `control`. + +This is the whole read chain, and it deliberately reuses the back-pointer that already exists rather than adding a second attached property: `UIElement` → `ReactorAttached.StateProperty` → `ReactorState.Element` → [`Element.CallSite`](../elements/Element.md#callsite). + +Returns `null` when the control was not produced by Reactor, or when the element behind it carries no [`Element.CallSite`](../elements/Element.md#callsite) — because it was built while [`ReactorSourceMap.Enabled`](#enabled) was false, or because no provider reaches that factory (see the known limitations in the source-mapping guide). Note this is a property of the ELEMENT, not of tagging: a control can be tagged for unrelated reasons (callbacks, a key, other extras) and still report no location, and an element hand-stamped with a `CallSite` reports one even with the flag off. + +Target-wrapping decorators are resolved through. `Flyout`, `MenuFlyout` and `CommandBarFlyout` mount their `Target`'s control and then deliberately replace that control's tag with themselves, because their Opened/Closed handlers read it back. The realized control is still the target's — a `Button` inside a `Flyout(...)` was created by the `Button(` line — so reporting the decorator's line would name the wrong creator, the same misattribution the generator avoids for pass-through factories. The walk is a loop so nested decorators resolve to the innermost target. + +Native AOT in diagnostics mode does not tag a control whose element's only extra is its call site (no managed inspector can load to read the tag); there the location is resolved from the control's published `ReactorSource` value and is the same [`SourceLocation`](../components/SourceLocation.md) the tag would give. + +Menu and command-bar items a flyout, menu bar or command bar builds from item records (`MenuItem(…)`, `AppBarButton(…)`) carry no element tag; in diagnostics mode their location is resolved the same way, from their published value. + +```csharp +public static SourceLocation? GetSource(UIElement control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `control` | `UIElement` | | diff --git a/docs/guide/reference/diagnostics/ReactorSourceTransparentAttribute.md b/docs/guide/reference/diagnostics/ReactorSourceTransparentAttribute.md new file mode 100644 index 0000000000..10a90571d4 --- /dev/null +++ b/docs/guide/reference/diagnostics/ReactorSourceTransparentAttribute.md @@ -0,0 +1,35 @@ +# ReactorSourceTransparentAttribute + +Spec 010 — marks a helper method as *source-transparent*: elements it returns are attributed to the line that CALLED it, not to the line inside it that ran the DSL factory. + +Without this, a thin forwarding helper collapses every one of its call sites onto a single line, because an interceptor replaces the *call site* and the call site of `TextBlock(...)` in `static Element MyHeader() => TextBlock("header");` is inside `MyHeader`. Annotating `MyHeader` flips the attribution outward: the source-map generator emits no interceptor for the factory calls in its body, and instead intercepts calls *to* `MyHeader` and stamps the caller's line. + +**Deliberately opt-in.** It is not a blanket rule for helpers, because for most element-returning methods the body line is the RIGHT answer — a `Component.Render()` body is where the author actually wrote the UI, and deferring it to the reconciler's call site would be a regression. Only a thin forwarder, whose own line carries no information a reader wants, benefits. This attribute is how that intent is expressed. + +**Nesting.** Annotated methods compose: a transparent helper calling another transparent helper keeps deferring outward until it reaches a caller that is not annotated, and that caller's line is what gets stamped. + +``[ReactorSourceTransparent] internal static Element Field(string label, string value) => HStack(TextBlock(label), TextBlock(value)); // Both rows report THEIR OWN line, instead of both reporting the // `HStack(` line inside Field. var form = VStack( Field("Name", name), Field("Email", email));`` + +```csharp +public sealed class ReactorSourceTransparentAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Diagnostics`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +**Learn more:** [Diagnostics](../../diagnostics.md) + +## Remarks + +**Requirements.** The generator has to be able to emit an interceptor that forwards to the annotated method, so it must be `static`, return an `Element`, and be reachable by name from a generated file in the same compilation — i.e. `public` or `internal` (never `private`), not declared in a `file`-local or generic type, and not a local function (C# interceptors cannot intercept those). An annotation the generator cannot honour is reported as `REACTOR_SOURCEMAP_001` rather than silently doing nothing, and attribution falls back to today's behaviour — the helper's own line — so a bad annotation never makes attribution worse than no annotation. + +**Where it takes effect.** Rule 1 (suppressing stamps inside the body) applies in the compilation that *declares* the method; rule 2 (stamping at the call site) applies in the compilation that *calls* it. Both need the source-map generator loaded, so annotating a method in a library whose consumer has not enabled `ReactorSourceMap` simply leaves those elements unstamped. + +A plain marker attribute with no members and no reflection surface, so it is trim- and AOT-safe. It is read by the generator from metadata, which is why it must be `public`. + +## Constructors + +### `ReactorSourceTransparentAttribute` + +```csharp +public ReactorSourceTransparentAttribute() +``` diff --git a/docs/guide/reference/diagnostics/ReactorTrace.md b/docs/guide/reference/diagnostics/ReactorTrace.md new file mode 100644 index 0000000000..22f48c0f00 --- /dev/null +++ b/docs/guide/reference/diagnostics/ReactorTrace.md @@ -0,0 +1,98 @@ +# ReactorTrace + +In-process subscription helper for the `Microsoft-UI-Reactor` [`EventSource`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventsource). Lets an app developer (or an internal devtools surface — `reactor.logs` MCP, an `ILogger` bridge) observe framework events without writing an [`EventListener`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventlistener) subclass. + +This is deliberately **not** a file-capture API. The .NET runtime already provides three: + +- `DOTNET_EnableEventPipe` + `DOTNET_EventPipeOutputPath` environment variables (zero app code). +- `dotnet-trace collect --providers Microsoft-UI-Reactor`. +- Visual Studio Performance Profiler → Events Viewer. + +See `docs/guide/diagnostics.md` for end-to-end examples. + +```csharp +public static class ReactorTrace +``` + +Namespace: `Microsoft.UI.Reactor.Diagnostics`. + +**Learn more:** [Diagnostics](../../diagnostics.md) + +## Methods + +### `GetComponentControl` + +Resolves the `componentId` carried by a `ComponentRendered` event (`Microsoft-UI-Reactor` EventId 40) to the realized control whose bounds are that component's — the component's wrapper, or for a host's root component the host's current root content control. Use it to flash the region that just re-rendered ("highlight updates"). + +Returns `null` for `0`, for an id this process never issued, once the component has unmounted or its control was collected, and while the control does not exist yet: a component's mount event is raised before its subtree mounts (the id is mapped once that finishes), and a root's first event before its reconcile pass has produced the content. An id from a render whose subtree was then discarded — caught by an `ErrorBoundary`, or a failure that propagated — may never resolve. So resolve after the pass completes (e.g. on the next dispatcher tick) rather than inside the event callback, and treat `null` as "nothing on screen for this id". Ids are only issued, and controls only recorded, while the event is enabled, so subscribe first. + +Call on the UI thread; the returned control is a live WinUI object. + +```csharp +public static UIElement? GetComponentControl(long componentId) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `componentId` | `long` | The event's `componentId` payload field. | + +### `Subscribe` + +Subscribes to `Microsoft-UI-Reactor` events in-process. Returns an [`IDisposable`](https://learn.microsoft.com/dotnet/api/system.idisposable) token; dispose it to detach. + +The callback fires on the emission thread — typically the UI dispatcher when an event originates from reconcile / render, or a thread-pool thread otherwise. Keep the callback work minimal and never let it throw across the framework boundary — a throwing subscriber propagates into [`EventSource`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventsource)'s emit path and surfaces as an ETW failure. + +Multiple concurrent subscribers are supported. Each subscriber's `level` and `keywords` are independently active until the returned token is disposed; the runtime unions them when computing whether `IsEnabled` on the event source returns true. Be aware that a broad subscriber ([`EventLevel.Verbose`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventlevel.verbose) + all keywords) raises the cost of every hot-path call site on the framework for as long as it lives. + +For writing a trace file, use one of: + +- `DOTNET_EnableEventPipe` / `DOTNET_EventPipeOutputPath` env vars. +- `dotnet-trace collect --providers Microsoft-UI-Reactor`. +- Visual Studio Performance Profiler → Events Viewer. + +```csharp +public static IDisposable Subscribe(Action onEvent, EventLevel level = (EventLevel)5, EventKeywords keywords = (EventKeywords)-1) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `onEvent` | `Action` | | Callback invoked once per matching event. Must be non-null. | +| `level` | `EventLevel` | `(EventLevel)5` | Minimum severity to forward. Defaults to [`EventLevel.Verbose`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventlevel.verbose) so subscribers see everything (state changes, per-trampoline dispatches) unless they explicitly pass a stricter level. | +| `keywords` | `EventKeywords` | `(EventKeywords)-1` | Keyword mask to forward. Defaults to all keywords (`(EventKeywords)(-1)`). | + +**Returns:** Disposable token. Disposing detaches the underlying [`EventListener`](https://learn.microsoft.com/dotnet/api/system.diagnostics.tracing.eventlistener); subsequent events do not reach `onEvent`. + +**Exceptions** + +| Exception | Condition | +| --- | --- | +| [`ArgumentNullException`](https://learn.microsoft.com/dotnet/api/system.argumentnullexception) | If `onEvent` is `null`. | + +### `TryGetComponentId` + +The reverse of [`ReactorTrace.GetComponentControl`](#getcomponentcontrol): the `componentId` that `ComponentRendered` events use for the component rendering into `control` (a component's wrapper control). Lets an inspector filter the event stream down to the component a user selected. + +Returns `false` when `control` is not a component wrapper, or when that component has not rendered since `ComponentRendered` was enabled. A host's root id is never returned here — the root content control is often also a child component's wrapper, and that child keeps the mapping. + +Call on the UI thread: the id is read from the control's Reactor state. + +```csharp +public static bool TryGetComponentId(UIElement control, out long componentId) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `control` | `UIElement` | | +| `componentId` | `long` | | + +**Exceptions** + +| Exception | Condition | +| --- | --- | +| [`ArgumentNullException`](https://learn.microsoft.com/dotnet/api/system.argumentnullexception) | If `control` is `null`. | diff --git a/docs/guide/reference/diagnostics/devtools.md b/docs/guide/reference/diagnostics/devtools.md new file mode 100644 index 0000000000..41288eef4e --- /dev/null +++ b/docs/guide/reference/diagnostics/devtools.md @@ -0,0 +1,373 @@ +# Developer tools hosting + +Types the developer tools use to start inside an app. + +**Learn more:** [Devtools](../../devtools.md) + +## `DevtoolsCliOptions` + +Parsed result of a `--devtools` / `--preview` invocation. [`DevtoolsCliOptions.Subverb`](#subverb) is `null` when neither flag is present. + +```csharp +public sealed record DevtoolsCliOptions(DevtoolsSubverb? Subverb, string? ComponentName, bool VsCodeMode, int Fps, string? ListOutputPath, string? ScreenshotOutputPath, int? McpPort, string? LogLevel, McpTransport Transport, bool UsedDeprecatedPreview, bool PreviewAndDevtoolsConflict, string? ProjectIdentifier = null, bool LogsDisabled = false, int? LogsCapacityMb = null, bool EmbedRequested = false, WindowEmbedStyle EmbedStyle = WindowEmbedStyle.Child, int? EmbedHostPid = null, string? EmbedValidationError = null, bool EmbedAutoEnabledVsCode = false, double? WindowWidth = null, double? WindowHeight = null, double? WindowX = null, double? WindowY = null) +``` + +Namespace: `Microsoft.UI.Reactor.Hosting.Devtools`. + +### Constructors + +#### `DevtoolsCliOptions` + +Parsed result of a `--devtools` / `--preview` invocation. [`DevtoolsCliOptions.Subverb`](#subverb) is `null` when neither flag is present. + +```csharp +public DevtoolsCliOptions(DevtoolsSubverb? Subverb, string? ComponentName, bool VsCodeMode, int Fps, string? ListOutputPath, string? ScreenshotOutputPath, int? McpPort, string? LogLevel, McpTransport Transport, bool UsedDeprecatedPreview, bool PreviewAndDevtoolsConflict, string? ProjectIdentifier = null, bool LogsDisabled = false, int? LogsCapacityMb = null, bool EmbedRequested = false, WindowEmbedStyle EmbedStyle = WindowEmbedStyle.Child, int? EmbedHostPid = null, string? EmbedValidationError = null, bool EmbedAutoEnabledVsCode = false, double? WindowWidth = null, double? WindowHeight = null, double? WindowX = null, double? WindowY = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `Subverb` | `DevtoolsSubverb?` | | | +| `ComponentName` | `string?` | | | +| `VsCodeMode` | `bool` | | | +| `Fps` | `int` | | | +| `ListOutputPath` | `string?` | | | +| `ScreenshotOutputPath` | `string?` | | | +| `McpPort` | `int?` | | | +| `LogLevel` | `string?` | | | +| `Transport` | [`McpTransport`](#mcptransport) | | | +| `UsedDeprecatedPreview` | `bool` | | | +| `PreviewAndDevtoolsConflict` | `bool` | | | +| `ProjectIdentifier` | `string?` | `null` | | +| `LogsDisabled` | `bool` | `false` | | +| `LogsCapacityMb` | `int?` | `null` | | +| `EmbedRequested` | `bool` | `false` | | +| `EmbedStyle` | [`WindowEmbedStyle`](../hosting/window-options.md#windowembedstyle) | `WindowEmbedStyle.Child` | | +| `EmbedHostPid` | `int?` | `null` | | +| `EmbedValidationError` | `string?` | `null` | | +| `EmbedAutoEnabledVsCode` | `bool` | `false` | | +| `WindowWidth` | `double?` | `null` | | +| `WindowHeight` | `double?` | `null` | | +| `WindowX` | `double?` | `null` | | +| `WindowY` | `double?` | `null` | | + +### Properties + +#### `ComponentName` + +```csharp +public string? ComponentName // get, init +``` + +#### `EmbedAutoEnabledVsCode` + +```csharp +public bool EmbedAutoEnabledVsCode // get, init +``` + +#### `EmbedHostPid` + +```csharp +public int? EmbedHostPid // get, init +``` + +#### `EmbedRequested` + +```csharp +public bool EmbedRequested // get, init +``` + +#### `EmbedStyle` + +```csharp +public WindowEmbedStyle EmbedStyle // get, init +``` + +#### `EmbedValidationError` + +```csharp +public string? EmbedValidationError // get, init +``` + +#### `Fps` + +```csharp +public int Fps // get, init +``` + +#### `ListOutputPath` + +```csharp +public string? ListOutputPath // get, init +``` + +#### `LogLevel` + +```csharp +public string? LogLevel // get, init +``` + +#### `LogsCapacityMb` + +```csharp +public int? LogsCapacityMb // get, init +``` + +#### `LogsDisabled` + +```csharp +public bool LogsDisabled // get, init +``` + +#### `McpPort` + +```csharp +public int? McpPort // get, init +``` + +#### `PreviewAndDevtoolsConflict` + +```csharp +public bool PreviewAndDevtoolsConflict // get, init +``` + +#### `ProjectIdentifier` + +```csharp +public string? ProjectIdentifier // get, init +``` + +#### `ScreenshotOutputPath` + +```csharp +public string? ScreenshotOutputPath // get, init +``` + +#### `Subverb` + +```csharp +public DevtoolsSubverb? Subverb // get, init +``` + +#### `Transport` + +```csharp +public McpTransport Transport // get, init +``` + +#### `UsedDeprecatedPreview` + +```csharp +public bool UsedDeprecatedPreview // get, init +``` + +#### `VsCodeMode` + +```csharp +public bool VsCodeMode // get, init +``` + +#### `WindowHeight` + +```csharp +public double? WindowHeight // get, init +``` + +#### `WindowWidth` + +```csharp +public double? WindowWidth // get, init +``` + +#### `WindowX` + +```csharp +public double? WindowX // get, init +``` + +#### `WindowY` + +```csharp +public double? WindowY // get, init +``` + +## `DevtoolsSubverb` + +```csharp +public enum DevtoolsSubverb +``` + +Namespace: `Microsoft.UI.Reactor.Hosting.Devtools`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `Run` | `0` | | +| `List` | `1` | | +| `Screenshot` | `2` | | +| `Tree` | `3` | | +| `App` | `4` | | + +## `IReactorDevtoolsHost` + +```csharp +public interface IReactorDevtoolsHost +``` + +Namespace: `Microsoft.UI.Reactor.Hosting.Devtools`. + +### Methods + +#### `BuildDevtoolsMenu` + +```csharp +public Element? BuildDevtoolsMenu(Func>? items, string glyph, string toolTip, string? automationId) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `items` | `Func>?` | | +| `glyph` | `string` | | +| `toolTip` | `string` | | +| `automationId` | `string?` | | + +#### `TryHandleCommandLine` + +```csharp +public bool TryHandleCommandLine(ReactorDevtoolsBootRequest request) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `request` | [`ReactorDevtoolsBootRequest`](#reactordevtoolsbootrequest) | | + +## `McpTransport` + +Which MCP transport the devtools surface uses. + +```csharp +public enum McpTransport +``` + +Namespace: `Microsoft.UI.Reactor.Hosting.Devtools`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `Http` | `0` | | +| `Stdio` | `1` | | + +## `ReactorDevtoolsBootRequest` + +```csharp +public sealed record ReactorDevtoolsBootRequest(DevtoolsCliOptions Options, string Title, double? Width, double? Height, bool FullScreen, Type? HostRoot, Func? HostRootFactory, Func? RootRenderFunc, Action? Configure) +``` + +Namespace: `Microsoft.UI.Reactor.Hosting.Devtools`. + +### Constructors + +#### `ReactorDevtoolsBootRequest` + +```csharp +public ReactorDevtoolsBootRequest(DevtoolsCliOptions Options, string Title, double? Width, double? Height, bool FullScreen, Type? HostRoot, Func? HostRootFactory, Func? RootRenderFunc, Action? Configure) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Options` | [`DevtoolsCliOptions`](#devtoolsclioptions) | | +| `Title` | `string` | | +| `Width` | `double?` | | +| `Height` | `double?` | | +| `FullScreen` | `bool` | | +| `HostRoot` | `Type?` | | +| `HostRootFactory` | `Func?` | | +| `RootRenderFunc` | `Func?` | | +| `Configure` | `Action?` | | + +### Properties + +#### `Configure` + +```csharp +public Action? Configure // get, init +``` + +#### `FullScreen` + +```csharp +public bool FullScreen // get, init +``` + +#### `Height` + +```csharp +public double? Height // get, init +``` + +#### `HostRoot` + +```csharp +public Type? HostRoot // get, init +``` + +#### `HostRootFactory` + +```csharp +public Func? HostRootFactory // get, init +``` + +#### `Options` + +```csharp +public DevtoolsCliOptions Options // get, init +``` + +#### `RootRenderFunc` + +```csharp +public Func? RootRenderFunc // get, init +``` + +#### `Title` + +```csharp +public string Title // get, init +``` + +#### `Width` + +```csharp +public double? Width // get, init +``` + +## `ReactorDevtoolsBootstrap` + +```csharp +public static class ReactorDevtoolsBootstrap +``` + +Namespace: `Microsoft.UI.Reactor.Hosting.Devtools`. + +### Methods + +#### `Register` + +```csharp +public static void Register(IReactorDevtoolsHost host) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `host` | [`IReactorDevtoolsHost`](#ireactordevtoolshost) | | diff --git a/docs/guide/reference/diagnostics/index.md b/docs/guide/reference/diagnostics/index.md new file mode 100644 index 0000000000..a06a88357e --- /dev/null +++ b/docs/guide/reference/diagnostics/index.md @@ -0,0 +1,16 @@ +# Diagnostics + +Tracing, source maps, component snapshots and developer tools hosting. + +**Learn more:** [Diagnostics](../../diagnostics.md), [Devtools](../../devtools.md) + +## Types + +| Type | Description | +| --- | --- | +| [Developer tools hosting](devtools.md) | Types the developer tools use to start inside an app. | +| [Diagnostic snapshots](snapshots.md) | Snapshots of the component tree that the diagnostics API returns. | +| [`ReactorEvent`](ReactorEvent.md) | A single event captured from the `Microsoft-UI-Reactor` `EventSource`, delivered to subscribers of `ReactorTrace.Subscribe`. | +| [`ReactorSourceMap`](ReactorSourceMap.md) | Spec 010 — runtime switch and read path for Reactor source mapping. | +| [`ReactorSourceTransparentAttribute`](ReactorSourceTransparentAttribute.md) | Spec 010 — marks a helper method as *source-transparent*: elements it returns are attributed to the line that CALLED it, not to the line inside it that ran the DSL factory. | +| [`ReactorTrace`](ReactorTrace.md) | In-process subscription helper for the `Microsoft-UI-Reactor` `EventSource`. | diff --git a/docs/guide/reference/diagnostics/snapshots.md b/docs/guide/reference/diagnostics/snapshots.md new file mode 100644 index 0000000000..8182d34d6c --- /dev/null +++ b/docs/guide/reference/diagnostics/snapshots.md @@ -0,0 +1,751 @@ +# Diagnostic snapshots + +Snapshots of the component tree that the diagnostics API returns. + +**Learn more:** [Diagnostics](../../diagnostics.md) + +## `AppliedProperty` + +A WinUI property Reactor writes on a control because the element that produced it sets a common modifier, or because Reactor derived it (the default automation name). + +```csharp +public sealed record AppliedProperty(string Modifier, string Property, string Value) +``` + +Namespace: `Microsoft.UI.Reactor.Core.Diagnostics`. + +### Constructors + +#### `AppliedProperty` + +A WinUI property Reactor writes on a control because the element that produced it sets a common modifier, or because Reactor derived it (the default automation name). + +```csharp +public AppliedProperty(string Modifier, string Property, string Value) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Modifier` | `string` | The modifier that carries the value: `"Width"`, `"IsVisible"`, `"Accessibility.HelpText"`, or `"DefaultAutomationName"` for the name Reactor derives from a control's caption. | +| `Property` | `string` | The WinUI property it is written to, as `OwnerType.PropertyName`: `"FrameworkElement.Width"`, `"UIElement.Visibility"`, `"AutomationProperties.Name"`. | +| `Value` | `string` | The element-side value as text. It can differ from the property value when Reactor converts it (`IsVisible` → `Visibility`) or folds several modifiers into one property (inline margins into `Margin`). | + +### Properties + +#### `Modifier` + +The modifier that carries the value: `"Width"`, `"IsVisible"`, `"Accessibility.HelpText"`, or `"DefaultAutomationName"` for the name Reactor derives from a control's caption. + +```csharp +public string Modifier // get, init +``` + +#### `Property` + +The WinUI property it is written to, as `OwnerType.PropertyName`: `"FrameworkElement.Width"`, `"UIElement.Visibility"`, `"AutomationProperties.Name"`. + +```csharp +public string Property // get, init +``` + +#### `Value` + +The element-side value as text. It can differ from the property value when Reactor converts it (`IsVisible` → `Visibility`) or folds several modifiers into one property (inline margins into `Margin`). + +```csharp +public string Value // get, init +``` + +## `ComponentSnapshot` + +A point-in-time description of one mounted component, for inspectors. Every value is text: the snapshot holds no reference into the component, so it can be kept, serialized or sent across a process boundary. + +```csharp +public sealed record ComponentSnapshot(string Name, string Kind, bool IsRoot, IReadOnlyList Props, IReadOnlyList State, IReadOnlyList Contexts) +``` + +Namespace: `Microsoft.UI.Reactor.Core.Diagnostics`. + +### Constructors + +#### `ComponentSnapshot` + +A point-in-time description of one mounted component, for inspectors. Every value is text: the snapshot holds no reference into the component, so it can be kept, serialized or sent across a process boundary. + +```csharp +public ComponentSnapshot(string Name, string Kind, bool IsRoot, IReadOnlyList Props, IReadOnlyList State, IReadOnlyList Contexts) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Name` | `string` | The component's name: its class (`Counter`) or, for a render function, where the function is defined (`RenderEachTime in MainPage.Render`, `Memo in MainPage.Render`, `render in App.Main` for a host root). | +| `Kind` | `string` | `"class"`, `"function"` or `"memo"`. | +| `IsRoot` | `bool` | True for a host's root component (the one passed to `Mount`). | +| `Props` | `IReadOnlyList` | The props of a `Component` (or the props carried by its element), one row per public property, or one row named `Props` for a scalar — or for a props type whose members were trimmed away (NativeAOT), described as ` (members unavailable)`. Empty for function components and propless classes. | +| `State` | `IReadOnlyList` | The component's hooks in call order. [`DiagnosticValue.Index`](#index) is the index [`ReactorDiagnostics.TrySetState`](#trysetstate) takes. | +| `Contexts` | `IReadOnlyList` | The contexts the component reads through `UseContext`. | + +### Properties + +#### `Contexts` + +The contexts the component reads through `UseContext`. + +```csharp +public IReadOnlyList Contexts // get, init +``` + +#### `IsRoot` + +True for a host's root component (the one passed to `Mount`). + +```csharp +public bool IsRoot // get, init +``` + +#### `Kind` + +`"class"`, `"function"` or `"memo"`. + +```csharp +public string Kind // get, init +``` + +#### `Name` + +The component's name: its class (`Counter`) or, for a render function, where the function is defined (`RenderEachTime in MainPage.Render`, `Memo in MainPage.Render`, `render in App.Main` for a host root). + +```csharp +public string Name // get, init +``` + +#### `Props` + +The props of a `Component` (or the props carried by its element), one row per public property, or one row named `Props` for a scalar — or for a props type whose members were trimmed away (NativeAOT), described as ` (members unavailable)`. Empty for function components and propless classes. + +```csharp +public IReadOnlyList Props // get, init +``` + +#### `State` + +The component's hooks in call order. [`DiagnosticValue.Index`](#index) is the index [`ReactorDiagnostics.TrySetState`](#trysetstate) takes. + +```csharp +public IReadOnlyList State // get, init +``` + +## `DiagnosticValue` + +One prop, hook or context value of a [`ComponentSnapshot`](#componentsnapshot), as text. + +```csharp +public sealed record DiagnosticValue(int Index, string Name, string Kind, string Type, string Value, bool Editable, bool MigratedByHotReload) +``` + +Namespace: `Microsoft.UI.Reactor.Core.Diagnostics`. + +### Constructors + +#### `DiagnosticValue` + +One prop, hook or context value of a [`ComponentSnapshot`](#componentsnapshot), as text. + +```csharp +public DiagnosticValue(int Index, string Name, string Kind, string Type, string Value, bool Editable, bool MigratedByHotReload) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Index` | `int` | Position in its list. For [`ComponentSnapshot.State`](#state) and [`ComponentSnapshot.Contexts`](#contexts) it is the hook's call-order index. | +| `Name` | `string` | The prop's name, or the context's declaration name (`Context` when it has none). Empty for hooks: hook names are not recorded. | +| `Kind` | `string` | For a prop, `"prop"`. For a hook, `"state"`, `"reducer"`, `"ref"`, `"memo"`, `"effect"`, `"context"`, `"persisted"`, `"navigationLifecycle"` or `"unknown"`. For a context, `"default"` when the value the component read equals the context's default value (no provider, or a provider supplying that same value), otherwise `"provided"`. | +| `Type` | `string` | The value's type as C# spells it (`int`, `int?`, `List`). Nullable reference annotations are not visible at runtime, so a `string?` reads `string`. Empty when the hook has no value. | +| `Value` | `string` | The value as text: strings quoted, collections summarised as `List (n items)` (`(count unknown)` for a sequence that does not advertise its count — it is never enumerated), long values cut at 200 characters. Values are not redacted: an inspector that shows them where a secret must not appear hides them itself. Empty when the hook has no value (effects). | +| `Editable` | `bool` | True when [`ReactorDiagnostics.TrySetState`](#trysetstate) can set it from text: a state, reducer or persisted hook of a text-typed value. | +| `MigratedByHotReload` | `bool` | For hooks: true when the most recent hot-reload pass migrated this value to an edited type. Always false for props and contexts. | + +### Properties + +#### `Editable` + +True when [`ReactorDiagnostics.TrySetState`](#trysetstate) can set it from text: a state, reducer or persisted hook of a text-typed value. + +```csharp +public bool Editable // get, init +``` + +#### `Index` + +Position in its list. For [`ComponentSnapshot.State`](#state) and [`ComponentSnapshot.Contexts`](#contexts) it is the hook's call-order index. + +```csharp +public int Index // get, init +``` + +#### `Kind` + +For a prop, `"prop"`. For a hook, `"state"`, `"reducer"`, `"ref"`, `"memo"`, `"effect"`, `"context"`, `"persisted"`, `"navigationLifecycle"` or `"unknown"`. For a context, `"default"` when the value the component read equals the context's default value (no provider, or a provider supplying that same value), otherwise `"provided"`. + +```csharp +public string Kind // get, init +``` + +#### `MigratedByHotReload` + +For hooks: true when the most recent hot-reload pass migrated this value to an edited type. Always false for props and contexts. + +```csharp +public bool MigratedByHotReload // get, init +``` + +#### `Name` + +The prop's name, or the context's declaration name (`Context` when it has none). Empty for hooks: hook names are not recorded. + +```csharp +public string Name // get, init +``` + +#### `Type` + +The value's type as C# spells it (`int`, `int?`, `List`). Nullable reference annotations are not visible at runtime, so a `string?` reads `string`. Empty when the hook has no value. + +```csharp +public string Type // get, init +``` + +#### `Value` + +The value as text: strings quoted, collections summarised as `List (n items)` (`(count unknown)` for a sequence that does not advertise its count — it is never enumerated), long values cut at 200 characters. Values are not redacted: an inspector that shows them where a secret must not appear hides them itself. Empty when the hook has no value (effects). + +```csharp +public string Value // get, init +``` + +## `KeyedListDiagnostic` + +One captured keyed-list key diagnostic: a null key, or duplicate keys in a keyed list or among a panel's `.WithKey` siblings. A list with duplicate keys is rebuilt in full when it changes (a bailout); a null-keyed item is matched by position and the list keeps diffing incrementally. Reported at mount as well as on update. Immutable record so the dev tools overlay can display an arbitrary subset without locking the producer. + +```csharp +public sealed record KeyedListDiagnostic(DateTime TimestampUtc, string? ControlContext, KeyedListDiagnosticKind Kind, IReadOnlyList SampleKeys, int Count) +``` + +Namespace: `Microsoft.UI.Reactor.Core.Diagnostics`. + +### Constructors + +#### `KeyedListDiagnostic` + +One captured keyed-list key diagnostic: a null key, or duplicate keys in a keyed list or among a panel's `.WithKey` siblings. A list with duplicate keys is rebuilt in full when it changes (a bailout); a null-keyed item is matched by position and the list keeps diffing incrementally. Reported at mount as well as on update. Immutable record so the dev tools overlay can display an arbitrary subset without locking the producer. + +```csharp +public KeyedListDiagnostic(DateTime TimestampUtc, string? ControlContext, KeyedListDiagnosticKind Kind, IReadOnlyList SampleKeys, int Count) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `TimestampUtc` | `DateTime` | When the diagnostic was first observed. | +| `ControlContext` | `string?` | Human-readable label — the host control's type name. May be `null` when the diff ran outside a control context (e.g. direct unit-test invocation of `KeyedListDiff.Apply`). | +| `Kind` | [`KeyedListDiagnosticKind`](#keyedlistdiagnostickind) | Which class of key problem was found (null key vs. duplicate keys). | +| `SampleKeys` | `IReadOnlyList` | A small, bounded set of representative offending keys (duplicates that collided, or the literal token `""` for the null-key case). Capped to keep large lists from blowing the record's footprint. | +| `Count` | `int` | Number of times this same (control, kind, sample-set) has fired since process start, including the first. Lets the dev overlay show "fired 1× / 12× / 134×" without spamming a fresh entry per render. | + +### Properties + +#### `CallSite` + +The C# call site of the list factory, or of the first duplicated child for sibling keys, when the source map recorded one (Debug builds by default); otherwise `null`. + +```csharp +public SourceLocation? CallSite // get, init +``` + +#### `ComponentName` + +The component whose render produced the list or panel, when known. Reactor knows it while an inspector is attached (`REACTOR_DIAGNOSTICS=1`); otherwise `null`. + +```csharp +public string? ComponentName // get, init +``` + +#### `ControlContext` + +Human-readable label — the host control's type name. May be `null` when the diff ran outside a control context (e.g. direct unit-test invocation of `KeyedListDiff.Apply`). + +```csharp +public string? ControlContext // get, init +``` + +#### `Count` + +Number of times this same (control, kind, sample-set) has fired since process start, including the first. Lets the dev overlay show "fired 1× / 12× / 134×" without spamming a fresh entry per render. + +```csharp +public int Count // get, init +``` + +#### `Kind` + +Which class of key problem was found (null key vs. duplicate keys). + +```csharp +public KeyedListDiagnosticKind Kind // get, init +``` + +#### `SampleKeys` + +A small, bounded set of representative offending keys (duplicates that collided, or the literal token `""` for the null-key case). Capped to keep large lists from blowing the record's footprint. + +```csharp +public IReadOnlyList SampleKeys // get, init +``` + +#### `TimestampUtc` + +When the diagnostic was first observed. + +```csharp +public DateTime TimestampUtc // get, init +``` + +## `KeyedListDiagnosticKind` + +Kind of structural list diagnostic surfaced through [`ReactorDiagnostics`](#reactordiagnostics). Tracked separately so the dev tools overlay can filter and color by severity-of-cause without parsing the message string. + +```csharp +public enum KeyedListDiagnosticKind +``` + +Namespace: `Microsoft.UI.Reactor.Core.Diagnostics`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `NullKey` | `0` | A `KeySelector` / `IReactorKeyed.Key` returned `null`. | +| `DuplicateKey` | `1` | Two or more items in the new list returned the same key. | + +## `ReactorDiagnostics` + +Process-wide diagnostic collector for structural problems the reconciler can detect at runtime (today: keyed-list bailouts). Read-only surface for agents, tests, and the in-app dev overlay; the producer side is `internal`. + +```csharp +public static class ReactorDiagnostics +``` + +Namespace: `Microsoft.UI.Reactor.Core.Diagnostics`. + +### Remarks + +The collector deduplicates by (control instance, kind, hashed sample keys). The first occurrence is logged in full; subsequent occurrences of the same triple bump a counter rather than appending a fresh entry. This matches the spec 042 §9 Q1 resolution ("warn-and-bailout via a one-shot diagnostic") and avoids drowning the dev overlay during a run-away render loop. + +The buffer is bounded to [`ReactorDiagnostics.MaxRecentEntries`](#maxrecententries); once full, the oldest entry is dropped. This is intentionally generous — keyed-list bailouts are a per-app rarity, not a per-frame event. + +Reads are lock-free against a snapshot; writes take a short lock. + +### Properties + +#### `IsSourcePublishingEnabled` + +True when Reactor is publishing [`ReactorDiagnostics.SourceProperty`](#sourceproperty) in this process: the `Reactor.DevtoolsSupport` build switch is on and the process was started with `REACTOR_DIAGNOSTICS=1`. + +```csharp +public static bool IsSourcePublishingEnabled // get +``` + +#### `RecentKeyedListWarnings` + +Recent keyed-list key diagnostics (see [`KeyedListDiagnostic`](#keyedlistdiagnostic)), newest first. Returns an independent snapshot — safe to enumerate while producers continue running. Empty when no key problem has ever been found (the common case). + +```csharp +public static IReadOnlyList RecentKeyedListWarnings // get +``` + +#### `SourceProperty` + +Attached string property, registered as `"ReactorSource"`, that Reactor sets on every control it realizes while diagnostics publishing is on. Its value describes where the control came from — call site, owning component, element kind, key, declared name, and for component boundaries the component's hooks — in the v1 grammar: + +```csharp +v=1|at=path:line[:col][|rel=]|owner=Comp|element=Kind[|mounts=Comp][|root=Comp][|key=k][|name=n][|hooks=i:name@line;...] +``` + +with `%` escaped as `%25` and `|` as `%7C` in values. `at` is never an absolute developer path: it is relative to the project directory, or to the solution/repo root (`rel=root`), or just the file name (`rel=0`) — the same posture as XAML's runtime source info, which reports `ms-appx:///` paths. + +**Why a string on the control.** An out-of-process inspector reads it through XamlDiagnostics like any other property (it is reported as `.ReactorSource`), with no managed code in the app — so it works for Native AOT apps, where no managed inspector agent can be loaded. + +**When it is set.** Only when the app was built with the `Reactor.DevtoolsSupport` switch on AND launched with `REACTOR_DIAGNOSTICS=1`; see [`ReactorDiagnostics.IsSourcePublishingEnabled`](#issourcepublishingenabled). Otherwise no control carries it and the publishing code is trimmed from AOT/trimmed builds. Reading this property registers the attached property (once) but publishes nothing. + +```csharp +public static DependencyProperty SourceProperty // get +``` + +### Methods + +#### `ClearRecentKeyedListWarnings` + +Drop every captured entry and contextual dedup state, retaining per-control counts. Tests use this between scenarios; production code never needs to call it. + +```csharp +public static void ClearRecentKeyedListWarnings() +``` + +#### `DescribeComponent` + +Describes the component hosted at `element`: a component's wrapper `Border` (every class, function and memo component is mounted into one), or a host's root content (its rendered root control, the window content or `ContentTarget` it was installed into, or a `ReactorHostControl` itself). Returns `null` for any other element. Works with or without source mapping. + +```csharp +public static ComponentSnapshot? DescribeComponent(UIElement element) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `element` | `UIElement` | | + +**Remarks** + +Must be called on the UI thread. + +One element can anchor two components: when a root renders a component directly (`Render() => Component()`), the root's rendered control *is* `Shell`'s wrapper. The wrapper wins — the element describes `Shell`, the innermost component it hosts — and [`ReactorDiagnostics.TrySetState`](#trysetstate) / [`ReactorDiagnostics.Rerender`](#rerender) address the same component. The root stays reachable through its other anchors: a `ContentTarget`, a `ReactorHostControl`, or the dev-overlay wrapper. A host that installs straight into `Window.Content` has none of those, so in that one shape its root is not reachable. + +#### `GetAppliedProperties` + +The WinUI properties Reactor writes on `control` from the common modifiers of the element that produced it, so an inspector can mark a property as set in C# (and overwritten when the element's value changes). Empty when the control is not tagged with its element — Reactor tags only controls something reads back (callbacks, a key, or a stamped source location), so turn on [`ReactorSourceMap.Enabled`](ReactorSourceMap.md#enabled) for full coverage. + +```csharp +public static IReadOnlyList GetAppliedProperties(UIElement control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `control` | `UIElement` | | + +**Remarks** + +Covers [`ElementModifiers`](../modifiers/ElementModifiers.md) and [`AccessibilityModifiers`](../modifiers/AccessibilityModifiers.md), plus the `AutomationProperties.Name` Reactor derives from a captioned control (`Button("Save")`, `CheckBox("Agree")`, …) when the author sets none. That one is reported as `"DefaultAutomationName"`, and only while the live name still equals it; a different live name was written by the app. Properties a control's own element record sets (`TextBlock("hi")` → `Text`) are not listed. Must be called on the UI thread. + +#### `GetHosts` + +Snapshot of every live Reactor host in the process, in creation order: windows opened through `ReactorApp` (including ones not yet mounted), hosts created with `new ReactorHost(window)`, and [`ReactorHostControl`](../hosting/ReactorHostControl.md) islands. Disposed hosts are excluded. Safe to call from any thread; see [`ReactorHostInfo`](#reactorhostinfo) for consistency rules. + +```csharp +public static IReadOnlyList GetHosts() +``` + +**Remarks** + +Provisional diagnostics API for external inspectors. A [`ReactorHostControl`](../hosting/ReactorHostControl.md) that was removed from the tree but never disposed stays listed until it is collected — Reactor cannot tell a transient reparent from a removal (issue #344); check its `XamlRoot` to skip detached islands. + +#### `GetReferenceEdges` + +The references `control` declares to other controls — including pending ones whose target has not mounted yet, for which the WinUI property itself (e.g. `XYFocusRight`, `AutomationProperties.LabeledBy`) still reads null. Grouped by property in a fixed order (control-descriptor references, then bindings, then the modifier references), then list position; both `LabeledBy` forms are adjacent, the `ElementRef` one first. + +```csharp +public static IReadOnlyList GetReferenceEdges(UIElement control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `control` | `UIElement` | | + +**Remarks** + +`ElementRef` references (modifiers such as `.LabeledBy(ref)` or `.XYFocusRight(ref)`, control descriptors and bindings) are always reported. An AutomationId `.LabeledBy("id")` is reported while pending; once resolved it is reported only while the control is loaded and tagged with its element (turn source mapping on). Reads existing reconciler state on demand. Must be called on the UI thread. + +#### `GetSource` + +Reads [`ReactorDiagnostics.SourceProperty`](#sourceproperty) from `element`; `null` when unset. + +```csharp +public static string? GetSource(DependencyObject element) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `element` | `DependencyObject` | | + +#### `Rerender` + +Schedules a re-render of the component hosted at `element`, bypassing its memoization (the path a state setter takes). + +```csharp +public static bool Rerender(UIElement element) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `element` | `UIElement` | | + +**Returns:** False when no component is hosted at `element` or it has never rendered. + +**Remarks** + +A re-render diffs the new element tree against the previous one, so it re-applies a property only when the element's value for it changed: it does **not** restore a property that was edited directly on the control while the element's value stayed the same. Must be called on the UI thread that renders the component. + +#### `TrySetState` + +Development-time state edit: parses `text` to the value type of hook `hookIndex` of the component hosted at `element`, writes it, and — when the value changed — schedules a re-render exactly as the hook's own setter would. + +```csharp +public static bool TrySetState(UIElement element, int hookIndex, string text, out string? error) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `element` | `UIElement` | A component wrapper or host root, as for [`ReactorDiagnostics.DescribeComponent`](#describecomponent). | +| `hookIndex` | `int` | The hook's [`DiagnosticValue.Index`](#index). | +| `text` | `string` | Invariant-culture text: a number, a single character, `true`/`false`, an enum member name, a date, time span or GUID, or the string itself (unquoted). `null` sets a string or nullable to null. | +| `error` | `string?` | Why the edit was refused, when this returns false. | + +**Returns:** True when the value was written (including when it was already equal). + +**Remarks** + +Only state, reducer and persisted hooks of a text-typed value can be set. Must be called on the UI thread that renders the component. + +### Fields + +#### `MaxRecentEntries` + +Maximum number of distinct (control, kind, sample-set) entries retained. New entries beyond this drop the oldest. + +```csharp +public const int MaxRecentEntries = 64 +``` + +#### `MaxSampleKeys` + +Maximum number of representative keys captured per entry. Larger duplicate sets are truncated and an ellipsis is appended. + +```csharp +public const int MaxSampleKeys = 8 +``` + +## `ReactorHostInfo` + +Point-in-time description of one live Reactor host: where it renders, what its root is, and where that root was mounted. Returned by [`ReactorDiagnostics.GetHosts`](#gethosts). + +```csharp +public sealed class ReactorHostInfo +``` + +Namespace: `Microsoft.UI.Reactor.Core.Diagnostics`. + +### Remarks + +Provisional diagnostics API for external inspectors (for example `winapp devtools`); shape may change while Reactor is in preview. + +Deliberately exposes no reconciler internals: the root is described by name and call site, and reached on screen through [`ReactorHostInfo.RootControl`](#rootcontrol) — the same WinUI control an inspector already walks. Everything else is an existing public WinUI or Reactor hosting type. + +A snapshot, not a live view: re-query after a render, window open, or close. The snapshot itself can be taken from any thread, and every value in it is read atomically (never half of one mount and half of another). A snapshot taken while the UI thread is remounting may still pair the outgoing root's name with the incoming root's site; take it on the UI thread when the values must agree with each other or with the visual tree you are about to walk. Touching the returned WinUI objects is subject to their usual UI-thread rules. + +Holding a snapshot keeps its host, window and root control alive; the registry behind [`ReactorDiagnostics.GetHosts`](#gethosts) does not. + +### Properties + +#### `Host` + +The window host, when [`ReactorHostInfo.Kind`](#kind_3) is [`ReactorHostKind.WindowHost`](#values_1). + +```csharp +public ReactorHost? Host // get +``` + +#### `HostControl` + +The embedded host control, when [`ReactorHostInfo.Kind`](#kind_3) is [`ReactorHostKind.HostControl`](#values_1). + +```csharp +public ReactorHostControl? HostControl // get +``` + +#### `HostElement` + +The element whose content is the Reactor root: the [`ReactorHostControl`](../hosting/ReactorHostControl.md) itself, a window host's [`ReactorHost.ContentTarget`](../hosting/ReactorHost.md#contenttarget), or null when a window host renders straight into `Window.Content`. + +```csharp +public FrameworkElement? HostElement // get +``` + +#### `Kind` + +Which host shape this is. + +```csharp +public ReactorHostKind Kind // get +``` + +#### `MountSite` + +Where the root was mounted — the `ReactorApp.Run`, `ReactorApp.OpenWindow`, `ReactorWindow.Mount`, `ReactorHost.Mount` or `ReactorHostControl.Mount` call in app code. Null unless the calling project was built with source mapping (`ReactorSourceMap=true`, the Debug default) and [`ReactorSourceMap.Enabled`](ReactorSourceMap.md#enabled) was true at mount time; also null for a root created from [`ReactorHostControl.ComponentFactory`](../hosting/ReactorHostControl.md#componentfactory) or [`ReactorHostControl.ComponentType`](../hosting/ReactorHostControl.md#componenttype), or mounted by framework code, none of which has a call site in app code. + +```csharp +public SourceLocation? MountSite // get +``` + +#### `ReactorWindow` + +The `ReactorApp` window that owns the host (its `Id`, `Key` and `NativeWindow` identify it), or null for a host constructed directly on a window and for every [`ReactorHostKind.HostControl`](#values_1). + +```csharp +public ReactorWindow? ReactorWindow // get +``` + +#### `RootComponentName` + +The root component's type name, namespace-qualified, with nested types joined by `.` and generic arguments spelled out (`MyApp.Pages.Dashboard`, `MyApp.ListPage`). Null for a render-function root and before the first mount. + +```csharp +public string? RootComponentName // get +``` + +#### `RootControl` + +The control the root currently renders as, or null before the first render. This is the control the host places in `Window.Content` / its content slot; when a dev overlay is on, that slot holds an overlay wrapper and this control is its child. After a render error it is the error fallback panel. + +```csharp +public UIElement? RootControl // get +``` + +#### `RootRenderFunctionName` + +A readable name for a render-function root: the method that declares it, with compiler-generated names undone — `MyApp.Program.Main (lambda)`, `MyApp.Program.Main.Render` for a local function, `MyApp.Shell.Render` for a method group. Null for a component root, before the first mount, and when the runtime cannot describe the delegate (for example NativeAOT with stack-trace data disabled). For a lambda, [`ReactorHostInfo.MountSite`](#mountsite) is usually the better identity. + +```csharp +public string? RootRenderFunctionName // get +``` + +#### `Window` + +The WinUI window a [`ReactorHostKind.WindowHost`](#values_1) renders into. Null for [`ReactorHostKind.HostControl`](#values_1), which does not own a window; use [`ReactorHostInfo.HostElement`](#hostelement)'s `XamlRoot` to place it. + +```csharp +public Window? Window // get +``` + +## `ReactorHostKind` + +Which kind of Reactor host a [`ReactorHostInfo`](#reactorhostinfo) describes. + +```csharp +public enum ReactorHostKind +``` + +Namespace: `Microsoft.UI.Reactor.Core.Diagnostics`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `WindowHost` | `0` | A [`ReactorHost`](../hosting/ReactorHost.md) rendering into a WinUI [`Window`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.window) — either a window opened through `ReactorApp.Run` / `ReactorApp.OpenWindow` (see [`ReactorHostInfo.ReactorWindow`](#reactorwindow)) or a `new ReactorHost(window)` on any window, optionally redirected into a [`ReactorHost.ContentTarget`](../hosting/ReactorHost.md#contenttarget). | +| `HostControl` | `1` | A [`ReactorHostControl`](../hosting/ReactorHostControl.md) embedded in a XAML tree (a hybrid "island"). | + +## `ReferenceEdgeSnapshot` + +One reference a control declares to another control — resolved, or still pending because the target has not mounted. + +```csharp +public sealed record ReferenceEdgeSnapshot(string Property, bool IsList, int Index, string? TargetAutomationId, string? ExpectedTargetTypeName, bool IsResolved, UIElement? Target) +``` + +Namespace: `Microsoft.UI.Reactor.Core.Diagnostics`. + +### Constructors + +#### `ReferenceEdgeSnapshot` + +One reference a control declares to another control — resolved, or still pending because the target has not mounted. + +```csharp +public ReferenceEdgeSnapshot(string Property, bool IsList, int Index, string? TargetAutomationId, string? ExpectedTargetTypeName, bool IsResolved, UIElement? Target) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Property` | `string` | The referencing property: `"LabeledBy"`, `"DescribedBy"`, `"FlowsTo"`, `"FlowsFrom"`, `"XYFocusUp"`, `"XYFocusDown"`, `"XYFocusLeft"`, `"XYFocusRight"` or `"ToolTipPlacementTarget"`. A control descriptor's or binding's reference carries no author-visible name and reports `"reference#N"` / `"binding#N"`. | +| `IsList` | `bool` | True for a list-valued reference (`DescribedBy`, `FlowsTo`, `FlowsFrom`, a descriptor's `ReferenceList`); each target is its own entry. | +| `Index` | `int` | Position of this target within a list-valued reference (0 for a scalar one), counting references only: a null entry in the authored list is not a reference and is skipped. | +| `TargetAutomationId` | `string?` | The AutomationId the author passed to `.LabeledBy("id")`; `null` for an `ElementRef` reference. | +| `ExpectedTargetTypeName` | `string?` | For a typed `ElementRef`, `T` as C# spells it (`Button`); otherwise `null`. | +| `IsResolved` | `bool` | True when the target is mounted. | +| `Target` | `UIElement?` | The mounted control the reference resolves to; `null` while pending. Unlike the rest of the diagnostics surface this is a live WinUI control, not text — use it in-process, on the UI thread, to locate the target (e.g. to inspect or highlight it). | + +### Properties + +#### `ExpectedTargetTypeName` + +For a typed `ElementRef`, `T` as C# spells it (`Button`); otherwise `null`. + +```csharp +public string? ExpectedTargetTypeName // get, init +``` + +#### `Index` + +Position of this target within a list-valued reference (0 for a scalar one), counting references only: a null entry in the authored list is not a reference and is skipped. + +```csharp +public int Index // get, init +``` + +#### `IsList` + +True for a list-valued reference (`DescribedBy`, `FlowsTo`, `FlowsFrom`, a descriptor's `ReferenceList`); each target is its own entry. + +```csharp +public bool IsList // get, init +``` + +#### `IsResolved` + +True when the target is mounted. + +```csharp +public bool IsResolved // get, init +``` + +#### `Property` + +The referencing property: `"LabeledBy"`, `"DescribedBy"`, `"FlowsTo"`, `"FlowsFrom"`, `"XYFocusUp"`, `"XYFocusDown"`, `"XYFocusLeft"`, `"XYFocusRight"` or `"ToolTipPlacementTarget"`. A control descriptor's or binding's reference carries no author-visible name and reports `"reference#N"` / `"binding#N"`. + +```csharp +public string Property // get, init +``` + +#### `Target` + +The mounted control the reference resolves to; `null` while pending. Unlike the rest of the diagnostics surface this is a live WinUI control, not text — use it in-process, on the UI thread, to locate the target (e.g. to inspect or highlight it). + +```csharp +public UIElement? Target // get, init +``` + +#### `TargetAutomationId` + +The AutomationId the author passed to `.LabeledBy("id")`; `null` for an `ElementRef` reference. + +```csharp +public string? TargetAutomationId // get, init +``` diff --git a/docs/guide/reference/elements/Element.md b/docs/guide/reference/elements/Element.md new file mode 100644 index 0000000000..a59296a5a1 --- /dev/null +++ b/docs/guide/reference/elements/Element.md @@ -0,0 +1,213 @@ +# Element + +A lightweight, immutable description of a UI node (the "virtual DOM"). Elements are cheap to create and diff — they never touch real controls directly. + +```csharp +public abstract record Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Reconciliation](../../reconciliation.md) + +## Constructors + +### `Element` + +```csharp +protected Element() +``` + +## Properties + +### `AnimationConfig` + +Compositor property animation configuration (.Animate() modifier). When set, the reconciler creates ImplicitAnimationCollection entries on the element's Visual for Opacity/Scale/Rotation/Offset/CenterPoint. + +```csharp +public AnimationConfig? AnimationConfig // get, init +``` + +### `Attached` + +Attached properties from parent containers (Grid.Row, Canvas.Left, etc.). Set via fluent extension methods: TextBlock("hi").Grid(row: 1, column: 2) Stored as a type-keyed dictionary so each provider defines its own data record. + +```csharp +public IReadOnlyDictionary? Attached // get, init +``` + +### `CallSite` + +Spec 010 — the C# source location that created this element, or `null` when nothing stamped it. + +This is a property of the ELEMENT, not of the current flag state. An element stamped while mapping was on keeps its location after the flag is turned off, and a hand-assigned value is honoured regardless of the flag; conversely an element built while mapping was off, or produced by a factory the provider does not reach, stays `null` forever. Elements are immutable, so this is fixed at construction. + +NOTE ON THE NAME: spec 010 proposes `Element.Source`. That name is unusable — five existing element records already declare a positional `Source` member of an incompatible type (`ImageElement(string Source)`, `WebView2Element(Uri? Source)`, `MediaPlayerElementElement(string? Source)`, plus `AnimatedIconElement` and `ParallaxViewElement`), and a base property of a different type makes their positional parameters fail to bind (CS8866). `CallSite` is the collision-free equivalent. + +The slot is present in every build configuration (the library ships as a Release-built NuGet package, so a `#if DEBUG` gate would make the property invisible to consumers). The *cost* is what is gated: nothing writes this slot unless a source-map provider is wired into the consuming compilation, and the generated interceptors check [`ReactorSourceMap.Enabled`](../diagnostics/ReactorSourceMap.md#enabled) before stamping. + +Tagging is NOT keyed on that runtime flag. A stamped element carries this value in its [`Element.Extensions`](#extensions) bucket, and `Reconciler.NeedsTag` already tags anything with a non-null bucket — so the back-pointer follows the stamp, not the flag. A hand-assigned `CallSite` is therefore tagged and readable even with the flag off (see the `HandStampedLeafIsTaggedWithFlagOff` selftest), and an element the provider never reached stays untagged and reports no location rather than a wrong one. + +Populated per call site, so it is a compile-time constant for a given DSL invocation and survives fluent modifier chains automatically (record `with` copies it). It is deliberately NOT consulted by [`Element.ShallowEquals`](Element.md) — see the reconciler's allow-list. + +STORAGE: this is a shim over the spec 047 §4.4 [`Element.Extensions`](#extensions) bucket, exactly like [`Element.Attached`](#attached) and [`Element.ThemeBindings`](#themebindings). Declaring it inline on the record instead costs +24 bytes on every element ever allocated, measured, in every build — a permanent retail tax for a debug-only feature. The public shape is identical either way, so this is a storage decision, not an API one. + +```csharp +public SourceLocation? CallSite // get, init +``` + +### `ConnectedAnimationKey` + +Connected animation key for cross-container transitions. When set, the reconciler automatically captures a visual snapshot on unmount (via ConnectedAnimationService.PrepareToAnimate) and starts the animation on mount if a prepared animation with the same key exists. Set via fluent extension method: Border(child).ConnectedAnimation("hero") + +```csharp +public string? ConnectedAnimationKey // get, init +``` + +### `ContextValues` + +Context values provided to this element's subtree via .Provide(). The reconciler pushes these onto the context scope when entering this element's subtree and pops them when leaving. + +```csharp +public IReadOnlyDictionary? ContextValues // get, init +``` + +### `ElementTransition` + +Element enter/exit transition configuration (.Transition() modifier). When set, the reconciler animates mount (enter) and unmount (exit) with compositor animations, deferring removal until exit animation completes. + +```csharp +public ElementTransition? ElementTransition // get, init +``` + +### `Extensions` + +Cross-cutting extras (attached properties, transitions, theme bindings, animation configs, resource overrides, context values) bucketed into a lazy sub-record (spec 047 §4.4). The common case — a leaf with none of these — leaves this slot null, so the 14 fields below cost one reference instead of 14 inline slots on every [`Element`](Element.md). The setter is `internal` (PR #455 CR item #6): ordinary code uses the field shim properties (Attached, ThemeBindings, AnimationConfig, …) below and never observes this slot. Keeping the setter off the public surface removes an initializer-ordering footgun — a public `with { Extensions = X }` after a shim write would have silently discarded the shim. The engine and perf-critical internal paths may still set it directly. + +```csharp +public ElementExtras? Extensions // get +``` + +**Remarks** + +Spec 047 §4.4. + +### `ImplicitTransitions` + +Implicit transitions (opacity, scale, rotation, translation, background). Set via fluent extension methods: Rectangle().OpacityTransition() Applied by the reconciler after mount/update, so they are always present when property values are set via .Set() callbacks. + +```csharp +public ImplicitTransitions? ImplicitTransitions // get, init +``` + +### `InteractionStates` + +Interaction states configuration (.InteractionStates() modifier). When set, the reconciler registers pointer event handlers that drive zero-reconcile visual state transitions (hover, pressed, focused). + +```csharp +public InteractionStatesConfig? InteractionStates // get, init +``` + +### `Key` + +Optional key for stable identity across re-renders (like React's key prop). When set, the reconciler uses it to match elements across list reorderings. + +```csharp +public string? Key // get, init +``` + +### `KeyframeAnimations` + +Keyframe animation definitions (.Keyframes() modifier). Trigger-based: plays when the trigger value changes between renders. + +```csharp +public KeyframeEntry[]? KeyframeAnimations // get, init +``` + +### `LayoutAnimation` + +Composition-layer layout animation configuration. When set, the reconciler attaches implicit animations to the element's Visual so that layout-driven position (and optionally size) changes animate smoothly. Set via fluent extension methods: Border(child).LayoutAnimation() + +```csharp +public LayoutAnimationConfig? LayoutAnimation // get, init +``` + +### `Margin` + +Outer margin shim that routes to [`Element.Modifiers`](#modifiers). Lets `el with { Margin = new Thickness(8) }` work directly on a record initializer (where extension methods are not visible). Identical semantics to `.Margin(...)`. + +```csharp +public Thickness? Margin // get, init +``` + +### `Modifiers` + +Layout modifiers (margin, padding, size, alignment, etc.) applied to this element. Set via fluent extension methods: TextBlock("hi").Margin(10).Width(200) Modifiers are stored inline so the concrete element type is preserved through chaining. + +```csharp +public ElementModifiers? Modifiers // get, init +``` + +### `Padding` + +Inner padding shim that routes to [`Element.Modifiers`](#modifiers). Lets `el with { Padding = new Thickness(8) }` work directly on a record initializer (where extension methods are not visible). Identical semantics to `.Padding(...)`. + +```csharp +public Thickness? Padding // get, init +``` + +### `ResourceOverrides` + +Per-control resource overrides (lightweight styling). When set, the reconciler injects these into [`FrameworkElement.Resources`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.frameworkelement.resources) so that the control's VisualStateManager picks them up for hover/pressed/disabled states. Set via fluent extension: `Button("Go").Resources(r => r.Set("ButtonBackground", "#0078D4"))` + +```csharp +public ResourceOverrides? ResourceOverrides // get, init +``` + +### `ScrollAnimation` + +Scroll-linked expression animation configuration (.ScrollLinked() modifier). Expression animations run on the compositor, driven by ScrollViewer position. + +```csharp +public ScrollAnimationConfig? ScrollAnimation // get, init +``` + +### `StaggerConfig` + +Stagger configuration for container children (.Stagger() modifier). When set, child animations (enter, layout, property) have incrementing DelayTime = childIndex \* staggerDelay. + +```csharp +public StaggerConfig? StaggerConfig // get, init +``` + +### `ThemeBindings` + +Theme-resource bindings for brush properties (Background, Foreground, BorderBrush). When set, the reconciler resolves from WinUI theme resources instead of using local values. Set via fluent extension methods: TextBlock("hi").Background(Theme.Accent) + +```csharp +public IReadOnlyDictionary? ThemeBindings // get, init +``` + +### `ThemeTransitions` + +Theme transitions (children, item container). Set via fluent extension methods: VStack(children).WithTransitions(...) + +```csharp +public ThemeTransitions? ThemeTransitions // get, init +``` + +## Operators + +### `op_Implicit` + +Convenience: implicitly convert a string to a TextBlockElement. Allows writing: VStack("Hello", "World") instead of VStack(TextBlock("Hello"), TextBlock("World")) + +```csharp +public static implicit operator Element(string text) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `text` | `string` | | diff --git a/docs/guide/reference/elements/buttons.md b/docs/guide/reference/elements/buttons.md new file mode 100644 index 0000000000..cd7f8dd961 --- /dev/null +++ b/docs/guide/reference/elements/buttons.md @@ -0,0 +1,165 @@ +# Elements: Buttons + +Buttons, toggle buttons, split buttons and hyperlink buttons. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Controls](../../controls.md), [Commanding](../../commanding.md) + +## `ButtonElement` + +The element record that describes a WinUI [`Button`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.button) control. + +```csharp +public record ButtonElement(string Label, Action? OnClick = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Button`](../factories/buttons.md#button) + +**Modifiers:** [`AccentButton`](../modifiers/buttons.md#accentbutton), [`Click`](../modifiers/buttons.md#click), [`Command`](../modifiers/buttons.md#command), [`DisabledFocusable`](../modifiers/buttons.md#disabledfocusable), [`IsDisabledFocusable`](../modifiers/buttons.md#isdisabledfocusable), [`Set`](../modifiers/native-properties.md#set), [`SubtleButton`](../modifiers/buttons.md#subtlebutton), [`TextLink`](../modifiers/buttons.md#textlink) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Command` | [`Command?`](../input/Command.md) | | The [`ButtonElement.Command`](#buttonelement) bound to this button via the `Button(Command)` factory, the `.Command()` modifier, or a direct `new ButtonElement(cmd.Label) { Command = cmd }` / `with { Command = cmd }` record-init (issue #153, made fully uniform in issue #637). Carries the command so the reconciler can compare it field-aware in [`Element.ShallowEquals`](Element.md) and apply its metadata + enabled state through a descriptor entry — no per-render [`ButtonElement.Setters`](#buttonelement) lambda. **Every** binding path is now equivalent: dispatch (Execute/ExecuteAsync) is invoked by the click trampoline when [`ButtonElement.OnClick`](#buttonelement) is null, [`Command.IsEnabled`](../input/Command.md#isenabled) is folded into the IsEnabled descriptor entry (see [`ButtonElement.EffectiveIsEnabled`](#buttonelement)), and the command counts as a callback source for [`ButtonElement.HasCallbacks`](#buttonelement). The `init` accessor is public: a bare record-init invokes the command on click exactly like the factory/modifier. | +| `ContentElement` | [`Element?`](Element.md) | | | +| `IsDisabledFocusable` | `bool` | | When true, the button is visually dimmed and its `OnClick` handler is suppressed, but it stays keyboard-focusable and reachable via Tab. Use for submit buttons gated on validation so users can discover them and the disable state doesn't trap keyboard navigation through commit- on-blur inputs. Conceptually equivalent to Fluent UI React's `disabledFocusable` / ARIA's `aria-disabled`. UIA still reports the button as enabled — full assistive-tech "unavailable" reporting requires a custom `ButtonAutomationPeer` and is tracked as a follow-up. | +| `IsEnabled` | `bool` | | | +| `Label` | `string` | | | +| `OnClick` | `Action?` | `null` | | + +## `DropDownButtonElement` + +The element record that describes a WinUI [`DropDownButton`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.dropdownbutton) control. + +```csharp +public record DropDownButtonElement(string Label, Element? Flyout = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`DropDownButton`](../factories/buttons.md#dropdownbutton) + +**Modifiers:** [`AccentButton`](../modifiers/buttons.md#accentbutton), [`Set`](../modifiers/native-properties.md#set), [`SubtleButton`](../modifiers/buttons.md#subtlebutton) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `ContentElement` | [`Element?`](Element.md) | | Declarative content, taking precedence over the text value. | +| `Flyout` | [`Element?`](Element.md) | `null` | | +| `Label` | `string` | | | + +## `HyperlinkButtonElement` + +The element record that describes a WinUI [`HyperlinkButton`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.hyperlinkbutton) control. + +```csharp +public record HyperlinkButtonElement(string Content, Uri? NavigateUri = null, Action? OnClick = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`HyperlinkButton`](../factories/buttons.md#hyperlinkbutton) + +**Modifiers:** [`Click`](../modifiers/buttons.md#click), [`Command`](../modifiers/buttons.md#command), [`NavigateUri`](../modifiers/buttons.md#navigateuri), [`Set`](../modifiers/native-properties.md#set), [`TextLink`](../modifiers/buttons.md#textlink) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Command` | [`Command?`](../input/Command.md) | | The command bound via `HyperlinkButton(Command)` / `.Command()` / a direct `new HyperlinkButtonElement(cmd.Label) { Command = cmd }` record-init (issue #153; made uniform in issue #637). All paths dispatch + apply IsEnabled identically. See [`ButtonElement.Command`](#buttonelement). | +| `Content` | `string` | | | +| `ContentElement` | [`Element?`](Element.md) | | Declarative content, taking precedence over the text value. | +| `NavigateUri` | `Uri?` | `null` | | +| `OnClick` | `Action?` | `null` | | + +## `RepeatButtonElement` + +The element record that describes a WinUI [`RepeatButton`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.repeatbutton) control. + +```csharp +public record RepeatButtonElement(string Label, Action? OnClick = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`RepeatButton`](../factories/buttons.md#repeatbutton) + +**Modifiers:** [`Click`](../modifiers/buttons.md#click), [`Command`](../modifiers/buttons.md#command), [`Delay`](../modifiers/buttons.md#delay), [`Interval`](../modifiers/buttons.md#interval), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Command` | [`Command?`](../input/Command.md) | | The command bound via `RepeatButton(Command)` / `.Command()` / a direct `new RepeatButtonElement(cmd.Label) { Command = cmd }` record-init (issue #153; made uniform in issue #637). All paths dispatch + apply IsEnabled identically. See [`ButtonElement.Command`](#buttonelement). | +| `ContentElement` | [`Element?`](Element.md) | | Declarative content, taking precedence over the text value. | +| `Delay` | `int` | | | +| `Interval` | `int` | | | +| `Label` | `string` | | | +| `OnClick` | `Action?` | `null` | | + +## `SplitButtonElement` + +The element record that describes a WinUI [`SplitButton`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.splitbutton) control. + +```csharp +public record SplitButtonElement(string Label, Action? OnClick = null, Element? Flyout = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`SplitButton`](../factories/buttons.md#splitbutton) + +**Modifiers:** [`AccentButton`](../modifiers/buttons.md#accentbutton), [`Click`](../modifiers/buttons.md#click), [`Set`](../modifiers/native-properties.md#set), [`SubtleButton`](../modifiers/buttons.md#subtlebutton) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Command` | [`Command?`](../input/Command.md) | | The command bound via `SplitButton(Command)` / a direct `new SplitButtonElement(cmd.Label) { Command = cmd }` record-init (issue #153; made uniform in issue #637). All paths dispatch the primary action + apply IsEnabled identically. See [`ButtonElement.Command`](#buttonelement). | +| `ContentElement` | [`Element?`](Element.md) | | Declarative content, taking precedence over the text value. | +| `Flyout` | [`Element?`](Element.md) | `null` | | +| `Label` | `string` | | | +| `OnClick` | `Action?` | `null` | | + +## `ToggleButtonElement` + +The element record that describes a WinUI [`ToggleButton`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.togglebutton) control. + +```csharp +public record ToggleButtonElement(string Label, bool IsChecked = false, Action? OnIsCheckedChanged = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ThreeStateToggleButton`](../factories/buttons.md#threestatetogglebutton), [`ToggleButton`](../factories/buttons.md#togglebutton) + +**Modifiers:** [`CheckedState`](../modifiers/buttons.md#checkedstate), [`CheckedStateChanged`](../modifiers/shared-controls.md#checkedstatechanged), [`Command`](../modifiers/buttons.md#command), [`IsCheckedChanged`](../modifiers/shared-controls.md#ischeckedchanged), [`IsThreeState`](../modifiers/buttons.md#isthreestate), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `CheckedState` | `bool?` | | Three-state value (`null` = indeterminate). Active only when [`ToggleButtonElement.IsThreeState`](#togglebuttonelement) is true. | +| `Command` | [`Command?`](../input/Command.md) | | The command bound via `ToggleButton(Command)` / `.Command()` / a direct `new ToggleButtonElement(cmd.Label) { Command = cmd }` record-init (issue #153; made uniform in issue #637). All paths fire the command on each toggle + apply IsEnabled identically. See [`ButtonElement.Command`](#buttonelement). | +| `ContentElement` | [`Element?`](Element.md) | | Declarative content, taking precedence over the text value. | +| `IsChecked` | `bool` | `false` | | +| `IsThreeState` | `bool` | | Enable the three-state cycle (true → false → null → true). Pair with [`ToggleButtonElement.CheckedState`](#togglebuttonelement) and [`ToggleButtonElement.OnCheckedStateChanged`](#togglebuttonelement); the non-nullable [`ToggleButtonElement.IsChecked`](#togglebuttonelement) primary is ignored in this mode. Mirrors the established `CheckBoxElement` precedent. | +| `Label` | `string` | | | +| `OnCheckedStateChanged` | `Action?` | | Three-state change handler. Receives `null` for indeterminate. | +| `OnIsCheckedChanged` | `Action?` | `null` | | + +## `ToggleSplitButtonElement` + +The element record that describes a WinUI [`ToggleSplitButton`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.togglesplitbutton) control. + +```csharp +public record ToggleSplitButtonElement(string Label, Optional IsChecked = default, Action? OnIsCheckedChanged = null, Element? Flyout = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ToggleSplitButton`](../factories/buttons.md#togglesplitbutton) + +**Modifiers:** [`AccentButton`](../modifiers/buttons.md#accentbutton), [`IsCheckedChanged`](../modifiers/shared-controls.md#ischeckedchanged), [`Set`](../modifiers/native-properties.md#set), [`SubtleButton`](../modifiers/buttons.md#subtlebutton) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Command` | [`Command?`](../input/Command.md) | | The command bound via `ToggleSplitButton(Command)` / a direct `new ToggleSplitButtonElement(cmd.Label) { Command = cmd }` record-init (issue #153; made uniform in issue #637). All paths fire the command on each toggle + apply IsEnabled identically. See [`ButtonElement.Command`](#buttonelement). | +| `ContentElement` | [`Element?`](Element.md) | | Declarative content, taking precedence over the text value. | +| `Flyout` | [`Element?`](Element.md) | `null` | | +| `IsChecked` | [`Optional`](../components/Optional.md) | `default` | | +| `Label` | `string` | | | +| `OnIsCheckedChanged` | `Action?` | `null` | | diff --git a/docs/guide/reference/elements/collections.md b/docs/guide/reference/elements/collections.md new file mode 100644 index 0000000000..bc9335d577 --- /dev/null +++ b/docs/guide/reference/elements/collections.md @@ -0,0 +1,658 @@ +# Elements: Collections + +Lists, grids, trees, flip views and virtualized collections. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Collections](../../collections.md) + +## `FlipViewElement` + +The element record that describes a WinUI [`FlipView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.flipview) control. + +```csharp +public record FlipViewElement(Element[] Items) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`FlipView`](../factories/collections.md#flipview) + +**Modifiers:** [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Items` | [`Element[]`](Element.md) | | +| `OnSelectedIndexChanged` | `Action?` | | +| `SelectedIndex` | [`Optional`](../components/Optional.md) | Selected item index. Defaults to [`Optional.Unset`](../components/Optional.md#unset); use `Optional.Of(-1)` to force no selection. | + +## `GridViewElement` + +```csharp +public record GridViewElement(Element[] Items) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`GridView`](../factories/collections.md#gridview) + +**Modifiers:** [`IncrementalLoadingTrigger`](../modifiers/collections.md#incrementalloadingtrigger), [`ItemClick`](../modifiers/collections.md#itemclick), [`ItemContainerStyle`](../modifiers/collections.md#itemcontainerstyle), [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`SelectionChanged`](../modifiers/shared-controls.md#selectionchanged), [`SelectionMode`](../modifiers/collections.md#selectionmode), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Header` | `string?` | | +| `IncrementalLoadingTrigger` | `IncrementalLoadingTrigger` | Controls when incremental data sources fetch the next page. Defaults to `Edge`. | +| `ItemContainerStyle` | `Style?` | Style applied to each generated `GridViewItem` container. | +| `Items` | [`Element[]`](Element.md) | | +| `OnItemClick` | `Action?` | | +| `OnSelectedIndexChanged` | `Action?` | | +| `OnSelectionChanged` | `Action>?` | Multi-select snapshot callback. See [`ListViewElement.OnSelectionChanged`](#listviewelement). | +| `SelectedIndex` | [`Optional`](../components/Optional.md) | Selected item index. Defaults to [`Optional.Unset`](../components/Optional.md#unset); use `Optional.Of(-1)` to force no selection. | +| `SelectionMode` | `ListViewSelectionMode` | | + +## `ItemContainerElement` + +The element record that describes a WinUI [`ItemContainer`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.itemcontainer) control. + +```csharp +public record ItemContainerElement(Element? Child) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ItemContainer`](../factories/collections.md#itemcontainer) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Child` | [`Element?`](Element.md) | | +| `IsSelected` | `bool` | Selection state as exposed by `ItemContainer.IsSelected`. | + +## `ItemsRepeaterElement` + +Spec 047 §14 Phase 3 finish — Port (7). Typed peer of [`ItemsRepeaterElementBase`](#itemsrepeaterelementbase). The lambdas mirror the [`LazyVStackElement`](#lazyvstackelementt) / [`LazyHStackElement`](#lazyhstackelementt) shape (Items + KeySelector + ViewBuilder) so authors moving from Lazy\*Stack to a custom-layout ItemsRepeater find the surface identical. + +```csharp +public record ItemsRepeaterElement(IReadOnlyList Items, Func KeySelector, Func ViewBuilder) : ItemsRepeaterElementBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`ItemsRepeaterElementBase`](#itemsrepeaterelementbase). + +**Created by:** [`ItemsRepeater`](../factories/collections.md#itemsrepeater) + +| Property | Type | Description | +| --- | --- | --- | +| `ItemCount` | `int` | | +| `Items` | `IReadOnlyList` | | +| `KeySelector` | `Func` | | +| `ViewBuilder` | `Func` | | + +| Member | Description | +| --- | --- | +| `BuildItemView(int)` | | +| `CreateFactory(Reconciler, Action, ElementPool?)` | | +| `RefreshRealizedItems(IElementFactory, ItemsRepeater)` | | +| `TryUpdateFactory(IElementFactory)` | | + +## `ItemsRepeaterElementBase` + +Spec 047 §14 Phase 3 finish — Port (7). Non-generic intermediate base for [`ItemsRepeaterElement`](#itemsrepeaterelementt). Same role as [`LazyStackElementBase`](#lazystackelementbase): lets the reconciler match on a single type AND lets the descriptor's [`Reconciler.RegisterHandlerForDerivedTypes`](../extensibility/Reconciler.md#registerhandlerforderivedtypes) registration catch every closed-T variant. Implements `IKeyedItemSource` + `IItemsRepeaterFactorySource` for the Engine (1) ItemsRepeater arm in [`Reconciler.BindErasedKeyedItemsSource`](../extensibility/Reconciler.md). + +**Distinct from [`LazyStackElementBase`](#lazystackelementbase):** no hard-coded [`StackLayout`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.stacklayout). The element exposes a nullable [`ItemsRepeaterElementBase.Layout`](#itemsrepeaterelementbase) property — the descriptor / legacy mount arm assigns it directly when non-null, otherwise leaves the ItemsRepeater on its default (Stack vertical). No [`ScrollViewer`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.scrollviewer) wrapping either — the rendered [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement) is the bare [`ItemsRepeater`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.itemsrepeater). Authors who need scrolling host the element inside their own `ScrollViewer` / `ScrollView` / `RefreshContainer`. + +```csharp +public abstract record ItemsRepeaterElementBase : Element, IKeyedItemSource, IItemViewSource +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +| Property | Type | Description | +| --- | --- | --- | +| `ItemCount` | `int` | Total number of items in the source list. | +| `Layout` | `Layout?` | Optional WinUI [`Layout`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.layout). Null = leave the ItemsRepeater on its default layout (which itself defaults to vertical [`StackLayout`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.stacklayout)). Authors typically pass a `UniformGridLayout` or `LinedFlowLayout` instance configured up-front; the engine reuses it across renders by reference identity (no per-update Layout allocation). | + +| Member | Description | +| --- | --- | +| `BuildItemView(int)` | Per-index Element factory — same shape as [`LazyStackElementBase.BuildItemView`](#lazystackelementbase). | +| `CreateFactory(Reconciler, Action, ElementPool?)` | | +| `RefreshRealizedItems(IElementFactory, ItemsRepeater)` | | +| `TryUpdateFactory(IElementFactory)` | | + +## `ItemsViewElement` + +```csharp +public record ItemsViewElement(IReadOnlyList Items, Func KeySelector, Func ViewBuilder) : ItemsViewElementBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`ItemsViewElementBase`](#itemsviewelementbase). + +**Created by:** [`ItemsView`](../factories/collections.md#itemsview) + +**Modifiers:** [`ItemInvoked`](../modifiers/shared-controls.md#iteminvoked), [`SelectionChanged`](../modifiers/shared-controls.md#selectionchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `ItemCount` | `int` | | +| `Items` | `IReadOnlyList` | | +| `KeySelector` | `Func` | | +| `OnItemInvoked` | `Action?` | | +| `OnSelectionChanged` | `Action>?` | Multi-select snapshot callback. Receives the full list of currently selected items. Use this when [`ItemsViewElementBase.SelectionMode`](#itemsviewelementbase) is Multiple or Extended. | +| `ViewBuilder` | `Func` | | + +| Member | Description | +| --- | --- | +| `CreateFactory(Reconciler, Action, ElementPool?)` | | +| `InvokeItemInvoked(int)` | | +| `InvokeSelectionChanged(IReadOnlyList)` | | +| `RefreshRealizedItems(IElementFactory, ItemsRepeater)` | | +| `TryUpdateFactory(IElementFactory)` | | + +## `ItemsViewElementBase` + +Non-generic base so [`Reconciler`](../extensibility/Reconciler.md) can pattern-match an ItemsView element without knowing the user's item type. Mirrors the [`LazyStackElementBase`](#lazystackelementbase) / [`TemplatedListElementBase`](#templatedlistelementbase) shape: virtual hooks for factory creation, in-place update, per-row reconcile, and event callback dispatch. + +```csharp +public abstract record ItemsViewElementBase : Element, IKeyedItemSource, IItemViewSource +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +| Property | Type | Description | +| --- | --- | --- | +| `IsItemInvokedEnabled` | `bool` | | +| `ItemCount` | `int` | Total number of items in the source list. | +| `LayoutKind` | [`ItemsViewLayoutKind`](../controls/collection-items.md#itemsviewlayoutkind) | | +| `SelectionMode` | `ItemsViewSelectionMode` | | + +| Member | Description | +| --- | --- | +| `CreateFactory(Reconciler, Action, ElementPool?)` | | +| `InvokeItemInvoked(int)` | Dispatch an `ItemInvoked` event to the typed callback. | +| `InvokeSelectionChanged(IReadOnlyList)` | Dispatch a `SelectionChanged` snapshot to the typed callback. | +| `RefreshRealizedItems(IElementFactory, ItemsRepeater)` | | +| `TryUpdateFactory(IElementFactory)` | | + +## `LazyHStackElement` + +```csharp +public record LazyHStackElement(IReadOnlyList Items, Func KeySelector, Func ViewBuilder) : LazyStackElementBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`LazyStackElementBase`](#lazystackelementbase). + +**Created by:** [`LazyHStack`](../factories/collections.md#lazyhstack) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set), [`SetRepeater`](../modifiers/collections.md#setrepeater) + +| Property | Type | Description | +| --- | --- | --- | +| `EstimatedItemSize` | `double` | | +| `ItemCount` | `int` | | +| `Items` | `IReadOnlyList` | | +| `KeySelector` | `Func` | | +| `Orientation` | `Orientation` | | +| `Spacing` | `double` | | +| `ViewBuilder` | `Func` | | + +| Member | Description | +| --- | --- | +| `BuildItemView(int)` | | +| `CreateFactory(Reconciler, Action, ElementPool?)` | | +| `GetItemsSource()` | | +| `RefreshRealizedItems(IElementFactory, ItemsRepeater)` | | +| `TryUpdateFactory(IElementFactory)` | | + +## `LazyStackElementBase` + +Abstract base for virtualized lazy stacks. Non-generic so the reconciler can match on a single type in its switch expression. + +Spec 047 §14 Phase 3 finish — Port (6): also implements `IKeyedItemSource` and `IItemsRepeaterFactorySource` so the descriptor-driven G2 port (`LazyStackDescriptor`) can flow Lazy\*Stack through [`Reconciler.BindErasedKeyedItemsSource`](../extensibility/Reconciler.md)'s ItemsRepeater arm — same realization plumbing as the hand-coded `MountLazyStack` / `UpdateLazyStack` bodies. + +```csharp +public abstract record LazyStackElementBase : Element, IKeyedItemSource, IItemViewSource +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +| Property | Type | Description | +| --- | --- | --- | +| `EstimatedItemSize` | `double` | | +| `ItemCount` | `int` | Total number of items in the source list. | +| `Orientation` | `Orientation` | | +| `Spacing` | `double` | | + +| Member | Description | +| --- | --- | +| `BuildItemView(int)` | §14 Phase 3 finish — Port (6): build the per-item Element subtree for index N. Same shape as `TemplatedListElementBase.BuildItemView`; the descriptor binder reads this through the `IItemViewSource` contract (bridged via `IKeyedItemSource`) when the factory realizes a container. | +| `CreateFactory(Reconciler, Action, ElementPool?)` | | +| `GetItemsSource()` | | +| `RefreshRealizedItems(IElementFactory, ItemsRepeater)` | After updating the factory in place, reconcile all realized items with the new viewBuilder output (property diffs only, no collection changes). | +| `TryUpdateFactory(IElementFactory)` | Update an existing factory's items and viewBuilder in place, avoiding ItemsRepeater re-realization. Returns true if the factory was updated. | + +## `LazyVStackElement` + +```csharp +public record LazyVStackElement(IReadOnlyList Items, Func KeySelector, Func ViewBuilder) : LazyStackElementBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`LazyStackElementBase`](#lazystackelementbase). + +**Created by:** [`LazyVStack`](../factories/collections.md#lazyvstack) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set), [`SetRepeater`](../modifiers/collections.md#setrepeater) + +| Property | Type | Description | +| --- | --- | --- | +| `EstimatedItemSize` | `double` | | +| `ItemCount` | `int` | | +| `Items` | `IReadOnlyList` | | +| `KeySelector` | `Func` | | +| `Orientation` | `Orientation` | | +| `Spacing` | `double` | | +| `ViewBuilder` | `Func` | | + +| Member | Description | +| --- | --- | +| `BuildItemView(int)` | | +| `CreateFactory(Reconciler, Action, ElementPool?)` | | +| `GetItemsSource()` | | +| `RefreshRealizedItems(IElementFactory, ItemsRepeater)` | | +| `TryUpdateFactory(IElementFactory)` | | + +## `ListBoxElement` + +The element record that describes a WinUI [`ListBox`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.listbox) control. + +```csharp +public record ListBoxElement(string[] Items) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ListBox`](../factories/collections.md#listbox) + +**Modifiers:** [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`SelectionChanged`](../modifiers/shared-controls.md#selectionchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Items` | `string[]` | | +| `OnSelectedIndexChanged` | `Action?` | | +| `OnSelectionChanged` | `Action>?` | Multi-select snapshot callback. Receives the FULL list of currently selected indices. Use this in multi-select selection modes. | +| `SelectedIndex` | [`Optional`](../components/Optional.md) | Selected item index. Defaults to [`Optional.Unset`](../components/Optional.md#unset); use `Optional.Of(-1)` to force no selection. | + +## `ListViewElement` + +```csharp +public record ListViewElement(Element[] Items) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ListView`](../factories/collections.md#listview) + +**Modifiers:** [`IncrementalLoadingTrigger`](../modifiers/collections.md#incrementalloadingtrigger), [`ItemClick`](../modifiers/collections.md#itemclick), [`ItemContainerStyle`](../modifiers/collections.md#itemcontainerstyle), [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`SelectionChanged`](../modifiers/shared-controls.md#selectionchanged), [`SelectionMode`](../modifiers/collections.md#selectionmode), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Header` | `string?` | | +| `IncrementalLoadingTrigger` | `IncrementalLoadingTrigger` | Controls when incremental data sources fetch the next page. Defaults to `Edge`. | +| `ItemContainerStyle` | `Style?` | Style applied to each generated `ListViewItem` container (e.g. for padding, hover background). | +| `Items` | [`Element[]`](Element.md) | | +| `OnItemClick` | `Action?` | | +| `OnSelectedIndexChanged` | `Action?` | | +| `OnSelectionChanged` | `Action>?` | Multi-select snapshot callback. Receives the FULL list of currently selected indices (snapshot semantics, matching [`CalendarViewElement.OnSelectedDatesChanged`](input.md#calendarviewelement)). Use this in Multiple / Extended selection modes — [`ListViewElement.OnSelectedIndexChanged`](#listviewelement) only carries the focused single index. Not raised on initial mount. | +| `SelectedIndex` | [`Optional`](../components/Optional.md) | Selected item index. Defaults to [`Optional.Unset`](../components/Optional.md#unset); use `Optional.Of(-1)` to force no selection. | +| `SelectionMode` | `ListViewSelectionMode` | | + +## `RefreshContainerElement` + +The element record that describes a WinUI [`RefreshContainer`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.refreshcontainer) control. + +```csharp +public record RefreshContainerElement(Element Content) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`RefreshContainer`](../factories/collections.md#refreshcontainer) + +**Modifiers:** [`PullDirection`](../modifiers/collections.md#pulldirection), [`RefreshRequested`](../modifiers/collections.md#refreshrequested), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Content` | [`Element`](Element.md) | | +| `OnRefreshRequested` | `Action?` | | +| `PullDirection` | `RefreshPullDirection` | Direction the user pulls to trigger refresh. Defaults to `TopToBottom`. | + +## `SemanticZoomElement` + +The element record that describes a WinUI [`SemanticZoom`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.semanticzoom) control. + +```csharp +public record SemanticZoomElement(Element ZoomedInView, Element ZoomedOutView) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`SemanticZoom`](../factories/collections.md#semanticzoom) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `ZoomedInView` | [`Element`](Element.md) | | +| `ZoomedOutView` | [`Element`](Element.md) | | + +## `SwipeControlElement` + +The element record that describes a WinUI [`SwipeControl`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.swipecontrol) control. + +```csharp +public record SwipeControlElement(Element Content) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`SwipeControl`](../factories/collections.md#swipecontrol) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Content` | [`Element`](Element.md) | | +| `LeftItems` | [`SwipeItemData[]?`](../controls/collection-items.md#swipeitemdata) | Items revealed when swiping from the left. When [`SwipeControlElement.LeftItemsMode`](#swipecontrolelement) is [`SwipeMode.Execute`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.swipemode.execute), WinUI supports only one item: Reactor keeps the first and ignores the rest (with a diagnostic warning). | +| `LeftItemsMode` | `SwipeMode` | | +| `RightItems` | [`SwipeItemData[]?`](../controls/collection-items.md#swipeitemdata) | Items revealed when swiping from the right. When [`SwipeControlElement.RightItemsMode`](#swipecontrolelement) is [`SwipeMode.Execute`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.swipemode.execute), WinUI supports only one item: Reactor keeps the first and ignores the rest (with a diagnostic warning). | +| `RightItemsMode` | `SwipeMode` | | + +## `TemplatedFlipViewElement` + +```csharp +public record TemplatedFlipViewElement(IReadOnlyList Items, Func KeySelector, Func ViewBuilder) : TemplatedFlipViewElementBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`TemplatedFlipViewElementBase`](#templatedflipviewelementbase). + +**Created by:** [`FlipView`](../factories/collections.md#flipview) + +**Modifiers:** [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `ItemCount` | `int` | | +| `Items` | `IReadOnlyList` | | +| `KeySelector` | `Func` | | +| `OnSelectedIndexChanged` | `Action?` | | +| `SelectedIndex` | [`Optional`](../components/Optional.md) | Selected item index. Defaults to [`Optional.Unset`](../components/Optional.md#unset); use `Optional.Of(-1)` to force no selection. | +| `ViewBuilder` | `Func` | | + +| Member | Description | +| --- | --- | +| `ApplyControlSetters(object)` | | +| `BuildItemView(int)` | | +| `GetHeader()` | | +| `GetIsItemClickEnabled()` | | +| `GetSelectedIndex()` | | +| `GetSelectionMode()` | | +| `InvokeItemClick(int)` | | +| `InvokeSelectionChanged(int)` | | + +## `TemplatedFlipViewElementBase` + +Spec 047 §14 Phase 3 close-out — see [`TemplatedListViewElementBase`](#templatedlistviewelementbase). FlipView descriptor port is carved to Phase 4 because FlipView does not support `ContainerContentChanging` (pre-mounts items via a different shape); the marker is reserved so the symmetry is visible in the element hierarchy. + +```csharp +public abstract record TemplatedFlipViewElementBase : TemplatedListElementBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`TemplatedListElementBase`](#templatedlistelementbase). + +| Property | Type | Description | +| --- | --- | --- | +| `ControlKind` | [`TemplatedControlKind`](../controls/collection-items.md#templatedcontrolkind) | | + +## `TemplatedGridViewElement` + +```csharp +public record TemplatedGridViewElement(IReadOnlyList Items, Func KeySelector, Func ViewBuilder) : TemplatedGridViewElementBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`TemplatedGridViewElementBase`](#templatedgridviewelementbase). + +**Created by:** [`GridView`](../factories/collections.md#gridview) + +**Modifiers:** [`ItemClick`](../modifiers/collections.md#itemclick), [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`SelectionChanged`](../modifiers/shared-controls.md#selectionchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Header` | `string?` | | +| `ItemCount` | `int` | | +| `Items` | `IReadOnlyList` | | +| `KeySelector` | `Func` | | +| `OnItemClick` | `Action?` | | +| `OnSelectedIndexChanged` | `Action?` | | +| `OnSelectionChanged` | `Action>?` | Multi-select snapshot callback for the typed peer (see [`TemplatedListViewElement.OnSelectionChanged`](#templatedlistviewelementt)). | +| `SelectedIndex` | `int` | | +| `SelectionMode` | `ListViewSelectionMode` | | +| `ViewBuilder` | `Func` | | + +| Member | Description | +| --- | --- | +| `ApplyControlSetters(object)` | | +| `BuildItemView(int)` | | +| `GetHeader()` | | +| `GetIsItemClickEnabled()` | | +| `GetSelectedIndex()` | | +| `GetSelectionMode()` | | +| `InvokeItemClick(int)` | | +| `InvokeSelectionChanged(int)` | | + +## `TemplatedGridViewElementBase` + +Spec 047 §14 Phase 3 close-out — see [`TemplatedListViewElementBase`](#templatedlistviewelementbase). + +```csharp +public abstract record TemplatedGridViewElementBase : TemplatedListElementBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`TemplatedListElementBase`](#templatedlistelementbase). + +| Property | Type | Description | +| --- | --- | --- | +| `ControlKind` | [`TemplatedControlKind`](../controls/collection-items.md#templatedcontrolkind) | | + +## `TemplatedListElementBase` + +Abstract base for data-driven items controls. Non-generic so the reconciler can match on a single type in its switch expression (same pattern as LazyStackElementBase). + +```csharp +public abstract record TemplatedListElementBase : Element, IItemViewSource, IKeyedItemSource +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +| Property | Type | Description | +| --- | --- | --- | +| `ControlKind` | [`TemplatedControlKind`](../controls/collection-items.md#templatedcontrolkind) | | +| `ItemCount` | `int` | | + +| Member | Description | +| --- | --- | +| `ApplyControlSetters(object)` | | +| `BuildItemView(int)` | | +| `GetHeader()` | | +| `GetIsItemClickEnabled()` | | +| `GetSelectedIndex()` | | +| `GetSelectionMode()` | | +| `InvokeItemClick(int)` | | +| `InvokeSelectionChanged(int)` | | + +## `TemplatedListViewElement` + +```csharp +public record TemplatedListViewElement(IReadOnlyList Items, Func KeySelector, Func ViewBuilder) : TemplatedListViewElementBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`TemplatedListViewElementBase`](#templatedlistviewelementbase). + +**Created by:** [`ListView`](../factories/collections.md#listview) + +**Modifiers:** [`ItemClick`](../modifiers/collections.md#itemclick), [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`SelectionChanged`](../modifiers/shared-controls.md#selectionchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Header` | `string?` | | +| `ItemCount` | `int` | | +| `Items` | `IReadOnlyList` | | +| `KeySelector` | `Func` | | +| `OnItemClick` | `Action?` | | +| `OnSelectedIndexChanged` | `Action?` | | +| `OnSelectionChanged` | `Action>?` | Multi-select snapshot callback for the typed peer. Receives the full list of currently selected items (not just indices). Snapshot semantics — not raised on initial mount. | +| `SelectedIndex` | `int` | | +| `SelectionMode` | `ListViewSelectionMode` | | +| `ViewBuilder` | `Func` | | + +| Member | Description | +| --- | --- | +| `ApplyControlSetters(object)` | | +| `BuildItemView(int)` | | +| `GetHeader()` | | +| `GetIsItemClickEnabled()` | | +| `GetSelectedIndex()` | | +| `GetSelectionMode()` | | +| `InvokeItemClick(int)` | | +| `InvokeSelectionChanged(int)` | | + +## `TemplatedListViewElementBase` + +Spec 047 §14 Phase 3 close-out — empty marker intermediate that lets the v1 handler registry route every closed `TemplatedListViewElement` through a single base-derived descriptor registration without an open-generic resolver. Adds no fields and no overrides, so record equality on the leaf type `TemplatedListViewElement` is unchanged. + +```csharp +public abstract record TemplatedListViewElementBase : TemplatedListElementBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`TemplatedListElementBase`](#templatedlistelementbase). + +| Property | Type | Description | +| --- | --- | --- | +| `ControlKind` | [`TemplatedControlKind`](../controls/collection-items.md#templatedcontrolkind) | | + +## `TemplatedTreeViewElement` + +Typed, data-driven `TreeView`. The hierarchical peer of [`TemplatedListViewElement`](#templatedlistviewelementt). See [`TemplatedTreeViewElementBase`](#templatedtreeviewelementbase). + +```csharp +public record TemplatedTreeViewElement(IReadOnlyList Items, Func KeySelector, Func?> ChildrenSelector, Func ViewBuilder) : TemplatedTreeViewElementBase +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`TemplatedTreeViewElementBase`](#templatedtreeviewelementbase). + +**Created by:** [`TreeView`](../factories/collections.md#treeview) + +**Modifiers:** [`Expanding`](../modifiers/collections.md#expanding), [`ItemInvoked`](../modifiers/shared-controls.md#iteminvoked) + +| Property | Type | Description | +| --- | --- | --- | +| `AllowDrop` | `bool` | | +| `CanDragItems` | `bool` | | +| `CanReorderItems` | `bool` | | +| `ChildrenSelector` | `Func?>` | | +| `IsExpanded` | `Func?` | Per-item initial-expansion selector. Defaults to collapsed. | +| `Items` | `IReadOnlyList` | | +| `KeySelector` | `Func` | | +| `OnExpanding` | `Action?` | Invoked with the developer's `T` just before a node expands. | +| `OnItemInvoked` | `Action?` | Invoked with the developer's `T` when a node is clicked/invoked. | +| `SelectionMode` | `TreeViewSelectionMode` | | +| `ViewBuilder` | `Func` | | + +| Member | Description | +| --- | --- | +| `ApplyControlSetters(object)` | | +| `BuildView(object)` | | +| `GetAllowDrop()` | | +| `GetCanDragItems()` | | +| `GetCanReorderItems()` | | +| `GetChildren(object)` | | +| `GetIsExpanded(object)` | | +| `GetKey(object)` | | +| `GetRoots()` | | +| `GetSelectionMode()` | | +| `InvokeExpanding(object)` | | +| `InvokeItemInvoked(object)` | | + +## `TemplatedTreeViewElementBase` + +Abstract non-generic base for the typed, data-driven `TreeView`. Non-generic so the reconciler can match a single type in its switch expression (same type-erasure pattern as [`TemplatedListElementBase`](#templatedlistelementbase)). + +This is the hierarchical peer of [`TemplatedListViewElement`](#templatedlistviewelementt): the developer supplies their own data items, a key selector, a children selector (the hierarchy), and a `viewBuilder` (`data → Element`, the WinUI `ItemTemplate` equivalent). It exists because WinUI's node-mode `TreeView` stringifies `TreeViewNode.Content` and cannot host a pre-built `UIElement` — rich per-node visuals must come from a template, never an element instance (the root cause of issue #447). + +The base exposes object-erased accessors; the generic leaf casts back to `T`. Reference-type `T` flows through the covariant [`IReadOnlyList`](https://learn.microsoft.com/dotnet/api/system.collections.generic.ireadonlylist-1) → `IReadOnlyList` conversion; value-type `T` is boxed once via the leaf's projection helper. + +```csharp +public abstract record TemplatedTreeViewElementBase : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +| Member | Description | +| --- | --- | +| `ApplyControlSetters(object)` | | +| `BuildView(object)` | Builds the per-node view (the `ItemTemplate` equivalent). | +| `GetAllowDrop()` | | +| `GetCanDragItems()` | | +| `GetCanReorderItems()` | | +| `GetChildren(object)` | The children of `item`, or null for a leaf. | +| `GetIsExpanded(object)` | Whether `item`'s node should start expanded. | +| `GetKey(object)` | The stable identity string for `item` (the keyed-diff key). | +| `GetRoots()` | The root data items (object-erased), in document order. | +| `GetSelectionMode()` | | +| `InvokeExpanding(object)` | Dispatches `OnExpanding` with the developer's own `T`. | +| `InvokeItemInvoked(object)` | Dispatches `OnItemInvoked` with the developer's own `T`. | + +## `TreeViewElement` + +The element record that describes a WinUI [`TreeView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.treeview) control. + +```csharp +public record TreeViewElement(TreeViewNodeData[] Nodes) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`TreeView`](../factories/collections.md#treeview) + +**Modifiers:** [`Expanding`](../modifiers/collections.md#expanding), [`ItemInvoked`](../modifiers/shared-controls.md#iteminvoked), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `AllowDrop` | `bool` | | +| `CanDragItems` | `bool` | | +| `CanReorderItems` | `bool` | | +| `Nodes` | [`TreeViewNodeData[]`](../controls/collection-items.md#treeviewnodedata) | | +| `OnExpanding` | `Action?` | | +| `OnItemInvoked` | `Action?` | | +| `SelectionMode` | `TreeViewSelectionMode` | | + +## `VirtualListElement` + +Element record for the VirtualList component — a count-based virtualized list backed by WinUI's ItemsRepeater. Unlike LazyVStack which takes a concrete IReadOnlyList\, VirtualList works with an item count and a render callback, making it suitable for data-source-driven scenarios where items are fetched on demand. + +```csharp +public record VirtualListElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`Element`](Element.md). + +**Modifiers:** [`VisibleRangeChanged`](../modifiers/collections.md#visiblerangechanged) + +| Property | Type | Description | +| --- | --- | --- | +| `EstimatedItemHeight` | `double` | Estimated item height for variable-height mode (default 40px). Used for initial scroll extent calculation before items are measured. Ignored when ItemHeight is set. | +| `GetItemKey` | `Func?` | Optional key function for stable identity across re-renders. When provided, the reconciler uses this to match items across reorderings. When omitted, identity is positional: an unchanged item count preserves row identities without projecting all keys again. Realized content still refreshes. | +| `ItemCount` | `int` | Total number of items (drives the virtualizer's extent). | +| `ItemHeight` | `double?` | Fixed item height in pixels. When set, enables the fixed-height fast path with O(1) offset calculation — no per-item measurement needed. When null, variable-height mode is used with EstimatedItemHeight. | +| `OnVisibleRangeChanged` | `Action?` | Callback fired when the visible range changes (viewport tracking). Receives the first and last visible item indices. | +| `Ref` | `Action?` | Callback ref for scroll operations. When set, receives a VirtualListRef that exposes ScrollToIndex and scroll position save/restore. | +| `RenderItem` | `Func` | Render callback: given an index, return the Element for that row. Called only for visible items (virtualized). | +| `Spacing` | `double` | Spacing between items in pixels (default 0). | diff --git a/docs/guide/reference/elements/composition.md b/docs/guide/reference/elements/composition.md new file mode 100644 index 0000000000..984c0d3e48 --- /dev/null +++ b/docs/guide/reference/elements/composition.md @@ -0,0 +1,196 @@ +# Elements: Composition + +Components, memoization, error boundaries, conditionals and other structural elements. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Components](../../components.md), [Advanced Patterns](../../advanced.md) + +## `ComponentElement` + +Wraps a Component class so it can participate in the element tree. Created automatically by Component\() factory method. + +```csharp +public record ComponentElement(Type ComponentType, object? Props = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Component`](../factories/composition.md#component) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `ComponentType` | `Type` | | | +| `Props` | `object?` | `null` | | + +## `ComponentElement` + +Strongly-typed [`ComponentElement`](#componentelement) that exposes [`ComponentElement.Props`](#componentelementtprops) as `TProps` instead of `object?`, so callers can use a record `with`-expression to produce a modified copy of the element with updated props: + +```csharp +var grid = DataGrid(source, columns); +var taller = grid with { Props = grid.Props with { RowHeight = 60 } }; +``` + +The typed [`ComponentElement.Props`](#componentelementtprops) is a thin view over the base [`ComponentElement.Props`](#componentelement) slot — there is no second storage field, so the reconciler (which reads `base.Props`) always sees the same value as the typed accessor on the cloned record. + +```csharp +public record ComponentElement : ComponentElement +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`ComponentElement`](#componentelement). + +**Created by:** [`Component`](../factories/composition.md#component), [`LocaleProvider`](../factories/composition.md#localeprovider), [`PropertyGrid`](../factories/composition.md#propertygrid), [`VirtualList`](../factories/composition.md#virtuallist) + +| Property | Type | Description | +| --- | --- | --- | +| `Props` | `TProps` | | + +## `EmptyElement` + +An element that renders nothing (used for conditional rendering). + +```csharp +public record EmptyElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +| Member | Description | +| --- | --- | +| `Instance` | | + +## `ErrorBoundaryElement` + +Catches render errors in its child subtree and displays fallback UI. Like React's ErrorBoundary — catches errors during rendering, not event handlers. When the ErrorBoundary re-renders, it retries the child (error recovery). + +```csharp +public record ErrorBoundaryElement(Element Child, Func Fallback) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ErrorBoundary`](../factories/composition.md#errorboundary) + +| Property | Type | Description | +| --- | --- | --- | +| `Child` | [`Element`](Element.md) | | +| `Fallback` | `Func` | | + +## `FuncElement` + +A component defined inline via a render function (like a React function component). + +```csharp +public record FuncElement(Func RenderFunc) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`RenderEachTime`](../factories/composition.md#rendereachtime) + +| Property | Type | Description | +| --- | --- | --- | +| `RenderFunc` | `Func` | | + +## `GroupElement` + +A transparent grouping element (like React's Fragment). Does not introduce any layout container — its children are flattened into the parent. Produced by `ForEach` and `Group()` in the DSL. + +```csharp +public record GroupElement(Element[] Children) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +| Property | Type | Description | +| --- | --- | --- | +| `Children` | [`Element[]`](Element.md) | | + +## `KeyedMemoElement` + +Issue #327 — an opt-in, typed keyed memo wrapper produced by the `Memo(key, factory)` factory (see [`Factories`](../factories/index.md)). The author asserts [`KeyedMemoElement.Factory`](#keyedmemoelement) is a **pure function of [`KeyedMemoElement.MemoKey`](#keyedmemoelement)**: when a virtualized [`ElementFactory`](../components/ElementFactory.md) recycles a container and asks for the same key again, the factory-scoped LRU returns the previously-built inner [`Element`](Element.md) instance unchanged instead of rebuilding+diffing the subtree. Returning the *same* instance lets `Element.ShallowEquals` hit its `ReferenceEquals` fast-path so the per-row reconcile descent is skipped entirely. + +**Purity contract.** The key must capture *every* input the factory reads. Closing over unkeyed mutable state (a `UseState` cell, an external counter, the theme) without folding it into the key will serve stale content — that is the author's responsibility. Widen the key to a tuple (e.g. `Memo((item.Id, isSelected), …)`) to capture extra inputs. [`KeyedMemoElement.MemoKey`](#keyedmemoelement) is compared with [`Object.Equals`](https://learn.microsoft.com/dotnet/api/system.object.equals) / [`Object.GetHashCode`](https://learn.microsoft.com/dotnet/api/system.object.gethashcode), so value keys (ints, strings, records, value tuples) dedupe by value — this is what makes the int-index VirtualList path hit the cache where the reference-identity `_viewBuilderCache` cannot. + +**Used outside a virtualized factory** (e.g. a plain `VStack` child), the reconciler treats it as a *transparent, keyed* wrapper: a re-render with the same [`KeyedMemoElement.MemoKey`](#keyedmemoelement) is a no-op (by the purity contract the factory output is identical to the mounted inner, so there is nothing to diff), and a CHANGED key replaces the inner (unmount + fresh mount of the new [`KeyedMemoElement.Factory`](#keyedmemoelement) output). The old factory is never re-invoked at update time, so it is always safe to drop a `Memo(key, …)` anywhere a normal element is expected. The one exception to the no-op: when a component inside the mounted subtree updates its own state, the reconciler runs the current [`KeyedMemoElement.Factory`](#keyedmemoelement) again and walks that output against itself to reach the component, so the update renders. The cross-recycle cache benefit only applies on the [`ElementFactory`](../components/ElementFactory.md) recycle path. + +The positional parameter is named `MemoKey` (not `Key`) so it does not clash with the inherited [`Element.Key`](Element.md#key) string used for keyed reconciliation. + +```csharp +public sealed record KeyedMemoElement(object MemoKey, Func Factory) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Memo`](../factories/composition.md#memo) + +| Property | Type | Description | +| --- | --- | --- | +| `Factory` | `Func` | | +| `MemoKey` | `object` | | + +## `LocaleProviderElement` + +A Reactor element that establishes a locale context for its subtree. Sets FlowDirection on the host and provides IntlAccessor to descendants via UseIntl(). + +```csharp +public record LocaleProviderElement(string Locale, Element Child, IStringResourceProvider? ResourceProvider = null, string DefaultLocale = "en-US", bool PseudoLocalize = false) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Localization`. Inherits from [`Element`](Element.md). + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Child` | [`Element`](Element.md) | | | +| `DefaultLocale` | `string` | `"en-US"` | | +| `Locale` | `string` | | | +| `PseudoLocalize` | `bool` | `false` | | +| `ResourceProvider` | [`IStringResourceProvider?`](../localization/IStringResourceProvider.md) | `null` | | + +## `MemoElement` + +A memoized function component. Skips re-render when Dependencies haven't changed. null Dependencies = render once on mount + self-triggered state changes only. + +```csharp +public record MemoElement(Func RenderFunc, object?[]? Dependencies = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Memo`](../factories/composition.md#memo) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Dependencies` | `object?[]?` | `null` | | +| `RenderFunc` | `Func` | | | + +## `ModifiedElement` + +Wraps any element with layout modifiers (margin, alignment, size, etc.). Kept for backward compatibility. New code stores modifiers inline on Element.Modifiers. + +```csharp +public record ModifiedElement(Element Inner, ElementModifiers WrappedModifiers) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +| Property | Type | Description | +| --- | --- | --- | +| `Inner` | [`Element`](Element.md) | | +| `WrappedModifiers` | [`ElementModifiers`](../modifiers/ElementModifiers.md) | | + +## `SemanticElement` + +Wraps a child element in a SemanticPanel that provides custom automation semantics to screen readers. This solves the problem where Reactor components can't override OnCreateAutomationPeer(). + +```csharp +public record SemanticElement(Element Child, SemanticDescription Semantics) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +| Property | Type | Description | +| --- | --- | --- | +| `Child` | [`Element`](Element.md) | | +| `Semantics` | [`SemanticDescription`](../accessibility/SemanticDescription.md) | | diff --git a/docs/guide/reference/elements/dialogs-and-flyouts.md b/docs/guide/reference/elements/dialogs-and-flyouts.md new file mode 100644 index 0000000000..1a58ffaba2 --- /dev/null +++ b/docs/guide/reference/elements/dialogs-and-flyouts.md @@ -0,0 +1,130 @@ +# Elements: Dialogs and flyouts + +Content dialogs, flyouts, popups and teaching tips. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Dialogs and Flyouts](../../dialogs-and-flyouts.md) + +## `ContentDialogElement` + +Declarative content dialog. Set IsOpen to true to show, false to close; content is reconciled live while the dialog is open. OnClosed reports how the dialog was dismissed — the button the user chose, or [`ContentDialogResult.None`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.contentdialogresult.none) for a declared IsOpen = false. It does not fire when the dialog is torn down because its owner unmounted or its host/reconciler was disposed. Disposal also cancels deferred opens without OnOpened. State reset needed during teardown belongs in effect cleanup, not OnClosed. + +```csharp +public record ContentDialogElement(string Title, Element Content, string PrimaryButtonText = "OK") : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ContentDialog`](../factories/dialogs-and-flyouts.md#contentdialog) + +**Modifiers:** [`Closed`](../modifiers/shared-controls.md#closed), [`IsPrimaryButtonEnabled`](../modifiers/dialogs-and-flyouts.md#isprimarybuttonenabled), [`IsSecondaryButtonEnabled`](../modifiers/dialogs-and-flyouts.md#issecondarybuttonenabled), [`Opened`](../modifiers/dialogs-and-flyouts.md#opened), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `CloseButtonText` | `string?` | | | +| `Content` | [`Element`](Element.md) | | | +| `DefaultButton` | `ContentDialogButton` | | | +| `IsOpen` | `bool` | | | +| `IsPrimaryButtonEnabled` | `bool` | | Enables/disables the primary button while the dialog is open. Defaults to `true`. | +| `IsSecondaryButtonEnabled` | `bool` | | Enables/disables the secondary button while the dialog is open. Defaults to `true`. | +| `OnClosed` | `Action?` | | | +| `OnOpened` | `Action?` | | Raised after the dialog finishes opening. | +| `PrimaryButtonText` | `string` | `"OK"` | | +| `SecondaryButtonText` | `string?` | | | +| `Title` | `string` | | | + +## `ContentFlyoutElement` + +Describes a content flyout (used as a slot value on buttons or as a modifier attachment). NOT independently mountable — the reconciler recognizes it in flyout slots. + +```csharp +public record ContentFlyoutElement(Element Content) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ContentFlyout`](../factories/dialogs-and-flyouts.md#contentflyout) + +| Property | Type | Description | +| --- | --- | --- | +| `Content` | [`Element`](Element.md) | | +| `Placement` | `FlyoutPlacementMode` | Preferred position of the flyout relative to its target. Defaults to [`FlyoutPlacementMode.Auto`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.auto), which means "no opinion — let WinUI decide": Reactor clears `FlyoutBase.Placement` so it falls back to the control's own default ([`FlyoutPlacementMode.Top`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.top)) instead of writing `Auto`, because WinUI's show-time validator rejects `Auto` and terminates the process. Changing an already-mounted flyout from an explicit placement back to [`FlyoutPlacementMode.Auto`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.auto) therefore returns it to that default, rather than leaving a stale local value that would outrank a `Style` setter. | + +## `FlyoutElement` + +A flyout attached to another element. Wrap the target element. + +```csharp +public record FlyoutElement(Element Target, Element FlyoutContent) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Flyout`](../factories/dialogs-and-flyouts.md#flyout) + +**Modifiers:** [`AreOpenCloseAnimationsEnabled`](../modifiers/dialogs-and-flyouts.md#areopencloseanimationsenabled), [`Closed`](../modifiers/shared-controls.md#closed), [`Opened`](../modifiers/dialogs-and-flyouts.md#opened), [`OverlayInputPassThroughElement`](../modifiers/dialogs-and-flyouts.md#overlayinputpassthroughelement), [`Set`](../modifiers/native-properties.md#set), [`ShowMode`](../modifiers/dialogs-and-flyouts.md#showmode) + +| Property | Type | Description | +| --- | --- | --- | +| `AreOpenCloseAnimationsEnabled` | `bool` | Whether the flyout animates on open/close. Defaults to `true`. | +| `FlyoutContent` | [`Element`](Element.md) | | +| `IsOpen` | `bool` | Opens the flyout declaratively. A one-shot trigger: the flyout is shown on mount when already `true`, and on the `false` → `true` edge of an update, against any target (a Button/SplitButton target holds the flyout in its own `Flyout` slot, any other target as `FlyoutBase.AttachedFlyout`). Setting it back to `false` does not close the flyout — the user dismisses it. Reset your state from [`FlyoutElement.OnClosed`](#flyoutelement) so the next `true` is a fresh edge. | +| `OnClosed` | `Action?` | | +| `OnOpened` | `Action?` | | +| `OverlayInputPassThroughElement` | [`Element?`](Element.md) | Element whose input is passed through the light-dismiss overlay (lets the user interact with one element behind the flyout). | +| `Placement` | `FlyoutPlacementMode` | Preferred position of the flyout relative to its target. Defaults to [`FlyoutPlacementMode.Auto`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.auto), which means "no opinion — let WinUI decide": Reactor clears `FlyoutBase.Placement` so it falls back to the control's own default ([`FlyoutPlacementMode.Top`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.top)) instead of writing `Auto`, because WinUI's show-time validator rejects `Auto` and terminates the process. Changing an already-mounted flyout from an explicit placement back to [`FlyoutPlacementMode.Auto`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.auto) therefore returns it to that default, rather than leaving a stale local value that would outrank a `Style` setter. | +| `ShowMode` | `FlyoutShowMode` | How the flyout reacts to clicks outside its bounds (Auto / Standard / Transient / TransientWithDismissOnPointerMoveAway). | +| `Target` | [`Element`](Element.md) | | + +## `PopupElement` + +```csharp +public record PopupElement(Element Child) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Popup`](../factories/dialogs-and-flyouts.md#popup) + +**Modifiers:** [`Closed`](../modifiers/shared-controls.md#closed), [`IsLightDismissEnabled`](../modifiers/dialogs-and-flyouts.md#islightdismissenabled), [`LightDismiss`](../modifiers/dialogs-and-flyouts.md#lightdismiss), [`Offset`](../modifiers/dialogs-and-flyouts.md#offset), [`Opened`](../modifiers/dialogs-and-flyouts.md#opened), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Child` | [`Element`](Element.md) | | +| `HorizontalOffset` | `double` | | +| `IsLightDismissEnabled` | `bool` | | +| `IsOpen` | `bool` | | +| `OnClosed` | `Action?` | | +| `OnOpened` | `Action?` | | +| `VerticalOffset` | `double` | | + +## `TeachingTipElement` + +The element record that describes a WinUI [`TeachingTip`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.teachingtip) control. + +```csharp +public record TeachingTipElement(string Title, string? Subtitle = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`TeachingTip`](../factories/dialogs-and-flyouts.md#teachingtip) + +**Modifiers:** [`ActionButtonClick`](../modifiers/shared-controls.md#actionbuttonclick), [`Closed`](../modifiers/shared-controls.md#closed), [`HeroContent`](../modifiers/dialogs-and-flyouts.md#herocontent), [`IconSource`](../modifiers/shared-controls.md#iconsource), [`PlacementMargin`](../modifiers/dialogs-and-flyouts.md#placementmargin), [`PreferredPlacement`](../modifiers/dialogs-and-flyouts.md#preferredplacement), [`Set`](../modifiers/native-properties.md#set), [`Target`](../modifiers/dialogs-and-flyouts.md#target) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `ActionButtonContent` | `string?` | | | +| `CloseButtonContent` | `string?` | | | +| `Content` | [`Element?`](Element.md) | | | +| `HeroContent` | [`Element?`](Element.md) | | Optional "hero" Element (image / banner) rendered above the title. | +| `IconSource` | [`IconData?`](../controls/icons.md#icondata) | | Custom icon source rendered in the tip's leading slot. | +| `IsOpen` | `bool` | | Whether the tip is shown. Defaults to `false` — drive it from state. **Edge-triggered.** This declares a *transition*, not a mirror: after the initial render Reactor writes the control only when the declared value *changes*. A light dismiss or the tip's own close button sets `IsOpen` to `false` on the control without touching the declared value, so re-rendering the same declared `true` will not re-open it. Wire [`TeachingTipElement.OnClosed`](#teachingtipelement) back into the state that drives this property; a later `false → true` transition then re-opens the tip. **Mount is the one exception** (issue #949): a first render that declares `true` does open the tip. WinUI drops a pending open if the tip is written again while it is still unparented, and Reactor configures controls before parenting them, so the mount-time open is deferred until the control is loaded. One consequence worth knowing: because that write lands after the setter pass, a `.Set(t => t.IsOpen = false)` cannot override a declared mount-time `true` the way setters normally win. Declare the value instead of reaching for `.Set` — this property is the supported channel for it. | +| `OnActionButtonClick` | `Action?` | | | +| `OnClosed` | `Action?` | | | +| `PlacementMargin` | `Thickness` | | Extra margin around the tip when placed relative to its target. | +| `PreferredPlacement` | `TeachingTipPlacementMode` | | Preferred placement edge. Defaults to `Auto`. | +| `Subtitle` | `string?` | `null` | | +| `Target` | [`ElementRef?`](../input/element-refs.md#elementref) | | Control the tip anchors to, referenced by `ElementRef` so it resolves regardless of mount order. | +| `Title` | `string` | | | diff --git a/docs/guide/reference/elements/forms.md b/docs/guide/reference/elements/forms.md new file mode 100644 index 0000000000..77a509ea2e --- /dev/null +++ b/docs/guide/reference/elements/forms.md @@ -0,0 +1,96 @@ +# Elements: Forms + +Form fields, validation rules, validation visualizers and the property grid. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Forms and Input](../../forms.md) + +## `FormFieldElement` + +A wrapper element that provides label, required indicator, description, and error display for a child form control. Acts as an inline visualizer: when the child has errors, the description text is replaced with error messages. + +```csharp +public sealed record FormFieldElement(Element Content, string? Label = null, bool Required = false, string? Description = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Controls.Validation`. Inherits from [`Element`](Element.md). + +**Created by:** [`FormField`](../factories/forms.md#formfield) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Content` | [`Element`](Element.md) | | | +| `Description` | `string?` | `null` | | +| `FieldName` | `string?` | | The field name to query from the ValidationContext. When null, auto-detected from any ValidationAttached on the Content element. | +| `Label` | `string?` | `null` | | +| `Required` | `bool` | `false` | | +| `ShowWhen` | [`ShowWhen`](../validation/enums.md#showwhen) | | Controls when error messages are shown (default: WhenTouched). | + +## `PropertyGridElement` + +Element record for the PropertyGrid component. Serves as both the virtual DOM element and the typed props for PropertyGridComponent. + +```csharp +public record PropertyGridElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`Element`](Element.md). + +**Modifiers:** [`RootChanged`](../modifiers/forms.md#rootchanged) + +| Property | Type | Description | +| --- | --- | --- | +| `ArrayItemTemplate` | [`ArrayItemTemplate?`](../controls/property-grid-templates.md#arrayitemtemplate) | | +| `ArrayToolbarTemplate` | [`ArrayToolbarTemplate?`](../controls/property-grid-templates.md#arraytoolbartemplate) | | +| `CategoryTemplate` | [`CategoryTemplate?`](../controls/property-grid-templates.md#categorytemplate) | | +| `Filter` | `Func?` | Optional filter predicate — return false to hide a property. | +| `OnRootChanged` | `Action?` | Callback when the root object is replaced (for immutable roots). | +| `PropertyLabelTemplate` | [`PropertyLabelTemplate?`](../controls/property-grid-templates.md#propertylabeltemplate) | | +| `PropertyRowTemplate` | [`PropertyRowTemplate?`](../controls/property-grid-templates.md#propertyrowtemplate) | | +| `Registry` | [`TypeRegistry`](../controls/property-grid-templates.md#typeregistry) | The type registry for resolving editors. | +| `ShowSearch` | `bool` | Whether to show the search/filter box. | +| `Target` | `object` | The target object whose properties are edited. | + +## `ValidationRuleElement` + +A virtual element that represents a cross-field validation rule. Place anywhere in the element tree; errors bubble to the nearest visualizer. Does not render any UI — it only produces validation messages. + +```csharp +public sealed record ValidationRuleElement(string Field, Func Predicate, string Message, Severity Severity = Severity.Error) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Controls.Validation`. Inherits from [`Element`](Element.md). + +**Created by:** [`ValidationRule`](../factories/forms.md#validationrule), [`ValidationRuleAsync`](../factories/forms.md#validationruleasync) + +**Modifiers:** [`EvaluateAsync`](../modifiers/forms.md#evaluateasync) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `AsyncPredicate` | `Func>?` | | Optional async predicate for rules that require I/O. When set, takes precedence over the sync Predicate. | +| `Field` | `string` | | | +| `Message` | `string` | | | +| `Predicate` | `Func` | | | +| `Severity` | [`Severity`](../validation/enums.md#severity) | `Severity.Error` | | + +## `ValidationVisualizerElement` + +An element that catches validation errors from its content subtree and displays them. Errors caught by a visualizer are removed from further bubbling. + +```csharp +public sealed record ValidationVisualizerElement(VisualizerStyle Style, Element Content) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Controls.Validation`. Inherits from [`Element`](Element.md). + +**Created by:** [`ValidationVisualizer`](../factories/forms.md#validationvisualizer) + +| Property | Type | Description | +| --- | --- | --- | +| `Content` | [`Element`](Element.md) | | +| `CustomRender` | `Func, Element>?` | Custom render function for Custom-style visualizers. Receives all caught messages and returns an Element to render. | +| `SeverityFilter` | `Severity?` | Optional severity filter. When set, only catches messages of this severity. Messages with other severities continue to bubble. | +| `ShowWhen` | [`ShowWhen`](../validation/enums.md#showwhen) | Controls when the visualizer shows its content. | +| `Style` | [`VisualizerStyle`](../validation/enums.md#visualizerstyle) | | +| `Title` | `string?` | Optional heading text for the visualizer. | diff --git a/docs/guide/reference/elements/index.md b/docs/guide/reference/elements/index.md new file mode 100644 index 0000000000..1e28883316 --- /dev/null +++ b/docs/guide/reference/elements/index.md @@ -0,0 +1,32 @@ +# Elements + +The immutable element records that describe each control. + +Every control in Reactor is described by an element record. Factory methods create them and modifiers return changed copies. The reconciler turns them into real WinUI controls. + +**Learn more:** [Controls](../../controls.md), [Reconciliation](../../reconciliation.md) + +## Areas + +| Area | Description | +| --- | --- | +| [Layout](layout.md) | Panels, stacks, grids, scrolling and other containers. | +| [Text](text.md) | Text blocks, rich text and the typography factories. | +| [Buttons](buttons.md) | Buttons, toggle buttons, split buttons and hyperlink buttons. | +| [Input](input.md) | Text boxes, check boxes, combo boxes, sliders, pickers and other input controls. | +| [Collections](collections.md) | Lists, grids, trees, flip views and virtualized collections. | +| [Navigation](navigation.md) | Navigation views, tabs, pivots, breadcrumbs and the title bar. | +| [Menus and commands](menus-and-commands.md) | Menus, menu bars, command bars and keyboard accelerators. | +| [Dialogs and flyouts](dialogs-and-flyouts.md) | Content dialogs, flyouts, popups and teaching tips. | +| [Media and icons](media.md) | Images, icons, animated visuals, media playback and person pictures. | +| [Shapes](shapes.md) | Rectangles, ellipses, lines, paths and brushes. | +| [Status and info](status-and-info.md) | Info bars, badges and progress indicators. | +| [Forms](forms.md) | Form fields, validation rules, validation visualizers and the property grid. | +| [Composition](composition.md) | Components, memoization, error boundaries, conditionals and other structural elements. | +| [Interop](interop.md) | Hosted XAML content, web views and maps. | + +## Types + +| Type | Description | +| --- | --- | +| [`Element`](Element.md) | A lightweight, immutable description of a UI node (the "virtual DOM"). | diff --git a/docs/guide/reference/elements/input.md b/docs/guide/reference/elements/input.md new file mode 100644 index 0000000000..72439cd0d4 --- /dev/null +++ b/docs/guide/reference/elements/input.md @@ -0,0 +1,504 @@ +# Elements: Input + +Text boxes, check boxes, combo boxes, sliders, pickers and other input controls. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Controls](../../controls.md), [Forms and Input](../../forms.md) + +## `AutoSuggestBoxElement` + +Auto-suggest box element. `Text` defaults to [`Optional.Unset`](../components/Optional.md#unset) so typed text is not overwritten unless explicitly set. + +```csharp +public record AutoSuggestBoxElement(Optional Text = default, Action? OnTextChanged = null, Action? OnQuerySubmitted = null, Action? OnSuggestionChosen = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`AutoSuggestBox`](../factories/input.md#autosuggestbox) + +**Modifiers:** [`Header`](../modifiers/input.md#header), [`IsSuggestionListOpen`](../modifiers/input.md#issuggestionlistopen), [`PlaceholderText`](../modifiers/input.md#placeholdertext), [`QueryIcon`](../modifiers/input.md#queryicon), [`QuerySubmitted`](../modifiers/input.md#querysubmitted), [`Set`](../modifiers/native-properties.md#set), [`SuggestionChosen`](../modifiers/input.md#suggestionchosen), [`TextChanged`](../modifiers/input.md#textchanged) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Header` | `string?` | | Optional label rendered above the box. | +| `IsSuggestionListOpen` | `bool` | | Programmatically open or close the suggestion list. Defaults to `false`. | +| `OnQuerySubmitted` | `Action?` | `null` | | +| `OnSuggestionChosen` | `Action?` | `null` | | +| `OnTextChanged` | `Action?` | `null` | | +| `PlaceholderText` | `string?` | | | +| `QueryIcon` | [`IconData?`](../controls/icons.md#icondata) | | Icon rendered in the trailing query slot (e.g. a Search symbol). | +| `Suggestions` | `string[]` | | | +| `Text` | [`Optional`](../components/Optional.md) | `default` | | + +## `AutoSuggestElement` + +A type-safe auto-suggest element with async search, debounce, and custom templates. + +```csharp +public sealed record AutoSuggestElement(T? Selected, Action? OnSelected = null, Func>>? Search = null, Func? DisplayText = null, string? PlaceholderText = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`Element`](Element.md). + +**Created by:** [`AutoSuggest`](../factories/input.md#autosuggest) + +**Modifiers:** [`PlaceholderText`](../modifiers/input.md#placeholdertext), [`Selected`](../modifiers/input.md#selected) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `DebounceMs` | `int` | | Debounce delay in milliseconds before triggering search. Default: 300ms. | +| `DisplayText` | `Func?` | `null` | | +| `EmptyMessage` | `string` | | Message to display when search returns no results. | +| `ErrorMessage` | `string` | | Error message to display when search fails. | +| `OnSelected` | `Action?` | `null` | | +| `PlaceholderText` | `string?` | `null` | | +| `Search` | `Func>>?` | `null` | | +| `Selected` | `T?` | | | +| `Template` | `Func?` | | Custom template for rendering suggestion items. | + +## `CalendarDatePickerElement` + +Calendar date picker element. `Date` defaults to [`Optional.Unset`](../components/Optional.md#unset); use an explicit `null` value to assert no date. + +```csharp +public record CalendarDatePickerElement(Optional Date = default, Action? OnDateChanged = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`CalendarDatePicker`](../factories/input.md#calendardatepicker) + +**Modifiers:** [`DateChanged`](../modifiers/input.md#datechanged), [`DateFormat`](../modifiers/input.md#dateformat), [`IsCalendarOpen`](../modifiers/input.md#iscalendaropen), [`IsGroupLabelVisible`](../modifiers/input.md#isgrouplabelvisible), [`IsTodayHighlighted`](../modifiers/input.md#istodayhighlighted), [`PlaceholderText`](../modifiers/input.md#placeholdertext), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Date` | [`Optional`](../components/Optional.md) | `default` | | +| `DateFormat` | `string?` | | Display format string for the picker's text (see WinUI `DateFormat` reference). | +| `Header` | `string?` | | | +| `IsCalendarOpen` | `bool` | | Programmatically open or close the calendar popup. | +| `IsGroupLabelVisible` | `bool` | | Show month/year group label headers in the popup. Defaults to `true`. | +| `IsTodayHighlighted` | `bool` | | Highlight today's date in the popup. Defaults to `true` (matches WinUI). | +| `MaxDate` | `DateTimeOffset?` | | | +| `MinDate` | `DateTimeOffset?` | | | +| `OnDateChanged` | `Action?` | `null` | | +| `PlaceholderText` | `string?` | | | + +## `CalendarViewElement` + +The element record that describes a WinUI [`CalendarView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.calendarview) control. + +```csharp +public record CalendarViewElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`CalendarView`](../factories/input.md#calendarview) + +**Modifiers:** [`DisplayMode`](../modifiers/input.md#displaymode), [`FirstDayOfWeek`](../modifiers/input.md#firstdayofweek), [`MaxDate`](../modifiers/input.md#maxdate), [`MinDate`](../modifiers/input.md#mindate), [`NumberOfWeeksInView`](../modifiers/input.md#numberofweeksinview), [`SelectedDates`](../modifiers/input.md#selecteddates), [`SelectedDatesChanged`](../modifiers/input.md#selecteddateschanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `CalendarIdentifier` | `string?` | | +| `DisplayMode` | `CalendarViewDisplayMode` | Initial display mode (Month / Year / Decade). Defaults to `Month`. | +| `FirstDayOfWeek` | `DayOfWeek?` | Day of the week that starts each row. `null` = locale default. | +| `IsGroupLabelVisible` | `bool` | | +| `IsOutOfScopeEnabled` | `bool` | | +| `Language` | `string?` | | +| `MaxDate` | `DateTimeOffset?` | Latest selectable date. `null` = WinUI default (~100 years ahead). | +| `MinDate` | `DateTimeOffset?` | Earliest selectable date. `null` = WinUI default (~100 years back). | +| `NumberOfWeeksInView` | `int` | How many week rows to display in month mode (2–8). Defaults to 6. | +| `OnSelectedDatesChanged` | `Action>?` | Raised when the user changes the selection. Receives a snapshot of the full selection (not just added/removed dates) — easier to bind into component state without diffing. Not raised on the initial declarative selection applied at mount. | +| `SelectedDates` | `IReadOnlyList?` | Initial selection. Bind for declarative selection on mount; subsequent programmatic updates re-apply only when the list reference differs. Combine with [`CalendarViewElement.OnSelectedDatesChanged`](#calendarviewelement) for two-way binding in multi-select mode. | +| `SelectionMode` | `CalendarViewSelectionMode` | | + +## `CheckBoxElement` + +Check box element. `IsChecked` defaults to [`Optional.Unset`](../components/Optional.md#unset) so the control owns its checked state until explicitly set. + +```csharp +public record CheckBoxElement(Optional IsChecked = default, Action? OnIsCheckedChanged = null, string? Label = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`CheckBox`](../factories/input.md#checkbox), [`ThreeStateCheckBox`](../factories/input.md#threestatecheckbox) + +**Modifiers:** [`CheckedStateChanged`](../modifiers/shared-controls.md#checkedstatechanged), [`IsCheckedChanged`](../modifiers/shared-controls.md#ischeckedchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `CheckedState` | `bool?` | | | +| `ContentElement` | [`Element?`](Element.md) | | Declarative content, taking precedence over the text value. | +| `IsChecked` | [`Optional`](../components/Optional.md) | `default` | | +| `IsThreeState` | `bool` | | | +| `Label` | `string?` | `null` | | +| `OnCheckedStateChanged` | `Action?` | | | +| `OnIsCheckedChanged` | `Action?` | `null` | | + +## `ColorPickerElement` + +Color picker element. `Color` defaults to [`Optional.Unset`](../components/Optional.md#unset) so the control owns its color until explicitly set. + +```csharp +public record ColorPickerElement(Optional Color = default, Action? OnColorChanged = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ColorPicker`](../factories/input.md#colorpicker) + +**Modifiers:** [`AlphaEnabled`](../modifiers/input.md#alphaenabled), [`ColorChanged`](../modifiers/input.md#colorchanged), [`ColorChannelTextInputVisible`](../modifiers/input.md#colorchanneltextinputvisible), [`ColorSliderVisible`](../modifiers/input.md#colorslidervisible), [`ColorSpectrumShape`](../modifiers/input.md#colorspectrumshape), [`ColorSpectrumVisible`](../modifiers/input.md#colorspectrumvisible), [`HexInputVisible`](../modifiers/input.md#hexinputvisible), [`HueRange`](../modifiers/input.md#huerange), [`MoreButtonVisible`](../modifiers/input.md#morebuttonvisible), [`SaturationRange`](../modifiers/input.md#saturationrange), [`Set`](../modifiers/native-properties.md#set), [`ValueRange`](../modifiers/input.md#valuerange) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Color` | [`Optional`](../components/Optional.md) | `default` | | +| `ColorSpectrumShape` | `ColorSpectrumShape` | | Shape of the 2D color spectrum (Box or Ring). Defaults to `Box`. | +| `IsAlphaEnabled` | `bool` | | | +| `IsColorChannelTextInputVisible` | `bool` | | | +| `IsColorSliderVisible` | `bool` | | | +| `IsColorSpectrumVisible` | `bool` | | | +| `IsHexInputVisible` | `bool` | | | +| `IsMoreButtonVisible` | `bool` | | | +| `MaxHue` | `int` | | Maximum hue (0–359). Defaults to 359. | +| `MaxSaturation` | `int` | | Maximum saturation (0–100). Defaults to 100. | +| `MaxValue` | `int` | | Maximum value/brightness (0–100). Defaults to 100. | +| `MinHue` | `int` | | Minimum hue (0–359). Defaults to 0. | +| `MinSaturation` | `int` | | Minimum saturation (0–100). Defaults to 0. | +| `MinValue` | `int` | | Minimum value/brightness (0–100). Defaults to 0. | +| `OnColorChanged` | `Action?` | `null` | | + +## `ComboBoxElement` + +ComboBox element. `SelectedIndex` defaults to [`Optional.Unset`](../components/Optional.md#unset); use `Optional.Of(-1)` to force no selection. + +```csharp +public record ComboBoxElement(string[] Items, Optional SelectedIndex = default, Action? OnSelectedIndexChanged = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ComboBox`](../factories/input.md#combobox) + +**Modifiers:** [`Description`](../modifiers/input.md#description), [`DropDownClosed`](../modifiers/input.md#dropdownclosed), [`DropDownOpened`](../modifiers/input.md#dropdownopened), [`Editable`](../modifiers/input.md#editable), [`Header`](../modifiers/input.md#header), [`IsEditable`](../modifiers/input.md#iseditable), [`MaxDropDownHeight`](../modifiers/input.md#maxdropdownheight), [`PlaceholderText`](../modifiers/input.md#placeholdertext), [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Description` | `string?` | | Help text rendered below the box. WinUI 3 1.2+ feature. | +| `Header` | `string?` | | | +| `IsEditable` | `bool` | | | +| `ItemElements` | [`Element[]?`](Element.md) | | | +| `Items` | `string[]` | | | +| `MaxDropDownHeight` | `double` | | Maximum pixel height of the open drop-down. `NaN` (default) uses the WinUI default. | +| `OnDropDownClosed` | `Action?` | | Raised when the drop-down list closes (either by selection or dismissal). | +| `OnDropDownOpened` | `Action?` | | Raised when the user opens the drop-down list. | +| `OnSelectedIndexChanged` | `Action?` | `null` | | +| `PlaceholderText` | `string?` | | | +| `SelectedIndex` | [`Optional`](../components/Optional.md) | `default` | | + +## `DatePickerElement` + +Date picker element. `Date` defaults to [`Optional.Unset`](../components/Optional.md#unset) so the control owns its date until explicitly set. + +```csharp +public record DatePickerElement(Optional Date = default, Action? OnDateChanged = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`DatePicker`](../factories/input.md#datepicker) + +**Modifiers:** [`DateChanged`](../modifiers/input.md#datechanged), [`DayFormat`](../modifiers/input.md#dayformat), [`MonthFormat`](../modifiers/input.md#monthformat), [`Orientation`](../modifiers/input.md#orientation), [`Set`](../modifiers/native-properties.md#set), [`YearFormat`](../modifiers/input.md#yearformat) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Date` | [`Optional`](../components/Optional.md) | `default` | | +| `DayFormat` | `string?` | | Display format string for the day column. `null` uses the WinUI default. | +| `DayVisible` | `bool` | | | +| `Header` | `string?` | | | +| `MaxYear` | `DateTimeOffset?` | | | +| `MinYear` | `DateTimeOffset?` | | | +| `MonthFormat` | `string?` | | Display format string for the month column. `null` uses the WinUI default. | +| `MonthVisible` | `bool` | | | +| `OnDateChanged` | `Action?` | `null` | | +| `Orientation` | `Orientation` | | Layout direction of the picker. Defaults to `Horizontal`. | +| `YearFormat` | `string?` | | Display format string for the year column. `null` uses the WinUI default. | +| `YearVisible` | `bool` | | | + +## `MaskedTextBoxElement` + +A text box that enforces a mask pattern for structured input. + +```csharp +public sealed record MaskedTextBoxElement(string Value, Action? OnChanged = null, string? Mask = null, string? Header = null, char Placeholder = '_') : Element +``` + +Namespace: `Microsoft.UI.Reactor.Controls`. Inherits from [`Element`](Element.md). + +**Created by:** [`MaskedTextBox`](../factories/input.md#maskedtextbox) + +**Modifiers:** [`Changed`](../modifiers/input.md#changed) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Header` | `string?` | `null` | | +| `IsComplete` | `bool` | | Whether all required positions in the mask are filled. | +| `Mask` | `string?` | `null` | | +| `OnChanged` | `Action?` | `null` | | +| `Placeholder` | `char` | `'_'` | | +| `RawValue` | `string` | | The raw value (without mask literals and placeholders). | +| `Value` | `string` | | | + +## `NumberBoxElement` + +Number box element. `Value` defaults to [`Optional.Unset`](../components/Optional.md#unset) so the control owns its value until explicitly set. + +```csharp +public record NumberBoxElement(Optional Value = default, Action? OnValueChanged = null, string? Header = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`NumberBox`](../factories/input.md#numberbox) + +**Modifiers:** [`AcceptsExpression`](../modifiers/input.md#acceptsexpression), [`Description`](../modifiers/input.md#description), [`Focus`](../modifiers/input.md#focus), [`NumberFormatter`](../modifiers/input.md#numberformatter), [`PlaceholderText`](../modifiers/input.md#placeholdertext), [`Range`](../modifiers/input.md#range), [`Set`](../modifiers/native-properties.md#set), [`SpinButtons`](../modifiers/input.md#spinbuttons), [`ValidationMode`](../modifiers/input.md#validationmode), [`ValueChanged`](../modifiers/input.md#valuechanged) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `AcceptsExpression` | `bool` | | Whether the user can type arithmetic expressions (e.g. `2*3+1`) that resolve on commit. | +| `Description` | `string?` | | Help text rendered below the box. WinUI 3 1.2+ feature. | +| `Header` | `string?` | `null` | | +| `LargeChange` | `double` | | | +| `Maximum` | `double` | | | +| `Minimum` | `double` | | | +| `NumberFormatter` | `INumberFormatter2?` | | Custom number formatter (e.g. currency, percent). Null uses WinUI's default DecimalFormatter. | +| `OnValueChanged` | `Action?` | `null` | | +| `PlaceholderText` | `string?` | | | +| `SmallChange` | `double` | | | +| `SpinButtonPlacement` | `NumberBoxSpinButtonPlacementMode` | | | +| `ValidationMode` | `NumberBoxValidationMode` | | How invalid input is treated. Defaults to `InvalidInputOverwritten` (matches WinUI default). | +| `Value` | [`Optional`](../components/Optional.md) | `default` | | + +## `PasswordBoxElement` + +Password box element. `Password` defaults to [`Optional.Unset`](../components/Optional.md#unset) so user input is not overwritten unless a value is explicitly provided. + +```csharp +public record PasswordBoxElement(Optional Password = default, Action? OnPasswordChanged = null, string? PlaceholderText = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`PasswordBox`](../factories/input.md#passwordbox) + +**Modifiers:** [`Header`](../modifiers/input.md#header), [`MaxLength`](../modifiers/input.md#maxlength), [`PasswordChanged`](../modifiers/input.md#passwordchanged), [`PasswordChar`](../modifiers/input.md#passwordchar), [`PasswordRevealMode`](../modifiers/input.md#passwordrevealmode), [`PlaceholderText`](../modifiers/input.md#placeholdertext), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Header` | `string?` | | Optional label rendered above the box. | +| `MaxLength` | `int` | | Maximum number of characters allowed. `0` (default) = no limit. | +| `OnPasswordChanged` | `Action?` | `null` | | +| `Password` | [`Optional`](../components/Optional.md) | `default` | | +| `PasswordChar` | `string?` | | Character displayed in place of the entered password (default '●' bullet). | +| `PasswordRevealMode` | `PasswordRevealMode` | | How the reveal button behaves. Defaults to `Peek` (matches WinUI). | +| `PlaceholderText` | `string?` | `null` | | + +## `RadioButtonElement` + +Radio button element. `IsChecked` defaults to [`Optional.Unset`](../components/Optional.md#unset) so the control owns its checked state until explicitly set. + +```csharp +public record RadioButtonElement(string Label, Optional IsChecked = default, Action? OnIsCheckedChanged = null, string? GroupName = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`RadioButton`](../factories/input.md#radiobutton) + +**Modifiers:** [`IsCheckedChanged`](../modifiers/shared-controls.md#ischeckedchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `ContentElement` | [`Element?`](Element.md) | | Declarative content, taking precedence over the text value. | +| `GroupName` | `string?` | `null` | | +| `IsChecked` | [`Optional`](../components/Optional.md) | `default` | | +| `Label` | `string` | | | +| `OnIsCheckedChanged` | `Action?` | `null` | | + +## `RadioButtonsElement` + +RadioButtons element. `SelectedIndex` defaults to [`Optional.Unset`](../components/Optional.md#unset); use `Optional.Of(-1)` to force no selection. + +```csharp +public record RadioButtonsElement(string[] Items, Optional SelectedIndex = default, Action? OnSelectedIndexChanged = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`RadioButtons`](../factories/input.md#radiobuttons) + +**Modifiers:** [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Header` | `string?` | | | +| `Items` | `string[]` | | | +| `OnSelectedIndexChanged` | `Action?` | `null` | | +| `SelectedIndex` | [`Optional`](../components/Optional.md) | `default` | | + +## `RatingControlElement` + +Rating control element. `Value` defaults to [`Optional.Unset`](../components/Optional.md#unset) so the control owns its rating until explicitly set. + +```csharp +public record RatingControlElement(Optional Value = default, Action? OnValueChanged = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`RatingControl`](../factories/input.md#ratingcontrol) + +**Modifiers:** [`Caption`](../modifiers/input.md#caption), [`InitialSetValue`](../modifiers/input.md#initialsetvalue), [`IsReadOnly`](../modifiers/input.md#isreadonly), [`MaxRating`](../modifiers/input.md#maxrating), [`PlaceholderValue`](../modifiers/input.md#placeholdervalue), [`ReadOnly`](../modifiers/input.md#readonly), [`Set`](../modifiers/native-properties.md#set), [`ValueChanged`](../modifiers/input.md#valuechanged) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Caption` | `string?` | | | +| `InitialSetValue` | `int` | | Integer rating to assume when the user first interacts. Defaults to 1. (WinUI's `InitialSetValue` is int.) | +| `IsReadOnly` | `bool` | | | +| `MaxRating` | `int` | | | +| `OnValueChanged` | `Action?` | `null` | | +| `PlaceholderValue` | `double` | | Star value shown when the rating is unset. Defaults to -1 (no placeholder). | +| `Value` | [`Optional`](../components/Optional.md) | `default` | | + +## `RichEditBoxElement` + +Rich edit box element. `Text` defaults to [`Optional.Unset`](../components/Optional.md#unset) so user text is not overwritten unless explicitly set. + +```csharp +public record RichEditBoxElement(Optional Text = default) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`RichEditBox`](../factories/input.md#richeditbox) + +**Modifiers:** [`AcceptsReturn`](../modifiers/input.md#acceptsreturn), [`IsSpellCheckEnabled`](../modifiers/input.md#isspellcheckenabled), [`MaxLength`](../modifiers/input.md#maxlength), [`PlaceholderText`](../modifiers/input.md#placeholdertext), [`SelectionHighlightColor`](../modifiers/typography.md#selectionhighlightcolor), [`Set`](../modifiers/native-properties.md#set), [`TextChanged`](../modifiers/input.md#textchanged), [`TextWrapping`](../modifiers/typography.md#textwrapping) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `AcceptsReturn` | `bool` | | Whether Enter inserts a newline (vs committing). Defaults to `true`. | +| `Header` | `string?` | | | +| `IsReadOnly` | `bool` | | | +| `IsSpellCheckEnabled` | `bool?` | | Whether built-in spell-check is enabled. Defaults to the WinUI default (true). | +| `MaxLength` | `int` | | Maximum number of characters allowed. `0` (default) = no limit. | +| `OnTextChanged` | `Action?` | | | +| `PlaceholderText` | `string?` | | | +| `SelectionHighlightColor` | `SolidColorBrush?` | | Brush used to render the selection highlight. `null` = WinUI default (accent). | +| `Text` | [`Optional`](../components/Optional.md) | `default` | | +| `TextWrapping` | `TextWrapping` | | How text wraps within the box. Defaults to `Wrap`. | + +## `SliderElement` + +Slider element. `Value` defaults to [`Optional.Unset`](../components/Optional.md#unset) so the control owns its value until explicitly set. + +```csharp +public record SliderElement(Optional Value = default, double Min = 0, double Max = 100, Action? OnValueChanged = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Slider`](../factories/input.md#slider) + +**Modifiers:** [`Header`](../modifiers/input.md#header), [`Orientation`](../modifiers/input.md#orientation), [`Set`](../modifiers/native-properties.md#set), [`SnapsTo`](../modifiers/input.md#snapsto), [`StepFrequency`](../modifiers/input.md#stepfrequency), [`ThumbToolTip`](../modifiers/input.md#thumbtooltip), [`TickFrequency`](../modifiers/input.md#tickfrequency), [`TickPlacement`](../modifiers/input.md#tickplacement), [`ValueChanged`](../modifiers/input.md#valuechanged) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Header` | `string?` | | | +| `IsThumbToolTipEnabled` | `bool` | | Whether the floating value tooltip appears while dragging the thumb. Defaults to `true`. | +| `Max` | `double` | `100` | | +| `Min` | `double` | `0` | | +| `OnValueChanged` | `Action?` | `null` | | +| `Orientation` | `Orientation` | | Slider orientation. Defaults to `Orientation.Horizontal`. | +| `SnapsTo` | `SliderSnapsTo` | | Whether the thumb snaps to ticks or step values during drag. | +| `StepFrequency` | `double` | | | +| `TickFrequency` | `double` | | Interval between tick marks on the slider's track. Defaults to `0` (no ticks). | +| `TickPlacement` | `TickPlacement` | | Where tick marks render relative to the track. Defaults to `TickPlacement.Inline`. | +| `Value` | [`Optional`](../components/Optional.md) | `default` | | + +## `TextBoxElement` + +Text box element. `Value` defaults to [`Optional.Unset`](../components/Optional.md#unset) so user text is not overwritten unless a value is explicitly provided. + +```csharp +public record TextBoxElement(Optional Value = default, Action? OnChanged = null, string? PlaceholderText = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`TextBox`](../factories/input.md#textbox) + +**Modifiers:** [`AcceptsReturn`](../modifiers/input.md#acceptsreturn), [`Changed`](../modifiers/input.md#changed), [`CharacterCasing`](../modifiers/input.md#charactercasing), [`Description`](../modifiers/input.md#description), [`EmailInput`](../modifiers/input.md#emailinput), [`Focus`](../modifiers/input.md#focus), [`Header`](../modifiers/input.md#header), [`InputScope`](../modifiers/input.md#inputscope), [`IsReadOnly`](../modifiers/input.md#isreadonly), [`IsSpellCheckEnabled`](../modifiers/input.md#isspellcheckenabled), [`MaxLength`](../modifiers/input.md#maxlength), [`NumericInput`](../modifiers/input.md#numericinput), [`PhoneInput`](../modifiers/input.md#phoneinput), [`PlaceholderText`](../modifiers/input.md#placeholdertext), [`ReadOnly`](../modifiers/input.md#readonly), [`SearchInput`](../modifiers/input.md#searchinput), [`SelectionChanged`](../modifiers/shared-controls.md#selectionchanged), [`Set`](../modifiers/native-properties.md#set), [`TextAlignment`](../modifiers/typography.md#textalignment), [`TextWrapping`](../modifiers/typography.md#textwrapping), [`UrlInput`](../modifiers/input.md#urlinput) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `AcceptsReturn` | `bool?` | | | +| `CharacterCasing` | `CharacterCasing` | | Forces input to upper/lower-case as the user types. Defaults to `Normal` (no transform). | +| `Description` | `string?` | | Help text rendered below the box. WinUI 3 1.2+ feature. | +| `Header` | `string?` | | | +| `IsReadOnly` | `bool?` | | | +| `IsSpellCheckEnabled` | `bool?` | | Whether built-in spell-check is enabled. Defaults to the WinUI default (true). | +| `MaxLength` | `int` | | Maximum number of characters allowed. `0` (default) means no limit. | +| `OnChanged` | `Action?` | `null` | | +| `OnSelectionChanged` | `Action?` | | Fires when the text selection changes. Receives (selectedText, selectionStart, selectionLength). | +| `PlaceholderText` | `string?` | `null` | | +| `SelectionLength` | `int?` | | Selection length. Set alongside SelectionStart to control the selection range. | +| `SelectionStart` | `int?` | | Caret / selection start position. Set this to control where the caret sits after a text update. | +| `TextAlignment` | `TextAlignment` | | Horizontal text alignment within the box. Defaults to `Left`. | +| `TextWrapping` | `TextWrapping?` | | | +| `Value` | [`Optional`](../components/Optional.md) | `default` | | + +## `TimePickerElement` + +Time picker element. `Time` defaults to [`Optional.Unset`](../components/Optional.md#unset) so the control owns its time until explicitly set. + +```csharp +public record TimePickerElement(Optional Time = default, Action? OnTimeChanged = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`TimePicker`](../factories/input.md#timepicker) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set), [`TimeChanged`](../modifiers/input.md#timechanged) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `ClockIdentifier` | `int` | | | +| `Header` | `string?` | | | +| `MinuteIncrement` | `int` | | | +| `OnTimeChanged` | `Action?` | `null` | | +| `Time` | [`Optional`](../components/Optional.md) | `default` | | + +## `ToggleSwitchElement` + +Toggle switch element. `IsOn` defaults to [`Optional.Unset`](../components/Optional.md#unset) so the control owns its state until explicitly set. + +```csharp +public record ToggleSwitchElement(Optional IsOn = default, Action? OnIsOnChanged = null, string? OnContent = null, string? OffContent = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ToggleSwitch`](../factories/input.md#toggleswitch) + +**Modifiers:** [`Header`](../modifiers/input.md#header), [`IsOnChanged`](../modifiers/input.md#isonchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Header` | `string?` | | | +| `IsOn` | [`Optional`](../components/Optional.md) | `default` | | +| `OffContent` | `string?` | `null` | | +| `OnContent` | `string?` | `null` | | +| `OnIsOnChanged` | `Action?` | `null` | | diff --git a/docs/guide/reference/elements/interop.md b/docs/guide/reference/elements/interop.md new file mode 100644 index 0000000000..54733fb5de --- /dev/null +++ b/docs/guide/reference/elements/interop.md @@ -0,0 +1,91 @@ +# Elements: Interop + +Hosted XAML content, web views and maps. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Coming from XAML](../../xaml-developers.md) + +## `MapControlElement` + +The element record that describes a WinUI [`MapControl`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.mapcontrol) control. + +```csharp +public record MapControlElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`MapControl`](../factories/interop.md#mapcontrol) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `MapServiceToken` | `string?` | | +| `ZoomLevel` | `double` | | + +## `WebView2Element` + +The element record that describes a WinUI [`WebView2`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.webview2) control. + +```csharp +public record WebView2Element(Uri? Source = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`WebView2`](../factories/interop.md#webview2) + +**Modifiers:** [`CoreWebView2Initialized`](../modifiers/interop.md#corewebview2initialized), [`NavigationCompleted`](../modifiers/interop.md#navigationcompleted), [`NavigationStarting`](../modifiers/interop.md#navigationstarting), [`Set`](../modifiers/native-properties.md#set), [`WebMessageReceived`](../modifiers/interop.md#webmessagereceived) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `OnCoreWebView2Initialized` | `Action?` | | Raised once `CoreWebView2` initialization completes — the earliest point at which features like `AddScriptToExecuteOnDocumentCreatedAsync` or `AddHostObjectToScript` become available. Fires on the UI thread. | +| `OnNavigationCompleted` | `Action?` | | | +| `OnNavigationStarting` | `Action?` | | | +| `OnWebMessageReceived` | `Action?` | | Raised when the hosted page posts a message via `window.chrome.webview.postMessage(...)`. The callback receives the JSON payload as a string. Threading: messages dispatch on the UI thread (the WinUI WebView2 raises `WebMessageReceived` via the control's dispatcher), so the handler is safe to mutate component state from directly. | +| `Source` | `Uri?` | `null` | | + +## `XamlHostElement` + +An element that embeds an arbitrary FrameworkElement (UserControl, custom control, etc.) into the Reactor tree. The factory creates the control; the updater patches it. + +```csharp +public record XamlHostElement(Func Factory, Action? Updater = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Hosting`. Inherits from [`Element`](Element.md). + +**Created by:** [`XamlHost`](../factories/interop.md#xamlhost) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Factory` | `Func` | | | +| `TypeKey` | `string?` | | Optional discriminator for the reconciler's CanUpdate check. When set, two XamlHostElements can only update in place if their TypeKeys match. Use this to prevent unrelated host elements from being reconciled against each other. | +| `Updater` | `Action?` | `null` | | + +**Remarks** + +Spec 058 §15 (P5.28) — migrated to a generated monomorphic decorator (`[WrapDecorator]`), replacing the hand-written `XamlHostDescriptor`. + +## `XamlPageElement` + +An element that embeds a XAML Page inside a Frame, enabling navigation to existing XAML pages from within a Reactor component tree. + +```csharp +public record XamlPageElement(Type PageType, object? Parameter = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Hosting`. Inherits from [`Element`](Element.md). + +**Created by:** [`XamlPage`](../factories/interop.md#xamlpage) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `PageType` | `Type` | | | +| `Parameter` | `object?` | `null` | | + +**Remarks** + +Spec 058 §15 (P5.28) — migrated to a generated monomorphic decorator (`[WrapDecorator]`): the generated Pattern-A cctor self-registers the decorator on first `new`, replacing the hand-written `XamlPageDescriptor`. The control is a [`Frame`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.frame) created once and re-navigated in place on update. diff --git a/docs/guide/reference/elements/layout.md b/docs/guide/reference/elements/layout.md new file mode 100644 index 0000000000..c2b4df4eb3 --- /dev/null +++ b/docs/guide/reference/elements/layout.md @@ -0,0 +1,322 @@ +# Elements: Layout + +Panels, stacks, grids, scrolling and other containers. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Layout](../../layout.md), [Flex Layout](../../flex-layout.md) + +## `AnnotatedScrollBarElement` + +The element record that describes a WinUI [`AnnotatedScrollBar`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.annotatedscrollbar) control. + +```csharp +public record AnnotatedScrollBarElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`AnnotatedScrollBar`](../factories/layout.md#annotatedscrollbar) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +## `BorderElement` + +Border element — a single-child container with brush/corner/thickness chrome. + +```csharp +public record BorderElement(Element? Child) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Border`](../factories/layout.md#border), [`Card`](../factories/layout.md#card) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Background` | `Brush?` | | +| `BorderBrush` | `Brush?` | | +| `BorderThickness` | `double?` | | +| `Child` | [`Element?`](Element.md) | | +| `CornerRadius` | `double?` | | + +## `CanvasElement` + +The element record that describes a WinUI [`Canvas`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.canvas) control. + +```csharp +public record CanvasElement(Element[] Children) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Canvas`](../factories/layout.md#canvas) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Background` | `Brush?` | | +| `Children` | [`Element[]`](Element.md) | | +| `Height` | `double?` | | +| `Width` | `double?` | | + +## `ExpanderElement` + +Expander element. `IsExpanded` defaults to [`Optional.Unset`](../components/Optional.md#unset) so the control owns its expansion state until explicitly set. + +```csharp +public record ExpanderElement(string Header, Element Content, Optional IsExpanded = default, Action? OnIsExpandedChanged = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Expander`](../factories/layout.md#expander) + +**Modifiers:** [`ContentTransitions`](../modifiers/animation.md#contenttransitions), [`Direction`](../modifiers/layout.md#direction), [`HeaderContent`](../modifiers/layout.md#headercontent), [`IsExpandedChanged`](../modifiers/layout.md#isexpandedchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Content` | [`Element`](Element.md) | | | +| `ContentTransitions` | `TransitionCollection?` | | Custom `TransitionCollection` applied to the expanding content area. | +| `ExpandDirection` | `ExpandDirection` | | | +| `Header` | `string` | | | +| `HeaderContent` | [`Element?`](Element.md) | | Custom Element content assigned to the native Expander's Header, overriding the string [`ExpanderElement.Header`](#expanderelement). This is a mounted child, not a DataTemplate. | +| `IsExpanded` | [`Optional`](../components/Optional.md) | `default` | | +| `OnIsExpandedChanged` | `Action?` | `null` | | + +## `FlexElement` + +The element record that describes a [`FlexPanel`](../layout/flex-enums.md#flexpanel) control. + +```csharp +public record FlexElement(Element[] Children) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Flex`](../factories/layout.md#flex), [`FlexColumn`](../factories/layout.md#flexcolumn), [`FlexRow`](../factories/layout.md#flexrow) + +**Modifiers:** [`FlexPadding`](../modifiers/layout-and-spacing.md#flexpadding), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `AlignContent` | [`FlexAlign`](../layout/flex-enums.md#flexalign) | | +| `AlignItems` | [`FlexAlign`](../layout/flex-enums.md#flexalign) | | +| `Children` | [`Element[]`](Element.md) | | +| `ColumnGap` | `double` | | +| `Direction` | [`FlexDirection`](../layout/flex-enums.md#flexdirection) | | +| `FlexPadding` | `Thickness` | | +| `JustifyContent` | [`FlexJustify`](../layout/flex-enums.md#flexjustify) | | +| `RowGap` | `double` | | +| `Wrap` | [`FlexWrap`](../layout/flex-enums.md#flexwrap) | | + +## `GridElement` + +The element record that describes a WinUI [`Grid`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.grid) control. + +```csharp +public record GridElement(GridDefinition Definition, Element[] Children) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Grid`](../factories/layout.md#grid), [`InterspersedGrid`](../factories/layout.md#interspersedgrid), [`UniformGrid`](../factories/layout.md#uniformgrid) + +**Modifiers:** [`BackgroundTransition`](../modifiers/animation.md#backgroundtransition), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Children` | [`Element[]`](Element.md) | | +| `ColumnSpacing` | `double` | | +| `Definition` | [`GridDefinition`](../layout/attached.md#griddefinition) | | +| `RowSpacing` | `double` | | + +## `ParallaxViewElement` + +The element record that describes a WinUI [`ParallaxView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.parallaxview) control. + +```csharp +public record ParallaxViewElement(Element Child) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ParallaxView`](../factories/layout.md#parallaxview) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set), [`Source`](../modifiers/layout.md#source), [`VerticalSourceEndOffset`](../modifiers/layout.md#verticalsourceendoffset), [`VerticalSourceStartOffset`](../modifiers/layout.md#verticalsourcestartoffset) + +| Property | Type | Description | +| --- | --- | --- | +| `Child` | [`Element`](Element.md) | | +| `HorizontalShift` | `double` | | +| `Source` | `UIElement?` | Source UIElement that drives the parallax (typically a ScrollViewer / ListView). `null` uses the nearest scroller. | +| `VerticalShift` | `double` | | +| `VerticalSourceEndOffset` | `double` | Vertical-axis source offset (in pixels) at which parallax ends. Defaults to 0 (auto). | +| `VerticalSourceStartOffset` | `double` | Vertical-axis source offset (in pixels) at which parallax begins. Defaults to 0. | + +## `RelativePanelElement` + +The element record that describes a WinUI [`RelativePanel`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.relativepanel) control. + +```csharp +public record RelativePanelElement(Element[] Children) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`RelativePanel`](../factories/layout.md#relativepanel) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Children` | [`Element[]`](Element.md) | | + +## `ScrollViewElement` + +Maps to the modern [`ScrollView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.scrollview) (InteractionTracker-backed, derives from `FrameworkElement`), as opposed to [`ScrollViewerElement`](#scrollviewerelement), which targets the classic `ScrollViewer`. Issue #348. + +Exposes capabilities that exist only on the new control: `ContentOrientation`, `HorizontalAnchorRatio` / `VerticalAnchorRatio`, and the `Scrolling*` enum surface. + +```csharp +public record ScrollViewElement(Element Child) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ScrollView`](../factories/layout.md#scrollview) + +**Modifiers:** [`AnchorRatio`](../modifiers/layout.md#anchorratio), [`ContentOrientation`](../modifiers/layout.md#contentorientation), [`HorizontalScrollMode`](../modifiers/layout.md#horizontalscrollmode), [`Set`](../modifiers/native-properties.md#set), [`VerticalScrollMode`](../modifiers/layout.md#verticalscrollmode), [`ViewChanged`](../modifiers/layout.md#viewchanged), [`ZoomMode`](../modifiers/layout.md#zoommode), [`ZoomRange`](../modifiers/layout.md#zoomrange) + +| Property | Type | Description | +| --- | --- | --- | +| `Child` | [`Element`](Element.md) | | +| `ContentOrientation` | `ScrollingContentOrientation` | | +| `HorizontalAnchorRatio` | `double` | | +| `HorizontalScrollBarVisibility` | `ScrollingScrollBarVisibility` | | +| `HorizontalScrollMode` | `ScrollingScrollMode` | | +| `MaxZoomFactor` | `double` | | +| `MinZoomFactor` | `double` | | +| `OnViewChanged` | `Action?` | Raised after the view (offset or zoom factor) changes. The modern control reports only the settled value — there is no intermediate flag like the classic `ScrollViewer.ViewChanged`. | +| `VerticalAnchorRatio` | `double` | | +| `VerticalScrollBarVisibility` | `ScrollingScrollBarVisibility` | | +| `VerticalScrollMode` | `ScrollingScrollMode` | | +| `ZoomMode` | `ScrollingZoomMode` | | + +## `ScrollViewerElement` + +The element record that describes a WinUI [`ScrollViewer`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.scrollviewer) control. + +```csharp +public record ScrollViewerElement(Element Child) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ScrollViewer`](../factories/layout.md#scrollviewer) + +**Modifiers:** [`HorizontalScrollMode`](../modifiers/layout.md#horizontalscrollmode), [`Set`](../modifiers/native-properties.md#set), [`VerticalScrollMode`](../modifiers/layout.md#verticalscrollmode), [`ViewChanged`](../modifiers/layout.md#viewchanged), [`ZoomMode`](../modifiers/layout.md#zoommode) + +| Property | Type | Description | +| --- | --- | --- | +| `Child` | [`Element`](Element.md) | | +| `HorizontalScrollBarVisibility` | `ScrollBarVisibility` | | +| `HorizontalScrollMode` | `ScrollMode` | | +| `OnViewChanged` | `Action?` | Raised when the scroll view's offset or zoom factor changes. The args expose `IsIntermediate` for callers who want to debounce until the scroll settles. | +| `Orientation` | `Orientation` | | +| `VerticalScrollBarVisibility` | `ScrollBarVisibility` | | +| `VerticalScrollMode` | `ScrollMode` | | +| `ZoomMode` | `ZoomMode` | | + +## `SplitViewElement` + +The element record that describes a WinUI [`SplitView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.splitview) control. + +```csharp +public record SplitViewElement(Element? Pane = null, Element? Content = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`SplitView`](../factories/layout.md#splitview) + +**Modifiers:** [`IsPaneOpen`](../modifiers/shared-controls.md#ispaneopen), [`LightDismissOverlayMode`](../modifiers/layout.md#lightdismissoverlaymode), [`PaneBackground`](../modifiers/layout.md#panebackground), [`PaneOpenChanged`](../modifiers/shared-controls.md#paneopenchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `CompactPaneLength` | `double` | | | +| `Content` | [`Element?`](Element.md) | `null` | | +| `DisplayMode` | `SplitViewDisplayMode` | | | +| `IsPaneOpen` | `bool` | | Whether the pane is open. Defaults to `true`. **Edge-triggered.** This declares a *transition*, not a mirror: Reactor writes the control only when the declared value *changes*. The control opens and closes its own pane (light dismiss, display-mode changes on resize) without touching the declared value, so re-rendering the same declared value will not force the pane back. Feed [`SplitViewElement.OnPaneOpenChanged`](#splitviewelement) into the state that drives this property. | +| `LightDismissOverlayMode` | `LightDismissOverlayMode` | | How the light-dismiss overlay reacts to taps in Overlay mode. Defaults to `Auto`. | +| `OnPaneOpenChanged` | `Action?` | | | +| `OpenPaneLength` | `double` | | | +| `Pane` | [`Element?`](Element.md) | `null` | | +| `PaneBackground` | `Brush?` | | Brush behind the pane. Pair with the `.PaneBackground(ThemeRef)` overload for theme-aware backgrounds. | + +## `StackElement` + +The element record that describes a WinUI [`StackPanel`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.stackpanel) control. + +```csharp +public record StackElement(Orientation Orientation, Element[] Children) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`HStack`](../factories/layout.md#hstack), [`VStack`](../factories/layout.md#vstack) + +**Modifiers:** [`BackgroundTransition`](../modifiers/animation.md#backgroundtransition), [`Set`](../modifiers/native-properties.md#set), [`Spacing`](../modifiers/layout.md#spacing) + +| Property | Type | Description | +| --- | --- | --- | +| `Children` | [`Element[]`](Element.md) | | +| `HorizontalAlignment` | `HorizontalAlignment?` | | +| `Orientation` | `Orientation` | | +| `Spacing` | `double` | Spacing between children, in DIPs. | +| `VerticalAlignment` | `VerticalAlignment?` | | + +## `ViewboxElement` + +The element record that describes a WinUI [`Viewbox`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.viewbox) control. + +```csharp +public record ViewboxElement(Element Child) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Viewbox`](../factories/layout.md#viewbox) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set), [`Stretch`](../modifiers/layout.md#stretch), [`StretchDirection`](../modifiers/layout.md#stretchdirection) + +| Property | Type | Description | +| --- | --- | --- | +| `Child` | [`Element`](Element.md) | | +| `Stretch` | `Stretch?` | | +| `StretchDirection` | `StretchDirection?` | | + +## `WrapGridElement` + +The element record that describes a WinUI [`VariableSizedWrapGrid`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.variablesizedwrapgrid) control. + +```csharp +public record WrapGridElement(Element[] Children) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`WrapGrid`](../factories/layout.md#wrapgrid) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Children` | [`Element[]`](Element.md) | | +| `ItemHeight` | `double` | | +| `ItemWidth` | `double` | | +| `MaximumRowsOrColumns` | `int` | | +| `Orientation` | `Orientation` | | diff --git a/docs/guide/reference/elements/media.md b/docs/guide/reference/elements/media.md new file mode 100644 index 0000000000..eab028d0dd --- /dev/null +++ b/docs/guide/reference/elements/media.md @@ -0,0 +1,131 @@ +# Elements: Media and icons + +Images, icons, animated visuals, media playback and person pictures. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Text and Media](../../text-and-media.md) + +## `AnimatedIconElement` + +The element record that describes a WinUI [`AnimatedIcon`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.animatedicon) control. + +```csharp +public record AnimatedIconElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`AnimatedIcon`](../factories/media.md#animatedicon) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `FallbackIconSource` | `IconSource?` | | +| `Source` | `object?` | | + +## `AnimatedVisualPlayerElement` + +The element record that describes a WinUI [`AnimatedVisualPlayer`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.animatedvisualplayer) control. + +```csharp +public record AnimatedVisualPlayerElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`AnimatedVisualPlayer`](../factories/media.md#animatedvisualplayer) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `AutoPlay` | `bool` | | + +## `IconElement` + +Standalone icon element that can be placed in the element tree. Wraps an [`IconData`](../controls/icons.md#icondata) and mounts to the corresponding native [`IconElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.iconelement) subtype. + +```csharp +public record IconElement(IconData Data) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Icon`](../factories/media.md#icon) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Data` | [`IconData`](../controls/icons.md#icondata) | | + +## `ImageElement` + +The element record that describes a WinUI [`Image`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.image) control. + +```csharp +public record ImageElement(string Source) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Image`](../factories/media.md#image) + +**Modifiers:** [`ImageFailed`](../modifiers/media.md#imagefailed), [`ImageOpened`](../modifiers/media.md#imageopened), [`NineGrid`](../modifiers/media.md#ninegrid), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Height` | `double?` | | +| `NineGrid` | `Thickness?` | Nine-grid (slice) values for resolution-independent corner stretching. | +| `OnImageFailed` | `Action?` | Raised when the image fails to load. Receives the failure message. | +| `OnImageOpened` | `Action?` | Raised after the image source loads successfully (marshalled to UI thread). | +| `Source` | `string` | | +| `Stretch` | `string?` | | +| `Width` | `double?` | | + +## `MediaPlayerElementElement` + +The element record that describes a WinUI [`MediaPlayerElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.mediaplayerelement) control. + +```csharp +public record MediaPlayerElementElement(string? Source = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`MediaPlayerElement`](../factories/media.md#mediaplayerelement) + +**Modifiers:** [`MediaEnded`](../modifiers/media.md#mediaended), [`MediaFailed`](../modifiers/media.md#mediafailed), [`MediaOpened`](../modifiers/media.md#mediaopened), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `AreTransportControlsEnabled` | `bool` | | | +| `AutoPlay` | `bool` | | | +| `OnMediaEnded` | `Action?` | | Raised when playback reaches the end of the source. Marshalled to the UI thread. | +| `OnMediaFailed` | `Action?` | | Raised when the underlying `MediaPlayer` fails to open or play. Receives the failure error message as a string. Marshalled to the UI thread. | +| `OnMediaOpened` | `Action?` | | Raised when the underlying `MediaPlayer` finishes opening the source. Marshalled to the element's UI thread; may fire after the element has unmounted (the handler is safe to ignore in that case). | +| `Source` | `string?` | `null` | | + +## `PersonPictureElement` + +The element record that describes a WinUI [`PersonPicture`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.personpicture) control. + +```csharp +public record PersonPictureElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`PersonPicture`](../factories/media.md#personpicture) + +**Modifiers:** [`DisplayName`](../modifiers/media.md#displayname), [`Initials`](../modifiers/media.md#initials), [`ProfilePicture`](../modifiers/media.md#profilepicture), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `BadgeNumber` | `int` | | +| `DisplayName` | `string?` | | +| `Initials` | `string?` | | +| `IsGroup` | `bool` | | +| `ProfilePicture` | `string?` | | diff --git a/docs/guide/reference/elements/menus-and-commands.md b/docs/guide/reference/elements/menus-and-commands.md new file mode 100644 index 0000000000..298ee0db99 --- /dev/null +++ b/docs/guide/reference/elements/menus-and-commands.md @@ -0,0 +1,114 @@ +# Elements: Menus and commands + +Menus, menu bars, command bars and keyboard accelerators. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Commanding](../../commanding.md) + +## `CommandBarElement` + +```csharp +public record CommandBarElement(AppBarItemBase[]? PrimaryCommands = null, AppBarItemBase[]? SecondaryCommands = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`CommandBar`](../factories/menus-and-commands.md#commandbar) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Content` | [`Element?`](Element.md) | | | +| `DefaultLabelPosition` | `CommandBarDefaultLabelPosition` | | | +| `IsOpen` | `bool` | | | +| `PrimaryCommands` | [`AppBarItemBase[]?`](../controls/menu-items.md#appbaritembase) | `null` | | +| `SecondaryCommands` | [`AppBarItemBase[]?`](../controls/menu-items.md#appbaritembase) | `null` | | + +## `CommandBarFlyoutElement` + +```csharp +public record CommandBarFlyoutElement(Element Target, AppBarItemBase[]? PrimaryCommands = null, AppBarItemBase[]? SecondaryCommands = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`CommandBarFlyout`](../factories/menus-and-commands.md#commandbarflyout) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `IsOpen` | `bool` | | Opens the flyout declaratively. Like [`FlyoutElement.IsOpen`](dialogs-and-flyouts.md#flyoutelement) this is a one-shot trigger: the flyout is shown on mount when already `true`, and on the `false` → `true` edge of an update. Setting it back to `false` does not close the flyout — the user dismisses it (outside click, Esc, or invoking a command). The target normally opens the flyout on click without this. | +| `Placement` | `FlyoutPlacementMode` | | Preferred position of the flyout relative to its target. Defaults to [`FlyoutPlacementMode.Auto`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.auto), which means "no opinion — let WinUI decide": Reactor clears `FlyoutBase.Placement` so it falls back to the control's own default ([`FlyoutPlacementMode.Top`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.top)) instead of writing `Auto`, because WinUI's show-time validator rejects `Auto` and terminates the process. Changing an already-mounted flyout from an explicit placement back to [`FlyoutPlacementMode.Auto`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.auto) therefore returns it to that default, rather than leaving a stale local value that would outrank a `Style` setter. | +| `PrimaryCommands` | [`AppBarItemBase[]?`](../controls/menu-items.md#appbaritembase) | `null` | | +| `SecondaryCommands` | [`AppBarItemBase[]?`](../controls/menu-items.md#appbaritembase) | `null` | | +| `Target` | [`Element`](Element.md) | | | + +## `CommandHostElement` + +Scopes keyboard accelerators from a set of commands to a subtree. Accelerators are only active when the host or its descendants have focus. + +```csharp +public record CommandHostElement(Command[] Commands, Element Child) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`CommandHost`](../factories/menus-and-commands.md#commandhost) + +| Property | Type | Description | +| --- | --- | --- | +| `Child` | [`Element`](Element.md) | | +| `Commands` | [`Command[]`](../input/Command.md) | | + +## `MenuBarElement` + +```csharp +public record MenuBarElement(MenuBarItemData[] Items) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`MenuBar`](../factories/menus-and-commands.md#menubar) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Items` | [`MenuBarItemData[]`](../controls/menu-items.md#menubaritemdata) | | + +## `MenuFlyoutContentElement` + +Describes a menu flyout (used as a slot value on buttons or as a modifier attachment). NOT independently mountable — the reconciler recognizes it in flyout slots. + +```csharp +public record MenuFlyoutContentElement(MenuFlyoutItemBase[] Items) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`MenuItems`](../factories/menus-and-commands.md#menuitems) + +| Property | Type | Description | +| --- | --- | --- | +| `Items` | [`MenuFlyoutItemBase[]`](../controls/menu-items.md#menuflyoutitembase) | | +| `Placement` | `FlyoutPlacementMode` | Preferred position of the flyout relative to its target. Defaults to [`FlyoutPlacementMode.Auto`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.auto), which means "no opinion — let WinUI decide": Reactor clears `FlyoutBase.Placement` so it falls back to the control's own default ([`FlyoutPlacementMode.Top`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.top)) instead of writing `Auto`, because WinUI's show-time validator rejects `Auto` and terminates the process. Changing an already-mounted flyout from an explicit placement back to [`FlyoutPlacementMode.Auto`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.primitives.flyoutplacementmode.auto) therefore returns it to that default, rather than leaving a stale local value that would outrank a `Style` setter. | + +## `MenuFlyoutElement` + +```csharp +public record MenuFlyoutElement(Element Target, MenuFlyoutItemBase[] Items) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`MenuFlyout`](../factories/menus-and-commands.md#menuflyout) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Items` | [`MenuFlyoutItemBase[]`](../controls/menu-items.md#menuflyoutitembase) | | +| `Target` | [`Element`](Element.md) | | diff --git a/docs/guide/reference/elements/navigation.md b/docs/guide/reference/elements/navigation.md new file mode 100644 index 0000000000..0a3e78e33b --- /dev/null +++ b/docs/guide/reference/elements/navigation.md @@ -0,0 +1,254 @@ +# Elements: Navigation + +Navigation views, tabs, pivots, breadcrumbs and the title bar. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Navigation](../../navigation.md) + +## `BreadcrumbBarElement` + +The element record that describes a WinUI [`BreadcrumbBar`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.breadcrumbbar) control. + +```csharp +public record BreadcrumbBarElement(BreadcrumbBarItemData[] Items, Action? OnItemClicked = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`BreadcrumbBar`](../factories/navigation.md#breadcrumbbar) + +**Modifiers:** [`ItemClicked`](../modifiers/navigation.md#itemclicked), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `Items` | [`BreadcrumbBarItemData[]`](../controls/navigation-items.md#breadcrumbbaritemdata) | | | +| `OnItemClicked` | `Action?` | `null` | | + +## `FrameElement` + +The element record that describes a WinUI [`Frame`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.frame) control. + +```csharp +public record FrameElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Frame`](../factories/navigation.md#frame) + +**Modifiers:** [`Navigated`](../modifiers/navigation.md#navigated), [`Navigating`](../modifiers/navigation.md#navigating), [`NavigationFailed`](../modifiers/navigation.md#navigationfailed), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `NavigationParameter` | `object?` | | +| `OnNavigated` | `Action?` | Raised after a successful navigation. Receives the new `SourcePageType`. | +| `OnNavigating` | `Action?` | Raised before navigation begins. Receives the target `SourcePageType`. Cancellation is not supported via this fluent — use `.Set(...)` to wire the raw `Navigating` event for that. | +| `OnNavigationFailed` | `Action?` | Raised when a navigation fails. Receives the target `SourcePageType` and the failure exception. Wiring this also marks the failure handled, so a page whose constructor throws degrades into this callback instead of tearing down the application. | +| `SourcePageType` | `Type?` | The [`Page`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.page)-derived type to navigate to on mount. | + +## `NavigationHostElement` + +Renders the content for the current route of a [`NavigationHandle`](../navigation/NavigationHandle.md). Created via `NavigationHost(nav, routeMap)` in the DSL. The reconciler uses a Grid container so outgoing/incoming pages can overlap during transitions (Phase 4). + +```csharp +public record NavigationHostElement(object NavigationHandle, Func RouteMap) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`NavigationHost`](../factories/navigation.md#navigationhost) + +| Property | Type | Description | +| --- | --- | --- | +| `CacheMode` | [`NavigationCacheMode`](../navigation/enums.md#navigationcachemode) | | +| `CacheSize` | `int` | | +| `NavigationHandle` | `object` | | +| `RouteMap` | `Func` | | +| `Transition` | [`NavigationTransition`](../navigation/transitions.md#navigationtransition) | | + +## `NavigationViewElement` + +The element record that describes a WinUI [`NavigationView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.navigationview) control. + +```csharp +public record NavigationViewElement(NavigationViewItemData[] MenuItems, Element? Content = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`NavigationView`](../factories/navigation.md#navigationview) + +**Modifiers:** [`AlwaysShowHeader`](../modifiers/navigation.md#alwaysshowheader), [`AutoSuggestBox`](../modifiers/navigation.md#autosuggestbox), [`BackButtonVisible`](../modifiers/navigation.md#backbuttonvisible), [`BackRequested`](../modifiers/navigation.md#backrequested), [`CompactModeThresholdWidth`](../modifiers/navigation.md#compactmodethresholdwidth), [`CompactPaneLength`](../modifiers/navigation.md#compactpanelength), [`ContentOverlay`](../modifiers/navigation.md#contentoverlay), [`DisplayModeChanged`](../modifiers/navigation.md#displaymodechanged), [`ExpandedModeThresholdWidth`](../modifiers/navigation.md#expandedmodethresholdwidth), [`FooterMenuItems`](../modifiers/navigation.md#footermenuitems), [`IsPaneOpen`](../modifiers/shared-controls.md#ispaneopen), [`ItemCollapsed`](../modifiers/navigation.md#itemcollapsed), [`ItemExpanding`](../modifiers/navigation.md#itemexpanding), [`ItemInvoked`](../modifiers/shared-controls.md#iteminvoked), [`OpenPaneLength`](../modifiers/navigation.md#openpanelength), [`OverflowLabelMode`](../modifiers/navigation.md#overflowlabelmode), [`PaneCustomContent`](../modifiers/navigation.md#panecustomcontent), [`PaneDisplayMode`](../modifiers/navigation.md#panedisplaymode), [`PaneFooter`](../modifiers/navigation.md#panefooter), [`PaneHeader`](../modifiers/navigation.md#paneheader), [`PaneOpenChanged`](../modifiers/shared-controls.md#paneopenchanged), [`PaneTitle`](../modifiers/navigation.md#panetitle), [`PaneToggleButtonVisible`](../modifiers/navigation.md#panetogglebuttonvisible), [`PaneVisible`](../modifiers/navigation.md#panevisible), [`SelectedTagChanged`](../modifiers/navigation.md#selectedtagchanged), [`SelectionFollowsFocus`](../modifiers/navigation.md#selectionfollowsfocus), [`Set`](../modifiers/native-properties.md#set), [`SettingsSelected`](../modifiers/navigation.md#settingsselected), [`ShoulderNavigation`](../modifiers/navigation.md#shouldernavigation), [`TitleBarAutoPadding`](../modifiers/navigation.md#titlebarautopadding), [`WithNavigation`](../modifiers/navigation.md#withnavigation) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `AlwaysShowHeader` | `bool` | | Whether [`NavigationViewElement.Header`](#navigationviewelement) stays visible in Minimal/Compact display modes. | +| `AutoSuggestBox` | [`AutoSuggestBoxElement?`](input.md#autosuggestboxelement) | | AutoSuggestBox rendered at the top of the pane. Mirrors `NavigationView.AutoSuggestBox`. | +| `CompactModeThresholdWidth` | `double` | | Window width below which the pane collapses to compact mode. `NaN` (the default) means Reactor never writes this property, leaving the WinUI default of 640. Sticky: changing an explicit value back to `NaN` skips the write rather than restoring 640. | +| `CompactPaneLength` | `double` | | Width of the pane when compact. `NaN` (the default) means Reactor never writes this property, leaving the WinUI default of 48. Sticky: changing an explicit value back to `NaN` skips the write rather than restoring 48. | +| `Content` | [`Element?`](Element.md) | `null` | | +| `ContentOverlay` | [`Element?`](Element.md) | | Element overlaid on top of [`NavigationViewElement.Content`](#navigationviewelement), e.g. a persistent player or status bar. | +| `ExpandedModeThresholdWidth` | `double` | | Window width at which the pane auto-expands. `NaN` (the default) means Reactor never writes this property, leaving the WinUI default of 1008. Sticky: changing an explicit value back to `NaN` skips the write rather than restoring 1008. | +| `FooterMenuItems` | [`NavigationViewItemData[]`](../controls/navigation-items.md#navigationviewitemdata) | | Menu items pinned to the bottom of the pane, below [`NavigationViewElement.PaneFooter`](#navigationviewelement)'s divider. Share the [`NavigationViewElement.SelectedTag`](#navigationviewelement) namespace with [`NavigationViewElement.MenuItems`](#navigationviewelement). | +| `Header` | [`Element?`](Element.md) | | | +| `IsBackButtonVisible` | `NavigationViewBackButtonVisible` | | Visibility of NavigationView's built-in back button. Mirrors `NavigationView.IsBackButtonVisible`. Set to [`NavigationViewBackButtonVisible.Collapsed`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.navigationviewbackbuttonvisible.collapsed) when a [`TitleBarElement`](#titlebarelement) owns the back button instead. | +| `IsBackEnabled` | `bool` | | | +| `IsPaneOpen` | `bool` | | Whether the pane is open. Defaults to `true`. **Edge-triggered.** This declares a *transition*, not a mirror: Reactor writes the control only when the declared value *changes*. The control opens and closes its own pane (light dismiss, adaptive display-mode changes on resize) without touching the declared value, so re-rendering the same declared value will not force the pane back. Feed [`NavigationViewElement.OnPaneOpenChanged`](#navigationviewelement) into the state that drives this property (issue #916). | +| `IsPaneToggleButtonVisible` | `bool` | | Whether NavigationView's built-in pane-toggle ("hamburger") button is shown. Mirrors `NavigationView.IsPaneToggleButtonVisible`. Set to `false` when a [`TitleBarElement`](#titlebarelement) owns the pane-toggle button instead. | +| `IsPaneVisible` | `bool` | | Whether the pane is shown at all. `false` hides the whole pane, leaving only the content area. | +| `IsSettingsVisible` | `bool` | | | +| `IsTitleBarAutoPaddingEnabled` | `bool` | | Whether NavigationView reserves top padding for the window's title bar. | +| `MenuItems` | [`NavigationViewItemData[]`](../controls/navigation-items.md#navigationviewitemdata) | | | +| `OnBackRequested` | `Action?` | | | +| `OnDisplayModeChanged` | `Action?` | | Raised when NavigationView switches between Minimal/Compact/Expanded in response to its width. | +| `OnItemCollapsed` | `Action?` | | Raised when a hierarchical menu item is collapsed. Carries the item's tag. | +| `OnItemExpanding` | `Action?` | | Raised when a hierarchical menu item is expanded. Carries the item's tag. | +| `OnItemInvoked` | `Action?` | | Raised when a menu item is invoked (clicked / activated), including re-invoking the already-selected item, which [`NavigationViewElement.OnSelectedTagChanged`](#navigationviewelement) does not report. Carries the item's tag, or [`NavigationViewElement.SettingsTag`](#navigationviewelement) for the settings item. | +| `OnPaneOpenChanged` | `Action?` | | Fires whenever the realized control's `IsPaneOpen` changes — including changes the app never requested (light dismiss, adaptive display-mode changes on resize) and the echo of a programmatic [`NavigationViewElement.IsPaneOpen`](#navigationviewelement) write. Feed the value back into the state that drives [`NavigationViewElement.IsPaneOpen`](#navigationviewelement) to keep controlled pane state in sync (issue #916). Same shape as `SplitViewElement.OnPaneOpenChanged`. | +| `OnSelectedTagChanged` | `Action?` | | | +| `OnSettingsSelected` | `Action?` | | Raised when NavigationView's built-in settings item becomes selected — by the user, or by setting [`NavigationViewElement.SelectedTag`](#navigationviewelement) to [`NavigationViewElement.SettingsTag`](#navigationviewelement). Distinguishes the settings item from "nothing selected" — [`NavigationViewElement.OnSelectedTagChanged`](#navigationviewelement) reports `null` for both. | +| `OpenPaneLength` | `double` | | Width of the pane when expanded. `NaN` (the default) means Reactor never writes this property, leaving the WinUI default of 320. Sticky: changing an explicit value back to `NaN` skips the write rather than restoring 320. | +| `OverflowLabelMode` | `NavigationViewOverflowLabelMode` | | Whether the Top pane's overflow button shows a "More" label or only the chevron. | +| `PaneCustomContent` | [`Element?`](Element.md) | | Custom element rendered between the AutoSuggestBox and the menu items. | +| `PaneDisplayMode` | `NavigationViewPaneDisplayMode` | | | +| `PaneFooter` | [`Element?`](Element.md) | | Element rendered at the bottom of the pane, below all menu items. | +| `PaneHeader` | [`Element?`](Element.md) | | Element rendered at the top of the pane, above the menu items and below the pane title. | +| `PaneTitle` | `string?` | | | +| `SelectedTag` | `string?` | | | +| `SelectionFollowsFocus` | `NavigationViewSelectionFollowsFocus` | | Whether moving keyboard focus between menu items also changes the selection. | +| `ShoulderNavigationEnabled` | `NavigationViewShoulderNavigationEnabled` | | Whether gamepad shoulder buttons cycle the selection. | + +| Member | Description | +| --- | --- | +| `SettingsTag` | Well-known [`NavigationViewElement.SelectedTag`](#navigationviewelement) value that selects NavigationView's built-in settings item — the only menu entry NavigationView creates itself, so it has no [`NavigationViewItemData`](../controls/navigation-items.md#navigationviewitemdata) and cannot be addressed by an author-chosen tag. Also the tag reported to [`NavigationViewElement.OnItemInvoked`](#navigationviewelement) when settings is invoked. An author item carrying this tag still wins: selection searches [`NavigationViewElement.MenuItems`](#navigationviewelement) and [`NavigationViewElement.FooterMenuItems`](#navigationviewelement) before falling back to the settings item, so the sentinel can never shadow real content. Reserved, so do not use it as an ordinary item tag. Selection would work, but `WithNavigation` skips it when mapping a tag back to a route — it routes the sentinel through its own `settingsRoute` parameter instead — so such an item would select without navigating. | + +## `PipsPagerElement` + +The element record that describes a WinUI [`PipsPager`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.pipspager) control. + +```csharp +public record PipsPagerElement(int NumberOfPages) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`PipsPager`](../factories/navigation.md#pipspager) + +**Modifiers:** [`MaxVisiblePips`](../modifiers/navigation.md#maxvisiblepips), [`NextButtonVisibility`](../modifiers/navigation.md#nextbuttonvisibility), [`PreviousButtonVisibility`](../modifiers/navigation.md#previousbuttonvisibility), [`SelectedPageIndexChanged`](../modifiers/navigation.md#selectedpageindexchanged), [`Set`](../modifiers/native-properties.md#set), [`WrapMode`](../modifiers/navigation.md#wrapmode) + +| Property | Type | Description | +| --- | --- | --- | +| `MaxVisiblePips` | `int` | Maximum number of visible pips. Defaults to 5 (matches WinUI). | +| `NextButtonVisibility` | `PipsPagerButtonVisibility` | When the next button shows. Defaults to `Collapsed`. | +| `NumberOfPages` | `int` | | +| `OnSelectedPageIndexChanged` | `Action?` | | +| `PreviousButtonVisibility` | `PipsPagerButtonVisibility` | When the previous button shows. Defaults to `Collapsed`. | +| `SelectedPageIndex` | [`Optional`](../components/Optional.md) | Selected page index. Defaults to [`Optional.Unset`](../components/Optional.md#unset); use `Optional.Of(-1)` to force no page selection. | +| `WrapMode` | `PipsPagerWrapMode` | Whether the selected index wraps around the ends. Defaults to `None`. | + +## `PivotElement` + +The element record that describes a WinUI [`Pivot`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.pivot) control. + +```csharp +public record PivotElement(PivotItemData[] Items) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Pivot`](../factories/navigation.md#pivot) + +**Modifiers:** [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Items` | [`PivotItemData[]`](../controls/navigation-items.md#pivotitemdata) | | +| `OnSelectedIndexChanged` | `Action?` | | +| `SelectedIndex` | [`Optional`](../components/Optional.md) | Selected pivot item index. Defaults to [`Optional.Unset`](../components/Optional.md#unset); use `Optional.Of(-1)` to force no selection. | +| `Title` | `string?` | | + +## `SelectorBarElement` + +The element record that describes a WinUI [`SelectorBar`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.selectorbar) control. + +```csharp +public record SelectorBarElement(SelectorBarItemData[] Items) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`SelectorBar`](../factories/navigation.md#selectorbar) + +**Modifiers:** [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Items` | [`SelectorBarItemData[]`](../controls/navigation-items.md#selectorbaritemdata) | | +| `OnSelectedIndexChanged` | `Action?` | | +| `SelectedIndex` | [`Optional`](../components/Optional.md) | Selected item index. Defaults to [`Optional.Unset`](../components/Optional.md#unset); use `Optional.Of(-1)` to force no selection. | + +## `TabViewElement` + +The element record that describes a WinUI [`TabView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.tabview) control. + +```csharp +public record TabViewElement(TabViewItemData[] Tabs) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`TabView`](../factories/navigation.md#tabview) + +**Modifiers:** [`AddTabButtonClick`](../modifiers/navigation.md#addtabbuttonclick), [`AllowDropTabs`](../modifiers/navigation.md#allowdroptabs), [`CanDragTabs`](../modifiers/navigation.md#candragtabs), [`CanReorderTabs`](../modifiers/navigation.md#canreordertabs), [`CloseButtonOverlayMode`](../modifiers/navigation.md#closebuttonoverlaymode), [`FillContentArea`](../modifiers/navigation.md#fillcontentarea), [`IsAddButtonVisible`](../modifiers/navigation.md#isaddbuttonvisible), [`IsAddTabButtonVisible`](../modifiers/navigation.md#isaddtabbuttonvisible), [`SelectedIndexChanged`](../modifiers/shared-controls.md#selectedindexchanged), [`Set`](../modifiers/native-properties.md#set), [`ShowAddButton`](../modifiers/navigation.md#showaddbutton), [`TabCloseRequested`](../modifiers/navigation.md#tabcloserequested), [`TabDragCompleted`](../modifiers/navigation.md#tabdragcompleted), [`TabDragStarting`](../modifiers/navigation.md#tabdragstarting), [`TabStripFooter`](../modifiers/navigation.md#tabstripfooter), [`TabStripHeader`](../modifiers/navigation.md#tabstripheader), [`TabWidthMode`](../modifiers/navigation.md#tabwidthmode) + +| Property | Type | Description | +| --- | --- | --- | +| `AllowDropTabs` | `bool` | Whether tabs from another TabView can be dropped onto this one. | +| `CanDragTabs` | `bool` | Whether tabs can be dragged out (to a window). | +| `CanReorderTabs` | `bool` | Whether tabs can be reordered within the strip. | +| `CloseButtonOverlayMode` | `TabViewCloseButtonOverlayMode` | Controls when the per-tab close button is visible. Defaults to `Auto`. | +| `FillContentArea` | `bool` | Opt in to having the tab content area fill the space the TabView is given by its parent (issue #914). | +| `IsAddTabButtonVisible` | `bool` | | +| `OnAddTabButtonClick` | `Action?` | | +| `OnSelectedIndexChanged` | `Action?` | | +| `OnTabCloseRequested` | `Action?` | | +| `OnTabDragCompleted` | `Action?` | Fires when a tab drag finishes — either landed on another TabView (`wasOutside == false`) or was dropped outside any TabView (`wasOutside == true`, used by §2.4 to trigger tear-out). | +| `OnTabDragStarting` | `Action?` | Fires when the user starts dragging a tab. `tabIndex` is the index of the dragged tab in [`TabViewElement.Tabs`](#tabviewelement). Used by spec 045 §2.4 docking drag pipeline to start a `DockDragSession`. | +| `SelectedIndex` | [`Optional`](../components/Optional.md) | Selected tab index. Defaults to [`Optional.Unset`](../components/Optional.md#unset); use `Optional.Of(-1)` to force no selection. | +| `TabStripFooter` | [`Element?`](Element.md) | Element rendered at the trailing edge of the tab strip. | +| `TabStripHeader` | [`Element?`](Element.md) | Element rendered at the leading edge of the tab strip. | +| `TabWidthMode` | `TabViewWidthMode` | How tab widths are sized. Defaults to `Equal` (matches WinUI default). | +| `Tabs` | [`TabViewItemData[]`](../controls/navigation-items.md#tabviewitemdata) | | + +## `TitleBarElement` + +The element record that describes a WinUI [`TitleBar`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.titlebar) control. + +```csharp +public record TitleBarElement(string Title) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`TitleBar`](../factories/text.md#titlebar) + +**Modifiers:** [`AutoRefreshDragRegions`](../modifiers/navigation.md#autorefreshdragregions), [`BackButtonEnabled`](../modifiers/navigation.md#backbuttonenabled), [`BackButtonVisible`](../modifiers/navigation.md#backbuttonvisible), [`BackRequested`](../modifiers/navigation.md#backrequested), [`Content`](../modifiers/shared-controls.md#content), [`HeightOption`](../modifiers/navigation.md#heightoption), [`Icon`](../modifiers/navigation.md#icon), [`LeftHeader`](../modifiers/navigation.md#leftheader), [`NoIcon`](../modifiers/navigation.md#noicon), [`PaneToggleButtonVisible`](../modifiers/navigation.md#panetogglebuttonvisible), [`PaneToggleRequested`](../modifiers/navigation.md#panetogglerequested), [`PreferredTheme`](../modifiers/navigation.md#preferredtheme), [`RightHeader`](../modifiers/navigation.md#rightheader), [`Set`](../modifiers/native-properties.md#set), [`Subtitle`](../modifiers/navigation.md#subtitle), [`Tall`](../modifiers/navigation.md#tall), [`WithNavigation`](../modifiers/navigation.md#withnavigation) + +| Property | Type | Description | +| --- | --- | --- | +| `AutoRefreshDragRegions` | `bool` | When `true`, the WinUI `TitleBar` re-derives its drag regions on every layout pass (WinApp SDK ≥ 2.1.3). Useful when [`TitleBarElement.Content`](#titlebarelement) changes across renders. Default `false` (matches the control default; interactive controls are still auto-excluded from the drag region). See spec 059. | +| `Content` | [`Element?`](Element.md) | | +| `HeightOption` | `WindowTitleBarHeight?` | System caption height for the hosting window. `Tall` is the standard layout when the title bar hosts navigation chrome (back button / pane toggle) and is the direct analogue of the XAML NavigationView template's `AppWindow.TitleBar.PreferredHeightOption = Tall` plus its ``. (issue #917) | +| `Icon` | [`IconData?`](../controls/icons.md#icondata) | Icon shown in the title bar's leading slot. Mirrors WinUI 3 `TitleBar.IconSource`. Pass a [`SymbolIconData`](../controls/icons.md#symbolicondata) / [`FontIconData`](../controls/icons.md#fonticondata) for built-in glyphs, or [`ImageIconData`](../controls/icons.md#imageicondata) / [`BitmapIconData`](../controls/icons.md#bitmapicondata) for a bundled `.ico` / image (e.g. `new ImageIconData(new Uri("ms-appx:///Assets/AppIcon.ico"))`). Left unset, the title bar inherits the **window's** icon — [`WindowSpec.Icon`](../hosting/WindowSpec.md#icon) if declared, otherwise the `Assets\AppIcon.ico` convention — so an app that already has an icon need not restate it here. The WinUI control does not do this itself. An icon that exists only as an executable PE resource is not inherited: that stage yields a raw `HICON` with no path, and a XAML `IconSource` needs an image source. Set [`TitleBarElement.SuppressIcon`](#titlebarelement) via `.NoIcon()` to show none. | +| `IsBackButtonEnabled` | `bool` | | +| `IsBackButtonVisible` | `bool` | | +| `IsPaneToggleButtonVisible` | `bool` | | +| `LeftHeader` | [`Element?`](Element.md) | Custom content in the title bar's leading header slot. | +| `OnBackRequested` | `Action?` | | +| `OnPaneToggleRequested` | `Action?` | | +| `PreferredTheme` | `WindowTitleBarTheme?` | Theme of the hosting window's system caption buttons (`AppWindow.TitleBar.PreferredTheme`). `null` (the default) leaves the caption alone. (issue #1297) | +| `RightHeader` | [`Element?`](Element.md) | | +| `Subtitle` | `string?` | | +| `SuppressIcon` | `bool` | Suppresses the icon entirely, including the one Reactor would otherwise inherit from the window (see [`TitleBarElement.Icon`](#titlebarelement)). Set via `.NoIcon()`. | +| `Title` | `string` | | diff --git a/docs/guide/reference/elements/shapes.md b/docs/guide/reference/elements/shapes.md new file mode 100644 index 0000000000..9cf94a8c78 --- /dev/null +++ b/docs/guide/reference/elements/shapes.md @@ -0,0 +1,115 @@ +# Elements: Shapes + +Rectangles, ellipses, lines, paths and brushes. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Styling and Theming](../../styling.md) + +## `EllipseElement` + +The element record that describes a WinUI [`Ellipse`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.shapes.ellipse) control. + +```csharp +public record EllipseElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Ellipse`](../factories/shapes.md#ellipse) + +**Modifiers:** [`Fill`](../modifiers/shapes.md#fill), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Fill` | `Brush?` | Maps `Ellipse.Fill`. | +| `Setters` | `Action[]` | Imperative escape hatch run after every Mount/Update. | +| `Stroke` | `Brush?` | Maps `Ellipse.Stroke`. | +| `StrokeThickness` | `double?` | Maps `Ellipse.StrokeThickness`. | + +| Member | Description | +| --- | --- | +| `Ellipse(Brush?, Brush?, double?)` | Creates a [`EllipseElement`](#ellipseelement) (and guarantees the handler is registered). | +| `Set(Action)` | Appends an action run against the live [`EllipseElement.Ellipse`](#ellipseelement) after every Mount/Update (imperative escape hatch). Chainable. | + +## `LineElement` + +The element record that describes a WinUI [`Line`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.shapes.line) control. + +```csharp +public record LineElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Line`](../factories/shapes.md#line) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set), [`Stroke`](../modifiers/shapes.md#stroke), [`StrokeThickness`](../modifiers/shapes.md#strokethickness) + +| Property | Type | Description | +| --- | --- | --- | +| `Stroke` | `Brush?` | | +| `StrokeThickness` | `double` | | +| `X1` | `double` | | +| `X2` | `double` | | +| `Y1` | `double` | | +| `Y2` | `double` | | + +## `PathElement` + +The element record that describes a WinUI [`Path`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.shapes.path) control. + +```csharp +public record PathElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Path2D`](../factories/shapes.md#path2d) + +**Modifiers:** [`Fill`](../modifiers/shapes.md#fill), [`FillRule`](../modifiers/shapes.md#fillrule), [`Set`](../modifiers/native-properties.md#set), [`Stroke`](../modifiers/shapes.md#stroke), [`StrokeDashArray`](../modifiers/shapes.md#strokedasharray), [`StrokeDashCap`](../modifiers/shapes.md#strokedashcap), [`StrokeDashOffset`](../modifiers/shapes.md#strokedashoffset), [`StrokeEndLineCap`](../modifiers/shapes.md#strokeendlinecap), [`StrokeLineJoin`](../modifiers/shapes.md#strokelinejoin), [`StrokeMiterLimit`](../modifiers/shapes.md#strokemiterlimit), [`StrokeStartLineCap`](../modifiers/shapes.md#strokestartlinecap), [`StrokeThickness`](../modifiers/shapes.md#strokethickness) + +| Property | Type | Description | +| --- | --- | --- | +| `Data` | `Geometry?` | Pre-parsed WinUI Geometry. When null, the reconciler resolves from [`PathElement.PathDataString`](#pathelement). Callers that construct PathElement directly (not via D3Path) can set this for non-SVG geometries. | +| `Fill` | `Brush?` | | +| `FillRule` | `FillRule` | How interior regions are determined for fills. Defaults to `EvenOdd`. | +| `PathDataString` | `string?` | The original SVG path data string. When set, geometry is parsed lazily by the reconciler — only when mounting or when the string changes between renders. This avoids expensive PathDataParser.Parse + COM Geometry creation on every tree build. | +| `RenderTransform` | `Transform?` | | +| `Stroke` | `Brush?` | | +| `StrokeDashArray` | `DoubleCollection?` | | +| `StrokeDashCap` | `PenLineCap` | Cap rendered on dashes when [`PathElement.StrokeDashArray`](#pathelement) is set. Defaults to `Flat`. | +| `StrokeDashOffset` | `double` | Distance into the dash pattern at which to begin drawing. Defaults to 0. | +| `StrokeEndLineCap` | `PenLineCap` | Cap rendered at the end of an open stroke. Defaults to `Flat`. | +| `StrokeLineJoin` | `PenLineJoin` | Join style between two connected stroke segments. Defaults to `Miter`. | +| `StrokeMiterLimit` | `double` | Maximum extent of a miter join relative to half the stroke thickness. Defaults to 10. | +| `StrokeStartLineCap` | `PenLineCap` | Cap rendered at the start of an open stroke. Defaults to `Flat`. | +| `StrokeThickness` | `double` | | + +## `RectangleElement` + +The element record that describes a WinUI [`Rectangle`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.shapes.rectangle) control. + +```csharp +public record RectangleElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Rectangle`](../factories/shapes.md#rectangle) + +**Modifiers:** [`Fill`](../modifiers/shapes.md#fill), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Fill` | `Brush?` | Maps `Rectangle.Fill`. | +| `RadiusX` | `double?` | Maps `Rectangle.RadiusX`. | +| `RadiusY` | `double?` | Maps `Rectangle.RadiusY`. | +| `Setters` | `Action[]` | Imperative escape hatch run after every Mount/Update. | +| `Stroke` | `Brush?` | Maps `Rectangle.Stroke`. | +| `StrokeThickness` | `double?` | Maps `Rectangle.StrokeThickness`. | + +| Member | Description | +| --- | --- | +| `Rectangle(Brush?, double?, double?, Brush?, double?)` | Creates a [`RectangleElement`](#rectangleelement) (and guarantees the handler is registered). | +| `Set(Action)` | Appends an action run against the live [`RectangleElement.Rectangle`](#rectangleelement) after every Mount/Update (imperative escape hatch). Chainable. | diff --git a/docs/guide/reference/elements/status-and-info.md b/docs/guide/reference/elements/status-and-info.md new file mode 100644 index 0000000000..b78a4087bf --- /dev/null +++ b/docs/guide/reference/elements/status-and-info.md @@ -0,0 +1,98 @@ +# Elements: Status and info + +Info bars, badges and progress indicators. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Status and Info](../../status-and-info.md) + +## `InfoBadgeElement` + +The element record that describes a WinUI [`InfoBadge`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.infobadge) control. + +```csharp +public record InfoBadgeElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`InfoBadge`](../factories/status-and-info.md#infobadge) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Description | +| --- | --- | --- | +| `Icon` | `string?` | | +| `Value` | `int?` | | + +## `InfoBarElement` + +The element record that describes a WinUI [`InfoBar`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.infobar) control. + +```csharp +public record InfoBarElement(string? Title = null, string? Message = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`InfoBar`](../factories/status-and-info.md#infobar) + +**Modifiers:** [`ActionButtonClick`](../modifiers/shared-controls.md#actionbuttonclick), [`Closable`](../modifiers/status-and-info.md#closable), [`Closed`](../modifiers/shared-controls.md#closed), [`Content`](../modifiers/shared-controls.md#content), [`Error`](../modifiers/status-and-info.md#error), [`IconSource`](../modifiers/shared-controls.md#iconsource), [`Informational`](../modifiers/status-and-info.md#informational), [`IsClosable`](../modifiers/status-and-info.md#isclosable), [`Set`](../modifiers/native-properties.md#set), [`Severity`](../modifiers/status-and-info.md#severity), [`Success`](../modifiers/status-and-info.md#success), [`Warning`](../modifiers/status-and-info.md#warning) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `ActionButtonContent` | `string?` | | | +| `Content` | [`Element?`](Element.md) | | Custom rich content rendered below the message (e.g. links, buttons, an embedded form). | +| `IconSource` | [`IconData?`](../controls/icons.md#icondata) | | Custom icon source. When set, overrides the severity-based icon. | +| `IsClosable` | `bool` | | Whether the bar shows its built-in close button. Defaults to `true`. | +| `IsOpen` | `bool` | | Whether the bar is shown. Defaults to `true`, so `InfoBar("Title", "Message")` is visible without ceremony. **Edge-triggered.** This declares a *transition*, not a mirror: Reactor writes the control only when the declared value *changes*. The user can dismiss the bar with its built-in close button, which sets `IsOpen` to `false` on the control without touching the declared value — re-rendering the same declared `true` will **not** bring it back, and is not meant to. Wire [`InfoBarElement.OnClosed`](#infobarelement) (or `.Closed(...)`) into the state that drives this property; a later `false → true` transition then re-opens the bar. | +| `Message` | `string?` | `null` | | +| `OnActionButtonClick` | `Action?` | | | +| `OnClosed` | `Action?` | | | +| `Severity` | `InfoBarSeverity` | | | +| `Title` | `string?` | `null` | | + +## `ProgressElement` + +The element record that describes a WinUI [`ProgressBar`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.progressbar) control. + +```csharp +public record ProgressElement(double? Value = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Progress`](../factories/status-and-info.md#progress), [`ProgressIndeterminate`](../factories/status-and-info.md#progressindeterminate) + +**Modifiers:** [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `IsIndeterminate` | `bool` | | | +| `Maximum` | `double` | | | +| `Minimum` | `double` | | | +| `ShowError` | `bool` | | | +| `ShowPaused` | `bool` | | | +| `Value` | `double?` | `null` | | + +## `ProgressRingElement` + +The element record that describes a WinUI [`ProgressRing`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.progressring) control. + +```csharp +public record ProgressRingElement(double? Value = null) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`ProgressRing`](../factories/status-and-info.md#progressring) + +**Modifiers:** [`Active`](../modifiers/status-and-info.md#active), [`IsActive`](../modifiers/status-and-info.md#isactive), [`Set`](../modifiers/native-properties.md#set) + +| Property | Type | Default | Description | +| --- | --- | --- | --- | +| `IsActive` | `bool` | | | +| `IsIndeterminate` | `bool` | | | +| `Maximum` | `double` | | | +| `Minimum` | `double` | | | +| `Value` | `double?` | `null` | | diff --git a/docs/guide/reference/elements/text.md b/docs/guide/reference/elements/text.md new file mode 100644 index 0000000000..7d5bf1770b --- /dev/null +++ b/docs/guide/reference/elements/text.md @@ -0,0 +1,80 @@ +# Elements: Text + +Text blocks, rich text and the typography factories. + +Element records are immutable descriptions of a control. You usually create them with a factory method and change them with modifiers. + +**Learn more:** [Text and Media](../../text-and-media.md) + +## `RichTextBlockElement` + +The element record that describes a WinUI [`RichTextBlock`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.richtextblock) control. + +```csharp +public record RichTextBlockElement(string Text) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`RichTextBlock`](../factories/text.md#richtextblock) + +**Modifiers:** [`CharacterSpacing`](../modifiers/typography.md#characterspacing), [`FontFamily`](../modifiers/typography.md#fontfamily), [`FontSize`](../modifiers/typography.md#fontsize), [`FontStretch`](../modifiers/typography.md#fontstretch), [`FontStyle`](../modifiers/typography.md#fontstyle), [`FontWeight`](../modifiers/typography.md#fontweight), [`Foreground`](../modifiers/appearance.md#foreground), [`HorizontalTextAlignment`](../modifiers/typography.md#horizontaltextalignment), [`IsColorFontEnabled`](../modifiers/typography.md#iscolorfontenabled), [`IsTextScaleFactorEnabled`](../modifiers/typography.md#istextscalefactorenabled), [`LineHeight`](../modifiers/typography.md#lineheight), [`LineStackingStrategy`](../modifiers/typography.md#linestackingstrategy), [`MaxLines`](../modifiers/typography.md#maxlines), [`OpticalMarginAlignment`](../modifiers/typography.md#opticalmarginalignment), [`SelectionHighlightColor`](../modifiers/typography.md#selectionhighlightcolor), [`Set`](../modifiers/native-properties.md#set), [`TextAlignment`](../modifiers/typography.md#textalignment), [`TextDecorations`](../modifiers/typography.md#textdecorations), [`TextIndent`](../modifiers/typography.md#textindent), [`TextLineBounds`](../modifiers/typography.md#textlinebounds), [`TextReadingOrder`](../modifiers/typography.md#textreadingorder), [`TextTrimming`](../modifiers/typography.md#texttrimming) + +| Property | Type | Description | +| --- | --- | --- | +| `CharacterSpacing` | `int` | Extra spacing between characters, in units of 1/1000em. Defaults to `0`. | +| `FontFamily` | `FontFamily?` | | +| `FontSize` | `double?` | | +| `FontStretch` | `FontStretch?` | | +| `FontStyle` | `FontStyle?` | | +| `FontWeight` | `FontWeight?` | | +| `Foreground` | `Brush?` | | +| `HorizontalTextAlignment` | `TextAlignment?` | Horizontal text alignment using the newer WinUI property. `null` uses the WinUI default. | +| `IsColorFontEnabled` | `bool?` | | +| `IsTextScaleFactorEnabled` | `bool?` | | +| `IsTextSelectionEnabled` | `bool` | | +| `LineHeight` | `double?` | Line height in pixels. `null` uses the WinUI default (proportional to FontSize). | +| `LineStackingStrategy` | `LineStackingStrategy?` | | +| `MaxLines` | `int` | Maximum number of lines before trimming per [`RichTextBlockElement.TextTrimming`](#richtextblockelement). `0` (default) = no limit. | +| `OpticalMarginAlignment` | `OpticalMarginAlignment?` | | +| `Paragraphs` | [`RichTextParagraph[]?`](../controls/rich-text.md#richtextparagraph) | | +| `SelectionHighlightColor` | `SolidColorBrush?` | | +| `Text` | `string` | | +| `TextAlignment` | `TextAlignment?` | Horizontal alignment of text within the block. `null` uses the WinUI default (Left). | +| `TextDecorations` | `TextDecorations?` | | +| `TextIndent` | `double?` | | +| `TextLineBounds` | `TextLineBounds?` | | +| `TextReadingOrder` | `TextReadingOrder?` | | +| `TextTrimming` | `TextTrimming?` | How overflowing text is truncated. `null` uses the WinUI default (None). | +| `TextWrapping` | `TextWrapping?` | | + +## `TextBlockElement` + +The element record that describes a WinUI [`TextBlock`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.textblock) control. + +```csharp +public record TextBlockElement(string Content) : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core`. Inherits from [`Element`](Element.md). + +**Created by:** [`Body`](../factories/text.md#body), [`BodyLarge`](../factories/text.md#bodylarge), [`BodyStrong`](../factories/text.md#bodystrong), [`Caption`](../factories/text.md#caption), [`Display`](../factories/text.md#display), [`Heading`](../factories/text.md#heading), [`SubHeading`](../factories/text.md#subheading), [`Subtitle`](../factories/text.md#subtitle), [`TextBlock`](../factories/text.md#textblock), [`Title`](../factories/text.md#title), [`TitleLarge`](../factories/text.md#titlelarge) + +**Modifiers:** [`Bold`](../modifiers/typography.md#bold), [`CharacterSpacing`](../modifiers/typography.md#characterspacing), [`FontFamily`](../modifiers/typography.md#fontfamily), [`FontSize`](../modifiers/typography.md#fontsize), [`FontStyle`](../modifiers/typography.md#fontstyle), [`IsTextSelectionEnabled`](../modifiers/typography.md#istextselectionenabled), [`LineHeight`](../modifiers/typography.md#lineheight), [`MaxLines`](../modifiers/typography.md#maxlines), [`Selectable`](../modifiers/typography.md#selectable), [`SemiBold`](../modifiers/typography.md#semibold), [`Set`](../modifiers/native-properties.md#set), [`TextAlignment`](../modifiers/typography.md#textalignment), [`TextDecorations`](../modifiers/typography.md#textdecorations), [`TextTrimming`](../modifiers/typography.md#texttrimming), [`TextWrapping`](../modifiers/typography.md#textwrapping) + +| Property | Type | Description | +| --- | --- | --- | +| `CharacterSpacing` | `int` | Extra spacing between characters, in units of 1/1000em. Defaults to `0` (no extra spacing). | +| `Content` | `string` | | +| `FontFamily` | `FontFamily?` | | +| `FontSize` | `double?` | | +| `FontStyle` | `FontStyle?` | | +| `HorizontalAlignment` | `HorizontalAlignment?` | | +| `IsTextSelectionEnabled` | `bool?` | | +| `LineHeight` | `double?` | Line height in pixels. `null` uses the WinUI default (proportional to FontSize). | +| `MaxLines` | `int` | Maximum number of lines to render before truncating per [`TextBlockElement.TextTrimming`](#textblockelement). `0` (default) = no limit. | +| `TextAlignment` | `TextAlignment?` | | +| `TextDecorations` | `TextDecorations` | Bitmask of underline / strikethrough decorations. Default `None`. | +| `TextTrimming` | `TextTrimming?` | | +| `TextWrapping` | `TextWrapping?` | | +| `Weight` | `FontWeight?` | | diff --git a/docs/guide/reference/extensibility/ControlDescriptor.md b/docs/guide/reference/extensibility/ControlDescriptor.md new file mode 100644 index 0000000000..790968e554 --- /dev/null +++ b/docs/guide/reference/extensibility/ControlDescriptor.md @@ -0,0 +1,469 @@ +# ControlDescriptor\ + +Spec 047 §6 / §14 Phase 2 (Q1 spike) — declarative control description. + +A descriptor is the data-driven alternative to a hand-coded [`IElementHandler`](IElementHandler.md). Authors declare property bindings (`OneWay`, [`ControlDescriptor.InitialOnly`](#initialonly), [`ControlDescriptor.Controlled`](#controlled)), an optional children strategy, and an optional factory; the interpreter ([`DescriptorHandler`](DescriptorHandler.md)) executes them against the same v1 protocol surface a hand-coded handler would use. + +**Phase 2 measurement gate (§13 Q1):** the descriptor and the hand-coded handler shapes are evaluated head-to-head on the same M1 / M2 / M5 / M7 / M10 micro-benches and the L4 / L9 macros, then the §13 Q1 decision matrix determines which surface ships as the primary author path. See `docs/specs/047-extensible-control-model.md` §13 Q1. + +**Echo suppression (issue #206).** A `.Controlled` / `.HandCodedControlled` entry suppresses the echo of its own programmatic write automatically — the interpreter wraps the write in the public [`ReactorBinding`](ReactorBinding.md) `WriteSuppressed` primitive (or arms a value-diff predicate when `valueDiffEcho` is set), so a framework-driven write never echoes back into the user's `OnChanged` callback. Descriptor authors therefore never touch the suppressor directly; hand-coded [`IElementHandler`](IElementHandler.md) authors call `WriteSuppressed` themselves. See `docs/guide/extending-reactor-controls.md`. + +**Fluent author pattern:** + +```csharp +public record ToggleSwitchElement(Optional IsOn = default) : Element; + +public static readonly ControlDescriptor Descriptor = + new ControlDescriptor() + .OneWay(e => e.OnContent, (c, v) => c.OnContent = v) + .OneWayConditional(e => e.Header, (c, v) => c.Header = v, e => e.Header is not null) + .Controlled( + get: e => e.IsOn, + set: (c, v) => c.IsOn = v, + subscribe: (fe, h) => ((ToggleSwitch)fe).Toggled += (s, e) => h(s, e), + unsubscribe: (fe, h) => { /* trampoline lives for control lifetime */ }, + callback: e => e.OnIsOnChanged, + readBack: c => c.IsOn); +``` + +```csharp +public sealed class ControlDescriptor where TElement : Element where TControl : FrameworkElement, new() +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol.Descriptor`. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md), [The Control Reconciler Protocol](../../control-reconciler-protocol.md) + +## Constructors + +### `ControlDescriptor` + +```csharp +public ControlDescriptor() +``` + +## Properties + +### `AfterChildrenMount` + +Spec 047 §14 Phase 3 prelude (Engine A1) — optional post-children mount hook. The interpreter ([`DescriptorHandler`](DescriptorHandler.md)) surfaces it through [`IElementHandler.AfterChildrenMount`](IElementHandler.md#afterchildrenmount), which the adapter invokes after every child has mounted. Use for events that must subscribe after children-add (TabView SelectionChanged), or for imperative work that must run strictly after the prop loop AND the event subscriptions (FrameElement's mount-time navigation, which would otherwise complete before its own Navigated/NavigationFailed handlers exist). Defaults to `null` (no hook). Set it from an object initializer, or — from a generated descriptor's `Customize` hook, which receives an already-constructed descriptor — via [`ControlDescriptor.WithAfterChildrenMount`](#withafterchildrenmount). + +```csharp +public AfterChildrenMountCallback? AfterChildrenMount // get, init +``` + +### `Children` + +Optional children strategy. Engine dispatches through it via `V1HandlerAdapter` after each Mount / Update body returns. Defaults to `null` (treated as [`None`](children-strategies.md#nonetelement-tcontrol) by the adapter). + +```csharp +public ChildrenStrategy? Children // get, set +``` + +### `Factory` + +Optional factory the engine invokes when the pool is empty or [`ControlDescriptor.PoolPolicy`](#poolpolicy) opts out. Defaults to `new TControl()` via the `new()` constraint. + +```csharp +public Func? Factory // get, init +``` + +### `GetSetters` + +`Setters` selector — the descriptor needs an opaque way to pull the element's `Action[]` setters chain because each element subclass declares its own `Setters` property (no common base interface). Authors register `e => e.Setters`; the interpreter passes the result to `Reconciler.ApplySetters` after the property entries have run. Defaults to "no setters" if not configured. + +```csharp +public Func[]>? GetSetters // get, init +``` + +### `OnUnmount` + +Optional teardown hook. The interpreter ([`DescriptorHandler`](DescriptorHandler.md)) surfaces it through [`IElementHandler.Unmount`](IElementHandler.md#unmount), which the engine invokes when the control leaves the tree. Use it to invalidate control-scoped state the descriptor created during mount and that the pool reset contract cannot see — a pending deferred write, a one-shot `Loaded` subscription, a disposable. Defaults to `null` (no hook). Set it from an object initializer, or — from a generated descriptor's `Customize` hook, which receives an already-constructed descriptor — via [`ControlDescriptor.WithUnmount`](#withunmount). + +Not for event trampolines: those anchor to the control's lifetime by design (see the `unsubscribe` no-op contract on [`ControlDescriptor.Controlled`](#controlled)). + +Declaring this hook makes [`DescriptorHandler`](DescriptorHandler.md) force the control's `ReactorState` into existence at mount, because the engine's unmount dispatch is tag-gated. That costs one small allocation per mounted control of this type, so declare it only when there is real teardown to do. + +```csharp +public DescriptorUnmountCallback? OnUnmount // get, init +``` + +### `PoolPolicy` + +Optional pool policy. When null the engine uses the default (poolable if the control type opts in via `PoolableTypes`). + +```csharp +public PoolPolicy? PoolPolicy // get, init +``` + +### `Properties` + +Read-only view of the property entries declared on this descriptor (in declaration order). + +```csharp +public IReadOnlyList> Properties // get +``` + +## Methods + +### `CoercingOneWay` + +Add a one-way property whose write may coerce a sibling controlled prop's value (e.g. `Slider.Minimum` coercing `Slider.Value`). When `coercesController` returns true the write is wrapped in `ReactorBinding.WriteSuppressed` so the coercion-driven change event is dropped. + +Declarative replacement for the imperative `if (ctrl.Value < n.Min) WriteSuppressed(...)` pattern in the hand-coded `SliderHandler`. Encodes the §8 audit's "coercion-tolerance" treatment for the 8 audited coercion sites (NumberBox / Slider Min/Max etc.) as a single declarative entry. + +```csharp +public ControlDescriptor CoercingOneWay(Func get, Action set, Func coercesController, IEqualityComparer? comparer = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `get` | `Func` | | | +| `set` | `Action` | | | +| `coercesController` | `Func` | | | +| `comparer` | `IEqualityComparer?` | `null` | | + +### `CollectionDiffControlled` + +§14 Phase 3-final — `.CollectionDiffControlled`. Two-way bound prop whose value is an [`IReadOnlyList`](https://learn.microsoft.com/dotnet/api/system.collections.generic.ireadonlylist-1) on the element side and an `IList` on the control side. Each Update applies a keyed hash-set diff and emits per-element `Add`/`Remove` ops inside `ChangeEchoSuppressor.BeginSuppress`. Used by CalendarView for `SelectedDates`; reusable for any control with a typed `IObservableVector` two-way slot. + +```csharp +public ControlDescriptor CollectionDiffControlled(Func> get, Func> getVector, Func key, Action subscribe, Func callbackPresent, TDelegate trampoline, Func slotIsNull, Action setSlot, IEqualityComparer? keyComparer = null) where TPayload : class, new() where TDelegate : Delegate +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `get` | `Func>` | | | +| `getVector` | `Func>` | | | +| `key` | `Func` | | | +| `subscribe` | `Action` | | | +| `callbackPresent` | `Func` | | | +| `trampoline` | `TDelegate` | | | +| `slotIsNull` | `Func` | | | +| `setSlot` | `Action` | | | +| `keyComparer` | `IEqualityComparer?` | `null` | | + +### `Controlled` + +Add a controlled (two-way) property binding. The engine writes from element state when `get` returns a value and leaves the control authoritative when it returns [`Optional.Unset`](../components/Optional.md#unset); writes use echo suppression on Update. The control raises `subscribe`'s event on user interaction; the trampoline invokes the element's `callback` with `readBack`'s value. + +**Callback gating:** if `callback` returns `null` on the element passed at Mount, no subscription happens at all — mirrors the hand-coded `Ensure*Wiring` gate. + +```csharp +public ControlDescriptor Controlled(Func> get, Action set, Action> subscribe, Action> unsubscribe, Func?> callback, Func readBack, IEqualityComparer? comparer = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `get` | `Func>` | | | +| `set` | `Action` | | | +| `subscribe` | `Action>` | | | +| `unsubscribe` | `Action>` | | | +| `callback` | `Func?>` | | | +| `readBack` | `Func` | | | +| `comparer` | `IEqualityComparer?` | `null` | | + +### `HandCodedControlled` + +§14 Phase 3 (3.0.1) — escape-hatch builder for controlled (two-way) props on a control that needs a hand-authored trampoline against a user-supplied per-control event payload (`TPayload`). Required for multi-event controls (e.g. `TextBox.Text` alongside `SelectionChanged`) where the single-event fast-path `DescriptorControlledPayload` would collide if two controlled entries shared the same closed generic. + +The payload type is typically reused from `ControlEventPayloads.cs` (e.g. `TextBoxEventPayload`) which already has a slot per event. `slotIsNull` + `setSlot` address the specific slot on the payload this entry owns; `subscribe` wires the user-supplied native `TDelegate` directly to the control's event (no `EventHandler` bridge closure). + +Mount/Update prop-write semantics are identical to [`ControlDescriptor.Controlled`](#controlled): unset skips writes, set values perform a bare initial write and a suppressed write on control drift. Subscription is gated on `callback` returning non-null on the mounted element. + +`valueDiffEcho` replaces the Update write's suppress-counter token with the spec 047 §8 value-diff arm, which the trampoline consumes on the next change event and which drops that event only when its readback matches the written value. `armOnMount` (requires `valueDiffEcho`) arms the Mount write too. Set it when the control raises its change event after the write returns (e.g. `RichEditBox`'s `Document.SetText`) and the trampoline cannot tell that echo apart on its own: the echo lands after the trampoline is wired and would otherwise reach the callback. The `set` lambda stays a plain write; the entry does the arming. + +```csharp +public ControlDescriptor HandCodedControlled(Func> get, Action set, Func readBack, Action subscribe, Func?> callback, TDelegate trampoline, Func slotIsNull, Action setSlot, IEqualityComparer? comparer = null, bool valueDiffEcho = false, bool armOnMount = false) where TPayload : class, new() where TDelegate : Delegate +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `get` | `Func>` | | | +| `set` | `Action` | | | +| `readBack` | `Func` | | | +| `subscribe` | `Action` | | | +| `callback` | `Func?>` | | | +| `trampoline` | `TDelegate` | | | +| `slotIsNull` | `Func` | | | +| `setSlot` | `Action` | | | +| `comparer` | `IEqualityComparer?` | `null` | | +| `valueDiffEcho` | `bool` | `false` | | +| `armOnMount` | `bool` | `false` | | + +### `HandCodedEvent` + +§14 Phase 3 (3.0.1) — escape-hatch builder for fire-and-forget control-intrinsic events that do not round-trip a DP (e.g. `TextBox.SelectionChanged`, `Image.ImageOpened`). Authors supply a per-control payload type and a native trampoline delegate; the entry wires subscription with the same payload-slot gating shape as [`ControlDescriptor.HandCodedControlled`](#handcodedcontrolled) but performs no Mount/Update prop writes. + +Subscription is gated on `callbackPresent` returning non-null — the element's callback shape can be anything (e.g. `Action`) so the gate is checked against the untyped `Delegate`. + +```csharp +public ControlDescriptor HandCodedEvent(Action subscribe, Func callbackPresent, TDelegate trampoline, Func slotIsNull, Action setSlot) where TPayload : class, new() where TDelegate : Delegate +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `subscribe` | `Action` | | +| `callbackPresent` | `Func` | | +| `trampoline` | `TDelegate` | | +| `slotIsNull` | `Func` | | +| `setSlot` | `Action` | | + +### `Immediate` + +§14 Phase 3-final — `.Immediate` entry. Pure subscription wiring for the "observed-DP callback + Loaded → inner template-part trampoline" pattern. The control's primary DP round-trip stays on a sibling `.HandCodedControlled` entry. See `ImmediatePropEntry` for the shape contract (NumberBox is the canonical proof point). Pass `loadedHook` as `null` when the DP observation is the whole subscription and there is no template part to walk. + +```csharp +public ControlDescriptor Immediate(Func callbackGate, DependencyProperty observeProperty, DependencyPropertyChangedCallback observeCallback, Func observeSlotIsNull, Action setObserveSlot, RoutedEventHandler? loadedHook) where TPayload : class, new() +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `callbackGate` | `Func` | | +| `observeProperty` | `DependencyProperty` | | +| `observeCallback` | `DependencyPropertyChangedCallback` | | +| `observeSlotIsNull` | `Func` | | +| `setObserveSlot` | `Action` | | +| `loadedHook` | `RoutedEventHandler?` | | + +### `Imperative` + +§14 Phase 3 finish — Engine (4). Escape hatch entry that receives `mount`+(`update` with BOTH old and new TElement, so the entry can express a diff the per-value get/set lambdas of [`ControlDescriptor.OneWayConditional`](#onewayconditional) can't: comparing one element field while writing a derived value elsewhere, or multi-source error context like `Path.PathDataString`'s XamlReader/PathDataParser branches. + +**When to reach for it:** only when the standard entries can't express the diff or the write. Imperative entries skip the engine's value-comparer fast-path, so a misused Imperative entry re-runs on every render. The other entry shapes (`OneWay`, [`ControlDescriptor.OneWayConditional`](#onewayconditional), [`ControlDescriptor.CoercingOneWay`](#coercingoneway), [`ControlDescriptor.HandCodedControlled`](#handcodedcontrolled)) still cover the 95% case. + +**Distinct from** [`Imperative`](children-strategies.md#imperativetelement-tcontrol) (a [`ChildrenStrategy`](children-strategies.md#childrenstrategytelement-tcontrol) that drives the whole CHILD subtree imperatively) — this is a property-level escape hatch that participates in the normal prop loop. + +```csharp +public ControlDescriptor Imperative(Action mount, Action update) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `mount` | `Action` | | +| `update` | `Action` | | + +### `ImperativeBridged` + +#### `ImperativeBridged(Action, Action)` + +§14 Phase 3 finish — Engine (2). Bridged variant of [`ControlDescriptor.Imperative`](#imperative) — the lambdas receive the [`MountContext`](lifecycle-contexts.md#mountcontext) / [`UpdateContext`](lifecycle-contexts.md#updatecontext) so they can call engine-internal helpers for bindings without owned child lifetime. + +For an owned secondary Element slot, use [`ControlDescriptor.ImperativeBridged`](#imperativebridgedactionmountcontext-tcontrol-telement-actionupdatecontext-tcontrol-telement-telement-actionunmountcontext-tcontrol) so the mounted child also receives terminal teardown. This overload is for bindings that do not own child lifetime. + +Same no-fast-path warning as [`ControlDescriptor.Imperative`](#imperative) — the Update lambda runs on every render. Reach for the standard shapes when they fit. + +```csharp +public ControlDescriptor ImperativeBridged(Action mount, Action update) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `mount` | `Action` | | +| `update` | `Action` | | + +#### `ImperativeBridged(Action, Action, Action)` + +Engine-bridged entry with terminal teardown, for owned secondary Element slots. Unmount the child while it is still parented, then detach it. The callback runs before, and independently of, the descriptor's [`ControlDescriptor.OnUnmount`](#onunmount) hook. Declaring this callback roots a ReactorState per control, including keyless controls without element callbacks. For example, Expander.HeaderContent owns a secondary Element child while the primary children strategy owns Content. Pair it with OneWayConditional for a string Header fallback when the Element slot is null. + +```csharp +public ControlDescriptor ImperativeBridged(Action mount, Action update, Action unmount) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `mount` | `Action` | | +| `update` | `Action` | | +| `unmount` | `Action` | | + +### `Initial` + +Add an initial-only property binding (write on Mount, never on Update). Use for seed-only props (e.g. `TextBox.InitialText`). + +```csharp +public ControlDescriptor Initial(Func get, Action set) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `get` | `Func` | | +| `set` | `Action` | | + +### `InitialOnly` + +Add an initial-only property binding (write on Mount, never on Update). Use for default-value-style props where the control owns the value after its initial seed. + +```csharp +public ControlDescriptor InitialOnly(Func get, Action set) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `get` | `Func` | | +| `set` | `Action` | | + +### `OneWay` + +#### `OneWay(Func, Action, IEqualityComparer?)` + +Add a one-way property binding (write on Mount, diff-and-write on Update). Engine never subscribes to a change event for this prop. Use for control props the framework writes but the user never subscribes to (Header text, brushes, layout values). + +```csharp +public ControlDescriptor OneWay(Func get, Action set, IEqualityComparer? comparer = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `get` | `Func` | | | +| `set` | `Action` | | | +| `comparer` | `IEqualityComparer?` | `null` | | + +#### `OneWay(Func>, Action, DependencyProperty, IEqualityComparer?)` + +Add a one-way property binding for an [`Optional`](../components/Optional.md) element value backed by a dependency property. Explicit values write via `set`; unset values call [`DependencyObject.ClearValue`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.dependencyobject.clearvalue) for `dp` so WinUI value precedence can fall back. + +```csharp +public ControlDescriptor OneWay(Func> get, Action set, DependencyProperty dp, IEqualityComparer? comparer = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `get` | `Func>` | | | +| `set` | `Action` | | | +| `dp` | `DependencyProperty` | | | +| `comparer` | `IEqualityComparer?` | `null` | | + +### `OneWayBridged` + +§14 Phase 3-final — engine-bridged one-way property. Same diff-and-write contract as [`ControlDescriptor.OneWayConditional`](#onewayconditional), but the set lambda receives the [`Reconciler`](Reconciler.md) and the rerender callback so it can call engine-internal helpers like `Reconciler.CreateFlyoutForDescriptor`. Used by the button-family Flyout port. + +```csharp +public ControlDescriptor OneWayBridged(Func get, OneWayBridgedSetter set, Func shouldWrite, IEqualityComparer? comparer = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `get` | `Func` | | | +| `set` | [`OneWayBridgedSetter`](descriptor-delegates.md#onewaybridgedsettertcontrol-tvalue) | | | +| `shouldWrite` | `Func` | | | +| `comparer` | `IEqualityComparer?` | `null` | | + +### `OneWayConditional` + +Add a one-way property with a "should I write?" predicate. The write is skipped when the predicate returns false — useful for nullable props where leaving the control at its default is the intent (e.g. `Border.Background` when the element has no background set). + +```csharp +public ControlDescriptor OneWayConditional(Func get, Action set, Func shouldWrite, IEqualityComparer? comparer = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `get` | `Func` | | | +| `set` | `Action` | | | +| `shouldWrite` | `Func` | | | +| `comparer` | `IEqualityComparer?` | `null` | | + +### `Reference` + +#### `Reference(Func, Action)` + +CR-004 untyped reference binding: accepts an element-record slot that stores an untyped [`ElementRef`](../input/element-refs.md#elementref) (so authors can supply any `ElementRef`). The resolved target is surfaced as a [`FrameworkElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.frameworkelement). + +```csharp +public ControlDescriptor Reference(Func get, Action set) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `get` | `Func` | | +| `set` | `Action` | | + +#### `Reference(Func?>, Action)` + +Add a reference property binding. The control property is written from the referenced cell at mount and whenever the cell changes. + +```csharp +public ControlDescriptor Reference(Func?> get, Action set) where TTarget : FrameworkElement +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `get` | `Func?>` | | +| `set` | `Action` | | + +### `ReferenceList` + +Add a list-valued reference binding. The control list is rebuilt from currently-resolved targets, preserving the author's declaration order. + +```csharp +public ControlDescriptor ReferenceList(Func>?> get, Action> apply) where TTarget : FrameworkElement +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `get` | `Func>?>` | | +| `apply` | `Action>` | | + +### `WithAfterChildrenMount` + +Fluent form of [`ControlDescriptor.AfterChildrenMount`](#afterchildrenmount), for authors whose descriptor is already constructed by the time they can customize it (the `[WrapManual]` `Customize` hook is handed a built descriptor, so the init-only property is out of reach there). + +```csharp +public ControlDescriptor WithAfterChildrenMount(AfterChildrenMountCallback callback) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `callback` | [`AfterChildrenMountCallback`](descriptor-delegates.md#afterchildrenmountcallbacktelement-tcontrol) | | + +### `WithUnmount` + +Fluent form of [`ControlDescriptor.OnUnmount`](#onunmount), for authors whose descriptor is already constructed by the time they can customize it (the `[WrapManual]` `Customize` hook is handed a built descriptor, so the init-only property is out of reach there). + +```csharp +public ControlDescriptor WithUnmount(DescriptorUnmountCallback callback) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `callback` | [`DescriptorUnmountCallback`](descriptor-delegates.md#descriptorunmountcallbacktcontrol) | | diff --git a/docs/guide/reference/extensibility/ControlRegistry.md b/docs/guide/reference/extensibility/ControlRegistry.md new file mode 100644 index 0000000000..f41ffd3d1d --- /dev/null +++ b/docs/guide/reference/extensibility/ControlRegistry.md @@ -0,0 +1,111 @@ +# ControlRegistry + +Spec 048 §8 — the global, lazy, lock-free control registry that backs the factory-as-registration pattern. Holds [`Type`](https://learn.microsoft.com/dotnet/api/system.type) → factory-of- `IV1HandlerEntry` entries; never roots a handler or WinUI control type by itself. Every static reference to a handler/control type lives in the *callers* of [`ControlRegistry.Register`](#register) — per-control factory cctors (Pattern A) or `Reg<…>` static-field initializers (Pattern B), each on a per-control rooted path. The trimmer therefore keeps a control iff its factory is reachable from the app entry point. + +**Idempotent first-wins.** Repeat [`ControlRegistry.Register`](#register) calls for the same element type are a silent no-op (spec §12.1). Multiple factories legitimately map to the same element type — e.g. `TextBlock()`, `Heading()`, and `Subheading()` all produce `TextBlockElement` (spec §10.3) — and a throw from a cctor would surface as a non-deterministic `TypeInitializationException` at the first-use point. The strict throw-on-duplicate policy from spec 047 §13 Q17 is preserved on the explicit per-host [`Reconciler.RegisterHandler`](Reconciler.md#registerhandler) path. + +**Hot path.** Per spec §9, [`ControlRegistry.Register`](#register) runs at most once per element type per process, on the cold first-use path. The steady-state per-host dispatch lookup short-circuits in the per-host `_v1Handlers` cache populated on the first registry hit; the registry itself is consulted at most once per (host, element type) pair. + +**AOT.** No reflection, no [`Type.MakeGenericType`](https://learn.microsoft.com/dotnet/api/system.type.makegenerictype); the closed-type capture happens inside the generic [`ControlRegistry.Register`](#register) entry point so the AOT compiler can see the closed types statically. The internal map is keyed by [`Type`](https://learn.microsoft.com/dotnet/api/system.type) and stores [`Func`](https://learn.microsoft.com/dotnet/api/system.func-1) delegates only — no MakeGenericType, no runtime type construction. + +```csharp +public static class ControlRegistry +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md), [The Control Reconciler Protocol](../../control-reconciler-protocol.md) + +## Methods + +### `Register` + +Spec §8 — register a handler factory for `TElement`. Idempotent first-wins: if an entry already exists for `typeof(TElement)`, this call is a silent no-op. The handler factory is invoked at most once per (host, element type) — on the first dispatch hit — and the resulting adapter is cached into the host's `_v1Handlers` map so steady-state dispatch is the existing fast per-host lookup. + +The `handlerFactory` delegate **should** be a `static` lambda (no captures) — Pattern A / Pattern B both rely on the single allocation being interned in a static field at the call site. A capturing lambda is functionally correct but allocates a closure on every `Reg<>.Init` / cctor run, undoing the cost-model claim in spec §9. + +**Echo suppression for value-bearing controls (issue #206).** A custom [`IElementHandler`](IElementHandler.md) registered here that writes a value-bearing property in `Update` must guard that write with the supported public primitive [`ReactorBinding`](ReactorBinding-1.md)'s `WriteSuppressed` method (or the static [`ReactorBinding`](ReactorBinding.md)) so the control's own echo does not flow back as a spurious user edit. Never reach into the internal `ChangeEchoSuppressor`. Descriptor authors get this through `.Controlled` / `.HandCodedControlled`. See `docs/guide/extending-reactor-controls.md`. + +```csharp +public static void Register(Func> handlerFactory) where TElement : Element where TControl : UIElement +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handlerFactory` | `Func>` | A factory that, when invoked, returns a fresh handler. Strongly recommended to be a `static` lambda (e.g. `static () => new MarqueeHandler()`) so the delegate is cached in a static field and no closure is allocated. | + +**Type parameters** + +| Name | Description | +| --- | --- | +| `TElement` | The element record type the handler dispatches against. Used as the dispatch key ([`Type`](https://learn.microsoft.com/dotnet/api/system.type)). | +| `TControl` | The WinUI control the handler mounts. | + +### `RegisterDecorator` + +Spec 048 §3.4 — decorator sibling of [`ControlRegistry.Register`](#register) for handlers that implement [`IDecoratorElementHandler`](IDecoratorElementHandler.md) (a separate, non-inheriting interface from [`IElementHandler`](IElementHandler.md)). Decorator handlers cover target-wrapping flyouts, modal lifecycle wrappers, polymorphic mounts (IconElement), interop bridges (XamlHost/XamlPage), and the keyed-reconcile panels (Stack/Grid/ Canvas/RelativePanel/WrapGrid/Flex) + Button/CheckBox/Expander — see [`IDecoratorElementHandler`](IDecoratorElementHandler.md) for the full use-case list. + +Stores the same [`Func`](https://learn.microsoft.com/dotnet/api/system.func-1) shape as the value-handler path, so [`Reconciler.TryResolveFromControlRegistry`](Reconciler.md) (dispatch arm 3) consumes both uniformly — no dispatch changes required. The adapter wrapping is the only difference: `V1DecoratorHandlerAdapter` versus `V1HandlerAdapter`. + +**One-shim invariant (§3.4 authoring rule).** For any given element type, factories must touch *exactly one* of `Reg<…>.Done` or `RegDecorator<…>.Done` — never both. The first-wins TryAdd silently keeps whichever path's cctor fires first; mixing them creates a non-deterministic dispatch outcome that depends on factory call order across the app's startup graph. This contrasts with the harmless aliasing case where multiple factories share the *same* closed-generic shim (spec §10.3 Heading/Subheading both touching `Reg`). + +**Singleton-handler factories.** A decorator handler exposed as a `public static readonly` singleton whose underlying type is a private nested class cannot satisfy `RegDecorator`'s `new()` constraint. Such a factory registers directly via this method with a `static` lambda returning the singleton: + +```csharp +public static MyElement My(...) +{ + ControlRegistry.RegisterDecorator( + static () => MyDescriptor.Handler); + return new MyElement(...); +} +``` + +This is functionally equivalent to `RegDecorator<…>.Done` — the static lambda still has no captures, the TryAdd still first-wins, and the trim story still routes every reference to the private handler type through the factory call-site path the trimmer can see. (The built-in Icon/XamlPage/XamlHost decorators that formerly used this pattern are now source-generated — spec 058 §15 P5.27/P5.28 — and self-register via a generated Pattern-A cctor.) + +```csharp +public static void RegisterDecorator(Func> handlerFactory) where TElement : Element +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handlerFactory` | `Func>` | A factory that, when invoked, returns a fresh decorator handler. Strongly recommended to be a `static` lambda (e.g. `static () => new ButtonHandler()`) so the delegate is cached in a static field and no closure is allocated. | + +**Type parameters** + +| Name | Description | +| --- | --- | +| `TElement` | The element record type the decorator handler dispatches against. Used as the dispatch key ([`Type`](https://learn.microsoft.com/dotnet/api/system.type)). | + +### `RegisterDecoratorForDerivedTypes` + +Spec 048 §3.4 — decorator sibling of [`ControlRegistry.RegisterForDerivedTypes`](#registerforderivedtypes). + +```csharp +public static void RegisterDecoratorForDerivedTypes(Func> handlerFactory) where TBase : Element +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handlerFactory` | `Func>` | | + +### `RegisterForDerivedTypes` + +Spec 048 §3.4 — base-derived sibling of [`ControlRegistry.Register`](#register). Registers a handler for `TBase` that also catches every concrete element type whose runtime [`Type`](https://learn.microsoft.com/dotnet/api/system.type) derives from `TBase`. Exact-type registrations (via [`ControlRegistry.Register`](#register) / [`ControlRegistry.RegisterDecorator`](#registerdecorator)) take precedence over a base-derived registration, matching the per-host `V1HandlerRegistry.TryGet` precedence. + +Used for the four cases that registered through `Reconciler.RegisterDescriptorForDerivedTypes` on the per-host path: `TemplatedListElementBase`, `LazyStackElementBase`, `ItemsRepeaterElement`, and `ItemsViewElement` — each is a non-generic intermediate base whose closed-T variants (`TemplatedListViewElement`, etc.) should all share the same handler. + +```csharp +public static void RegisterForDerivedTypes(Func> handlerFactory) where TBase : Element where TControl : UIElement +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handlerFactory` | `Func>` | | diff --git a/docs/guide/reference/extensibility/DescriptorHandler.md b/docs/guide/reference/extensibility/DescriptorHandler.md new file mode 100644 index 0000000000..d07e1799d1 --- /dev/null +++ b/docs/guide/reference/extensibility/DescriptorHandler.md @@ -0,0 +1,125 @@ +# DescriptorHandler\ + +Spec 047 §6 / §14 Phase 2 (Q1 spike) — interpreter that drives a [`ControlDescriptor`](ControlDescriptor.md) against the v1 protocol surface. + +Implemented as a regular [`IElementHandler`](IElementHandler.md) so the `V1HandlerAdapter` dispatch shell is identical between the descriptor and hand-coded handler paths — the only thing that differs between the Q1 A|B variants is the body of Mount / Update. Any measured delta is the interpreter's tax, not a different dispatch shape. + +**Mount sequence** (matches the hand-coded handlers' KD-1b ordering): + +1. Rent the control via [`MountContext.RentControl`](lifecycle-contexts.md#rentcontrol). +2. Iterate [`ControlDescriptor.Properties`](ControlDescriptor.md#properties_1) and invoke [`PropEntry.Mount`](PropEntry.md#mounttcontrol-telement) on each — all bare initial writes happen first. +3. Iterate again and invoke [`PropEntry.EnsureSubscribed`](PropEntry.md#ensuresubscribed) — controlled entries wire their change-event trampolines now (no echo on the just- written values because nothing is listening yet). +4. Apply setters. + +```csharp +public class DescriptorHandler : IElementHandler where TElement : Element where TControl : FrameworkElement, new() +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol.Descriptor`. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md), [The Control Reconciler Protocol](../../control-reconciler-protocol.md) + +## Remarks + +Spec 048 §7 — **unsealed** so the built-in catalog can expose a thin, `new()`-constructible registration subclass per descriptor (e.g. `TextBlockDescriptorHandler(): DescriptorHandler<…>(TextBlockDescriptor.Descriptor)`). That subclass is what the `Reg` shim instantiates via its `static () => new THandler()` lambda, so the descriptor path registers through the exact same zero-closure mechanism as a hand-coded handler. The base interpreter has no virtual members the subclass overrides; unsealing carries no dispatch cost (calls already route through the [`IElementHandler`](IElementHandler.md) interface via the adapter). + +## Constructors + +### `DescriptorHandler` + +```csharp +public DescriptorHandler(ControlDescriptor descriptor) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `descriptor` | [`ControlDescriptor`](ControlDescriptor.md) | | + +## Properties + +### `Children` + +Children strategy surfaced to `V1HandlerAdapter`. Returns the descriptor's strategy except when it's an [`ItemsHost`](children-strategies.md#itemshosttelement-tcontrol) — that one is dispatched inline by [`DescriptorHandler.Mount`](#mount) / [`DescriptorHandler.Update`](#update) before the prop loop runs so initial writes like `SelectedIndex` land against a populated collection (matches legacy mount ordering). + +```csharp +public ChildrenStrategy? Children // get +``` + +### `ChildrenForUnmount` + +Issue #375 — on Unmount the bind-before-props ordering constraint that motivates hiding [`ItemsHost`](children-strategies.md#itemshosttelement-tcontrol) / `IItemsBinderStrategy` strategies from [`DescriptorHandler.Children`](#children) no longer applies, so expose the descriptor's real strategy here. Lets `V1HandlerAdapter`'s unmount-side dispatch walk descendant items (e.g. `TabView` tabs whose content holds Components) and fire their `UseEffect` cleanups. + +```csharp +public ChildrenStrategy? ChildrenForUnmount // get +``` + +### `Descriptor` + +The descriptor this handler interprets. Exposed for tests and bench harnesses — not part of the steady-state author API. + +```csharp +public ControlDescriptor Descriptor // get +``` + +## Methods + +### `AfterChildrenMount` + +§14 Phase 3 prelude (Engine A1) — forwards to the descriptor's optional [`ControlDescriptor.AfterChildrenMount`](ControlDescriptor.md#afterchildrenmount) callback. The adapter invokes this after every child has mounted. + +```csharp +public void AfterChildrenMount(MountContext ctx, TElement element, TControl control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`MountContext`](lifecycle-contexts.md#mountcontext) | | +| `element` | `TElement` | | +| `control` | `TControl` | | + +### `Mount` + +```csharp +public TControl Mount(MountContext ctx, TElement el) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`MountContext`](lifecycle-contexts.md#mountcontext) | | +| `el` | `TElement` | | + +### `Unmount` + +Forwards to the descriptor's optional [`ControlDescriptor.OnUnmount`](ControlDescriptor.md#onunmount) hook. Without this the descriptor path had no teardown seam at all, so control-scoped state a descriptor set up during mount — most notably a one-shot `Loaded` subscription carrying a deferred write — could outlive the mount that created it. + +```csharp +public void Unmount(UnmountContext ctx, TControl control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`UnmountContext`](lifecycle-contexts.md#unmountcontext) | | +| `control` | `TControl` | | + +### `Update` + +```csharp +public void Update(UpdateContext ctx, TElement oldEl, TElement newEl, TControl ctrl) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`UpdateContext`](lifecycle-contexts.md#updatecontext) | | +| `oldEl` | `TElement` | | +| `newEl` | `TElement` | | +| `ctrl` | `TControl` | | diff --git a/docs/guide/reference/extensibility/ElementPool.md b/docs/guide/reference/extensibility/ElementPool.md new file mode 100644 index 0000000000..f408b77bc7 --- /dev/null +++ b/docs/guide/reference/extensibility/ElementPool.md @@ -0,0 +1,75 @@ +# ElementPool + +Per-CLR-type pool (cap 32) that recycles unmounted WinUI FrameworkElement instances. V1: pools only non-interactive controls (no event handlers to worry about). + +```csharp +public sealed class ElementPool : IDisposable +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Element Pool](../../element-pool.md) + +## Constructors + +### `ElementPool` + +```csharp +public ElementPool() +``` + +## Properties + +### `Enabled` + +When false, TryRent always returns null and Return is a no-op. Useful for scenarios like the live previewer where recycled controls with stale property state can cause visual glitches. + +```csharp +public bool Enabled // get, set +``` + +## Methods + +### `Clear` + +Empties all per-type stacks and releases the scratch panel. Called from [`Reconciler.Dispose`](Reconciler.md#dispose) to release pooled elements. + +```csharp +public void Clear() +``` + +### `Dispose` + +Releases the resources that this object holds. + +```csharp +public void Dispose() +``` + +### `Return` + +Return an element to the pool after unmount. Cleans it first. Silently drops if the type is not poolable or the pool is full. + +```csharp +public void Return(FrameworkElement element) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `element` | `FrameworkElement` | | + +### `TryRent` + +Try to rent an element of the given type from the pool. Returns null if the pool is empty or the type is not poolable. + +```csharp +public FrameworkElement? TryRent(Type type) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `type` | `Type` | | diff --git a/docs/guide/reference/extensibility/IDecoratorElementHandler.md b/docs/guide/reference/extensibility/IDecoratorElementHandler.md new file mode 100644 index 0000000000..dc2d30eb7d --- /dev/null +++ b/docs/guide/reference/extensibility/IDecoratorElementHandler.md @@ -0,0 +1,84 @@ +# IDecoratorElementHandler\ + +Spec 047 §14 Phase 3 completion — decorator-style V1 handler contract for elements whose returned [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement) identity may change on update or whose unmount disposition diverges from the standard pool-return. + +Use this contract instead of [`IElementHandler`](IElementHandler.md) for: + +- **Target-wrapping decorators** (Flyout, MenuFlyout, CommandBarFlyout) where the returned [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement) IS the user's inner `Target` child — the control type isn't known until the element is inspected, and may change on update if the user swaps Target's element type. +- **Modal lifecycle wrappers** (ContentDialog, Popup) where the returned control is a placeholder and the actual modal surface is created lazily or as a sibling. +- **Polymorphic mounts** (IconElement) where the concrete control type depends on the element's runtime subtype. +- **Interop bridges** (XamlHost, XamlPage) where the returned control hosts arbitrary user-side XAML. + +Distinct from [`IElementHandler`](IElementHandler.md) to keep the §13 Q12 "no substitution" invariant on the standard author-facing surface — only built-in V1 ports use this decorator shape. External authors continue to use [`IElementHandler`](IElementHandler.md). + +```csharp +public interface IDecoratorElementHandler where TElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md), [The Control Reconciler Protocol](../../control-reconciler-protocol.md) + +## Methods + +### `GetSourceTarget` + +Optional source-map override for target-wrapping decorators that return a child element's control but tag that control with the decorator element. Return the child element that created the control so [`ReactorSourceMap.GetSource`](../diagnostics/ReactorSourceMap.md#getsource) reports the target's call site rather than the decorator's. + +```csharp +public Element? GetSourceTarget(TElement element) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `element` | `TElement` | | + +### `Mount` + +Mount the element and return the [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement) the engine installs in the parent's slot. Decorator handlers may recursively mount inner elements via `ctx.MountChild(...)` and return one of them (e.g., FlyoutElement returns its Target's mounted control). + +```csharp +public UIElement Mount(MountContext ctx, TElement element) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`MountContext`](lifecycle-contexts.md#mountcontext) | | +| `element` | `TElement` | | + +### `Unmount` + +Unmount the element and return the engine's post-unmount disposition for the control. The `element` is read from the attached state DP at unmount time; it may be null if the tag was already detached (defensive — should not happen for well-behaved decorator handlers). + +```csharp +public V1UnmountDisposition Unmount(UnmountContext ctx, TElement? element, UIElement control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`UnmountContext`](lifecycle-contexts.md#unmountcontext) | | +| `element` | `TElement?` | | +| `control` | `UIElement` | | + +### `Update` + +Diff old vs. new element and apply updates. Returns the [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement) that should occupy the parent's slot after the update — typically the same `control` instance for an in-place update, or a different instance when the wrapped target changed type. The engine installs the returned value in the slot (replacing `control` if different). + +```csharp +public UIElement Update(UpdateContext ctx, TElement oldEl, TElement newEl, UIElement control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`UpdateContext`](lifecycle-contexts.md#updatecontext) | | +| `oldEl` | `TElement` | | +| `newEl` | `TElement` | | +| `control` | `UIElement` | | diff --git a/docs/guide/reference/extensibility/IElementHandler.md b/docs/guide/reference/extensibility/IElementHandler.md new file mode 100644 index 0000000000..7f2fbf9533 --- /dev/null +++ b/docs/guide/reference/extensibility/IElementHandler.md @@ -0,0 +1,119 @@ +# IElementHandler\ + +Spec 047 §4 / §14 Phase 1 (1.6) — author-facing handler contract for porting a control onto the v1 protocol. + +Implementations register themselves via [`Reconciler.RegisterHandler`](Reconciler.md#registerhandler); dispatch is exact-type by `element.GetType()` (§13 Q17). Update returns `void` — substitution is forbidden (§13 Q12); a type change flows through the unmount-and-remount path on the wrapping container. + +**Hot path:** dispatch is dictionary lookup + interface call (both already paid by `V1HandlerRegistry`). Implementations should avoid allocations in [`IElementHandler.Mount`](#mount) / [`IElementHandler.Update`](#update) bodies; the `ref struct` context types are allocation-free by construction. + +**Echo suppression for value-bearing controls (issue #206).** If the control raises the same change event for a programmatic property write as it does for a user edit, a write from [`IElementHandler.Update`](#update) would echo back through the trampoline into the owning component's `OnChanged` state setter — indistinguishable from real input. Guard every programmatic controlled-value write with the supported, RCW-safe public primitive [`ReactorBinding`](ReactorBinding-1.md)'s `WriteSuppressed` method (or the static [`ReactorBinding`](ReactorBinding.md)): `ctx.BindFor(ctrl, newEl).WriteSuppressed(() => ctrl.Value = newEl.Value)`. Pair it 1:1 with the write and gate it on an equality check so the token is always consumed by the engine-provoked echo. Descriptor authors get this for free through `.Controlled` / `.HandCodedControlled`. Never reach into the internal `ChangeEchoSuppressor`. See `docs/guide/extending-reactor-controls.md`. + +```csharp +public interface IElementHandler where TElement : Element where TControl : UIElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md), [The Control Reconciler Protocol](../../control-reconciler-protocol.md) + +## Properties + +### `Children` + +Optional children strategy. Engine dispatches through it when non-null (and not [`None`](children-strategies.md#nonetelement-tcontrol)); otherwise the handler is a leaf for the purposes of child reconciliation. + +```csharp +public virtual ChildrenStrategy? Children // get +``` + +### `ChildrenForUnmount` + +Issue #375 — children strategy the engine uses for the unmount-side child walk. Defaults to [`IElementHandler.Children`](#children); some implementations (notably [`DescriptorHandler`](DescriptorHandler.md)) suppress [`IElementHandler.Children`](#children) when they dispatch a strategy inline during Mount/Update for ordering reasons (e.g. items-binder strategies whose collection must be populated before `SelectedIndex` initial writes land). On Unmount the ordering constraint no longer applies, so they expose the real strategy here so descendant Component `UseEffect` cleanups still fire. + +```csharp +public virtual ChildrenStrategy? ChildrenForUnmount // get +``` + +## Methods + +### `AfterChildrenMount` + +Spec 047 §14 Phase 3 prelude (Engine A1) — optional hook the engine invokes from `V1HandlerAdapter` after the [`IElementHandler.Children`](#children) strategy has mounted/bound every child (and after any items-binder strategy the handler dispatched inline). Default no-op. + +Override this to wire events whose subscription must happen strictly after children-add — e.g. `TabView.SelectionChanged`, which WinUI fires spuriously while the first tab is being added if the handler subscribes during the prop-apply phase. Subscribing here side- steps that first-add echo. + +```csharp +public void AfterChildrenMount(MountContext ctx, TElement element, TControl control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`MountContext`](lifecycle-contexts.md#mountcontext) | | +| `element` | `TElement` | | +| `control` | `TControl` | | + +### `Mount` + +Create or rent the WinUI control, apply initial writes, and subscribe event trampolines. Returns the control the engine places into the parent's children collection. + +```csharp +public TControl Mount(MountContext ctx, TElement element) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`MountContext`](lifecycle-contexts.md#mountcontext) | | +| `element` | `TElement` | | + +### `ReconcileChildren` + +Optional override for handlers that want to drive child reconciliation manually instead of through [`IElementHandler.Children`](#children). Phase 1 strategy dispatch routes through [`IElementHandler.Children`](#children); this overload is retained for parity with the spec §4 surface and Phase 3 use. + +```csharp +public void ReconcileChildren(MountContext ctx, TElement oldEl, TElement newEl, TControl control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`MountContext`](lifecycle-contexts.md#mountcontext) | | +| `oldEl` | `TElement` | | +| `newEl` | `TElement` | | +| `control` | `TControl` | | + +### `Unmount` + +Optional override for handlers with explicit teardown (e.g. control-side IDisposable resources). Default no-op — the engine still runs the pool reset contract. + +```csharp +public void Unmount(UnmountContext ctx, TControl control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`UnmountContext`](lifecycle-contexts.md#unmountcontext) | | +| `control` | `TControl` | | + +### `Update` + +Diff `oldEl` vs `newEl` and apply minimal writes to `control`. Returns void: the control identity is preserved (§13 Q12). + +```csharp +public void Update(UpdateContext ctx, TElement oldEl, TElement newEl, TControl control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`UpdateContext`](lifecycle-contexts.md#updatecontext) | | +| `oldEl` | `TElement` | | +| `newEl` | `TElement` | | +| `control` | `TControl` | | diff --git a/docs/guide/reference/extensibility/PathDataParser.md b/docs/guide/reference/extensibility/PathDataParser.md new file mode 100644 index 0000000000..98ae146a54 --- /dev/null +++ b/docs/guide/reference/extensibility/PathDataParser.md @@ -0,0 +1,23 @@ +# PathDataParser + +Parses SVG path data strings into WinUI PathGeometry. General-purpose SVG-path parsing — lives in core so the Path control and other consumers can use it without the core depending on the Charting subsystem. Handles the subset of commands output by D3's PathBuilder. + +```csharp +public static class PathDataParser +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +## Methods + +### `Parse` + +```csharp +public static Geometry Parse(string pathData) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `pathData` | `string` | | diff --git a/docs/guide/reference/extensibility/PoolPolicy.md b/docs/guide/reference/extensibility/PoolPolicy.md new file mode 100644 index 0000000000..b22c89a38c --- /dev/null +++ b/docs/guide/reference/extensibility/PoolPolicy.md @@ -0,0 +1,43 @@ +# PoolPolicy\ + +Spec 047 §13 Q18 / §14 Phase 1 (1.5) — author-facing pool policy. + +External and built-in V1 handlers attach a `PoolPolicy` to their `RentControl` / `ReturnControl` calls to opt out of pooling (e.g. for controls with persistent native resources like MediaPlayerElement, MapControl, SwapChainPanel) or to layer an author-defined reset action on top of the engine's default contract. + +Pool key is `typeof(TControl)` only (Q18). Finer keys (e.g. by style hash) are a Phase 3+ addition. + +Provisional surface — see [`ReactorBinding`](ReactorBinding.md) for the `REACTOR_V1_PREVIEW` diagnostic id. + +```csharp +public sealed class PoolPolicy where TControl : class +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Element Pool](../../element-pool.md) + +## Constructors + +### `PoolPolicy` + +```csharp +public PoolPolicy() +``` + +## Properties + +### `IsPoolable` + +When false, `RentControl` always allocates a fresh instance and `ReturnControl` is a no-op (the control is dropped on the floor for the GC to collect). Default true. + +```csharp +public bool IsPoolable // get, init +``` + +### `Reset` + +Optional extra reset action invoked AFTER the engine's default contract clears (ControlEventState, ModifierEventHandlerState, ReactorAttached.StateProperty Tag, Reactor-set DataContext). Use for control-specific transient state the engine can't know about (e.g. ScrollViewer.ChangeView animation queue). + +```csharp +public Action? Reset // get, init +``` diff --git a/docs/guide/reference/extensibility/PropEntry.md b/docs/guide/reference/extensibility/PropEntry.md new file mode 100644 index 0000000000..b891c96bec --- /dev/null +++ b/docs/guide/reference/extensibility/PropEntry.md @@ -0,0 +1,116 @@ +# PropEntry\ + +Spec 047 §6 / §14 Phase 2 (Q1 spike) — base class for descriptor entries declared on a [`ControlDescriptor`](ControlDescriptor.md). + +The interpreter (see [`DescriptorHandler`](DescriptorHandler.md)) iterates the entry list during Mount and Update. The property's value type stays inside each concrete entry — the interpreter never sees it, so iterating a heterogeneous list of entries does not box value types (each generic specialization keeps its own monomorphic code path). + +**Phase ordering inside Mount:** + +1. [`PropEntry.Mount`](#mounttcontrol-telement) runs once per entry. Controlled entries write their initial value bare — event subscription has not yet been wired, so a synchronous change event has no trampoline to fire (no echo). Mirrors the KD-1b fix on the hand-coded handlers. A control whose change event is raised after the write returns echoes after the wiring below; its entry arms the Mount write instead (`HandCodedControlled`'s `armOnMount`). +2. [`PropEntry.EnsureSubscribed`](#ensuresubscribed) runs once per entry. Controlled entries subscribe to their change event here, guarded by [`DescriptorHandler`](DescriptorHandler.md)'s per-control subscription gate (so pool-reused controls do not double-subscribe). + +On Update, [`PropEntry.Update`](#updatetcontrol-telement-telement) runs and writes through `ReactorBinding.WriteSuppressed` when the entry is controlled. + +```csharp +public abstract class PropEntry where TElement : Element where TControl : UIElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol.Descriptor`. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md), [The Control Reconciler Protocol](../../control-reconciler-protocol.md) + +## Constructors + +### `PropEntry` + +```csharp +protected PropEntry() +``` + +## Methods + +### `EnsureSubscribed` + +Event subscription hook. Default = no-op (one-way / initial entries do not subscribe to events). Controlled entries override. + +The interpreter calls this after every [`PropEntry.Mount`](#mounttcontrol-telement) in the entry list so all bare initial writes complete before any event trampoline goes live (KD-1b ordering invariant). + +```csharp +public virtual void EnsureSubscribed(ReactorBinding binding, TControl ctrl, TElement el) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `binding` | [`ReactorBinding`](ReactorBinding-1.md) | | +| `ctrl` | `TControl` | | +| `el` | `TElement` | | + +### `Mount` + +#### `Mount(TControl, TElement)` + +Initial write at Mount. Controlled entries write bare here (no echo suppression — subscription has not yet been wired). + +```csharp +public abstract void Mount(TControl ctrl, TElement el) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctrl` | `TControl` | | +| `el` | `TElement` | | + +#### `Mount(MountContext, TControl, TElement)` + +Spec 047 §14 Phase 3-final — context-carrying Mount overload. Default implementation forwards to the parameterless [`PropEntry.Mount`](#mounttcontrol-telement); entry types that need reconciler/rerender access (e.g. `OneWayBridgedPropEntry` for Flyout descriptor bridging) override this overload instead. + +```csharp +public virtual void Mount(in MountContext ctx, TControl ctrl, TElement el) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`MountContext`](lifecycle-contexts.md#mountcontext) | | +| `ctrl` | `TControl` | | +| `el` | `TElement` | | + +### `Update` + +#### `Update(TControl, TElement, TElement)` + +Diff old/new element and apply the minimal write. Controlled entries write through `ReactorBinding.WriteSuppressed`. + +```csharp +public abstract void Update(TControl ctrl, TElement oldEl, TElement newEl) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctrl` | `TControl` | | +| `oldEl` | `TElement` | | +| `newEl` | `TElement` | | + +#### `Update(UpdateContext, TControl, TElement, TElement)` + +Spec 047 §14 Phase 3-final — context-carrying Update overload. Same forwarding contract as [`PropEntry.Mount`](#mountmountcontext-tcontrol-telement). + +```csharp +public virtual void Update(in UpdateContext ctx, TControl ctrl, TElement oldEl, TElement newEl) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `ctx` | [`UpdateContext`](lifecycle-contexts.md#updatecontext) | | +| `ctrl` | `TControl` | | +| `oldEl` | `TElement` | | +| `newEl` | `TElement` | | diff --git a/docs/guide/reference/extensibility/ReactorBinding-1.md b/docs/guide/reference/extensibility/ReactorBinding-1.md new file mode 100644 index 0000000000..47f2f8f153 --- /dev/null +++ b/docs/guide/reference/extensibility/ReactorBinding-1.md @@ -0,0 +1,271 @@ +# ReactorBinding\ + +Spec 047 §9 / §14 Phase 1 (1.6) — per-binding event helper. + +One `On` method per WinUI true-routed input family (pointer, key, tap, focus). Plain CLR events (Toggled, Click, ValueChanged, TextChanged) go through [`ReactorBinding.OnCustomEvent`](#oncustomevent); that path stores its delegate in the per-control event payload box (`ControlEventStateBox`) so pool/recycle correctly clears it. + +**Trampoline-refresh pattern** (§3): the handler closure captures [`ReactorBinding._control`](ReactorBinding-1.md) but NOT the element. On each event fire, the live element is re-read via [`Reconciler.GetElementTag`](Reconciler.md#getelementtagframeworkelement); the binding survives re-renders without resubscribing. + +**WriteSuppressed** wraps the 1.4 primitive so authors can suppress the next change-event echo on the bound control. + +```csharp +public readonly struct ReactorBinding where TElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md), [The Control Reconciler Protocol](../../control-reconciler-protocol.md) + +## Properties + +### `Control` + +The control the binding is anchored to. + +```csharp +public FrameworkElement Control // get +``` + +## Methods + +### `OnCustomEvent` + +Spec 047 §9.2 — subscribe to a plain CLR event (Toggled, Click, ValueChanged, TextChanged …). The handler closure re-fetches the live element via [`Reconciler.GetElementTag`](Reconciler.md#getelementtagframeworkelement) on each fire so it survives re-renders. + +The subscription is anchored to the control's lifetime. The engine's pool reset contract clears the per-control event payload on return, so ported handlers are safe to call this once per Mount. Handlers should NOT call it inside [`IElementHandler.Update`](IElementHandler.md#update) (subscriptions would multiply across renders). + +```csharp +public void OnCustomEvent(Action> subscribe, Action> unsubscribe, Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `subscribe` | `Action>` | | +| `unsubscribe` | `Action>` | | +| `handler` | `Action` | | + +### `OnDoubleTapped` + +```csharp +public void OnDoubleTapped(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnGotFocus` + +```csharp +public void OnGotFocus(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnHolding` + +```csharp +public void OnHolding(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnKeyDown` + +```csharp +public void OnKeyDown(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnKeyUp` + +```csharp +public void OnKeyUp(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnLostFocus` + +```csharp +public void OnLostFocus(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnPointerCaptureLost` + +```csharp +public void OnPointerCaptureLost(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnPointerEntered` + +```csharp +public void OnPointerEntered(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnPointerExited` + +```csharp +public void OnPointerExited(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnPointerMoved` + +```csharp +public void OnPointerMoved(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnPointerPressed` + +```csharp +public void OnPointerPressed(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnPointerReleased` + +```csharp +public void OnPointerReleased(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnPointerWheelChanged` + +```csharp +public void OnPointerWheelChanged(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnRightTapped` + +```csharp +public void OnRightTapped(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `OnTapped` + +```csharp +public void OnTapped(Action handler) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | `Action` | | + +### `Reference` + +Registers a reference-property edge for hand-coded handlers. Slot indices are assigned by call order for each `BindFor` instance and offset away from descriptor slots; repeated reconciles of the same handler call order therefore hit the same per-control reference slot. + +```csharp +public void Reference(Func?> get, Action set) where TTarget : FrameworkElement +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `get` | `Func?>` | | +| `set` | `Action` | | + +### `ReferenceList` + +Registers a list-valued reference-property edge for hand-coded handlers. The target list is rebuilt from resolved cells in author declaration order. + +```csharp +public void ReferenceList(Func>?> get, Action> apply) where TTarget : FrameworkElement +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `get` | `Func>?>` | | +| `apply` | `Action>` | | + +### `WriteSuppressed` + +Per-binding wrapper around the 1.4 primitive ([`ReactorBinding.WriteSuppressed`](ReactorBinding.md#writesuppresseduielement-action)). + +```csharp +public void WriteSuppressed(Action mutate) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `mutate` | `Action` | | diff --git a/docs/guide/reference/extensibility/ReactorBinding.md b/docs/guide/reference/extensibility/ReactorBinding.md new file mode 100644 index 0000000000..a47b3719a1 --- /dev/null +++ b/docs/guide/reference/extensibility/ReactorBinding.md @@ -0,0 +1,75 @@ +# ReactorBinding + +Spec 047 §14 Phase 1 (1.4) — public author-facing surface for the echo suppression primitive (§13 Q19). Today this delegates to `ChangeEchoSuppressor.BeginSuppress`; Phase 4 swaps the body for per-control tolerance / coercion metadata as part of the §8 cleanup — the signature does not change. The per-binding wrapper `ReactorBinding` (per spec §4) lands in 1.6; this static class is just the primitive entry point. + +```csharp +public static class ReactorBinding +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md) + +## Methods + +### `ShouldSuppressEcho` + +Read-side counterpart of [`ReactorBinding.WriteSuppressed`](#writesuppresseduielement-action). Call as the first line of a change-event handler: returns `true` when the current fire is the engine-synthesized echo of a prior `WriteSuppressed` write against `target` — **consuming one suppression token** on that counter-based path — so the handler should return early before invoking the user's callback. It also returns `true` *without* consuming a token while inside the non-consuming `ApplySetters` suppression scope. Returns `false` for a genuine user interaction (no outstanding token/scope), for a target that is not a [`FrameworkElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.frameworkelement), or when the target carries no Reactor state. + +This is the public primitive the wrapper generator emits for a `[WrapControlled(Deferred = true)]` prop, so a deferred-controlled generated wrapper compiles against Reactor's public surface alone (no `InternalsVisibleTo`) — the read-side gap called out in spec 062 §14. It maps to the counter/scope channel (paired with `WriteSuppressed`), not the value-diff channel. + +```csharp +public static bool ShouldSuppressEcho(UIElement target) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `target` | `UIElement` | | + +**Exceptions** + +| Exception | Condition | +| --- | --- | +| [`ArgumentNullException`](https://learn.microsoft.com/dotnet/api/system.argumentnullexception) | `target` is `null`. | + +### `WriteSuppressed` + +#### `WriteSuppressed(UIElement, Action)` + +Runs `mutate` after registering a one-shot suppression token for `target`. The next change-event handler invocation against `target` consumes the token via `ChangeEchoSuppressor.ShouldSuppress` and short-circuits before the user's OnChanged callback fires. + +No try/finally — the consumption is event-driven and the counter is harmless if a single token is left at +1 after an exceptional path (it gets consumed by the next change event for that control, which by contract should be one the engine itself just provoked). + +```csharp +public static void WriteSuppressed(UIElement target, Action mutate) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `target` | `UIElement` | | +| `mutate` | `Action` | | + +#### `WriteSuppressed(T, Action)` + +Typed overload — saves a cast at the call site for the common case where the handler already has a strongly-typed control reference. + +```csharp +public static void WriteSuppressed(T target, Action mutate) where T : UIElement +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `target` | `T` | | +| `mutate` | `Action` | | + +**Exceptions** + +| Exception | Condition | +| --- | --- | +| [`ArgumentNullException`](https://learn.microsoft.com/dotnet/api/system.argumentnullexception) | `target` or `mutate` is `null`. | diff --git a/docs/guide/reference/extensibility/ReactorFeatureFlags.md b/docs/guide/reference/extensibility/ReactorFeatureFlags.md new file mode 100644 index 0000000000..86b89ab537 --- /dev/null +++ b/docs/guide/reference/extensibility/ReactorFeatureFlags.md @@ -0,0 +1,67 @@ +# ReactorFeatureFlags + +Process-wide feature flags that gate risky or in-progress behavior. Each flag is a plain mutable boolean so apps can flip it on startup; the defaults are chosen to preserve existing behavior. + +```csharp +public static class ReactorFeatureFlags +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +## Remarks + +A flag lives here only while its feature is rolling out. Once a flag's default flips to `true` and has soaked for a release, the flag is removed along with the legacy code path it was gating — leaving permanent config knobs here would slow future refactors. + +Flags are read lazily — changes after a feature has already initialized are not guaranteed to take effect. Tests that need to toggle a flag should save and restore the value around the scope that depends on it. + +## Properties + +### `FocusRevalidation` + +When true, stale `UseResource` entries refetch on window activation / app resume events. Per-resource opt-out is exposed through `ResourceOptions.RefetchOnWindowFocus` (default `false`). + +```csharp +public static bool FocusRevalidation // get, set +``` + +**Remarks** + +Default: `false`. This mirrors TanStack Query's opt-in posture — window-focus revalidation is surprising in desktop apps where Alt-Tab is a common idiom. + +### `HighlightReconcileChanges` + +When true, the reconciler records which `UIElement`s were mounted or modified during each pass and Reactor hosts ([`ReactorHost`](../hosting/ReactorHost.md) and [`ReactorHostControl`](../hosting/ReactorHostControl.md), via the shared `HighlightOverlayWiring`) draw semi-transparent overlays (red = new mount, yellow = property update) so you can visualize reconcile impact. The overlay is rendered via Composition visuals and is hit-test invisible. + +```csharp +public static bool HighlightReconcileChanges // get, set +``` + +**Remarks** + +Default: `false`. Intended for interactive debugging sessions. When off, the reconciler skips all collection work so there is zero overhead. + +### `UseHookBasedPaging` + +When true, `DataGridComponent` reads paged data through `UseInfiniteResource` / `UseDataSource` instead of the legacy `DataPageCache`. Part of the Phase-3 migration in `docs/specs/020-async-resources-design.md` §11. + +```csharp +public static bool UseHookBasedPaging // get, set +``` + +**Remarks** + +Default: `false`. The hook-based path is covered by `DataGridParityFixtures` but is not yet the default for consumers with custom `IDataSource` implementations. + +### `WarnLayoutFootguns` + +When true, the reconciler emits a one-time diagnostic warning — at mount and on update — for layout "footguns" that silently collapse to `0×0` — most notably an `HStack`/`VStack` placed in a `Grid` [`GridSize.Auto`](../layout/GridSize.md#auto) track with no explicit size and no explicitly-sized children (issue #345). Each warning is written to `Debug.WriteLine`. + +```csharp +public static bool WarnLayoutFootguns // get, set +``` + +**Remarks** + +Default: `false`. In `DEBUG` builds the detection is always on regardless of this flag — the flag is the opt-in switch for `Release` builds. When off in `Release` the detection call site is gated by a single read of this flag per mounted/updated element (the check then no-ops for any non-`Grid` element), so it is effectively free. + +Detection runs on both the mount and update reconcile paths, so a warning can appear after a state-driven layout change (e.g. a column flipped to `Auto` or an explicit size removed), not just on first render. Each distinct offending placement warns at most once per process. diff --git a/docs/guide/reference/extensibility/Reconciler.md b/docs/guide/reference/extensibility/Reconciler.md new file mode 100644 index 0000000000..c52b557ffd --- /dev/null +++ b/docs/guide/reference/extensibility/Reconciler.md @@ -0,0 +1,456 @@ +# Reconciler + +The reconciler diffs old and new element trees and patches the real WinUI control tree. + +Split across partial classes: - Reconciler.cs — orchestration, children, unmount, helpers - Reconciler.Mount.cs — Mount() dispatch + per-control MountXxx methods - Reconciler.Update.cs — Update() dispatch + per-control UpdateXxx methods + +```csharp +public sealed class Reconciler : IDisposable +``` + +Namespace: `Microsoft.UI.Reactor.Core`. + +**Learn more:** [Reconciliation](../../reconciliation.md) + +## Constructors + +### `Reconciler` + +Spec 047 §14 — the V1 protocol is the unconditional production path. The Phase 1 `UseV1Protocol` feature flag, its AppContext switch, and the descriptor-vs-handler A|B harness ctor were all removed in §4.6 once the legacy `MountXxx`/`UpdateXxx` switch was deleted (§4.5). + +Built-in V1 handlers register automatically into the internal `V1HandlerRegistry`; external authors add handlers via [`Reconciler.RegisterHandler`](#registerhandler) / [`Reconciler.RegisterType`](#registertype) (which populate `_typeRegistry`). Dispatch order is V1 → external → the four composition primitives that sit above the protocol. + +```csharp +public Reconciler(ILogger? logger = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `logger` | `ILogger?` | `null` | | + +## Properties + +### `EnableBitmaskDiff` + +```csharp +public static bool EnableBitmaskDiff // get, set +``` + +### `LastModifiedElements` + +UIElements that were modified in-place during the last top-level Reconcile pass. Only populated when [`ReactorFeatureFlags.HighlightReconcileChanges`](ReactorFeatureFlags.md#highlightreconcilechanges) is true; returns an empty list otherwise so callers never see stale data after the flag is toggled off. + +```csharp +public IReadOnlyList LastModifiedElements // get +``` + +### `LastMountedElements` + +UIElements that were newly mounted during the last top-level Reconcile pass. Only populated when [`ReactorFeatureFlags.HighlightReconcileChanges`](ReactorFeatureFlags.md#highlightreconcilechanges) is true; returns an empty list otherwise so callers never see stale data after the flag is toggled off. + +```csharp +public IReadOnlyList LastMountedElements // get +``` + +### `Pool` + +The element pool used by this reconciler. Disable via Pool.Enabled = false to prevent recycled controls from retaining stale property state. + +```csharp +public ElementPool Pool // get +``` + +## Methods + +### `ApplyDefaultAutomationName` + +Spec 047 §14 Phase 1 (1.3) — promoted from internal. Mirrors a control's caption into `AutomationProperties.Name` when the author has not set one explicitly, so UIA clients that read the attached property directly (not via the peer) still find the name. Provisional API; see `REACTOR_V1_PREVIEW`. + +```csharp +public static void ApplyDefaultAutomationName(FrameworkElement fe, string? caption) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `fe` | `FrameworkElement` | | +| `caption` | `string?` | | + +### `ApplyResourceOverrides` + +#### `ApplyResourceOverrides(FrameworkElement, ResourceOverrides?, ResourceOverrides?)` + +Applies per-control resource overrides (lightweight styling) to a [`FrameworkElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.frameworkelement). Literal values are set directly; [`ThemeRef`](../theming/ThemeRef.md)-based values are resolved from `Application.Current.Resources` using the element's own effective theme. + +```csharp +public static void ApplyResourceOverrides(FrameworkElement fe, ResourceOverrides? oldOverrides, ResourceOverrides? newOverrides) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `fe` | `FrameworkElement` | | +| `oldOverrides` | [`ResourceOverrides?`](../theming/ResourceOverrides.md) | | +| `newOverrides` | [`ResourceOverrides?`](../theming/ResourceOverrides.md) | | + +**Remarks** + +Binary-compatible original 3-arg surface (Spec 047 §14 Phase 1 (1.3), promoted from private per audit existing-api-surface.md). Delegates to the 4-arg overload with [`ElementTheme.Default`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.elementtheme.default); the reconciler uses the 4-arg form to pass an explicit ancestor-aware theme (needed at mount, before the control is parented). Provisional API; see `REACTOR_V1_PREVIEW`. + +#### `ApplyResourceOverrides(FrameworkElement, ResourceOverrides?, ResourceOverrides?, ElementTheme)` + +Applies per-control resource overrides (lightweight styling), resolving [`ThemeRef`](../theming/ThemeRef.md)-backed values against an explicit `effectiveTheme`. Provisional API (Spec 047 §14 Phase 1); see `REACTOR_V1_PREVIEW`. + +```csharp +public static void ApplyResourceOverrides(FrameworkElement fe, ResourceOverrides? oldOverrides, ResourceOverrides? newOverrides, ElementTheme effectiveTheme) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `fe` | `FrameworkElement` | The control whose `Resources` receive the overrides. | +| `oldOverrides` | [`ResourceOverrides?`](../theming/ResourceOverrides.md) | The previously-applied overrides, or null at mount. | +| `newOverrides` | [`ResourceOverrides?`](../theming/ResourceOverrides.md) | The overrides to apply, or null to clear managed keys. | +| `effectiveTheme` | `ElementTheme` | The ancestor-aware effective theme threaded by the reconciler. When non-Default, ThemeRef-backed overrides resolve their concrete brush against it via [`ThemeRef.Resolve`](../theming/ThemeRef.md#resolve) — necessary at mount, where the element is not yet parented and so an ancestor `RequestedTheme` is unreachable through `fe`'s own visual-tree walk. Pass [`ElementTheme.Default`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.elementtheme.default) to fall back to fe-based resolution (for example, callers of the 3-arg overload). | + +### `ApplySetters` + +Spec 047 §14 Phase 1 (1.3) — promoted from internal. Runs each setter inside the §8.2 echo-suppression scope so user-authored `.Set(c => c.IsOn = true)` writes don't echo through the engine-wired OnXChanged callback. Provisional API; see `REACTOR_V1_PREVIEW`. + +```csharp +public static void ApplySetters(Action[] setters, T control) where T : class +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `setters` | `Action[]` | | +| `control` | `T` | | + +### `ApplyThemeBindings` + +Applies ThemeRef bindings by setting properties through WinUI's \{ThemeResource\} mechanism. Builds a local Style with ThemeResource setters and applies it to the element. WinUI then handles theme-reactive resolution natively — the live \{ThemeResource\} Style setter re-resolves on the control's effective-theme change, which tracks the per-element/inherited `ActualTheme` (an ancestor `RequestedTheme` override included), not just the app-level theme. This native self-heal is why a ThemeBindings-only element is safe to structurally skip (#758; empirically verified in `ThemeBindingsSkipSelfHealFixtures` across immediate and inherited ancestor `RequestedTheme` toggles). Contrast a `ResourceOverrides.ThemeRef`, which resolves to a CONCRETE brush at reconcile and does NOT self-heal (so it stays theme-sensitive for the skip gate). + +```csharp +public static void ApplyThemeBindings(FrameworkElement fe, IReadOnlyDictionary bindings) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `fe` | `FrameworkElement` | | +| `bindings` | `IReadOnlyDictionary` | | + +### `DetachReactorState` + +Fully detaches reactor state from a control: nulls the Element and clears the ModifierEventHandlerState's Current\* delegates so any already- attached trampoline on the native event source becomes a no-op if it fires. Use when the control leaves reactor's ownership for good (XamlHost / XamlPage unmount) but may remain alive because the app holds a reference — without this, captured closures stay reachable and stale reactor callbacks can still fire. + +```csharp +public static void DetachReactorState(FrameworkElement fe) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `fe` | `FrameworkElement` | | + +### `Dispose` + +Releases the resources that this object holds. + +```csharp +public void Dispose() +``` + +### `FlushConnectedAnimations` + +Starts all queued connected animations. Call AFTER the new tree has been attached to the visual tree (e.g., after Window.Content = newControl). + +```csharp +public void FlushConnectedAnimations() +``` + +**Remarks** + +Source and destination must appear in the SAME reconcile pass — that is the shape Reactor's model produces, since a single state change swaps both subtrees. + +### `GetElementTag` + +#### `GetElementTag(FrameworkElement)` + +Spec 047 §14 Phase 1 (1.3) — promoted from internal. Provisional API; see `REACTOR_V1_PREVIEW`. + +```csharp +public static Element? GetElementTag(FrameworkElement fe) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `fe` | `FrameworkElement` | | + +**Remarks** + +For the built-in Flyout, MenuFlyout, and CommandBarFlyout decorators, this reads the target's tag; decorator identity is stored separately. + +#### `GetElementTag(UIElement)` + +Spec 047 §14 Phase 1 (1.3) — promoted from internal. Retrieves the element associated with a control, or null. Provisional API; see `REACTOR_V1_PREVIEW`. + +```csharp +public static Element? GetElementTag(UIElement control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `control` | `UIElement` | | + +**Remarks** + +For the built-in Flyout, MenuFlyout, and CommandBarFlyout decorators, this reads the target's tag; decorator identity is stored separately. + +### `Mount` + +Creates a WinUI control tree from an Element tree. Returns null for EmptyElement. + +```csharp +public UIElement? Mount(Element element, Action requestRerender) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `element` | [`Element`](../elements/Element.md) | | +| `requestRerender` | `Action` | | + +### `Reconcile` + +Reconciles one child slot: brings `existingControl`, the control mounted for `oldElement`, up to date with `newElement`, and returns the control the slot should now hold. + +```csharp +public UIElement? Reconcile(Element? oldElement, Element? newElement, UIElement? existingControl, Action requestRerender) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `oldElement` | [`Element?`](../elements/Element.md) | | +| `newElement` | [`Element?`](../elements/Element.md) | | +| `existingControl` | `UIElement?` | | +| `requestRerender` | `Action` | | + +**Remarks** + +When `newElement` has the element type and key of `oldElement`, the control is patched in place and returned unchanged, unless the update had to build a new control. In every other case the old control is unmounted before the new one is returned: a changed element type or key, an update that built a new control, or a null or empty `newElement`, which returns null. Without an `existingControl` the new element is mounted. Put the result in the slot when it differs from `existingControl`. A custom control updates the child elements it hosts with this method; in an `IElementHandler`, `UpdateContext.ReconcileChild` does the same. + +### `RegisterHandler` + +Spec 047 §14 Phase 1 (1.6 / 1.9) — register a v1 [`IElementHandler`](IElementHandler.md) for the given element type. Dispatched ahead of [`Reconciler.RegisterType`](#registertype) callbacks. Throws on duplicate (including across registries) and on open-generic element types (spec §13 Q17). + +```csharp +public void RegisterHandler(IElementHandler handler) where TElement : Element where TControl : UIElement +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | [`IElementHandler`](IElementHandler.md) | | + +**Remarks** + +Value-bearing handlers (a control whose programmatic property write raises the same change event as a user edit) must suppress their own write echo with the supported public primitive [`ReactorBinding`](ReactorBinding-1.md)'s `WriteSuppressed` method (or the static [`ReactorBinding`](ReactorBinding.md)); descriptor authors get it via `.Controlled` / `.HandCodedControlled`. See [`IElementHandler`](IElementHandler.md) and `docs/guide/extending-reactor-controls.md` (issue #206). + +### `RegisterHandlerForDerivedTypes` + +§14 Phase 3 close-out — register a v1 handler that catches every closed runtime type whose chain reaches `TBase`. Used by the typed templated-list descriptor ports (`TemplatedListViewElement` family) so a single registration on a non-generic intermediate base routes every closed-T variant — same T-erasure pattern the legacy [`Reconciler.Mount`](#mount) switch uses. + +Exact-type registrations via [`Reconciler.RegisterHandler`](#registerhandler) always win over a derived-type registration. Throws on duplicate base-type registration. + +```csharp +public void RegisterHandlerForDerivedTypes(IElementHandler handler) where TBase : Element where TControl : UIElement +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `handler` | [`IElementHandler`](IElementHandler.md) | | + +### `RegisterType` + +Registers a custom element type so the reconciler knows how to mount, update, and unmount it. Registered types take priority over built-in types. + +Spec 047 §13 Q17 / §14 Phase 1 (1.9) — v1 semantics: - Exact-type lookup via `element.GetType()`; no base-class fallback. - Throws [`InvalidOperationException`](https://learn.microsoft.com/dotnet/api/system.invalidoperationexception) on duplicate registration, including duplicates against a previously-registered V1 handler (`V1HandlerRegistry`). - Throws on open-generic element types. + +The mount and update handlers receive the Reconciler instance so they can recursively mount/update/unmount child elements without capturing external state. + +The reconciler records the element on the control it gets back from `mount` or `update` (the element tag) wherever it reads the tag back itself: keyed reconciliation, the `unmount` lookup, `.Ref(...)` cleanup and exit transitions. The callbacks don't call [`Reconciler.SetElementTag`](#setelementtag) for those. Code of your own that reads the element back with [`Reconciler.GetElementTag`](#getelementtagframeworkelement), such as an event handler, still tags the control itself. The tag lives on a [`FrameworkElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.frameworkelement). `TControl` may be declared as [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement), but in WinUI 3 [`FrameworkElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.frameworkelement) is its only subclass, so every control a registration returns is tagged the same way. + +`mount` and `update` are expected to return a control the registration owns. The tag holds one element, so a control that already carries the tag of an element of another type (registration is by exact type, so a derived type counts), for example one `mount` got from [`Reconciler.Mount`](#mount) for a child element, keeps that tag: overwriting it would silence that element's own callbacks (the collision issue #942 tracks for target-wrapping decorators). The registration's key, ref, transitions and `unmount` are not tracked for such a control. To wrap built-in elements, compose them in a component instead. + +`update` returns null after patching the control in place; returning the control it was handed means the same. Return a different control only when you replaced it. + +`unmount` runs when the reconciler unmounts the control, in place of its own walk over the control's children: a child the callbacks mounted through the reconciler has to be torn down there, for example with [`Reconciler.UnmountChild`](#unmountchild). Calling [`Reconciler.UnmountChild`](#unmountchild) on the control itself from `unmount` walks its children once rather than calling `unmount` again. Without an `unmount` callback the reconciler walks the control's children itself. A control that `update` replaced is unmounted wherever the reconciler reconciles the slot that holds it: a panel, a `Border`, a named slot such as `SplitView.Pane`, a tab's content. A few slots that a control fills by hand still swap a replaced control out without `unmount`: `CommandBar` content, `Expander` content and header template, `ContentDialog`, `Flyout` and `Popup` content, content attached with `.WithFlyout`, `.WithContextFlyout` or `.WithToolTip(element)`, and the realized item content of `ListView`, `GridView`, `TreeView` and templated `FlipView`. + +Not part of the `REACTOR_V1_PREVIEW` surface — this is the legacy type-registry path, public since before Spec 047. The §13 Q17 hardening (throw on duplicate, no base-class fallback, no open generics) tightens previously-undefined behavior; it does not change the shape of this API. + +```csharp +public void RegisterType(Func mount, Func update, Action? unmount = null) where TElement : Element where TControl : UIElement +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `mount` | `Func` | | | +| `update` | `Func` | | | +| `unmount` | `Action?` | `null` | | + +**Remarks** + +A value-bearing custom control (one that raises the same change event for a programmatic write as for a user edit) must suppress its own write echo from the `update` callback. Use the supported public primitive [`ReactorBinding`](ReactorBinding.md)'s `WriteSuppressed` method — wrap the programmatic write, gate it on an equality check, and pair it 1:1 with the write. For new controls prefer the V1 path: a [`ControlDescriptor`](ControlDescriptor.md) (the primary, descriptor-first authoring shape — its `.Controlled` / `.HandCodedControlled` handle echo suppression for you), or a hand-coded [`IElementHandler`](IElementHandler.md) via [`Reconciler.RegisterHandler`](#registerhandler) only for irregular controls (its [`ReactorBinding`](ReactorBinding-1.md) wraps the same primitive). See `docs/guide/extending-reactor-controls.md` (issue #206). + +### `RentControl` + +Spec 047 §14 Phase 1 (1.5) — rent a control instance, either from the per-type pool (if poolable and a pooled instance is available) or via `factory` / `new T()`. Pool key is `typeof(T)` only. + +```csharp +public T RentControl(PoolPolicy? policy = null, Func? factory = null) where T : class, new() +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `policy` | [`PoolPolicy?`](PoolPolicy.md) | `null` | | +| `factory` | `Func?` | `null` | | + +### `ReturnControl` + +Spec 047 §14 Phase 1 (1.5) — return a control to its per-type pool, after running the Q18 reset contract: + +- Clear `ControlEventState` (per-control event payload box, §9.2). +- Clear `ModifierEventHandlerState` (modifier / routed-input handler state). +- Clear `ReactorAttached.StateProperty` Tag / DataContext set by Reactor. +- Invoke `policy.Reset` last (author-defined extra cleanup). + +Double-return is safe: [`ElementPool.Return`](ElementPool.md#return) dedupes via the per-type stack cap (`MaxPerType`). + +```csharp +public void ReturnControl(T control, PoolPolicy? policy = null) where T : class +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `control` | `T` | | | +| `policy` | [`PoolPolicy?`](PoolPolicy.md) | `null` | | + +### `SetElementTag` + +Spec 047 §14 Phase 1 (1.3) — promoted from internal. Associates a control with its current Reactor element via the [`ReactorAttached.StateProperty`](Reconciler.md) attached DP so that trampolines can resolve the live element on dispatch. Provisional API; see `REACTOR_V1_PREVIEW`. + +```csharp +public static void SetElementTag(FrameworkElement control, Element? element) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `control` | `FrameworkElement` | | +| `element` | [`Element?`](../elements/Element.md) | | + +### `UnmountChild` + +Unmounts a child control. Public so registered type handlers can unmount children. + +```csharp +public void UnmountChild(UIElement control) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `control` | `UIElement` | | + +### `UpdateChild` + +Low-level update of one child control, for callers that have already checked the new element can update it in place. Code outside the framework should call [`Reconciler.Reconcile`](#reconcile), which makes that check and unmounts a control it replaces. + +```csharp +public UIElement? UpdateChild(Element oldEl, Element newEl, UIElement control, Action requestRerender) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `oldEl` | [`Element`](../elements/Element.md) | | +| `newEl` | [`Element`](../elements/Element.md) | | +| `control` | `UIElement` | | +| `requestRerender` | `Action` | | + +**Remarks** + +Patches `control` to match `newEl` and returns null, or returns a new control when the update had to build one. The caller then unmounts `control` with [`Reconciler.UnmountChild`](#unmountchild) and puts the new control in its slot, in that order, as [`Reconciler.Reconcile`](#reconcile) does: unmounting reads state from the control while it is still in the tree, such as a connected-animation snapshot. It doesn't check that `newEl` has the element type and key of `oldEl`: a changed type throws `InvalidCastException` for a built-in control. The analyzer rule `REACTOR_LIFECYCLE_003` flags calls to this method and offers to switch them to [`Reconciler.Reconcile`](#reconcile). + +### `UpdateDefaultAutomationName` + +Spec 047 §14 Phase 1 (1.3) — promoted from internal. Update-time pair for [`Reconciler.ApplyDefaultAutomationName`](#applydefaultautomationname); overwrites the automation Name only when it matches the previous caption (i.e. the author hasn't intervened). Clears that default when the new content has no caption. Provisional API; see `REACTOR_V1_PREVIEW`. + +```csharp +public static void UpdateDefaultAutomationName(FrameworkElement fe, string? oldCaption, string? newCaption) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `fe` | `FrameworkElement` | | +| `oldCaption` | `string?` | | +| `newCaption` | `string?` | | + +## Fields + +### `DebugElementsDiffed` + +Per-reconcile counters for diagnosing diff and mount/update volume. Reset before each top-level Reconcile() call; read afterward. Always populated (including Release builds) so ETW trace consumers can read them off the `ReconcileStop` event payload. + +```csharp +public int DebugElementsDiffed +``` + +### `DebugElementsSkipped` + +```csharp +public int DebugElementsSkipped +``` + +### `DebugUIElementsCreated` + +```csharp +public int DebugUIElementsCreated +``` + +### `DebugUIElementsModified` + +```csharp +public int DebugUIElementsModified +``` diff --git a/docs/guide/reference/extensibility/children-strategies.md b/docs/guide/reference/extensibility/children-strategies.md new file mode 100644 index 0000000000..7f83f62b75 --- /dev/null +++ b/docs/guide/reference/extensibility/children-strategies.md @@ -0,0 +1,691 @@ +# Children strategies + +Records that tell the reconciler how a control holds its children. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md), [The Control Reconciler Protocol](../../control-reconciler-protocol.md) + +## `AttachedPropWriter` + +Spec 047 §6 / §14 Phase 1 (1.8) — writer for an attached DP from a parent container onto a child control (Grid.Row, Canvas.Left, DockPanel.Dock, etc.). Authors of container handlers register these on the child element type; the engine invokes them during child mount. + +**Type-safety contract:** [`AttachedPropWriter.Get`](#get) pulls the value off the typed child element; [`AttachedPropWriter.Write`](#write) applies it to the [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement) control. Both lambdas are strongly typed — no reflection, AOT-compatible. + +```csharp +public sealed record AttachedPropWriter(string Name, Func Get, Action Write) where TChildElement : Element +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `AttachedPropWriter` + +Spec 047 §6 / §14 Phase 1 (1.8) — writer for an attached DP from a parent container onto a child control (Grid.Row, Canvas.Left, DockPanel.Dock, etc.). Authors of container handlers register these on the child element type; the engine invokes them during child mount. + +**Type-safety contract:** [`AttachedPropWriter.Get`](#get) pulls the value off the typed child element; [`AttachedPropWriter.Write`](#write) applies it to the [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement) control. Both lambdas are strongly typed — no reflection, AOT-compatible. + +```csharp +public AttachedPropWriter(string Name, Func Get, Action Write) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Name` | `string` | | +| `Get` | `Func` | | +| `Write` | `Action` | | + +### Properties + +#### `Get` + +```csharp +public Func Get // get, init +``` + +#### `Name` + +```csharp +public string Name // get, init +``` + +#### `Write` + +```csharp +public Action Write // get, init +``` + +## `ChildrenStrategy` + +Spec 047 §6 / §14 Phase 1 (1.8) — children-handling strategy declared by a handler. Engine dispatches through the strategy in `V1HandlerAdapter` after the handler's Mount / Update body has returned. Phase 1 ships shape + dispatch; the keyed-reconcile integration with spec-042 lands in Phase 3. + +```csharp +public abstract record ChildrenStrategy where TElement : Element where TControl : UIElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `ChildrenStrategy` + +```csharp +protected ChildrenStrategy() +``` + +## `Imperative` + +Escape hatch — the handler drives child reconciliation imperatively via [`Imperative.Reconcile`](#reconcile). Use sparingly; the typed strategies above cover the 95% case. + +```csharp +public sealed record Imperative(Action Reconcile) where TElement : Element where TControl : UIElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `Imperative` + +Escape hatch — the handler drives child reconciliation imperatively via [`Imperative.Reconcile`](#reconcile). Use sparingly; the typed strategies above cover the 95% case. + +```csharp +public Imperative(Action Reconcile) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Reconcile` | `Action` | | + +### Properties + +#### `Reconcile` + +```csharp +public Action Reconcile // get, init +``` + +#### `Unmount` + +Optional teardown for the children [`Imperative.Reconcile`](#reconcile) mounted. The engine has no view onto imperative slots, so when unmount dispatches to the handler it calls this instead of walking them. Unmount each owned child while it is still parented, then detach it. Declaring it does not tag every control: a control without an element tag is torn down by the engine's generic child walk, which must therefore be able to reach the owned children. That walk also tears down what the handler does not own, so tag the control ([`Reconciler.SetElementTag`](Reconciler.md#setelementtag)) when a slot can hold such UI. + +```csharp +public Action? Unmount // get, init +``` + +## `ItemsHost` + +Flat items host for native ItemCollection sinks and third-party controls that forward an IList\ to an ItemsRepeater. Element children are reconciled in place: keys match across insertions and moves; unkeyed children retain positional identity. Raw items are compared with ItemEquals (object.Equals by default). + +The live collection is incrementally inserted, removed and reordered, never reset on update. ObservableCollection moves emit one Move notification. Property-only and descendant-state updates do not mutate the collection. + +SetCollection opts interface-typed, writable Items properties into a stable observable backing collection when their initial list has no change notifications. Native read-only ItemCollection properties keep their sink. Removed and terminally unmounted Element children receive real teardown. + +```csharp +public sealed record ItemsHost(Func> GetItems, Func> GetCollection) where TElement : Element where TControl : UIElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `ItemsHost` + +Flat items host for native ItemCollection sinks and third-party controls that forward an IList\ to an ItemsRepeater. Element children are reconciled in place: keys match across insertions and moves; unkeyed children retain positional identity. Raw items are compared with ItemEquals (object.Equals by default). + +The live collection is incrementally inserted, removed and reordered, never reset on update. ObservableCollection moves emit one Move notification. Property-only and descendant-state updates do not mutate the collection. + +SetCollection opts interface-typed, writable Items properties into a stable observable backing collection when their initial list has no change notifications. Native read-only ItemCollection properties keep their sink. Removed and terminally unmounted Element children receive real teardown. + +```csharp +public ItemsHost(Func> GetItems, Func> GetCollection) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `GetItems` | `Func>` | | +| `GetCollection` | `Func>` | | + +### Properties + +#### `GetCollection` + +```csharp +public Func> GetCollection // get, init +``` + +#### `GetItems` + +```csharp +public Func> GetItems // get, init +``` + +#### `ItemEquals` + +Optional equality predicate for raw (non-Element) items. A positionally equal list retains its existing raw instances, matching the legacy unchanged-list fast path. On a structural update, matched raw value-equal instances are retained; Id-equal objects with changed payloads are replaced. Element children follow panel skip rules: dirty paths, changed context, theme sensitivity, resource refresh and force-rendering decline the skip. Defaults to object.Equals. + +```csharp +public Func? ItemEquals // get, init +``` + +#### `SetCollection` + +Optional setter for an interface-typed Items property. On mount the engine replaces a non-observable backing list with a stable observable collection. Read-only native ItemCollection sinks are never replaced. + +```csharp +public Action>? SetCollection // get, init +``` + +## `ItemsHostOptions` + +Placeholder for future ItemsHost options (virtualization mode, container template etc.). Phase 1 carries no fields — Phase 3 may add when more handler authors arrive. Retained for source compat with the Phase 1 ItemsHost shape. + +```csharp +public sealed record ItemsHostOptions +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `ItemsHostOptions` + +```csharp +public ItemsHostOptions() +``` + +## `NamedSlot` + +One named slot on a [`NamedSlots`](#namedslotstelement-tcontrol) host. [`NamedSlot.Name`](#name_1) is informational; binding is by lambda. + +```csharp +public sealed record NamedSlot(string Name, Func GetChild, Action SetChild) where TElement : Element where TControl : UIElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `NamedSlot` + +One named slot on a [`NamedSlots`](#namedslotstelement-tcontrol) host. [`NamedSlot.Name`](#name_1) is informational; binding is by lambda. + +```csharp +public NamedSlot(string Name, Func GetChild, Action SetChild) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Name` | `string` | | +| `GetChild` | `Func` | | +| `SetChild` | `Action` | | + +### Properties + +#### `GetChild` + +```csharp +public Func GetChild // get, init +``` + +#### `GetCurrentChild` + +Optional: read the current child from the control. Required for structural child reconciliation; same contract as [`SingleContent.GetCurrentChild`](#getcurrentchild_1). + +```csharp +public Func? GetCurrentChild // get, init +``` + +#### `Name` + +```csharp +public string Name // get, init +``` + +#### `SetChild` + +```csharp +public Action SetChild // get, init +``` + +## `NamedSlots` + +Named-slot host (SplitView with Pane + Content, NavigationView with Header + Content + PaneFooter, etc.). Each [`NamedSlot`](#namedslottelement-tcontrol) binds one slot. + +```csharp +public sealed record NamedSlots(IReadOnlyList> Slots) where TElement : Element where TControl : UIElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `NamedSlots` + +Named-slot host (SplitView with Pane + Content, NavigationView with Header + Content + PaneFooter, etc.). Each [`NamedSlot`](#namedslottelement-tcontrol) binds one slot. + +```csharp +public NamedSlots(IReadOnlyList> Slots) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Slots` | `IReadOnlyList>` | | + +### Properties + +#### `Slots` + +```csharp +public IReadOnlyList> Slots // get, init +``` + +## `None` + +Leaf — no children. Engine performs no dispatch beyond the handler's Mount/Update body. + +```csharp +public sealed record None where TElement : Element where TControl : UIElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `None` + +Leaf — no children. Engine performs no dispatch beyond the handler's Mount/Update body. + +```csharp +public None() +``` + +## `Panel` + +Panel host (StackPanel, Grid, Canvas). Engine mounts each child and appends to the panel's [`UIElementCollection`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.uielementcollection). + +**Phase 1 limitation:** the dispatch is append-only; structural diff against the previous render goes through the host's child collection wholesale. Spec-042 keyed-reconcile integration is a Phase 3 follow-up. + +**§14 Phase 3-final addition:** [`Panel.PerChildAttached`](#perchildattached) — optional callback invoked after each child mount AND after each child Update. Receives the mounted [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement) alongside the child element so the descriptor can write WinUI attached DPs (e.g. `Grid.SetRow`, `Canvas.SetLeft`) based on attached-prop hints carried on the child element. No-op by default. + +**§14 Phase 3 close-out addition:** [`Panel.PerChildAttachedAfterAll`](#perchildattachedafterall) — optional two-pass callback invoked once after every child has been mounted (Mount path) or reconciled (Update path). Receives the full `(UIElement, Element)` pair list in collection order so the descriptor can apply attached DPs that reference OTHER children by name (e.g. `RelativePanel.SetRightOf(b, a)`). Distinct from [`Panel.PerChildAttached`](#perchildattached), which fires per-child mid-pass and cannot see siblings that haven't mounted yet. Most descriptors set only one of the two; `RelativePanel` is the canonical consumer of the after-all shape. + +```csharp +public sealed record Panel(Func> GetChildren, Func GetCollection) where TElement : Element where TControl : UIElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `Panel` + +Panel host (StackPanel, Grid, Canvas). Engine mounts each child and appends to the panel's [`UIElementCollection`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.uielementcollection). + +**Phase 1 limitation:** the dispatch is append-only; structural diff against the previous render goes through the host's child collection wholesale. Spec-042 keyed-reconcile integration is a Phase 3 follow-up. + +**§14 Phase 3-final addition:** [`Panel.PerChildAttached`](#perchildattached) — optional callback invoked after each child mount AND after each child Update. Receives the mounted [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement) alongside the child element so the descriptor can write WinUI attached DPs (e.g. `Grid.SetRow`, `Canvas.SetLeft`) based on attached-prop hints carried on the child element. No-op by default. + +**§14 Phase 3 close-out addition:** [`Panel.PerChildAttachedAfterAll`](#perchildattachedafterall) — optional two-pass callback invoked once after every child has been mounted (Mount path) or reconciled (Update path). Receives the full `(UIElement, Element)` pair list in collection order so the descriptor can apply attached DPs that reference OTHER children by name (e.g. `RelativePanel.SetRightOf(b, a)`). Distinct from [`Panel.PerChildAttached`](#perchildattached), which fires per-child mid-pass and cannot see siblings that haven't mounted yet. Most descriptors set only one of the two; `RelativePanel` is the canonical consumer of the after-all shape. + +```csharp +public Panel(Func> GetChildren, Func GetCollection) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `GetChildren` | `Func>` | | +| `GetCollection` | `Func` | | + +### Properties + +#### `GetChildren` + +```csharp +public Func> GetChildren // get, init +``` + +#### `GetCollection` + +```csharp +public Func GetCollection // get, init +``` + +#### `PerChildAttached` + +Optional per-child attached-prop writer. Called by the engine after each child is mounted (Mount path) AND after each child is reconciled (Update path). The descriptor reads attached-prop hints off the child element (via `Element.GetAttached()` or similar) and writes the corresponding WinUI attached DPs onto the mounted [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement). Defaults to `null` for containers that don't carry per-child attached props (e.g. `StackPanel`). + +```csharp +public Action? PerChildAttached // get, init +``` + +#### `PerChildAttachedAfterAll` + +Optional two-pass callback fired once after every child has been mounted/reconciled, receiving the full ordered list of `(UIElement, Element)` pairs. Use for attached DPs that reference siblings by name — e.g. `RelativePanel.SetRightOf`. Defaults to `null`; only RelativePanel-shaped descriptors set it. + +```csharp +public Action>? PerChildAttachedAfterAll // get, init +``` + +## `PreMountedItems` + +§14 Phase 3 completion — pre-mounted, Element-aware positional items host for templated controls whose host has no `ContainerContentChanging` (i.e. [`FlipView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.flipview) templated peer). Items come from the element's `IItemViewSource` implementation — `ItemCount` + `BuildItemView(int)` — and are pre-mounted up-front into the control's flat `IList` sink (e.g. `FlipView.Items`). Closes the carry-forward from §14 Phase 3 finish where `TemplatedFlipViewElement` stayed legacy because the FlipView host can't share the [`TemplatedItemsErased`](#templateditemserasedtelement-tcontrol) realization pipeline used by ListView / GridView (those route through [`Reconciler.BindKeyedItemsSource`](Reconciler.md) which assumes `ContainerContentChanging`). + +**Update semantics:** positional reconcile against the previous element. For each shared index, the engine helper [`Reconciler.ReconcileV1Child`](Reconciler.md) runs the standard CanUpdate-or-Mount-or-Unmount slot decision. Excess old slots are `UnmountChild`-ed and removed; surplus new slots are mounted and appended. Mirrors the legacy `UpdateTemplatedFlipView` arm 1:1. + +**Invariants asserted in Debug:** the dispatched old element is the same closed type as the new (the engine's `CanUpdate` gate guarantees this for Update arms); `items.Count` tracks the previous source's `ItemCount`. Release builds full-rebuild when an invariant is violated rather than indexing into a stale collection. + +```csharp +public sealed record PreMountedItems(Func GetSource, Func> GetCollection) where TElement : Element where TControl : FrameworkElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `PreMountedItems` + +§14 Phase 3 completion — pre-mounted, Element-aware positional items host for templated controls whose host has no `ContainerContentChanging` (i.e. [`FlipView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.flipview) templated peer). Items come from the element's `IItemViewSource` implementation — `ItemCount` + `BuildItemView(int)` — and are pre-mounted up-front into the control's flat `IList` sink (e.g. `FlipView.Items`). Closes the carry-forward from §14 Phase 3 finish where `TemplatedFlipViewElement` stayed legacy because the FlipView host can't share the [`TemplatedItemsErased`](#templateditemserasedtelement-tcontrol) realization pipeline used by ListView / GridView (those route through [`Reconciler.BindKeyedItemsSource`](Reconciler.md) which assumes `ContainerContentChanging`). + +**Update semantics:** positional reconcile against the previous element. For each shared index, the engine helper [`Reconciler.ReconcileV1Child`](Reconciler.md) runs the standard CanUpdate-or-Mount-or-Unmount slot decision. Excess old slots are `UnmountChild`-ed and removed; surplus new slots are mounted and appended. Mirrors the legacy `UpdateTemplatedFlipView` arm 1:1. + +**Invariants asserted in Debug:** the dispatched old element is the same closed type as the new (the engine's `CanUpdate` gate guarantees this for Update arms); `items.Count` tracks the previous source's `ItemCount`. Release builds full-rebuild when an invariant is violated rather than indexing into a stale collection. + +```csharp +public PreMountedItems(Func GetSource, Func> GetCollection) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `GetSource` | `Func` | | +| `GetCollection` | `Func>` | | + +### Properties + +#### `GetCollection` + +```csharp +public Func> GetCollection // get, init +``` + +#### `GetSource` + +```csharp +public Func GetSource // get, init +``` + +## `SingleContent` + +Single-content host (Border, ContentControl, Viewbox). The engine mounts `GetChild`'s result and assigns it via `SetChild`. + +A null child on mount, or null on both sides of an update, leaves native content supplied through setters alone. Declare an Empty element to intentionally clear content without rendering a child. + +**Structural reconcile:** set [`SingleContent.GetCurrentChild`](#getcurrentchild_1) so the engine can read the existing slot value during `Update` and route through `Reconciler.ReconcileV1Child` — that preserves descendant component state across parent re-renders. When left null, the engine remounts the child on every update (only safe for slots that are reset every render anyway). All built-in handlers set it. + +```csharp +public sealed record SingleContent(Func GetChild, Action SetChild) where TElement : Element where TControl : UIElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `SingleContent` + +Single-content host (Border, ContentControl, Viewbox). The engine mounts `GetChild`'s result and assigns it via `SetChild`. + +A null child on mount, or null on both sides of an update, leaves native content supplied through setters alone. Declare an Empty element to intentionally clear content without rendering a child. + +**Structural reconcile:** set [`SingleContent.GetCurrentChild`](#getcurrentchild_1) so the engine can read the existing slot value during `Update` and route through `Reconciler.ReconcileV1Child` — that preserves descendant component state across parent re-renders. When left null, the engine remounts the child on every update (only safe for slots that are reset every render anyway). All built-in handlers set it. + +```csharp +public SingleContent(Func GetChild, Action SetChild) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `GetChild` | `Func` | | +| `SetChild` | `Action` | | + +### Properties + +#### `GetChild` + +```csharp +public Func GetChild // get, init +``` + +#### `GetCurrentChild` + +Optional: read the current child from the control. Required for structural child reconciliation; if null the engine falls back to remounting the child every Update. + +```csharp +public Func? GetCurrentChild // get, init +``` + +#### `SetChild` + +```csharp +public Action SetChild // get, init +``` + +## `TabItemsHost` + +§14 Phase 3 finish — Ports (10) + (11). Heterogeneous items host for [`TabView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.tabview) and [`Pivot`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.pivot). Each item declares a header + an Element content + (TabView-only) an optional IsClosable / icon hint; the strategy mounts the content, builds the per-control container (e.g. `WinUI.TabViewItem`), and adds it to the host's items sink. + +**Update semantics:** in-place positional reconcile against the previous element. For each shared index the existing container is kept and its `Content` reconciled through [`Reconciler.ReconcileV1Child`](Reconciler.md) (CanUpdate-or-mount-or-unmount); the container's own metadata (header / icon / closable) is refreshed via the optional [`TabItemsHost.UpdateContainer`](#updatecontainer) callback. Excess containers are unmounted + removed; surplus new items are created + appended. Containers (and the mounted Content subtree underneath them) therefore survive renders that don't change the tab/pivot set — re-adding every `TabViewItem` / `PivotItem` would re-trigger the tab-strip entrance animation and steal focus from descendant controls. Mirrors the legacy `UpdateTabView` / `UpdatePivot` in-place arms. + +**Not covered (still legacy-only):** keyed reorder, pinnable tab headers, and the docking drag pipeline. Index-keyed pairing assumes the item at index `i` in the old list corresponds to index `i` in the new list. + +```csharp +public sealed record TabItemsHost(Func> GetItems, Func> GetCollection, Func GetContent, Func CreateContainer, Action? UpdateContainer = null) where TElement : Element where TControl : FrameworkElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `TabItemsHost` + +§14 Phase 3 finish — Ports (10) + (11). Heterogeneous items host for [`TabView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.tabview) and [`Pivot`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.pivot). Each item declares a header + an Element content + (TabView-only) an optional IsClosable / icon hint; the strategy mounts the content, builds the per-control container (e.g. `WinUI.TabViewItem`), and adds it to the host's items sink. + +**Update semantics:** in-place positional reconcile against the previous element. For each shared index the existing container is kept and its `Content` reconciled through [`Reconciler.ReconcileV1Child`](Reconciler.md) (CanUpdate-or-mount-or-unmount); the container's own metadata (header / icon / closable) is refreshed via the optional [`TabItemsHost.UpdateContainer`](#updatecontainer) callback. Excess containers are unmounted + removed; surplus new items are created + appended. Containers (and the mounted Content subtree underneath them) therefore survive renders that don't change the tab/pivot set — re-adding every `TabViewItem` / `PivotItem` would re-trigger the tab-strip entrance animation and steal focus from descendant controls. Mirrors the legacy `UpdateTabView` / `UpdatePivot` in-place arms. + +**Not covered (still legacy-only):** keyed reorder, pinnable tab headers, and the docking drag pipeline. Index-keyed pairing assumes the item at index `i` in the old list corresponds to index `i` in the new list. + +```csharp +public TabItemsHost(Func> GetItems, Func> GetCollection, Func GetContent, Func CreateContainer, Action? UpdateContainer = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `GetItems` | `Func>` | | | +| `GetCollection` | `Func>` | | | +| `GetContent` | `Func` | | | +| `CreateContainer` | `Func` | | | +| `UpdateContainer` | `Action?` | `null` | | + +### Properties + +#### `CreateContainer` + +```csharp +public Func CreateContainer // get, init +``` + +#### `GetCollection` + +```csharp +public Func> GetCollection // get, init +``` + +#### `GetContent` + +```csharp +public Func GetContent // get, init +``` + +#### `GetItems` + +```csharp +public Func> GetItems // get, init +``` + +#### `UpdateContainer` + +```csharp +public Action? UpdateContainer // get, init +``` + +## `TemplatedItems` + +Keyed templated-items host for descriptor-driven typed lists (`ListView`, `GridView`, future `LazyVStack` / `LazyHStack` / `ItemsRepeater`). The strategy declares only the data shape; the engine partial [`Reconciler.BindKeyedItemsSource`](Reconciler.md) owns the realization plumbing (spec-042 `ReactorListState` + `KeyedListDiff`, the shared `ContainerContentChanging` handler, the per-control `ItemsSource` binding). + +**Lifecycle:** Mount runs once on first render; Update runs on every subsequent render with the same control instance. Both go through [`Reconciler.BindKeyedItemsSource`](Reconciler.md); the boolean `isMount` parameter selects between fresh-state construction (Mount) and keyed-diff application (Update). + +**Key contract:** [`TemplatedItems.KeySelector`](#keyselector) must produce stable, non-null, non-duplicate strings across renders for any given user item. Null / duplicate keys trigger the same `DiffStats.Bailout` path the legacy element-based binder uses — correctness preserved, animation degraded for that diff. + +**Per-item Element:** [`TemplatedItems.BuildItemView`](#builditemview) is called lazily by the realization machinery as containers materialize, so large lists never realize all items up front. The returned [`Element`](../elements/Element.md) is reconciled into the container's `ContentControl`. + +```csharp +public sealed record TemplatedItems(Func> GetItems, Func KeySelector, Func BuildItemView) where TElement : Element where TControl : FrameworkElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `TemplatedItems` + +Keyed templated-items host for descriptor-driven typed lists (`ListView`, `GridView`, future `LazyVStack` / `LazyHStack` / `ItemsRepeater`). The strategy declares only the data shape; the engine partial [`Reconciler.BindKeyedItemsSource`](Reconciler.md) owns the realization plumbing (spec-042 `ReactorListState` + `KeyedListDiff`, the shared `ContainerContentChanging` handler, the per-control `ItemsSource` binding). + +**Lifecycle:** Mount runs once on first render; Update runs on every subsequent render with the same control instance. Both go through [`Reconciler.BindKeyedItemsSource`](Reconciler.md); the boolean `isMount` parameter selects between fresh-state construction (Mount) and keyed-diff application (Update). + +**Key contract:** [`TemplatedItems.KeySelector`](#keyselector) must produce stable, non-null, non-duplicate strings across renders for any given user item. Null / duplicate keys trigger the same `DiffStats.Bailout` path the legacy element-based binder uses — correctness preserved, animation degraded for that diff. + +**Per-item Element:** [`TemplatedItems.BuildItemView`](#builditemview) is called lazily by the realization machinery as containers materialize, so large lists never realize all items up front. The returned [`Element`](../elements/Element.md) is reconciled into the container's `ContentControl`. + +```csharp +public TemplatedItems(Func> GetItems, Func KeySelector, Func BuildItemView) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `GetItems` | `Func>` | | +| `KeySelector` | `Func` | | +| `BuildItemView` | `Func` | | + +### Properties + +#### `BuildItemView` + +```csharp +public Func BuildItemView // get, init +``` + +#### `GetItems` + +```csharp +public Func> GetItems // get, init +``` + +#### `KeySelector` + +```csharp +public Func KeySelector // get, init +``` + +## `TemplatedItemsErased` + +§14 Phase 3 close-out — keyed templated-items host that erases the per-item type at the strategy level by reading items through the element's `IKeyedItemSource` implementation. The element is the carrier of T; the descriptor is non-generic in TItem. + +This is the shape used to port the existing `TemplatedListViewElement` / `TemplatedGridViewElement` family — registered once on a non-generic intermediate base ([`TemplatedListViewElementBase`](../elements/collections.md#templatedlistviewelementbase) / [`TemplatedGridViewElementBase`](../elements/collections.md#templatedgridviewelementbase)) via [`Reconciler.RegisterHandlerForDerivedTypes`](Reconciler.md#registerhandlerforderivedtypes); the engine's base-derived registry walk routes every closed-T variant to the same descriptor. Same realization plumbing as [`TemplatedItems`](#templateditemstitem-telement-tcontrol): [`Reconciler.BindKeyedItemsSource`](Reconciler.md) owns the `ReactorListState` + `KeyedListDiff` + container-realization pipeline. + +```csharp +public sealed record TemplatedItemsErased(Func GetSource) where TElement : Element where TControl : FrameworkElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `TemplatedItemsErased` + +§14 Phase 3 close-out — keyed templated-items host that erases the per-item type at the strategy level by reading items through the element's `IKeyedItemSource` implementation. The element is the carrier of T; the descriptor is non-generic in TItem. + +This is the shape used to port the existing `TemplatedListViewElement` / `TemplatedGridViewElement` family — registered once on a non-generic intermediate base ([`TemplatedListViewElementBase`](../elements/collections.md#templatedlistviewelementbase) / [`TemplatedGridViewElementBase`](../elements/collections.md#templatedgridviewelementbase)) via [`Reconciler.RegisterHandlerForDerivedTypes`](Reconciler.md#registerhandlerforderivedtypes); the engine's base-derived registry walk routes every closed-T variant to the same descriptor. Same realization plumbing as [`TemplatedItems`](#templateditemstitem-telement-tcontrol): [`Reconciler.BindKeyedItemsSource`](Reconciler.md) owns the `ReactorListState` + `KeyedListDiff` + container-realization pipeline. + +```csharp +public TemplatedItemsErased(Func GetSource) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `GetSource` | `Func` | | + +### Properties + +#### `GetSource` + +```csharp +public Func GetSource // get, init +``` + +## `TreeChildren` + +§14 Phase 3 finish — Port (8). Hierarchical children for [`TreeView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.treeview). The strategy declares only the data shape (a [`TreeViewNodeData`](../controls/collection-items.md#treeviewnodedata) tree); the engine builds a matching [`TreeViewNode`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.treeviewnode) tree on [`TreeView.RootNodes`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.treeview.rootnodes), mounting per-node `ContentElement` through the reconciler when any node uses one. + +**MVP scope:** positional rebuild on Update — old `ContentElement` subtrees are unmounted and the WinUI tree is reconstructed. No keyed reconcile (descendant component state inside ContentElement nodes is lost across renders that touch the tree). Same correctness contract as the legacy `UpdateTreeView` arm. + +```csharp +public sealed record TreeChildren(Func> GetNodes) where TElement : Element where TControl : TreeView +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Constructors + +#### `TreeChildren` + +§14 Phase 3 finish — Port (8). Hierarchical children for [`TreeView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.treeview). The strategy declares only the data shape (a [`TreeViewNodeData`](../controls/collection-items.md#treeviewnodedata) tree); the engine builds a matching [`TreeViewNode`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.treeviewnode) tree on [`TreeView.RootNodes`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.treeview.rootnodes), mounting per-node `ContentElement` through the reconciler when any node uses one. + +**MVP scope:** positional rebuild on Update — old `ContentElement` subtrees are unmounted and the WinUI tree is reconstructed. No keyed reconcile (descendant component state inside ContentElement nodes is lost across renders that touch the tree). Same correctness contract as the legacy `UpdateTreeView` arm. + +```csharp +public TreeChildren(Func> GetNodes) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `GetNodes` | `Func>` | | + +### Properties + +#### `GetNodes` + +```csharp +public Func> GetNodes // get, init +``` diff --git a/docs/guide/reference/extensibility/descriptor-delegates.md b/docs/guide/reference/extensibility/descriptor-delegates.md new file mode 100644 index 0000000000..cd801ee4fe --- /dev/null +++ b/docs/guide/reference/extensibility/descriptor-delegates.md @@ -0,0 +1,61 @@ +# Descriptor callbacks + +Delegates and attributes used by control descriptors. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md), [The Control Reconciler Protocol](../../control-reconciler-protocol.md) + +## `AfterChildrenMountCallback` + +Spec 047 §14 Phase 3 prelude (Engine A1) — post-children mount callback signature for [`ControlDescriptor.AfterChildrenMount`](ControlDescriptor.md#afterchildrenmount). Invoked by `V1HandlerAdapter` after the descriptor's children strategy has mounted/bound every child, so a descriptor can wire events that must subscribe strictly after children-add (e.g. `TabView.SelectionChanged`). Takes [`MountContext`](lifecycle-contexts.md#mountcontext) by `in` to preserve the allocation-free ref-struct contract. + +```csharp +public delegate void AfterChildrenMountCallback(in MountContext ctx, TElement element, TControl control) where TElement : Element where TControl : FrameworkElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol.Descriptor`. + +## `DescriptorUnmountCallback` + +Teardown callback signature for [`ControlDescriptor.OnUnmount`](ControlDescriptor.md#onunmount). Invoked by [`DescriptorHandler`](DescriptorHandler.md) from the engine's [`IElementHandler.Unmount`](IElementHandler.md#unmount) dispatch, so a descriptor can invalidate control-scoped state it set up during mount — pending deferred writes, one-shot lifecycle subscriptions, disposables. Takes [`UnmountContext`](lifecycle-contexts.md#unmountcontext) by `in` to preserve the allocation-free ref-struct contract. + +```csharp +public delegate void DescriptorUnmountCallback(in UnmountContext ctx, TControl control) where TControl : FrameworkElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol.Descriptor`. + +### Remarks + +The engine still runs the pool reset contract afterwards; this hook is for state the reset contract cannot see, such as a `Loaded` handler the descriptor attached itself. + +## `NoClearValueAttribute` + +Suppresses the REACTOR0050 analyzer for a descriptor field or property whose `OneWay` entries intentionally use [`Optional`](../components/Optional.md) without a dependency-property backing value to clear. + +```csharp +public sealed class NoClearValueAttribute : Attribute +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol.Descriptor`. Inherits from [`Attribute`](https://learn.microsoft.com/dotnet/api/system.attribute). + +### Remarks + +Prefer providing the `dp:` argument to `ControlDescriptor.OneWay` whenever the target WinUI property is backed by a dependency property. Use this attribute only for descriptor entries whose unset value should skip the write because there is no dependency property, or because clearing the local value would be semantically wrong for that control. + +### Constructors + +#### `NoClearValueAttribute` + +```csharp +public NoClearValueAttribute() +``` + +## `OneWayBridgedSetter` + +Spec 047 §14 Phase 3-final — set-lambda signature for `OneWayBridgedPropEntry`. Named delegate type (not `Action<...>`) so the [`MountContext`](lifecycle-contexts.md#mountcontext) / [`UpdateContext`](lifecycle-contexts.md#updatecontext) doesn't need to be passed — the entry projects the two pieces a bridge typically needs (the [`Reconciler`](Reconciler.md) and the rerender callback). + +```csharp +public delegate void OneWayBridgedSetter(TControl ctrl, TValue value, Reconciler reconciler, Action requestRerender) where TControl : UIElement +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol.Descriptor`. diff --git a/docs/guide/reference/extensibility/index.md b/docs/guide/reference/extensibility/index.md new file mode 100644 index 0000000000..ad276f51c9 --- /dev/null +++ b/docs/guide/reference/extensibility/index.md @@ -0,0 +1,28 @@ +# Extensibility + +The control protocol, control descriptors, the reconciler and element pooling. + +Use these types to add your own controls to Reactor or to change how built-in controls are created and updated. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md), [The Control Reconciler Protocol](../../control-reconciler-protocol.md), [Element Pool](../../element-pool.md) + +## Types + +| Type | Description | +| --- | --- | +| [Children strategies](children-strategies.md) | Records that tell the reconciler how a control holds its children. | +| [Descriptor callbacks](descriptor-delegates.md) | Delegates and attributes used by control descriptors. | +| [Handler contexts](lifecycle-contexts.md) | Contexts passed to an element handler when it mounts, updates or unmounts a control. | +| [`ControlDescriptor`](ControlDescriptor.md) | Spec 047 §6 / §14 Phase 2 (Q1 spike) — declarative control description. | +| [`ControlRegistry`](ControlRegistry.md) | Spec 048 §8 — the global, lazy, lock-free control registry that backs the factory-as-registration pattern. | +| [`DescriptorHandler`](DescriptorHandler.md) | Spec 047 §6 / §14 Phase 2 (Q1 spike) — interpreter that drives a `ControlDescriptor` against the v1 protocol surface. | +| [`ElementPool`](ElementPool.md) | Per-CLR-type pool (cap 32) that recycles unmounted WinUI FrameworkElement instances. | +| [`IDecoratorElementHandler`](IDecoratorElementHandler.md) | Spec 047 §14 Phase 3 completion — decorator-style V1 handler contract for elements whose returned `UIElement` identity may change on update or whose unmount disposition diverges from the standard pool-return. | +| [`IElementHandler`](IElementHandler.md) | Spec 047 §4 / §14 Phase 1 (1.6) — author-facing handler contract for porting a control onto the v1 protocol. | +| [`PathDataParser`](PathDataParser.md) | Parses SVG path data strings into WinUI PathGeometry. | +| [`PoolPolicy`](PoolPolicy.md) | Spec 047 §13 Q18 / §14 Phase 1 (1.5) — author-facing pool policy. | +| [`PropEntry`](PropEntry.md) | Spec 047 §6 / §14 Phase 2 (Q1 spike) — base class for descriptor entries declared on a `ControlDescriptor`. | +| [`ReactorBinding`](ReactorBinding.md) | Spec 047 §14 Phase 1 (1.4) — public author-facing surface for the echo suppression primitive (§13 Q19). | +| [`ReactorBinding`](ReactorBinding-1.md) | Spec 047 §9 / §14 Phase 1 (1.6) — per-binding event helper. | +| [`ReactorFeatureFlags`](ReactorFeatureFlags.md) | Process-wide feature flags that gate risky or in-progress behavior. | +| [`Reconciler`](Reconciler.md) | The reconciler diffs old and new element trees and patches the real WinUI control tree. | diff --git a/docs/guide/reference/extensibility/lifecycle-contexts.md b/docs/guide/reference/extensibility/lifecycle-contexts.md new file mode 100644 index 0000000000..44e4154073 --- /dev/null +++ b/docs/guide/reference/extensibility/lifecycle-contexts.md @@ -0,0 +1,372 @@ +# Handler contexts + +Contexts passed to an element handler when it mounts, updates or unmounts a control. + +**Learn more:** [Extending Reactor with Native Controls](../../extending-reactor-controls.md), [The Control Reconciler Protocol](../../control-reconciler-protocol.md) + +## `MountContext` + +Spec 047 §4 / §14 Phase 1 (1.6) — mount-time context passed to [`IElementHandler.Mount`](IElementHandler.md#mount). + +**UI-thread guarantee (Q14):** handlers run on the reconciler's UI dispatcher. Mount bodies may freely access control state without synchronization. Calls from other threads throw in Debug builds today; Phase 1 plan is to measure first before tightening to unconditional throw. See `docs/specs/047/phase1-results/q14-dispatcher-affinity.md`. + +**Allocation contract:** [`MountContext`](#mountcontext) is a `readonly ref struct`, so it cannot escape the call stack and never allocates on its own. Hot path (Mount body) pays only the dictionary lookup + interface call already incurred by the V1HandlerRegistry dispatch. + +**Sample skeleton** (per spec §4 ToggleSwitchHandler example): + +```csharp +public sealed class ToggleSwitchHandler : IElementHandler +{ + public ToggleSwitch Mount(MountContext ctx, ToggleSwitchElement el) + { + var ctrl = ctx.RentControl(); + ctrl.IsOn = el.IsOn; + ctrl.OnContent = el.OnContent; + var bind = ctx.BindFor(ctrl, el); + bind.OnCustomEvent( + (c, h) => ((ToggleSwitch)c).Toggled += (s, e) => h(s, e), + (c, h) => { /* trampoline lives for the control's lifetime */ }, + (e, args) => e.OnIsOnChanged?.Invoke(((ToggleSwitch)args.OriginalSource).IsOn)); + return ctrl; + } + public void Update(UpdateContext ctx, ToggleSwitchElement oldEl, ToggleSwitchElement newEl, ToggleSwitch ctrl) + { + if (oldEl.IsOn != newEl.IsOn) + ctx.BindFor(ctrl, newEl).WriteSuppressed(() => ctrl.IsOn = newEl.IsOn); + } +} +``` + +```csharp +public readonly struct MountContext +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +> **Obsolete.** Types with embedded references are not supported in this version of your compiler. + +### Properties + +#### `Reconciler` + +The owning reconciler. Provided as an escape hatch for handlers that need to forward a child mount through some non-strategy path. + +```csharp +public Reconciler Reconciler // get +``` + +#### `RequestRerender` + +The rerender callback for the owning component subtree. + +```csharp +public Action RequestRerender // get +``` + +### Methods + +#### `AddRawRoutedHandler` + +Escape hatch (Q11) — attach a raw routed handler directly to the control. Handlers should prefer the typed `On*` family on [`ReactorBinding`](ReactorBinding-1.md); use this only for events the binding doesn't cover (e.g. `UIElement.PreviewKeyDown` on a non-FrameworkElement, or app-side custom routed events). + +```csharp +public void AddRawRoutedHandler(UIElement target, RoutedEvent re, Delegate h, bool handledEventsToo) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `target` | `UIElement` | | +| `re` | `RoutedEvent` | | +| `h` | `Delegate` | | +| `handledEventsToo` | `bool` | | + +#### `ApplySetters` + +The [`Reconciler.ApplySetters`](Reconciler.md#applysetters) helper; provided on the context for symmetry with handler-authored mount bodies. + +```csharp +public void ApplySetters(Action[] setters, T control) where T : class +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `setters` | `Action[]` | | +| `control` | `T` | | + +#### `BindFor` + +Construct a per-binding event helper for the given control + element. The returned binding closes over the control identity, not the element — handlers re-fetch the live element via `ReactorState.Element` on each event fire, so the same binding survives element re-renders. + +```csharp +public ReactorBinding BindFor(FrameworkElement control, TElement element) where TElement : Element +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `control` | `FrameworkElement` | | +| `element` | `TElement` | | + +#### `MountChild` + +Mount a child element through the reconciler. The returned [`UIElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.uielement) is whatever the reconciler decided to mount (possibly null for `EmptyElement`). + +```csharp +public UIElement? MountChild(Element child) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `child` | [`Element`](../elements/Element.md) | | + +#### `PushContext` + +Push a typed context value for the duration of the returned [`IDisposable`](https://learn.microsoft.com/dotnet/api/system.idisposable). Used by handlers that mount children which must see an author-supplied context. + +```csharp +public IDisposable PushContext(Context context, T value) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `context` | [`Context`](../components/Context.md) | | +| `value` | `T` | | + +#### `PushStaggerScope` + +Push a stagger scope; children mounted inside the scope consume stagger indices for their enter transitions. + +```csharp +public IDisposable PushStaggerScope(TimeSpan delay) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `delay` | `TimeSpan` | | + +#### `ReconcileChild` + +Reconcile a secondary element slot (mount / update-in-place / unmount) against an already-mounted control, preserving descendant component state across re-renders. `existing` is the control currently in the slot (or `null`). Returns the control to assign back into the slot. Public counterpart to the engine-internal child reconcile, so external wrappers (not just built-in descriptors) can host stateful secondary element slots — see `[WrapElementSlot]`. + +```csharp +public UIElement? ReconcileChild(Element? oldChild, Element? newChild, UIElement? existing) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `oldChild` | [`Element?`](../elements/Element.md) | | +| `newChild` | [`Element?`](../elements/Element.md) | | +| `existing` | `UIElement?` | | + +#### `RentControl` + +Rent a control instance from the per-type pool, or allocate a fresh one if the pool is empty / the policy opts out. + +```csharp +public T RentControl(PoolPolicy? policy = null, Func? factory = null) where T : class, new() +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `policy` | [`PoolPolicy?`](PoolPolicy.md) | `null` | | +| `factory` | `Func?` | `null` | | + +## `UnmountContext` + +Spec 047 §4 / §14 Phase 1 (1.6) — unmount-time context. Handlers use [`UnmountContext.ReturnControl`](#returncontrol) to participate in the pool reset contract; the engine takes care of detaching from the parent tree. + +```csharp +public readonly struct UnmountContext +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +> **Obsolete.** Types with embedded references are not supported in this version of your compiler. + +### Properties + +#### `Reconciler` + +```csharp +public Reconciler Reconciler // get +``` + +#### `RequestRerender` + +```csharp +public Action RequestRerender // get +``` + +### Methods + +#### `ReturnControl` + +Return a control to its per-type pool via the engine's reset contract. Safe to call twice — the pool dedupes by stack cap. + +```csharp +public void ReturnControl(T control, PoolPolicy? policy = null) where T : class +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `control` | `T` | | | +| `policy` | [`PoolPolicy?`](PoolPolicy.md) | `null` | | + +## `UpdateContext` + +Spec 047 §4 / §14 Phase 1 (1.6) — update-time context passed to [`IElementHandler.Update`](IElementHandler.md#update). + +Same shape as [`MountContext`](#mountcontext) minus `RentControl` — updates run against an existing control, so allocation is forbidden on this path. UI-thread guarantee applies (see [`MountContext`](#mountcontext)). + +```csharp +public readonly struct UpdateContext +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +> **Obsolete.** Types with embedded references are not supported in this version of your compiler. + +### Properties + +#### `Reconciler` + +```csharp +public Reconciler Reconciler // get +``` + +#### `RequestRerender` + +```csharp +public Action RequestRerender // get +``` + +### Methods + +#### `AddRawRoutedHandler` + +```csharp +public void AddRawRoutedHandler(UIElement target, RoutedEvent re, Delegate h, bool handledEventsToo) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `target` | `UIElement` | | +| `re` | `RoutedEvent` | | +| `h` | `Delegate` | | +| `handledEventsToo` | `bool` | | + +#### `ApplySetters` + +```csharp +public void ApplySetters(Action[] setters, T control) where T : class +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `setters` | `Action[]` | | +| `control` | `T` | | + +#### `BindFor` + +```csharp +public ReactorBinding BindFor(FrameworkElement control, TElement element) where TElement : Element +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `control` | `FrameworkElement` | | +| `element` | `TElement` | | + +#### `MountChild` + +```csharp +public UIElement? MountChild(Element child) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `child` | [`Element`](../elements/Element.md) | | + +#### `PushContext` + +```csharp +public IDisposable PushContext(Context context, T value) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `context` | [`Context`](../components/Context.md) | | +| `value` | `T` | | + +#### `PushStaggerScope` + +```csharp +public IDisposable PushStaggerScope(TimeSpan delay) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `delay` | `TimeSpan` | | + +#### `ReconcileChild` + +Reconcile a secondary element slot (mount / update-in-place / unmount), preserving descendant component state across re-renders. See [`MountContext.ReconcileChild`](#reconcilechild). + +```csharp +public UIElement? ReconcileChild(Element? oldChild, Element? newChild, UIElement? existing) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `oldChild` | [`Element?`](../elements/Element.md) | | +| `newChild` | [`Element?`](../elements/Element.md) | | +| `existing` | `UIElement?` | | + +## `V1UnmountDisposition` + +Spec 047 §14 Phase 3 completion — controls the engine's pool-return / child-traversal decision after a V1 handler's `Unmount` body runs. Returned from `IV1HandlerEntry.Unmount`; the standard hand-coded + descriptor handlers always return [`V1UnmountDisposition.CollectSelf`](#values), matching the pre-Phase-3-completion behavior. Decorator-style handlers ([`IDecoratorElementHandler`](IDecoratorElementHandler.md)) return the other dispositions to opt out of pool return / let the engine continue the default unmount traversal into the wrapped child. + +```csharp +public enum V1UnmountDisposition +``` + +Namespace: `Microsoft.UI.Reactor.Core.V1Protocol`. + +### Values + +| Name | Value | Description | +| --- | --- | --- | +| `CollectSelf` | `0` | Default for standard handlers. The handler created the control via `RentControl`; the engine pools the control (if poolable) and stops the traversal — children were already torn down by the handler. | +| `ContinueDefaultTraversal` | `1` | The handler's returned control is owned by another element (e.g., a decorator's wrapped `Target` child element). The engine must NOT pool the control and MUST continue the default unmount traversal as if no V1 handler had claimed it, so the inner element's own teardown runs. | +| `SkipPool` | `2` | The handler manages teardown itself; the control is a placeholder/wrapper that should NOT be pooled and whose children were already torn down by the handler. Engine returns immediately without pool collection or traversal. | diff --git a/docs/guide/reference/factories/buttons.md b/docs/guide/reference/factories/buttons.md new file mode 100644 index 0000000000..f2ecdd34c7 --- /dev/null +++ b/docs/guide/reference/factories/buttons.md @@ -0,0 +1,211 @@ +# Factories: Buttons + +Buttons, toggle buttons, split buttons and hyperlink buttons. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Controls](../../controls.md), [Commanding](../../commanding.md) + +## `Button` + +Creates a Button driven by a Command. Maps Label → Content; the command's Execute/ExecuteAsync is invoked on click and its IsEnabled / Description / Accelerator / AccessKey are applied by the reconciler from the typed [`ButtonElement.Command`](../elements/buttons.md#buttonelement) property (issues #153, #637) — no per-render Setters array or lambda is allocated, and a bare `new ButtonElement(cmd.Label) { Command = cmd }` record-init behaves identically. + +```csharp +ButtonElement Button(Command command) +ButtonElement Button(Element content, Action? onClick = null) +ButtonElement Button(string label, Action? onClick = null) +``` + +**Returns:** [`ButtonElement`](../elements/buttons.md#buttonelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `command` | [`Command`](../input/Command.md) | | | +| `content` | [`Element`](../elements/Element.md) | | | +| `onClick` | `Action?` | `null` | | +| `label` | `string` | | | + +## `DropDownButton` + +Creates a drop-down button with declarative content. + +```csharp +DropDownButtonElement DropDownButton(Element content, Element? flyout = null) +DropDownButtonElement DropDownButton(string label, Element? flyout = null) +``` + +**Returns:** [`DropDownButtonElement`](../elements/buttons.md#dropdownbuttonelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `content` | [`Element`](../elements/Element.md) | | | +| `flyout` | [`Element?`](../elements/Element.md) | `null` | | +| `label` | `string` | | | + +## `HyperlinkButton` + +Creates a HyperlinkButton driven by a Command. Maps Label → Content, Execute → Click. For external navigation, chain [`NavigateUri`](../modifiers/buttons.md#navigateuri): `HyperlinkButton(cmd).NavigateUri(new Uri("https://..."))`. + +```csharp +HyperlinkButtonElement HyperlinkButton(Command command) +HyperlinkButtonElement HyperlinkButton(Element content, Uri? navigateUri = null, Action? onClick = null) +HyperlinkButtonElement HyperlinkButton(string content, Uri? navigateUri = null, Action? onClick = null) +``` + +| Overload | Description | +| --- | --- | +| `HyperlinkButton(Command)` | Creates a HyperlinkButton driven by a Command. Maps Label → Content, Execute → Click. For external navigation, chain [`NavigateUri`](../modifiers/buttons.md#navigateuri): `HyperlinkButton(cmd).NavigateUri(new Uri("https://..."))`. | +| `HyperlinkButton(Element, Uri?, Action?)` | Creates a hyperlink button with declarative content. | +| `HyperlinkButton(string, Uri?, Action?)` | | + +**Returns:** [`HyperlinkButtonElement`](../elements/buttons.md#hyperlinkbuttonelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `command` | [`Command`](../input/Command.md) | | | +| `content` | [`Element`](../elements/Element.md) or `string` | | | +| `navigateUri` | `Uri?` | `null` | | +| `onClick` | `Action?` | `null` | | + +## `RepeatButton` + +Creates a RepeatButton driven by a Command. Click auto-repeats while held. + +```csharp +RepeatButtonElement RepeatButton(Command command) +RepeatButtonElement RepeatButton(Element content, Action? onClick = null) +RepeatButtonElement RepeatButton(string label, Action? onClick = null) +``` + +| Overload | Description | +| --- | --- | +| `RepeatButton(Command)` | Creates a RepeatButton driven by a Command. Click auto-repeats while held. | +| `RepeatButton(Element, Action?)` | Creates a repeat button with declarative content. | +| `RepeatButton(string, Action?)` | | + +**Returns:** [`RepeatButtonElement`](../elements/buttons.md#repeatbuttonelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `command` | [`Command`](../input/Command.md) | | | +| `content` | [`Element`](../elements/Element.md) | | | +| `onClick` | `Action?` | `null` | | +| `label` | `string` | | | + +## `SplitButton` + +Creates a SplitButton driven by a Command for the primary action. The flyout (dropdown portion) is independent and supplied separately. + +```csharp +SplitButtonElement SplitButton(Command command, Element? flyout = null) +SplitButtonElement SplitButton(Element content, Action? onClick = null, Element? flyout = null) +SplitButtonElement SplitButton(string label, Action? onClick = null, Element? flyout = null) +``` + +| Overload | Description | +| --- | --- | +| `SplitButton(Command, Element?)` | Creates a SplitButton driven by a Command for the primary action. The flyout (dropdown portion) is independent and supplied separately. | +| `SplitButton(Element, Action?, Element?)` | Creates a split button with declarative primary content. | +| `SplitButton(string, Action?, Element?)` | | + +**Returns:** [`SplitButtonElement`](../elements/buttons.md#splitbuttonelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `command` | [`Command`](../input/Command.md) | | | +| `flyout` | [`Element?`](../elements/Element.md) | `null` | | +| `content` | [`Element`](../elements/Element.md) | | | +| `onClick` | `Action?` | `null` | | +| `label` | `string` | | | + +## `ThreeStateToggleButton` + +Creates a three-state toggle button with declarative content. + +```csharp +ToggleButtonElement ThreeStateToggleButton(Element content, bool? checkedState = null, Action? onCheckedStateChanged = null) +ToggleButtonElement ThreeStateToggleButton(string label, bool? checkedState = null, Action? onCheckedStateChanged = null) +``` + +| Overload | Description | +| --- | --- | +| `ThreeStateToggleButton(Element, bool?, Action?)` | Creates a three-state toggle button with declarative content. | +| `ThreeStateToggleButton(string, bool?, Action?)` | Three-state toggle button (true → false → null → ...). Matches the established `ThreeStateCheckBox` factory pattern from spec 039 §2.4. | + +**Returns:** [`ToggleButtonElement`](../elements/buttons.md#togglebuttonelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `content` | [`Element`](../elements/Element.md) | | | +| `checkedState` | `bool?` | `null` | | +| `onCheckedStateChanged` | `Action?` | `null` | | +| `label` | `string` | | | + +## `ToggleButton` + +Creates a ToggleButton driven by a Command. The command fires on each toggle (both check and uncheck) — per the spec's "Option A" semantics. Use the `isChecked` parameter to seed the initial state. + +```csharp +ToggleButtonElement ToggleButton(Command command, bool isChecked = false) +ToggleButtonElement ToggleButton(Element content, bool isChecked = false, Action? onIsCheckedChanged = null) +ToggleButtonElement ToggleButton(string label, bool isChecked = false, Action? onIsCheckedChanged = null) +``` + +| Overload | Description | +| --- | --- | +| `ToggleButton(Command, bool)` | Creates a ToggleButton driven by a Command. The command fires on each toggle (both check and uncheck) — per the spec's "Option A" semantics. Use the `isChecked` parameter to seed the initial state. | +| `ToggleButton(Element, bool, Action?)` | Creates a toggle button with declarative content. | +| `ToggleButton(string, bool, Action?)` | | + +**Returns:** [`ToggleButtonElement`](../elements/buttons.md#togglebuttonelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `command` | [`Command`](../input/Command.md) | | | +| `isChecked` | `bool` | `false` | | +| `content` | [`Element`](../elements/Element.md) | | | +| `onIsCheckedChanged` | `Action?` | `null` | | +| `label` | `string` | | | + +## `ToggleSplitButton` + +Creates a ToggleSplitButton driven by a Command (fires on each toggle). + +```csharp +ToggleSplitButtonElement ToggleSplitButton(Command command, Optional isChecked = default, Element? flyout = null) +ToggleSplitButtonElement ToggleSplitButton(Element content, Optional isChecked = default, Action? onIsCheckedChanged = null, Element? flyout = null) +ToggleSplitButtonElement ToggleSplitButton(string label, Optional isChecked = default, Action? onIsCheckedChanged = null, Element? flyout = null) +``` + +| Overload | Description | +| --- | --- | +| `ToggleSplitButton(Command, Optional, Element?)` | Creates a ToggleSplitButton driven by a Command (fires on each toggle). | +| `ToggleSplitButton(Element, Optional, Action?, Element?)` | Creates a toggle split button with declarative primary content. | +| `ToggleSplitButton(string, Optional, Action?, Element?)` | Creates a [`ToggleSplitButtonElement`](../elements/buttons.md#togglesplitbuttonelement). `isChecked` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the WinUI control own its checked state (uncontrolled). Pass `true`/`false` (implicit `T → Optional`) to control it from a parent state. | + +**Returns:** [`ToggleSplitButtonElement`](../elements/buttons.md#togglesplitbuttonelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `command` | [`Command`](../input/Command.md) | | | +| `isChecked` | [`Optional`](../components/Optional.md) | `default` | | +| `flyout` | [`Element?`](../elements/Element.md) | `null` | | +| `content` | [`Element`](../elements/Element.md) | | | +| `onIsCheckedChanged` | `Action?` | `null` | | +| `label` | `string` | | | diff --git a/docs/guide/reference/factories/collections.md b/docs/guide/reference/factories/collections.md new file mode 100644 index 0000000000..92cd06c7dc --- /dev/null +++ b/docs/guide/reference/factories/collections.md @@ -0,0 +1,344 @@ +# Factories: Collections + +Lists, grids, trees, flip views and virtualized collections. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Collections](../../collections.md) + +## `FlipView` + +[`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`FlipView`](#flipview); `KeySelector` defaults to `t => t.Key`. (spec 042 §5) + +```csharp +FlipViewElement FlipView(params Element[] items) +TemplatedFlipViewElement FlipView(IReadOnlyList items, Func viewBuilder) where T : IReactorKeyed +FlipViewElement FlipView(Optional selectedIndex, Action? onSelectedIndexChanged = null, params Element[] items) +FlipViewElement FlipView(int selectedIndex, Action? onSelectedIndexChanged = null, params Element[] items) +FlipViewElement FlipView(int? selectedIndex, Action? onSelectedIndexChanged = null, params Element[] items) +TemplatedFlipViewElement FlipView(IReadOnlyList items, Func keySelector, Func viewBuilder) +``` + +| Overload | Description | +| --- | --- | +| `FlipView(Element[])` | | +| `FlipView(IReadOnlyList, Func)` | [`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`FlipView`](#flipview); `KeySelector` defaults to `t => t.Key`. (spec 042 §5) | +| `FlipView(Optional, Action?, Element[])` | Creates a flip view whose selected index is controlled only when `selectedIndex` has a value. | +| `FlipView(int, Action?, Element[])` | Creates a flip view with a controlled selected index. Disambiguates a plain [`Int32`](https://learn.microsoft.com/dotnet/api/system.int32) argument, which converts equally well to [`Nullable`](https://learn.microsoft.com/dotnet/api/system.nullable-1) and [`Optional`](../components/Optional.md). Any [`Int32`](https://learn.microsoft.com/dotnet/api/system.int32) — including `default`, which is `0` — selects that index; pass `(int?)null` or [`Optional.Unset`](../components/Optional.md#unset) to leave the selection uncontrolled. | +| `FlipView(int?, Action?, Element[])` | Creates a flip view whose selected index is unset when `selectedIndex` is `null`. | +| `FlipView(IReadOnlyList, Func, Func)` | Creates a typed, data-driven [`TemplatedFlipViewElement`](../elements/collections.md#templatedflipviewelementt) — the templated peer of WinUI's untyped `FlipView`. | + +**Returns:** [`FlipViewElement`](../elements/collections.md#flipviewelement), [`TemplatedFlipViewElement`](../elements/collections.md#templatedflipviewelementt). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `items` | [`Element[]`](../elements/Element.md) or `IReadOnlyList` | | | +| `viewBuilder` | `Func` | | | +| `selectedIndex` | [`Optional`](../components/Optional.md) or `int` or `int?` | | | +| `onSelectedIndexChanged` | `Action?` | `null` | | +| `keySelector` | `Func` | | | + +**Remarks** + +Reactor-original — see [`ListView`](#listview) for the templated-peer naming rationale. (spec 039 §0.3) + +## `GridView` + +[`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`GridView`](#gridview); `KeySelector` defaults to `t => t.Key`. (spec 042 §5) + +```csharp +GridViewElement GridView(params Element[] items) +TemplatedGridViewElement GridView(IReadOnlyList items, Func viewBuilder) where T : IReactorKeyed +GridViewElement GridView(Optional selectedIndex, Action? onSelectedIndexChanged = null, params Element[] items) +GridViewElement GridView(int selectedIndex, Action? onSelectedIndexChanged = null, params Element[] items) +GridViewElement GridView(int? selectedIndex, Action? onSelectedIndexChanged = null, params Element[] items) +TemplatedGridViewElement GridView(IReadOnlyList items, Func keySelector, Func viewBuilder) +``` + +| Overload | Description | +| --- | --- | +| `GridView(Element[])` | | +| `GridView(IReadOnlyList, Func)` | [`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`GridView`](#gridview); `KeySelector` defaults to `t => t.Key`. (spec 042 §5) | +| `GridView(Optional, Action?, Element[])` | Creates a grid view whose selected index is controlled only when `selectedIndex` has a value. | +| `GridView(int, Action?, Element[])` | Creates a grid view with a controlled selected index. Disambiguates a plain [`Int32`](https://learn.microsoft.com/dotnet/api/system.int32) argument, which converts equally well to [`Nullable`](https://learn.microsoft.com/dotnet/api/system.nullable-1) and [`Optional`](../components/Optional.md). Any [`Int32`](https://learn.microsoft.com/dotnet/api/system.int32) — including `default`, which is `0` — selects that index; pass `(int?)null` or [`Optional.Unset`](../components/Optional.md#unset) to leave the selection uncontrolled. | +| `GridView(int?, Action?, Element[])` | Creates a grid view whose selected index is unset when `selectedIndex` is `null`. | +| `GridView(IReadOnlyList, Func, Func)` | Creates a typed, data-driven [`TemplatedGridViewElement`](../elements/collections.md#templatedgridviewelementt) — the templated peer of WinUI's untyped `GridView`. | + +**Returns:** [`GridViewElement`](../elements/collections.md#gridviewelement), [`TemplatedGridViewElement`](../elements/collections.md#templatedgridviewelementt). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `items` | [`Element[]`](../elements/Element.md) or `IReadOnlyList` | | | +| `viewBuilder` | `Func` | | | +| `selectedIndex` | [`Optional`](../components/Optional.md) or `int` or `int?` | | | +| `onSelectedIndexChanged` | `Action?` | `null` | | +| `keySelector` | `Func` | | | + +**Remarks** + +Reactor-original — see [`ListView`](#listview) for the templated-peer naming rationale. (spec 039 §0.3) + +## `ItemContainer` + +Wraps a child element in a WinUI `ItemContainer`. Required as the root element returned from an [`ItemsViewElement`](../elements/collections.md#itemsviewelementt) view builder — ItemsView's selection / focus / animation infrastructure depends on it. + +```csharp +ItemContainerElement ItemContainer(Element? child) +``` + +**Returns:** [`ItemContainerElement`](../elements/collections.md#itemcontainerelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `child` | [`Element?`](../elements/Element.md) | | + +## `ItemsRepeater` + +[`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`ItemsRepeater`](#itemsrepeater); `KeySelector` defaults to `t => t.Key`. + +```csharp +ItemsRepeaterElement ItemsRepeater(IReadOnlyList items, Func viewBuilder) where T : IReactorKeyed +ItemsRepeaterElement ItemsRepeater(IReadOnlyList items, Func keySelector, Func viewBuilder) +``` + +| Overload | Description | +| --- | --- | +| `ItemsRepeater(IReadOnlyList, Func)` | [`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`ItemsRepeater`](#itemsrepeater); `KeySelector` defaults to `t => t.Key`. | +| `ItemsRepeater(IReadOnlyList, Func, Func)` | Creates a virtualized [`ItemsRepeaterElement`](../elements/collections.md#itemsrepeaterelementt) — a bare `WinUI.ItemsRepeater` driven through the spec-042 keyed realization pipeline (same machinery LazyVStack/LazyHStack use, but without the implicit `ScrollViewer` wrap and with no hard-coded `StackLayout`). Author supplies a [`Layout`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.layout) instance via the `Layout` init-property (typically `UniformGridLayout` or `LinedFlowLayout`); host the result in a `ScrollViewer` / `ScrollView` / `RefreshContainer` for scrolling. Spec 047 §14 Phase 3 finish — Port (7). | + +**Returns:** [`ItemsRepeaterElement`](../elements/collections.md#itemsrepeaterelementt). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `items` | `IReadOnlyList` | | +| `viewBuilder` | `Func` | | +| `keySelector` | `Func` | | + +## `ItemsView` + +```csharp +ItemsViewElement ItemsView(IReadOnlyList items, Func keySelector, Func viewBuilder) +``` + +**Returns:** [`ItemsViewElement`](../elements/collections.md#itemsviewelementt). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `items` | `IReadOnlyList` | | +| `keySelector` | `Func` | | +| `viewBuilder` | `Func` | | + +## `LazyHStack` + +[`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`LazyHStack`](#lazyhstack); `KeySelector` defaults to `t => t.Key`. (spec 042 §5) + +```csharp +LazyHStackElement LazyHStack(IReadOnlyList items, Func viewBuilder) where T : IReactorKeyed +LazyHStackElement LazyHStack(IReadOnlyList items, Func keySelector, Func viewBuilder) +``` + +| Overload | Description | +| --- | --- | +| `LazyHStack(IReadOnlyList, Func)` | [`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`LazyHStack`](#lazyhstack); `KeySelector` defaults to `t => t.Key`. (spec 042 §5) | +| `LazyHStack(IReadOnlyList, Func, Func)` | Creates a virtualized horizontal stack of templated items — the horizontal peer of [`LazyVStack`](#lazyvstack). | + +**Returns:** [`LazyHStackElement`](../elements/collections.md#lazyhstackelementt). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `items` | `IReadOnlyList` | | +| `viewBuilder` | `Func` | | +| `keySelector` | `Func` | | + +**Remarks** + +Reactor-original — see [`LazyVStack`](#lazyvstack) for the naming rationale. (spec 039 §0.3) + +## `LazyVStack` + +[`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`LazyVStack`](#lazyvstack); `KeySelector` defaults to `t => t.Key`. (spec 042 §5) + +```csharp +LazyVStackElement LazyVStack(IReadOnlyList items, Func viewBuilder) where T : IReactorKeyed +LazyVStackElement LazyVStack(IReadOnlyList items, Func keySelector, Func viewBuilder) +``` + +| Overload | Description | +| --- | --- | +| `LazyVStack(IReadOnlyList, Func)` | [`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`LazyVStack`](#lazyvstack); `KeySelector` defaults to `t => t.Key`. (spec 042 §5) | +| `LazyVStack(IReadOnlyList, Func, Func)` | Creates a virtualized vertical stack of templated items. Backed by a WinUI `ItemsRepeater` inside a `ScrollViewer` — children are materialized on demand, so this scales to large item counts. | + +**Returns:** [`LazyVStackElement`](../elements/collections.md#lazyvstackelementt). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `items` | `IReadOnlyList` | | +| `viewBuilder` | `Func` | | +| `keySelector` | `Func` | | + +**Remarks** + +Reactor-original — there is no WinUI `LazyVStack`; the name is borrowed from SwiftUI for the "vertical stack, lazy materialization" semantics. Prefer this over [`VStack`](layout.md#vstack) when the child count is large or the children are expensive to instantiate. (spec 039 §0.3) + +## `ListBox` + +Creates a [`ListBoxElement`](../elements/collections.md#listboxelement). `selectedIndex` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its selection. + +```csharp +ListBoxElement ListBox(string[] items, Optional selectedIndex = default, Action? onSelectedIndexChanged = null) +``` + +**Returns:** [`ListBoxElement`](../elements/collections.md#listboxelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `items` | `string[]` | | | +| `selectedIndex` | [`Optional`](../components/Optional.md) | `default` | | +| `onSelectedIndexChanged` | `Action?` | `null` | | + +## `ListView` + +Creates a typed, data-driven [`TemplatedListViewElement`](../elements/collections.md#templatedlistviewelementt) for items that implement [`IReactorKeyed`](../components/IReactorKeyed.md). The `KeySelector` defaults to `t => t.Key` so call sites can omit it. (spec 042 §5) + +```csharp +ListViewElement ListView(params Element[] items) +TemplatedListViewElement ListView(IReadOnlyList items, Func viewBuilder) where T : IReactorKeyed +ListViewElement ListView(Optional selectedIndex, Action? onSelectedIndexChanged = null, params Element[] items) +ListViewElement ListView(int selectedIndex, Action? onSelectedIndexChanged = null, params Element[] items) +ListViewElement ListView(int? selectedIndex, Action? onSelectedIndexChanged = null, params Element[] items) +TemplatedListViewElement ListView(IReadOnlyList items, Func keySelector, Func viewBuilder) +``` + +| Overload | Description | +| --- | --- | +| `ListView(Element[])` | | +| `ListView(IReadOnlyList, Func)` | Creates a typed, data-driven [`TemplatedListViewElement`](../elements/collections.md#templatedlistviewelementt) for items that implement [`IReactorKeyed`](../components/IReactorKeyed.md). The `KeySelector` defaults to `t => t.Key` so call sites can omit it. (spec 042 §5) | +| `ListView(Optional, Action?, Element[])` | Creates a list view whose selected index is controlled only when `selectedIndex` has a value. | +| `ListView(int, Action?, Element[])` | Creates a list view with a controlled selected index. Disambiguates a plain [`Int32`](https://learn.microsoft.com/dotnet/api/system.int32) argument, which converts equally well to [`Nullable`](https://learn.microsoft.com/dotnet/api/system.nullable-1) and [`Optional`](../components/Optional.md). Any [`Int32`](https://learn.microsoft.com/dotnet/api/system.int32) — including `default`, which is `0` — selects that index; pass `(int?)null` or [`Optional.Unset`](../components/Optional.md#unset) to leave the selection uncontrolled. | +| `ListView(int?, Action?, Element[])` | Creates a list view whose selected index is unset when `selectedIndex` is `null`. | +| `ListView(IReadOnlyList, Func, Func)` | Creates a typed, data-driven [`TemplatedListViewElement`](../elements/collections.md#templatedlistviewelementt). The reconciler builds a WinUI `ListView` bound to `items` and instantiates one view per item via `viewBuilder`. | + +**Returns:** [`ListViewElement`](../elements/collections.md#listviewelement), [`TemplatedListViewElement`](../elements/collections.md#templatedlistviewelementt). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `items` | [`Element[]`](../elements/Element.md) or `IReadOnlyList` | | | +| `viewBuilder` | `Func` | | | +| `selectedIndex` | [`Optional`](../components/Optional.md) or `int` or `int?` | | | +| `onSelectedIndexChanged` | `Action?` | `null` | | +| `keySelector` | `Func` | | | + +**Remarks** + +Reactor-original generic peer of WinUI's untyped `ListView`. The element record name is `TemplatedListViewElement` (templated + typed) but the factory is the short `ListView`; the type parameter disambiguates from the existing untyped factory at the call site. (spec 039 §0.3) + +## `RefreshContainer` + +```csharp +RefreshContainerElement RefreshContainer(Element content, Action? onRefreshRequested = null) +``` + +**Returns:** [`RefreshContainerElement`](../elements/collections.md#refreshcontainerelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `content` | [`Element`](../elements/Element.md) | | | +| `onRefreshRequested` | `Action?` | `null` | | + +## `SemanticZoom` + +```csharp +SemanticZoomElement SemanticZoom(Element zoomedInView, Element zoomedOutView) +``` + +**Returns:** [`SemanticZoomElement`](../elements/collections.md#semanticzoomelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `zoomedInView` | [`Element`](../elements/Element.md) | | +| `zoomedOutView` | [`Element`](../elements/Element.md) | | + +## `SwipeControl` + +```csharp +SwipeControlElement SwipeControl(Element content, SwipeItemData[]? leftItems = null, SwipeItemData[]? rightItems = null) +``` + +**Returns:** [`SwipeControlElement`](../elements/collections.md#swipecontrolelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `content` | [`Element`](../elements/Element.md) | | | +| `leftItems` | [`SwipeItemData[]?`](../controls/collection-items.md#swipeitemdata) | `null` | | +| `rightItems` | [`SwipeItemData[]?`](../controls/collection-items.md#swipeitemdata) | `null` | | + +## `TreeNode` + +```csharp +TreeViewNodeData TreeNode(string content, params TreeViewNodeData[] children) +``` + +**Returns:** [`TreeViewNodeData`](../controls/collection-items.md#treeviewnodedata). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | +| `children` | [`TreeViewNodeData[]`](../controls/collection-items.md#treeviewnodedata) | | + +## `TreeView` + +[`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`TreeView`](#treeview); `KeySelector` defaults to `t => t.Key` so call sites can omit it. (spec 042 §5) + +```csharp +TreeViewElement TreeView(params TreeViewNodeData[] nodes) +TemplatedTreeViewElement TreeView(IReadOnlyList items, Func?> childrenSelector, Func viewBuilder) where T : IReactorKeyed +TemplatedTreeViewElement TreeView(IReadOnlyList items, Func keySelector, Func?> childrenSelector, Func viewBuilder) +``` + +| Overload | Description | +| --- | --- | +| `TreeView(TreeViewNodeData[])` | | +| `TreeView(IReadOnlyList, Func?>, Func)` | [`IReactorKeyed`](../components/IReactorKeyed.md)-typed overload of [`TreeView`](#treeview); `KeySelector` defaults to `t => t.Key` so call sites can omit it. (spec 042 §5) | +| `TreeView(IReadOnlyList, Func, Func?>, Func)` | Creates a typed, data-driven [`TemplatedTreeViewElement`](../elements/collections.md#templatedtreeviewelementt) — the hierarchical peer of [`ListView`](#listview). The reconciler builds a WinUI `TreeView` from `items`, walks the hierarchy via `childrenSelector`, and renders each node via `viewBuilder` (the `ItemTemplate` equivalent — a `data → Element` function). | + +**Returns:** [`TreeViewElement`](../elements/collections.md#treeviewelement), [`TemplatedTreeViewElement`](../elements/collections.md#templatedtreeviewelementt). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `nodes` | [`TreeViewNodeData[]`](../controls/collection-items.md#treeviewnodedata) | | +| `items` | `IReadOnlyList` | | +| `childrenSelector` | `Func?>` | | +| `viewBuilder` | `Func` | | +| `keySelector` | `Func` | | + +**Remarks** + +Heterogeneous nodes with per-shape visuals are expressed as a `switch` inside `viewBuilder` (the C# equivalent of WinUI's `ItemTemplateSelector`). This supersedes the deprecated [`TreeViewNodeData.ContentElement`](../controls/collection-items.md#contentelement) (issue #447). (spec 039 §0.3) diff --git a/docs/guide/reference/factories/composition.md b/docs/guide/reference/factories/composition.md new file mode 100644 index 0000000000..64e177e9de --- /dev/null +++ b/docs/guide/reference/factories/composition.md @@ -0,0 +1,290 @@ +# Factories: Composition + +Components, memoization, error boundaries, conditionals and other structural elements. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Components](../../components.md), [Advanced Patterns](../../advanced.md) + +## `Component` + +Embed a Component class as a child element. Usage: Component\() + +```csharp +ComponentElement Component() where T : Component, new() +ComponentElement Component(TProps props) where T : Component, new() +``` + +| Overload | Description | +| --- | --- | +| `Component()` | Embed a Component class as a child element. Usage: Component\() | +| `Component(TProps)` | Embed a Component class with typed props as a child element. Returns [`ComponentElement`](../elements/composition.md#componentelementtprops) so callers can use a record `with`-expression to produce a modified copy with updated typed props (records are immutable — `with` clones, it does not mutate). Usage: Component\("param") | + +**Returns:** [`ComponentElement`](../elements/composition.md#componentelement), [`ComponentElement`](../elements/composition.md#componentelementtprops). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `props` | `TProps` | | + +## `Empty` + +Renders nothing. Useful as a default/fallback. + +```csharp +Element Empty() +``` + +**Returns:** [`Element`](../elements/Element.md). + +## `ErrorBoundary` + +Wraps a child subtree in an error boundary with a static fallback element. + +```csharp +ErrorBoundaryElement ErrorBoundary(Element child, Element fallback) +ErrorBoundaryElement ErrorBoundary(Element child, Func fallback) +``` + +| Overload | Description | +| --- | --- | +| `ErrorBoundary(Element, Element)` | Wraps a child subtree in an error boundary with a static fallback element. | +| `ErrorBoundary(Element, Func)` | Wraps a child subtree in an error boundary. If any component in the subtree throws during rendering, the fallback function is called with the exception. When the ErrorBoundary re-renders, it retries the child (error recovery). | + +**Returns:** [`ErrorBoundaryElement`](../elements/composition.md#errorboundaryelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `child` | [`Element`](../elements/Element.md) | | +| `fallback` | [`Element`](../elements/Element.md) or `Func` | | + +## `Expr` + +Inline block-expression escape hatch: invokes `render` and returns its element, or `EmptyElement.Instance` when the lambda returns `null`. Lets callers write multi-statement bodies inside a DSL tree without extracting a local function or relying on the `((Func)(() => …))()` cast trick. + +```csharp +Element Expr(Func render) +``` + +**Returns:** [`Element`](../elements/Element.md). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `render` | `Func` | | + +**Remarks** + +Spec 033 §5. `Expr` performs no memoization, owns no `RenderContext`, and is not a reconciler boundary — it is purely composition sugar. If the body needs hooks, use `Memo(...)` or a `Component` instead. + +Exceptions thrown inside `render` propagate unchanged so the surrounding error-boundary path applies. + +**Example** + +```csharp +VStack( + Header(), + Expr(() => { + var summary = ComputeSummary(orders); + return summary.Total > 0 + ? TotalsBanner(summary) + : null; + }), + Footer()) +``` + +**Exceptions** + +| Exception | Condition | +| --- | --- | +| [`ArgumentNullException`](https://learn.microsoft.com/dotnet/api/system.argumentnullexception) | `render` is `null`. | + +## `ForEach` + +Map a list to elements (like .map() in React JSX): ForEach(items, item =\> TextBlock(item.Name)) + +When `T` implements [`IReactorKeyed`](../components/IReactorKeyed.md), each projected element is keyed from `item.Key` unless the projection already set one, so the reconciler matches rows by identity instead of by position. + +```csharp +Element ForEach(IEnumerable items, Func render) +Element ForEach(IEnumerable items, Func render) +``` + +| Overload | Description | +| --- | --- | +| `ForEach(IEnumerable, Func)` | Map a list to elements (like .map() in React JSX): ForEach(items, item =\> TextBlock(item.Name)) When `T` implements [`IReactorKeyed`](../components/IReactorKeyed.md), each projected element is keyed from `item.Key` unless the projection already set one, so the reconciler matches rows by identity instead of by position. | +| `ForEach(IEnumerable, Func)` | Map with index: ForEach(items, (item, i) =\> TextBlock($"\{i\}: \{item\}")) Keys from [`IReactorKeyed`](../components/IReactorKeyed.md) items exactly as the single-parameter overload does. | + +**Returns:** [`Element`](../elements/Element.md). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `items` | `IEnumerable` | | +| `render` | `Func` or `Func` | | + +## `Group` + +Groups elements without introducing a layout container (like React's Fragment). Children are flattened into the parent container. + +```csharp +Element Group(params Element?[] children) +``` + +**Returns:** [`Element`](../elements/Element.md). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `children` | [`Element?[]`](../elements/Element.md) | | + +## `If` + +If/else as an expression: If(loggedIn, () =\> TextBlock("Welcome"), () =\> Button("Login", ...)) + +```csharp +Element If(bool condition, Func then, Func? otherwise = null) +``` + +**Returns:** [`Element`](../elements/Element.md). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `condition` | `bool` | | | +| `then` | `Func` | | | +| `otherwise` | `Func?` | `null` | | + +## `LocaleProvider` + +```csharp +ComponentElement LocaleProvider(string locale, Element child, IStringResourceProvider? resourceProvider = null, string defaultLocale = "en-US", bool pseudoLocalize = false) +``` + +**Returns:** [`ComponentElement`](../elements/composition.md#componentelementtprops). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `locale` | `string` | | | +| `child` | [`Element`](../elements/Element.md) | | | +| `resourceProvider` | [`IStringResourceProvider?`](../localization/IStringResourceProvider.md) | `null` | | +| `defaultLocale` | `string` | `"en-US"` | | +| `pseudoLocalize` | `bool` | `false` | | + +## `Memo` + +Define a memoized inline function component. Skips re-render when dependencies haven't changed. Empty deps array = render once + own state changes only. Non-empty = re-render when any dep changes. Usage: Memo(ctx =\> TextBlock("stable"), someProp, otherProp) + +```csharp +MemoElement Memo(Func render, params object?[] dependencies) +KeyedMemoElement Memo(TKey key, Func factory) +``` + +| Overload | Description | +| --- | --- | +| `Memo(Func, object?[])` | Define a memoized inline function component. Skips re-render when dependencies haven't changed. Empty deps array = render once + own state changes only. Non-empty = re-render when any dep changes. Usage: Memo(ctx =\> TextBlock("stable"), someProp, otherProp) | +| `Memo(TKey, Func)` | Opt-in typed keyed memo for virtualized rows (issue #327). Wrap a row body in `Memo(key, () => …)` to assert the body is a **pure function of `key`**. Inside a virtualized list (`VirtualList`, `LazyVStack`, …) the owning [`ElementFactory`](../components/ElementFactory.md) caches the built element per key in a bounded LRU, so a container recycle that re-asks for the same key returns the *same* element instance — the reconciler then skips the row's rebuild + per-row diff entirely (sub-µs). This targets the fast-scroll cost of variable-height rows, where every recycle otherwise rebuilds and diffs the row from scratch. Usage: `renderItem: i => Memo(items[i].Id, () => Border(BigVariableHeightRow(items[i])))` **Purity is your responsibility.** The key must capture every input the factory reads. If the body also depends on, say, a selection flag, fold it into the key: `Memo((items[i].Id, isSelected), () => …)`. Closing over unkeyed mutable state will serve stale content. The cache is cleared automatically when the list's items/renderItem change. **Apply modifiers inside the factory, not on the wrapper.** The cross-recycle cache only unwraps a *bare* `Memo(key, …)` — one with no fluent modifiers, no `.WithKey(…)`, and no attached state (Grid/Canvas attached properties, `.Provide(…)` context, or theme bindings) on the wrapper itself. Decorating the wrapper (`Memo(id, () => …).Padding(8)`) opts the row out of caching and silently loses the perf benefit; put modifiers on the element the factory returns instead: `Memo(id, () => Border(…).Padding(8))`. Outside a virtualized factory the wrapper is transparent but *keyed*: a re-render with the same key is a no-op (the factory is not re-invoked and the inner subtree is not diffed), while a changed key replaces the inner (unmount + fresh mount of the new factory output). The exception is a component inside the subtree that updates its own state: the factory then runs again so the reconciler can walk down to that component. The cross-recycle cache only applies on the virtualized-list path. It is always safe to use anywhere an element is expected. | + +**Returns:** [`MemoElement`](../elements/composition.md#memoelement), [`KeyedMemoElement`](../elements/composition.md#keyedmemoelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `render` | `Func` | | +| `dependencies` | `object?[]` | | +| `key` | `TKey` | Stable identity that fully determines `factory`'s output. | +| `factory` | `Func` | Builds the row element. Invoked once per key on a cache miss. | + +**Type parameters** + +| Name | Description | +| --- | --- | +| `TKey` | Key type. Boxed to [`Object`](https://learn.microsoft.com/dotnet/api/system.object) and compared with [`Object.Equals`](https://learn.microsoft.com/dotnet/api/system.object.equals) / [`Object.GetHashCode`](https://learn.microsoft.com/dotnet/api/system.object.gethashcode), so value keys (ints, strings, records, value tuples) dedupe by value. This is what lets the int-index `VirtualList` path hit the cache. | + +## `PropertyGrid` + +Creates a PropertyGrid element for editing the target object's properties. Keyed by target type so switching between different target types creates a fresh component (avoiding broken reconciliation of different structures). + +```csharp +ComponentElement PropertyGrid(object target, TypeRegistry registry, Action? onRootChanged = null) +``` + +**Returns:** [`ComponentElement`](../elements/composition.md#componentelementtprops). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `target` | `object` | | | +| `registry` | [`TypeRegistry`](../controls/property-grid-templates.md#typeregistry) | | | +| `onRootChanged` | `Action?` | `null` | | + +## `RenderEachTime` + +Define an inline function component that re-renders on every parent render (no memoization), keeping its own hook scope. Made explicit so the reader can tell the always-re-render case apart from a missing deps array. + +```csharp +FuncElement RenderEachTime(Func render) +``` + +**Returns:** [`FuncElement`](../elements/composition.md#funcelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `render` | `Func` | | + +**Remarks** + +Spec 033 §4. Use sparingly — components that re-render on every parent render defeat the memoization story and can amplify render storms. Prefer [`Memo`](#memo) with an explicit deps array whenever the re-render trigger can be enumerated. + +## `VirtualList` + +Creates a VirtualList element — a count-based virtualized list. Items are rendered on demand via the renderItem callback. + +```csharp +ComponentElement VirtualList(int itemCount, Func renderItem, Func? getItemKey = null, double? itemHeight = null, double estimatedItemHeight = 40, double spacing = 0, Action? ref = null, Action? onVisibleRangeChanged = null) +``` + +**Returns:** [`ComponentElement`](../elements/composition.md#componentelementtprops). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `itemCount` | `int` | | | +| `renderItem` | `Func` | | | +| `getItemKey` | `Func?` | `null` | | +| `itemHeight` | `double?` | `null` | | +| `estimatedItemHeight` | `double` | `40` | | +| `spacing` | `double` | `0` | | +| `ref` | `Action?` | `null` | | +| `onVisibleRangeChanged` | `Action?` | `null` | | + +## `When` + +Renders element only when condition is true. Reads nicely: When(items.Any(), () =\> TextBlock("Has items")) + +```csharp +Element When(bool condition, Func then) +``` + +**Returns:** [`Element`](../elements/Element.md). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `condition` | `bool` | | +| `then` | `Func` | | diff --git a/docs/guide/reference/factories/dialogs-and-flyouts.md b/docs/guide/reference/factories/dialogs-and-flyouts.md new file mode 100644 index 0000000000..de69f2c7b8 --- /dev/null +++ b/docs/guide/reference/factories/dialogs-and-flyouts.md @@ -0,0 +1,85 @@ +# Factories: Dialogs and flyouts + +Content dialogs, flyouts, popups and teaching tips. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Dialogs and Flyouts](../../dialogs-and-flyouts.md) + +## `ContentDialog` + +```csharp +ContentDialogElement ContentDialog(string title, Element content, string primaryButtonText = "OK") +``` + +**Returns:** [`ContentDialogElement`](../elements/dialogs-and-flyouts.md#contentdialogelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `title` | `string` | | | +| `content` | [`Element`](../elements/Element.md) | | | +| `primaryButtonText` | `string` | `"OK"` | | + +## `ContentFlyout` + +```csharp +ContentFlyoutElement ContentFlyout(Element content, FlyoutPlacementMode placement = (FlyoutPlacementMode)13) +``` + +**Returns:** [`ContentFlyoutElement`](../elements/dialogs-and-flyouts.md#contentflyoutelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `content` | [`Element`](../elements/Element.md) | | | +| `placement` | `FlyoutPlacementMode` | `(FlyoutPlacementMode)13` | | + +## `Flyout` + +```csharp +FlyoutElement Flyout(Element target, Element flyoutContent) +``` + +**Returns:** [`FlyoutElement`](../elements/dialogs-and-flyouts.md#flyoutelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `target` | [`Element`](../elements/Element.md) | | +| `flyoutContent` | [`Element`](../elements/Element.md) | | + +## `Popup` + +```csharp +PopupElement Popup(Element child, bool isOpen = false, Action? onClosed = null) +``` + +**Returns:** [`PopupElement`](../elements/dialogs-and-flyouts.md#popupelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `child` | [`Element`](../elements/Element.md) | | | +| `isOpen` | `bool` | `false` | | +| `onClosed` | `Action?` | `null` | | + +## `TeachingTip` + +```csharp +TeachingTipElement TeachingTip(string title, string? subtitle = null, ElementRef? target = null) +``` + +**Returns:** [`TeachingTipElement`](../elements/dialogs-and-flyouts.md#teachingtipelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `title` | `string` | | | +| `subtitle` | `string?` | `null` | | +| `target` | [`ElementRef?`](../input/element-refs.md#elementref) | `null` | | diff --git a/docs/guide/reference/factories/forms.md b/docs/guide/reference/factories/forms.md new file mode 100644 index 0000000000..b6fa5a8027 --- /dev/null +++ b/docs/guide/reference/factories/forms.md @@ -0,0 +1,111 @@ +# Factories: Forms + +Form fields, validation rules, validation visualizers and the property grid. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Forms and Input](../../forms.md) + +## `FormField` + +Creates an auto-wired FormField from a FieldDescriptor. Resolves the editor from TypeRegistry, sets label/description from the descriptor, detects required from validators, and wires validation. + +```csharp +FormFieldElement FormField(FieldDescriptor field, object value, Action onChange, TypeRegistry? registry = null) +FormFieldElement FormField(Element content, string? label = null, bool required = false, string? description = null, string? fieldName = null, ShowWhen showWhen = ShowWhen.WhenTouched) +``` + +Declared in `FormFieldDsl`. + +| Overload | Description | +| --- | --- | +| `FormField(FieldDescriptor, object, Action, TypeRegistry?)` | Creates an auto-wired FormField from a FieldDescriptor. Resolves the editor from TypeRegistry, sets label/description from the descriptor, detects required from validators, and wires validation. | +| `FormField(Element, string?, bool, string?, string?, ShowWhen)` | Wraps a form control with a label, required indicator, and description/error area. | + +**Returns:** [`FormFieldElement`](../elements/forms.md#formfieldelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `field` | [`FieldDescriptor`](../data/descriptors.md#fielddescriptor) | | | +| `value` | `object` | | | +| `onChange` | `Action` | | | +| `registry` | [`TypeRegistry?`](../controls/property-grid-templates.md#typeregistry) | `null` | | +| `content` | [`Element`](../elements/Element.md) | | | +| `label` | `string?` | `null` | | +| `required` | `bool` | `false` | | +| `description` | `string?` | `null` | | +| `fieldName` | `string?` | `null` | | +| `showWhen` | [`ShowWhen`](../validation/enums.md#showwhen) | `ShowWhen.WhenTouched` | | + +## `ValidationRule` + +Creates a cross-field validation rule. When the predicate returns false, the message is added to the ValidationContext under the given field name. When the predicate returns true, any previous message for this rule is cleared. + +```csharp +ValidationRuleElement ValidationRule(Func predicate, string message, string field, Severity severity = Severity.Error) +``` + +Declared in `ValidationRuleDsl`. + +**Returns:** [`ValidationRuleElement`](../elements/forms.md#validationruleelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `predicate` | `Func` | | Returns true when the rule passes (valid). | +| `message` | `string` | | Error message when the rule fails. | +| `field` | `string` | | Field name to associate the error with. | +| `severity` | [`Severity`](../validation/enums.md#severity) | `Severity.Error` | Severity level (default: Error). | + +## `ValidationRuleAsync` + +Creates an async cross-field validation rule. + +```csharp +ValidationRuleElement ValidationRuleAsync(Func> asyncPredicate, string message, string field, Severity severity = Severity.Error) +``` + +Declared in `ValidationRuleDsl`. + +**Returns:** [`ValidationRuleElement`](../elements/forms.md#validationruleelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `asyncPredicate` | `Func>` | | | +| `message` | `string` | | | +| `field` | `string` | | | +| `severity` | [`Severity`](../validation/enums.md#severity) | `Severity.Error` | | + +## `ValidationVisualizer` + +Creates a custom validation visualizer with a render function. + +```csharp +ValidationVisualizerElement ValidationVisualizer(Func, Element> render, Element content, Severity? severityFilter = null, ShowWhen showWhen = ShowWhen.Always) +ValidationVisualizerElement ValidationVisualizer(VisualizerStyle style, Element content, string? title = null, Severity? severityFilter = null, ShowWhen showWhen = ShowWhen.Always) +``` + +Declared in `ValidationVisualizerDsl`. + +| Overload | Description | +| --- | --- | +| `ValidationVisualizer(Func, Element>, Element, Severity?, ShowWhen)` | Creates a custom validation visualizer with a render function. | +| `ValidationVisualizer(VisualizerStyle, Element, string?, Severity?, ShowWhen)` | Creates a validation visualizer that catches errors from its content subtree. | + +**Returns:** [`ValidationVisualizerElement`](../elements/forms.md#validationvisualizerelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `render` | `Func, Element>` | | | +| `content` | [`Element`](../elements/Element.md) | | | +| `severityFilter` | `Severity?` | `null` | | +| `showWhen` | [`ShowWhen`](../validation/enums.md#showwhen) | `ShowWhen.Always` | | +| `style` | [`VisualizerStyle`](../validation/enums.md#visualizerstyle) | | | +| `title` | `string?` | `null` | | diff --git a/docs/guide/reference/factories/index.md b/docs/guide/reference/factories/index.md new file mode 100644 index 0000000000..504874a331 --- /dev/null +++ b/docs/guide/reference/factories/index.md @@ -0,0 +1,26 @@ +# Factories + +The DSL factory methods that create element records. + +Add `using static Microsoft.UI.Reactor.Factories;` and call these methods to build an element tree, for example `VStack(TextBlock("Hello"), Button("OK", onClick))`. + +**Learn more:** [Controls](../../controls.md), [Layout](../../layout.md), [Cheat Sheet](../../cheat-sheet.md) + +## Areas + +| Area | Description | +| --- | --- | +| [Layout](layout.md) | Panels, stacks, grids, scrolling and other containers. | +| [Text](text.md) | Text blocks, rich text and the typography factories. | +| [Buttons](buttons.md) | Buttons, toggle buttons, split buttons and hyperlink buttons. | +| [Input](input.md) | Text boxes, check boxes, combo boxes, sliders, pickers and other input controls. | +| [Collections](collections.md) | Lists, grids, trees, flip views and virtualized collections. | +| [Navigation](navigation.md) | Navigation views, tabs, pivots, breadcrumbs and the title bar. | +| [Menus and commands](menus-and-commands.md) | Menus, menu bars, command bars and keyboard accelerators. | +| [Dialogs and flyouts](dialogs-and-flyouts.md) | Content dialogs, flyouts, popups and teaching tips. | +| [Media and icons](media.md) | Images, icons, animated visuals, media playback and person pictures. | +| [Shapes](shapes.md) | Rectangles, ellipses, lines, paths and brushes. | +| [Status and info](status-and-info.md) | Info bars, badges and progress indicators. | +| [Forms](forms.md) | Form fields, validation rules, validation visualizers and the property grid. | +| [Composition](composition.md) | Components, memoization, error boundaries, conditionals and other structural elements. | +| [Interop](interop.md) | Hosted XAML content, web views and maps. | diff --git a/docs/guide/reference/factories/input.md b/docs/guide/reference/factories/input.md new file mode 100644 index 0000000000..e9f1eea23c --- /dev/null +++ b/docs/guide/reference/factories/input.md @@ -0,0 +1,398 @@ +# Factories: Input + +Text boxes, check boxes, combo boxes, sliders, pickers and other input controls. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Controls](../../controls.md), [Forms and Input](../../forms.md) + +## `AutoSuggest` + +Creates an auto-suggest element with async search. + +```csharp +AutoSuggestElement AutoSuggest(T? selected, Action? onSelected = null, Func>>? search = null, Func? displayText = null, string? placeholderText = null, int debounceMs = 300, Func? template = null) +``` + +Declared in `AutoSuggestDsl`. + +**Returns:** [`AutoSuggestElement`](../elements/input.md#autosuggestelementt). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `selected` | `T?` | | | +| `onSelected` | `Action?` | `null` | | +| `search` | `Func>>?` | `null` | | +| `displayText` | `Func?` | `null` | | +| `placeholderText` | `string?` | `null` | | +| `debounceMs` | `int` | `300` | | +| `template` | `Func?` | `null` | | + +## `AutoSuggestBox` + +Creates an [`AutoSuggestBoxElement`](../elements/input.md#autosuggestboxelement). `text` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the WinUI control own its text. + +```csharp +AutoSuggestBoxElement AutoSuggestBox(Optional text = default, Action? onTextChanged = null, Action? onQuerySubmitted = null) +``` + +**Returns:** [`AutoSuggestBoxElement`](../elements/input.md#autosuggestboxelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `text` | [`Optional`](../components/Optional.md) | `default` | | +| `onTextChanged` | `Action?` | `null` | | +| `onQuerySubmitted` | `Action?` | `null` | | + +## `CalendarDatePicker` + +Creates a [`CalendarDatePickerElement`](../elements/input.md#calendardatepickerelement). `date` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its date. Pass `null` to explicitly control the date to "no selection". + +```csharp +CalendarDatePickerElement CalendarDatePicker(Optional date = default, Action? onDateChanged = null) +``` + +**Returns:** [`CalendarDatePickerElement`](../elements/input.md#calendardatepickerelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `date` | [`Optional`](../components/Optional.md) | `default` | | +| `onDateChanged` | `Action?` | `null` | | + +## `CalendarView` + +```csharp +CalendarViewElement CalendarView() +``` + +**Returns:** [`CalendarViewElement`](../elements/input.md#calendarviewelement). + +## `CheckBox` + +Creates a check box with declarative content. + +```csharp +CheckBoxElement CheckBox(Optional isChecked, Action? onIsCheckedChanged, Element content) +CheckBoxElement CheckBox(Optional isChecked = default, Action? onIsCheckedChanged = null, string? label = null) +``` + +| Overload | Description | +| --- | --- | +| `CheckBox(Optional, Action?, Element)` | Creates a check box with declarative content. | +| `CheckBox(Optional, Action?, string?)` | Creates a [`CheckBoxElement`](../elements/input.md#checkboxelement). `isChecked` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the WinUI control own its checked state. | + +**Returns:** [`CheckBoxElement`](../elements/input.md#checkboxelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `isChecked` | [`Optional`](../components/Optional.md) | `default` | | +| `onIsCheckedChanged` | `Action?` | `null` | | +| `content` | [`Element`](../elements/Element.md) | | | +| `label` | `string?` | `null` | | + +## `ColorPicker` + +Creates a [`ColorPickerElement`](../elements/input.md#colorpickerelement). `color` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its color. + +```csharp +ColorPickerElement ColorPicker(Optional color = default, Action? onColorChanged = null) +``` + +**Returns:** [`ColorPickerElement`](../elements/input.md#colorpickerelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `color` | [`Optional`](../components/Optional.md) | `default` | | +| `onColorChanged` | `Action?` | `null` | | + +## `ComboBox` + +Creates a [`ComboBoxElement`](../elements/input.md#comboboxelement) from element items. `selectedIndex` is taken as-is — pass [`Optional.Unset`](../components/Optional.md#unset) for uncontrolled, or any int (implicit `int → Optional`) for controlled. Both trailing args are required (rather than defaulted) to disambiguate from the `string[]` overload — `string` has an implicit conversion to `Element`, so a collection-expression call like `ComboBox(["A","B"], selectedIndex: 0)` would otherwise resolve to either. + +```csharp +ComboBoxElement ComboBox(Element[] itemElements, Optional selectedIndex, Action? onSelectedIndexChanged) +ComboBoxElement ComboBox(string[] items, Optional selectedIndex = default, Action? onSelectedIndexChanged = null) +``` + +| Overload | Description | +| --- | --- | +| `ComboBox(Element[], Optional, Action?)` | Creates a [`ComboBoxElement`](../elements/input.md#comboboxelement) from element items. `selectedIndex` is taken as-is — pass [`Optional.Unset`](../components/Optional.md#unset) for uncontrolled, or any int (implicit `int → Optional`) for controlled. Both trailing args are required (rather than defaulted) to disambiguate from the `string[]` overload — `string` has an implicit conversion to `Element`, so a collection-expression call like `ComboBox(["A","B"], selectedIndex: 0)` would otherwise resolve to either. | +| `ComboBox(string[], Optional, Action?)` | Creates a [`ComboBoxElement`](../elements/input.md#comboboxelement). `selectedIndex` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its selection. | + +**Returns:** [`ComboBoxElement`](../elements/input.md#comboboxelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `itemElements` | [`Element[]`](../elements/Element.md) | | | +| `selectedIndex` | [`Optional`](../components/Optional.md) | `default` | | +| `onSelectedIndexChanged` | `Action?` | `null` | | +| `items` | `string[]` | | | + +## `DatePicker` + +Creates a [`DatePickerElement`](../elements/input.md#datepickerelement). `date` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its date. + +```csharp +DatePickerElement DatePicker(Optional date = default, Action? onDateChanged = null) +``` + +**Returns:** [`DatePickerElement`](../elements/input.md#datepickerelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `date` | [`Optional`](../components/Optional.md) | `default` | | +| `onDateChanged` | `Action?` | `null` | | + +## `MaskedTextBox` + +Creates a [`MaskedTextBoxElement`](../elements/input.md#maskedtextboxelement) — a Reactor-original masked input control (cf. WinForms `MaskedTextBox`; WinUI ships no first-party equivalent). + +```csharp +MaskedTextBoxElement MaskedTextBox(string value, Action? onChanged = null, string? mask = null, string? header = null, char placeholder = '_') +``` + +Declared in `MaskedTextBoxDsl`. + +**Returns:** [`MaskedTextBoxElement`](../elements/input.md#maskedtextboxelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `value` | `string` | | | +| `onChanged` | `Action?` | `null` | | +| `mask` | `string?` | `null` | | +| `header` | `string?` | `null` | | +| `placeholder` | `char` | `'_'` | | + +**Remarks** + +Named to align with WinUI's `TextBox` and Reactor's `TextBox()` factory. (issue #389) + +## `NumberBox` + +Creates a [`NumberBoxElement`](../elements/input.md#numberboxelement). `value` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the WinUI control own its value. + +```csharp +NumberBoxElement NumberBox(Optional value = default, Action? onValueChanged = null, string? header = null) +``` + +**Returns:** [`NumberBoxElement`](../elements/input.md#numberboxelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `value` | [`Optional`](../components/Optional.md) | `default` | | +| `onValueChanged` | `Action?` | `null` | | +| `header` | `string?` | `null` | | + +## `PasswordBox` + +Creates a [`PasswordBoxElement`](../elements/input.md#passwordboxelement). `password` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the WinUI control own its password. + +```csharp +PasswordBoxElement PasswordBox(Optional password = default, Action? onPasswordChanged = null, string? placeholderText = null) +``` + +**Returns:** [`PasswordBoxElement`](../elements/input.md#passwordboxelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `password` | [`Optional`](../components/Optional.md) | `default` | | +| `onPasswordChanged` | `Action?` | `null` | | +| `placeholderText` | `string?` | `null` | | + +## `RadioButton` + +Creates a radio button with declarative content. + +```csharp +RadioButtonElement RadioButton(Element content, Optional isChecked = default, Action? onIsCheckedChanged = null, string? groupName = null) +RadioButtonElement RadioButton(string label, Optional isChecked = default, Action? onIsCheckedChanged = null, string? groupName = null) +``` + +| Overload | Description | +| --- | --- | +| `RadioButton(Element, Optional, Action?, string?)` | Creates a radio button with declarative content. | +| `RadioButton(string, Optional, Action?, string?)` | Creates a [`RadioButtonElement`](../elements/input.md#radiobuttonelement). `isChecked` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its checked state. | + +**Returns:** [`RadioButtonElement`](../elements/input.md#radiobuttonelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `content` | [`Element`](../elements/Element.md) | | | +| `isChecked` | [`Optional`](../components/Optional.md) | `default` | | +| `onIsCheckedChanged` | `Action?` | `null` | | +| `groupName` | `string?` | `null` | | +| `label` | `string` | | | + +## `RadioButtons` + +Creates a [`RadioButtonsElement`](../elements/input.md#radiobuttonselement). `selectedIndex` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its selection. + +```csharp +RadioButtonsElement RadioButtons(string[] items, Optional selectedIndex = default, Action? onSelectedIndexChanged = null) +``` + +**Returns:** [`RadioButtonsElement`](../elements/input.md#radiobuttonselement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `items` | `string[]` | | | +| `selectedIndex` | [`Optional`](../components/Optional.md) | `default` | | +| `onSelectedIndexChanged` | `Action?` | `null` | | + +## `RatingControl` + +Creates a [`RatingControlElement`](../elements/input.md#ratingcontrolelement). `value` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its value. + +```csharp +RatingControlElement RatingControl(Optional value = default, Action? onValueChanged = null) +``` + +**Returns:** [`RatingControlElement`](../elements/input.md#ratingcontrolelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `value` | [`Optional`](../components/Optional.md) | `default` | | +| `onValueChanged` | `Action?` | `null` | | + +## `RichEditBox` + +Creates a [`RichEditBoxElement`](../elements/input.md#richeditboxelement). `text` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the WinUI control own its text (uncontrolled). Pass any string (implicit `T → Optional`) to control the text from a parent state. + +```csharp +RichEditBoxElement RichEditBox(Optional text = default, Action? onTextChanged = null) +``` + +**Returns:** [`RichEditBoxElement`](../elements/input.md#richeditboxelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `text` | [`Optional`](../components/Optional.md) | `default` | | +| `onTextChanged` | `Action?` | `null` | | + +## `Slider` + +Creates a [`SliderElement`](../elements/input.md#sliderelement). `value` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its value. + +```csharp +SliderElement Slider(Optional value = default, double min = 0, double max = 100, Action? onValueChanged = null) +``` + +**Returns:** [`SliderElement`](../elements/input.md#sliderelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `value` | [`Optional`](../components/Optional.md) | `default` | | +| `min` | `double` | `0` | | +| `max` | `double` | `100` | | +| `onValueChanged` | `Action?` | `null` | | + +## `TextBox` + +Creates a [`TextBoxElement`](../elements/input.md#textboxelement) wrapping WinUI's `Microsoft.UI.Xaml.Controls.TextBox`. + +```csharp +TextBoxElement TextBox(Optional value = default, Action? onChanged = null, string? placeholderText = null, string? header = null) +``` + +**Returns:** [`TextBoxElement`](../elements/input.md#textboxelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `value` | [`Optional`](../components/Optional.md) | `default` | | +| `onChanged` | `Action?` | `null` | | +| `placeholderText` | `string?` | `null` | | +| `header` | `string?` | `null` | | + +## `ThreeStateCheckBox` + +Creates a three-state check box with declarative content. + +```csharp +CheckBoxElement ThreeStateCheckBox(Optional checkedState, Action? onCheckedStateChanged, Element content) +CheckBoxElement ThreeStateCheckBox(Optional checkedState = default, Action? onCheckedStateChanged = null, string? label = null) +``` + +| Overload | Description | +| --- | --- | +| `ThreeStateCheckBox(Optional, Action?, Element)` | Creates a three-state check box with declarative content. | +| `ThreeStateCheckBox(Optional, Action?, string?)` | Creates a three-state [`CheckBoxElement`](../elements/input.md#checkboxelement). `checkedState` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its state. | + +**Returns:** [`CheckBoxElement`](../elements/input.md#checkboxelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `checkedState` | [`Optional`](../components/Optional.md) | `default` | | +| `onCheckedStateChanged` | `Action?` | `null` | | +| `content` | [`Element`](../elements/Element.md) | | | +| `label` | `string?` | `null` | | + +## `TimePicker` + +Creates a [`TimePickerElement`](../elements/input.md#timepickerelement). `time` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its time. + +```csharp +TimePickerElement TimePicker(Optional time = default, Action? onTimeChanged = null) +``` + +**Returns:** [`TimePickerElement`](../elements/input.md#timepickerelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `time` | [`Optional`](../components/Optional.md) | `default` | | +| `onTimeChanged` | `Action?` | `null` | | + +## `ToggleSwitch` + +Creates a [`ToggleSwitchElement`](../elements/input.md#toggleswitchelement). `isOn` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its on/off state. + +```csharp +ToggleSwitchElement ToggleSwitch(Optional isOn = default, Action? onIsOnChanged = null, string? onContent = null, string? offContent = null, string? header = null) +``` + +**Returns:** [`ToggleSwitchElement`](../elements/input.md#toggleswitchelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `isOn` | [`Optional`](../components/Optional.md) | `default` | | +| `onIsOnChanged` | `Action?` | `null` | | +| `onContent` | `string?` | `null` | | +| `offContent` | `string?` | `null` | | +| `header` | `string?` | `null` | | diff --git a/docs/guide/reference/factories/interop.md b/docs/guide/reference/factories/interop.md new file mode 100644 index 0000000000..a5a4799f1f --- /dev/null +++ b/docs/guide/reference/factories/interop.md @@ -0,0 +1,71 @@ +# Factories: Interop + +Hosted XAML content, web views and maps. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Coming from XAML](../../xaml-developers.md) + +## `MapControl` + +```csharp +MapControlElement MapControl(string? mapServiceToken = null, double zoomLevel = 1) +``` + +**Returns:** [`MapControlElement`](../elements/interop.md#mapcontrolelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `mapServiceToken` | `string?` | `null` | | +| `zoomLevel` | `double` | `1` | | + +## `WebView2` + +```csharp +WebView2Element WebView2(Uri? source = null) +``` + +**Returns:** [`WebView2Element`](../elements/interop.md#webview2element). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `source` | `Uri?` | `null` | | + +## `XamlHost` + +Embeds an arbitrary [`FrameworkElement`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.frameworkelement) (a UserControl, a custom control) created by `factory` on mount; `updater` runs after creation and on every update. Equivalent to `new XamlHostElement(factory, updater) { TypeKey = typeKey }`, but records the call site for the source map like every other factory. + +```csharp +XamlHostElement XamlHost(Func factory, Action? updater = null, string? typeKey = null) +``` + +**Returns:** [`XamlHostElement`](../elements/interop.md#xamlhostelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `factory` | `Func` | | Creates the hosted control on mount. | +| `updater` | `Action?` | `null` | Patches the hosted control after creation and on every update. | +| `typeKey` | `string?` | `null` | Discriminator for in-place updates: two hosts update in place only when their keys match, so unrelated hosted controls are not reconciled against each other. | + +## `XamlPage` + +Embeds an existing XAML [`Page`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.page) in a [`Frame`](navigation.md#frame), navigated to `pageType` with `parameter`. Re-navigates in place when either changes. Equivalent to `new XamlPageElement(pageType, parameter)`, but records the call site for the source map like every other factory. + +```csharp +XamlPageElement XamlPage(Type pageType, object? parameter = null) +``` + +**Returns:** [`XamlPageElement`](../elements/interop.md#xamlpageelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `pageType` | `Type` | | | +| `parameter` | `object?` | `null` | | diff --git a/docs/guide/reference/factories/layout.md b/docs/guide/reference/factories/layout.md new file mode 100644 index 0000000000..cf84f8182a --- /dev/null +++ b/docs/guide/reference/factories/layout.md @@ -0,0 +1,423 @@ +# Factories: Layout + +Panels, stacks, grids, scrolling and other containers. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Layout](../../layout.md), [Flex Layout](../../flex-layout.md) + +## `AnnotatedScrollBar` + +```csharp +AnnotatedScrollBarElement AnnotatedScrollBar() +``` + +**Returns:** [`AnnotatedScrollBarElement`](../elements/layout.md#annotatedscrollbarelement). + +## `Border` + +```csharp +BorderElement Border(Element? child) +``` + +**Returns:** [`BorderElement`](../elements/layout.md#borderelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `child` | [`Element?`](../elements/Element.md) | | + +## `Canvas` + +```csharp +CanvasElement Canvas(params Element?[] children) +``` + +**Returns:** [`CanvasElement`](../elements/layout.md#canvaselement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `children` | [`Element?[]`](../elements/Element.md) | | + +## `Card` + +Renders `child` inside a card-styled [`BorderElement`](../elements/layout.md#borderelement). Defaults match the canonical WinUI card: 8px corner radius, ~16px padding, theme-aware `CardBackgroundFillColorDefaultBrush` + `CardStrokeColorDefaultBrush` 1px stroke. Re-themes on light / dark / contrast switches because the brushes resolve through [`ThemeRef`](../theming/ThemeRef.md). + +```csharp +BorderElement Card(Element child) +``` + +**Returns:** [`BorderElement`](../elements/layout.md#borderelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `child` | [`Element`](../elements/Element.md) | | + +**Remarks** + +Override any preset by chaining a fluent on the returned border: `Card(child).Padding(24).CornerRadius(16).Background(Theme.SubtleFill)`. + +## `Expander` + +Creates an [`ExpanderElement`](../elements/layout.md#expanderelement). `isExpanded` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it and the WinUI control owns its expansion state (uncontrolled — user clicks persist across rerenders). Pass `true`/`false` (implicit `T → Optional`) to control it from a parent state. + +```csharp +ExpanderElement Expander(string header, Element content, Optional isExpanded = default, Action? onIsExpandedChanged = null) +``` + +**Returns:** [`ExpanderElement`](../elements/layout.md#expanderelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `header` | `string` | | | +| `content` | [`Element`](../elements/Element.md) | | | +| `isExpanded` | [`Optional`](../components/Optional.md) | `default` | | +| `onIsExpandedChanged` | `Action?` | `null` | | + +## `Flex` + +Creates a Yoga-based flexbox container ([`FlexElement`](../elements/layout.md#flexelement)). Default direction is [`FlexDirection.Row`](../layout/flex-enums.md#values_1). + +```csharp +FlexElement Flex(params Element?[] children) +FlexElement Flex(FlexDirection direction, params Element?[] children) +``` + +| Overload | Description | +| --- | --- | +| `Flex(Element?[])` | Creates a Yoga-based flexbox container ([`FlexElement`](../elements/layout.md#flexelement)). Default direction is [`FlexDirection.Row`](../layout/flex-enums.md#values_1). | +| `Flex(FlexDirection, Element?[])` | Creates a Yoga flexbox container with an explicit direction. | + +**Returns:** [`FlexElement`](../elements/layout.md#flexelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `children` | [`Element?[]`](../elements/Element.md) | | +| `direction` | [`FlexDirection`](../layout/flex-enums.md#flexdirection) | | + +**Remarks** + +Reactor-original — there is no WinUI `Flex` control. This is a custom panel backed by Yoga (Facebook's flexbox engine, see [`FlexPanel`](../layout/flex-enums.md#flexpanel)) for full CSS-flexbox semantics inside a WinUI tree. Prefer [`VStack`](#vstack) / [`HStack`](#hstack) for simple stacks; reach for Flex when you need wrap, justify-content / align-items, or per-child grow/shrink. (spec 039 §0.3) + +Reactor-original — see [`Flex`](#flex) for the rationale. + +## `FlexColumn` + +Creates a Yoga flexbox container with [`FlexDirection.Column`](../layout/flex-enums.md#values_1). + +```csharp +FlexElement FlexColumn(params Element?[] children) +``` + +**Returns:** [`FlexElement`](../elements/layout.md#flexelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `children` | [`Element?[]`](../elements/Element.md) | | + +**Remarks** + +Reactor-original convenience for the column-direction flex case — see [`Flex`](#flex) for the rationale. (spec 039 §0.3) + +## `FlexRow` + +Creates a Yoga flexbox container with [`FlexDirection.Row`](../layout/flex-enums.md#values_1). + +```csharp +FlexElement FlexRow(params Element?[] children) +``` + +**Returns:** [`FlexElement`](../elements/layout.md#flexelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `children` | [`Element?[]`](../elements/Element.md) | | + +**Remarks** + +Reactor-original convenience for the row-direction flex case — see [`Flex`](#flex) for the rationale. (spec 039 §0.3) + +## `Grid` + +Creates a [`GridElement`](../elements/layout.md#gridelement) with strongly-typed track sizes. + +```csharp +GridElement Grid(GridSize[] columns, GridSize[] rows, params Element?[] children) +``` + +**Returns:** [`GridElement`](../elements/layout.md#gridelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `columns` | [`GridSize[]`](../layout/GridSize.md) | | +| `rows` | [`GridSize[]`](../layout/GridSize.md) | | +| `children` | [`Element?[]`](../elements/Element.md) | | + +**Remarks** + +Spec 033 §1. Use [`GridSize.Auto`](../layout/GridSize.md#auto) / [`GridSize.Star`](../layout/GridSize.md#star) / [`GridSize.Px`](../layout/GridSize.md#px) instead of the legacy string-form (`"Auto"`/`"*"`/`"200"`) for compile-time validation and IntelliSense over the legal track shapes. + +**Exceptions** + +| Exception | Condition | +| --- | --- | +| [`ArgumentNullException`](https://learn.microsoft.com/dotnet/api/system.argumentnullexception) | Thrown when `columns` or `rows` is null. | + +## `HStack` + +Creates a horizontal [`StackElement`](../elements/layout.md#stackelement) (WinUI `StackPanel` with [`Orientation.Horizontal`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.orientation.horizontal)). Default `Spacing` is 8 — see [`StackElement.Spacing`](../elements/layout.md#stackelement). + +```csharp +StackElement HStack(params Element?[] children) +StackElement HStack(double spacing, params Element?[] children) +``` + +| Overload | Description | +| --- | --- | +| `HStack(Element?[])` | Creates a horizontal [`StackElement`](../elements/layout.md#stackelement) (WinUI `StackPanel` with [`Orientation.Horizontal`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.orientation.horizontal)). Default `Spacing` is 8 — see [`StackElement.Spacing`](../elements/layout.md#stackelement). | +| `HStack(double, Element?[])` | Creates a horizontal [`StackElement`](../elements/layout.md#stackelement) with an explicit `Spacing` override (the first positional argument). | + +**Returns:** [`StackElement`](../elements/layout.md#stackelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `children` | [`Element?[]`](../elements/Element.md) | | +| `spacing` | `double` | | + +**Remarks** + +Reactor-original name — see [`VStack`](#vstack) for the naming rationale. (spec 039 §0.3) + +Reactor-original convenience overload — see [`VStack`](#vstack) for the naming rationale. + +## `InterspersedGrid` + +Creates a grid with items interspersed with separator elements along one axis. Commonly used for split panels where children are separated by splitters. + +Each item gets a proportional (\*) size from `proportions`, and separators get a fixed pixel size of `separatorSize`. + +Example: InterspersedGrid(Orientation.Horizontal, children, proportions, 6, i =\> MySplitter(i)) produces columns: "0.33\*", "6", "0.33\*", "6", "0.34\*" with children and splitters placed. + +```csharp +GridElement InterspersedGrid(Orientation orientation, Element[] items, double[] proportions, double separatorSize, Func separatorFactory) +``` + +**Returns:** [`GridElement`](../elements/layout.md#gridelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `orientation` | `Orientation` | | +| `items` | [`Element[]`](../elements/Element.md) | | +| `proportions` | `double[]` | | +| `separatorSize` | `double` | | +| `separatorFactory` | `Func` | | + +## `ParallaxView` + +```csharp +ParallaxViewElement ParallaxView(Element child, double verticalShift = 0, double horizontalShift = 0) +``` + +**Returns:** [`ParallaxViewElement`](../elements/layout.md#parallaxviewelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `child` | [`Element`](../elements/Element.md) | | | +| `verticalShift` | `double` | `0` | | +| `horizontalShift` | `double` | `0` | | + +## `RelativePanel` + +```csharp +RelativePanelElement RelativePanel(params Element?[] children) +``` + +**Returns:** [`RelativePanelElement`](../elements/layout.md#relativepanelelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `children` | [`Element?[]`](../elements/Element.md) | | + +## `ScrollView` + +Creates a [`ScrollViewElement`](../elements/layout.md#scrollviewelement) wrapping `child` in the modern [`ScrollView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.scrollview) (InteractionTracker-backed, derives from `FrameworkElement`). + +```csharp +ScrollViewElement ScrollView(Element child) +``` + +**Returns:** [`ScrollViewElement`](../elements/layout.md#scrollviewelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `child` | [`Element`](../elements/Element.md) | | + +**Remarks** + +Exposes capabilities the legacy `ScrollViewer` lacks — `ContentOrientation`, `HorizontalAnchorRatio` / `VerticalAnchorRatio`, and the `Scrolling*` enum surface. For the classic control, use [`ScrollViewer`](#scrollviewer). Issue #348. + +## `ScrollViewer` + +Creates a [`ScrollViewerElement`](../elements/layout.md#scrollviewerelement) wrapping `child` in the classic [`ScrollViewer`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.scrollviewer) container (derives from `Control`; pan + zoom). + +```csharp +ScrollViewerElement ScrollViewer(Element child) +``` + +**Returns:** [`ScrollViewerElement`](../elements/layout.md#scrollviewerelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `child` | [`Element`](../elements/Element.md) | | + +**Remarks** + +For the newer InteractionTracker-backed [`ScrollView`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.scrollview) (different enum surface, different events, additive features like `ContentOrientation` and anchor ratios), use [`ScrollView`](#scrollview). Issue #348. + +## `SplitView` + +```csharp +SplitViewElement SplitView(Element? pane = null, Element? content = null) +``` + +**Returns:** [`SplitViewElement`](../elements/layout.md#splitviewelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `pane` | [`Element?`](../elements/Element.md) | `null` | | +| `content` | [`Element?`](../elements/Element.md) | `null` | | + +## `Thick` + +Creates a uniform Thickness. Shorthand for new Thickness(uniform). + +```csharp +Thickness Thick(double uniform) +Thickness Thick(double horizontal, double vertical) +Thickness Thick(double left, double top, double right, double bottom) +``` + +| Overload | Description | +| --- | --- | +| `Thick(double)` | Creates a uniform Thickness. Shorthand for new Thickness(uniform). | +| `Thick(double, double)` | Creates a Thickness with horizontal and vertical values. Usage: Thick(16, 8) → Thickness(16, 8, 16, 8) | +| `Thick(double, double, double, double)` | Creates a Thickness with all four sides specified. | + +**Returns:** [`Thickness`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.thickness). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `uniform` | `double` | | +| `horizontal` | `double` | | +| `vertical` | `double` | | +| `left` | `double` | | +| `top` | `double` | | +| `right` | `double` | | +| `bottom` | `double` | | + +## `UniformGrid` + +Creates a uniform grid with equal-sized cells along one axis. Shorthand for a grid where all items share equal proportions with no separators. + +```csharp +GridElement UniformGrid(Orientation orientation, params Element?[] items) +``` + +**Returns:** [`GridElement`](../elements/layout.md#gridelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `orientation` | `Orientation` | | +| `items` | [`Element?[]`](../elements/Element.md) | | + +## `VStack` + +Creates a vertical [`StackElement`](../elements/layout.md#stackelement) (WinUI `StackPanel` with [`Orientation.Vertical`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.orientation.vertical)). Default `Spacing` is 8 — see [`StackElement.Spacing`](../elements/layout.md#stackelement). + +```csharp +StackElement VStack(params Element?[] children) +StackElement VStack(double spacing, params Element?[] children) +``` + +| Overload | Description | +| --- | --- | +| `VStack(Element?[])` | Creates a vertical [`StackElement`](../elements/layout.md#stackelement) (WinUI `StackPanel` with [`Orientation.Vertical`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.orientation.vertical)). Default `Spacing` is 8 — see [`StackElement.Spacing`](../elements/layout.md#stackelement). | +| `VStack(double, Element?[])` | Creates a vertical [`StackElement`](../elements/layout.md#stackelement) with an explicit `Spacing` override (the first positional argument). | + +**Returns:** [`StackElement`](../elements/layout.md#stackelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `children` | [`Element?[]`](../elements/Element.md) | | +| `spacing` | `double` | | + +**Remarks** + +Reactor-original name — WinUI exposes one `StackPanel` control keyed by `Orientation`; Reactor splits it into two factories ([`VStack`](#vstack) / [`HStack`](#hstack)) because the orientation is almost always known at the call site and the shorter names reduce DSL noise. The SwiftUI / React Native names are load-bearing for cross-platform agent familiarity. (spec 039 §0.3) + +Reactor-original convenience overload — see [`VStack`](#vstack) for the naming rationale. + +## `Viewbox` + +```csharp +ViewboxElement Viewbox(Element child) +``` + +**Returns:** [`ViewboxElement`](../elements/layout.md#viewboxelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `child` | [`Element`](../elements/Element.md) | | + +## `WrapGrid` + +```csharp +WrapGridElement WrapGrid(params Element?[] children) +WrapGridElement WrapGrid(int maxRowsOrColumns, params Element?[] children) +``` + +**Returns:** [`WrapGridElement`](../elements/layout.md#wrapgridelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `children` | [`Element?[]`](../elements/Element.md) | | +| `maxRowsOrColumns` | `int` | | diff --git a/docs/guide/reference/factories/media.md b/docs/guide/reference/factories/media.md new file mode 100644 index 0000000000..c14cc2cd98 --- /dev/null +++ b/docs/guide/reference/factories/media.md @@ -0,0 +1,164 @@ +# Factories: Media and icons + +Images, icons, animated visuals, media playback and person pictures. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Text and Media](../../text-and-media.md) + +## `AnimatedIcon` + +```csharp +AnimatedIconElement AnimatedIcon(object? source = null, IconSource? fallbackIconSource = null) +``` + +**Returns:** [`AnimatedIconElement`](../elements/media.md#animatediconelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `source` | `object?` | `null` | | +| `fallbackIconSource` | `IconSource?` | `null` | | + +## `AnimatedVisualPlayer` + +```csharp +AnimatedVisualPlayerElement AnimatedVisualPlayer() +``` + +**Returns:** [`AnimatedVisualPlayerElement`](../elements/media.md#animatedvisualplayerelement). + +## `BitmapIcon` + +```csharp +BitmapIconData BitmapIcon(Uri source, bool showAsMonochrome = true) +``` + +**Returns:** [`BitmapIconData`](../controls/icons.md#bitmapicondata). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `source` | `Uri` | | | +| `showAsMonochrome` | `bool` | `true` | | + +## `FontIcon` + +```csharp +FontIconData FontIcon(string glyph, string? fontFamily = null, double? fontSize = null) +``` + +**Returns:** [`FontIconData`](../controls/icons.md#fonticondata). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `glyph` | `string` | | | +| `fontFamily` | `string?` | `null` | | +| `fontSize` | `double?` | `null` | | + +## `Icon` + +Creates a standalone icon element from an [`IconData`](../controls/icons.md#icondata) instance. + +```csharp +IconElement Icon(IconData data) +IconElement Icon(Symbol symbol) +IconElement Icon(string symbol) +``` + +| Overload | Description | +| --- | --- | +| `Icon(IconData)` | Creates a standalone icon element from an [`IconData`](../controls/icons.md#icondata) instance. | +| `Icon(Symbol)` | Creates a standalone symbol icon element from a [`Symbol`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.symbol) enum value. | +| `Icon(string)` | Creates a standalone symbol icon element (e.g. `Icon("Home")`). | + +**Returns:** [`IconElement`](../elements/media.md#iconelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `data` | [`IconData`](../controls/icons.md#icondata) | | +| `symbol` | `Symbol` or `string` | | + +## `Image` + +```csharp +ImageElement Image(string source) +``` + +**Returns:** [`ImageElement`](../elements/media.md#imageelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `source` | `string` | | + +## `ImageIcon` + +```csharp +ImageIconData ImageIcon(Uri source) +``` + +**Returns:** [`ImageIconData`](../controls/icons.md#imageicondata). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `source` | `Uri` | | + +## `MediaPlayerElement` + +```csharp +MediaPlayerElementElement MediaPlayerElement(string? source = null) +``` + +**Returns:** [`MediaPlayerElementElement`](../elements/media.md#mediaplayerelementelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `source` | `string?` | `null` | | + +## `PathIcon` + +```csharp +PathIconData PathIcon(string data) +``` + +**Returns:** [`PathIconData`](../controls/icons.md#pathicondata). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `data` | `string` | | + +## `PersonPicture` + +```csharp +PersonPictureElement PersonPicture() +``` + +**Returns:** [`PersonPictureElement`](../elements/media.md#personpictureelement). + +## `SymbolIcon` + +```csharp +SymbolIconData SymbolIcon(string symbol) +``` + +**Returns:** [`SymbolIconData`](../controls/icons.md#symbolicondata). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `symbol` | `string` | | diff --git a/docs/guide/reference/factories/menus-and-commands.md b/docs/guide/reference/factories/menus-and-commands.md new file mode 100644 index 0000000000..06c5f5fb28 --- /dev/null +++ b/docs/guide/reference/factories/menus-and-commands.md @@ -0,0 +1,280 @@ +# Factories: Menus and commands + +Menus, menu bars, command bars and keyboard accelerators. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Commanding](../../commanding.md) + +## `Accelerator` + +```csharp +KeyboardAcceleratorData Accelerator(VirtualKey key, VirtualKeyModifiers modifiers = default) +``` + +**Returns:** [`KeyboardAcceleratorData`](../controls/menu-items.md#keyboardacceleratordata). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `key` | `VirtualKey` | | | +| `modifiers` | `VirtualKeyModifiers` | `default` | | + +## `AppBarButton` + +Creates an AppBarButton driven by a Command. Maps Label, Icon, Execute, Accelerator, IsEnabled, AccessKey, and Description. + +```csharp +AppBarButtonData AppBarButton(Command command) +AppBarButtonData AppBarButton(string label, Action? onClick = null, string? icon = null) +``` + +**Returns:** [`AppBarButtonData`](../controls/menu-items.md#appbarbuttondata). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `command` | [`Command`](../input/Command.md) | | | +| `label` | `string` | | | +| `onClick` | `Action?` | `null` | | +| `icon` | `string?` | `null` | | + +## `AppBarSeparator` + +```csharp +AppBarSeparatorData AppBarSeparator() +``` + +**Returns:** [`AppBarSeparatorData`](../controls/menu-items.md#appbarseparatordata). + +## `AppBarToggleButton` + +```csharp +AppBarToggleButtonData AppBarToggleButton(string label, bool isChecked = false, Action? onIsCheckedChanged = null, string? icon = null) +``` + +**Returns:** [`AppBarToggleButtonData`](../controls/menu-items.md#appbartogglebuttondata). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `label` | `string` | | | +| `isChecked` | `bool` | `false` | | +| `onIsCheckedChanged` | `Action?` | `null` | | +| `icon` | `string?` | `null` | | + +## `CommandBar` + +```csharp +CommandBarElement CommandBar(AppBarItemBase[]? primaryCommands = null, AppBarItemBase[]? secondaryCommands = null) +``` + +**Returns:** [`CommandBarElement`](../elements/menus-and-commands.md#commandbarelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `primaryCommands` | [`AppBarItemBase[]?`](../controls/menu-items.md#appbaritembase) | `null` | | +| `secondaryCommands` | [`AppBarItemBase[]?`](../controls/menu-items.md#appbaritembase) | `null` | | + +## `CommandBarFlyout` + +```csharp +CommandBarFlyoutElement CommandBarFlyout(Element target, AppBarItemBase[]? primaryCommands = null, AppBarItemBase[]? secondaryCommands = null) +``` + +**Returns:** [`CommandBarFlyoutElement`](../elements/menus-and-commands.md#commandbarflyoutelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `target` | [`Element`](../elements/Element.md) | | | +| `primaryCommands` | [`AppBarItemBase[]?`](../controls/menu-items.md#appbaritembase) | `null` | | +| `secondaryCommands` | [`AppBarItemBase[]?`](../controls/menu-items.md#appbaritembase) | `null` | | + +## `CommandHost` + +Scopes keyboard accelerators from the given commands to the child subtree. Only commands with an Accelerator produce keyboard accelerators on the host element. + +```csharp +CommandHostElement CommandHost(Command[] commands, Element child) +``` + +**Returns:** [`CommandHostElement`](../elements/menus-and-commands.md#commandhostelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `commands` | [`Command[]`](../input/Command.md) | | +| `child` | [`Element`](../elements/Element.md) | | + +## `DevtoolsMenu` + +Renders the optional in-app devtools menu when Microsoft.UI.Reactor.Devtools is referenced and active; otherwise returns [`Empty`](composition.md#empty). + +```csharp +Element DevtoolsMenu(Func>? items = null, string glyph = "⚡", string toolTip = "Devtools", string? automationId = null) +``` + +**Returns:** [`Element`](../elements/Element.md). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `items` | `Func>?` | `null` | | +| `glyph` | `string` | `"⚡"` | | +| `toolTip` | `string` | `"Devtools"` | | +| `automationId` | `string?` | `null` | | + +## `Menu` + +```csharp +MenuBarItemData Menu(string title, params MenuFlyoutItemBase[] items) +``` + +**Returns:** [`MenuBarItemData`](../controls/menu-items.md#menubaritemdata). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `title` | `string` | | +| `items` | [`MenuFlyoutItemBase[]`](../controls/menu-items.md#menuflyoutitembase) | | + +## `MenuBar` + +```csharp +MenuBarElement MenuBar(params MenuBarItemData[] items) +``` + +**Returns:** [`MenuBarElement`](../elements/menus-and-commands.md#menubarelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `items` | [`MenuBarItemData[]`](../controls/menu-items.md#menubaritemdata) | | + +## `MenuFlyout` + +```csharp +MenuFlyoutElement MenuFlyout(Element target, params MenuFlyoutItemBase[] items) +``` + +**Returns:** [`MenuFlyoutElement`](../elements/menus-and-commands.md#menuflyoutelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `target` | [`Element`](../elements/Element.md) | | +| `items` | [`MenuFlyoutItemBase[]`](../controls/menu-items.md#menuflyoutitembase) | | + +## `MenuItem` + +Creates a MenuFlyoutItem driven by a Command. Maps Label → Text, Icon, Execute → OnClick, Accelerator, IsEnabled, AccessKey. + +```csharp +MenuFlyoutItemData MenuItem(Command command) +MenuFlyoutItemData MenuItem(Command command, T parameter) +MenuFlyoutItemData MenuItem(string text, Action? onClick = null, string? icon = null) +``` + +| Overload | Description | +| --- | --- | +| `MenuItem(Command)` | Creates a MenuFlyoutItem driven by a Command. Maps Label → Text, Icon, Execute → OnClick, Accelerator, IsEnabled, AccessKey. | +| `MenuItem(Command, T)` | Creates a MenuFlyoutItem driven by a parameterized Command. Wraps the action to invoke with the bound parameter. | +| `MenuItem(string, Action?, string?)` | | + +**Returns:** [`MenuFlyoutItemData`](../controls/menu-items.md#menuflyoutitemdata). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `command` | [`Command`](../input/Command.md) or [`Command`](../input/Command-1.md) | | | +| `parameter` | `T` | | | +| `text` | `string` | | | +| `onClick` | `Action?` | `null` | | +| `icon` | `string?` | `null` | | + +## `MenuItems` + +```csharp +MenuFlyoutContentElement MenuItems(params MenuFlyoutItemBase[] items) +MenuFlyoutContentElement MenuItems(FlyoutPlacementMode placement, params MenuFlyoutItemBase[] items) +``` + +**Returns:** [`MenuFlyoutContentElement`](../elements/menus-and-commands.md#menuflyoutcontentelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `items` | [`MenuFlyoutItemBase[]`](../controls/menu-items.md#menuflyoutitembase) | | +| `placement` | `FlyoutPlacementMode` | | + +## `MenuSeparator` + +```csharp +MenuFlyoutSeparatorData MenuSeparator() +``` + +**Returns:** [`MenuFlyoutSeparatorData`](../controls/menu-items.md#menuflyoutseparatordata). + +## `MenuSubItem` + +```csharp +MenuFlyoutSubItemData MenuSubItem(string text, params MenuFlyoutItemBase[] items) +``` + +**Returns:** [`MenuFlyoutSubItemData`](../controls/menu-items.md#menuflyoutsubitemdata). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `text` | `string` | | +| `items` | [`MenuFlyoutItemBase[]`](../controls/menu-items.md#menuflyoutitembase) | | + +## `RadioMenuItem` + +```csharp +RadioMenuFlyoutItemData RadioMenuItem(string text, string groupName, bool isChecked = false, Action? onClick = null, string? icon = null) +``` + +**Returns:** [`RadioMenuFlyoutItemData`](../controls/menu-items.md#radiomenuflyoutitemdata). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `text` | `string` | | | +| `groupName` | `string` | | | +| `isChecked` | `bool` | `false` | | +| `onClick` | `Action?` | `null` | | +| `icon` | `string?` | `null` | | + +## `ToggleMenuItem` + +```csharp +ToggleMenuFlyoutItemData ToggleMenuItem(string text, bool isChecked = false, Action? onIsCheckedChanged = null, string? icon = null) +``` + +**Returns:** [`ToggleMenuFlyoutItemData`](../controls/menu-items.md#togglemenuflyoutitemdata). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `text` | `string` | | | +| `isChecked` | `bool` | `false` | | +| `onIsCheckedChanged` | `Action?` | `null` | | +| `icon` | `string?` | `null` | | diff --git a/docs/guide/reference/factories/navigation.md b/docs/guide/reference/factories/navigation.md new file mode 100644 index 0000000000..8b0f5e68fd --- /dev/null +++ b/docs/guide/reference/factories/navigation.md @@ -0,0 +1,255 @@ +# Factories: Navigation + +Navigation views, tabs, pivots, breadcrumbs and the title bar. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Navigation](../../navigation.md) + +## `Breadcrumb` + +```csharp +BreadcrumbBarItemData Breadcrumb(string label, object? tag = null) +``` + +**Returns:** [`BreadcrumbBarItemData`](../controls/navigation-items.md#breadcrumbbaritemdata). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `label` | `string` | | | +| `tag` | `object?` | `null` | | + +## `BreadcrumbBar` + +```csharp +BreadcrumbBarElement BreadcrumbBar(BreadcrumbBarItemData[] items, Action? onItemClicked = null) +``` + +**Returns:** [`BreadcrumbBarElement`](../elements/navigation.md#breadcrumbbarelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `items` | [`BreadcrumbBarItemData[]`](../controls/navigation-items.md#breadcrumbbaritemdata) | | | +| `onItemClicked` | `Action?` | `null` | | + +## `Frame` + +A WinUI `Frame` that navigates to `sourcePageType` once on mount. + +`Frame` is for interop with pages that already have a `.xaml` file. A `Page` declared only in C# is absent from the XAML metadata the compiler generates, so WinUI cannot resolve it; Reactor refuses such a navigation and reports it through `.NavigationFailed(...)` rather than letting it fault. For navigation inside a Reactor app use `UseNavigation` with `NavigationHost`. + +```csharp +FrameElement Frame(Type? sourcePageType = null, object? navigationParameter = null) +``` + +**Returns:** [`FrameElement`](../elements/navigation.md#frameelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `sourcePageType` | `Type?` | `null` | | +| `navigationParameter` | `object?` | `null` | | + +## `NavItem` + +```csharp +NavigationViewItemData NavItem(string content, string? icon = null, string? tag = null) +``` + +**Returns:** [`NavigationViewItemData`](../controls/navigation-items.md#navigationviewitemdata). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `content` | `string` | | | +| `icon` | `string?` | `null` | | +| `tag` | `string?` | `null` | | + +## `NavItemHeader` + +```csharp +NavigationViewItemData NavItemHeader(string content) +``` + +**Returns:** [`NavigationViewItemData`](../controls/navigation-items.md#navigationviewitemdata). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | + +## `NavigationHost` + +Creates a navigation host that renders the current route's content. Automatically provides the navigation handle via context so child components can retrieve it with `UseNavigation()`. Use `with { }` to set Transition, CacheMode, and CacheSize. + +```csharp +NavigationHostElement NavigationHost(NavigationHandle nav, Func routeMap) +``` + +**Returns:** [`NavigationHostElement`](../elements/navigation.md#navigationhostelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `nav` | [`NavigationHandle`](../navigation/NavigationHandle.md) | | +| `routeMap` | `Func` | | + +## `NavigationView` + +```csharp +NavigationViewElement NavigationView(NavigationViewItemData[] menuItems, Element? content = null) +``` + +**Returns:** [`NavigationViewElement`](../elements/navigation.md#navigationviewelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `menuItems` | [`NavigationViewItemData[]`](../controls/navigation-items.md#navigationviewitemdata) | | | +| `content` | [`Element?`](../elements/Element.md) | `null` | | + +## `PipsPager` + +Creates a [`PipsPagerElement`](../elements/navigation.md#pipspagerelement). `selectedPageIndex` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its current page. + +```csharp +PipsPagerElement PipsPager(int numberOfPages, Optional selectedPageIndex = default, Action? onSelectedPageIndexChanged = null) +``` + +**Returns:** [`PipsPagerElement`](../elements/navigation.md#pipspagerelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `numberOfPages` | `int` | | | +| `selectedPageIndex` | [`Optional`](../components/Optional.md) | `default` | | +| `onSelectedPageIndexChanged` | `Action?` | `null` | | + +## `Pivot` + +Creates a pivot whose selected index is controlled only when `selectedIndex` has a value. + +```csharp +PivotElement Pivot(params PivotItemData[] items) +PivotElement Pivot(Optional selectedIndex, Action? onSelectedIndexChanged = null, params PivotItemData[] items) +PivotElement Pivot(int selectedIndex, Action? onSelectedIndexChanged = null, params PivotItemData[] items) +PivotElement Pivot(int? selectedIndex, Action? onSelectedIndexChanged = null, params PivotItemData[] items) +``` + +| Overload | Description | +| --- | --- | +| `Pivot(PivotItemData[])` | | +| `Pivot(Optional, Action?, PivotItemData[])` | Creates a pivot whose selected index is controlled only when `selectedIndex` has a value. | +| `Pivot(int, Action?, PivotItemData[])` | Creates a pivot with a controlled selected index. Disambiguates a plain [`Int32`](https://learn.microsoft.com/dotnet/api/system.int32) argument, which converts equally well to [`Nullable`](https://learn.microsoft.com/dotnet/api/system.nullable-1) and [`Optional`](../components/Optional.md). Any [`Int32`](https://learn.microsoft.com/dotnet/api/system.int32) — including `default`, which is `0` — selects that index; pass `(int?)null` or [`Optional.Unset`](../components/Optional.md#unset) to leave the selection uncontrolled. | +| `Pivot(int?, Action?, PivotItemData[])` | Creates a pivot whose selected index is unset when `selectedIndex` is `null`. | + +**Returns:** [`PivotElement`](../elements/navigation.md#pivotelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `items` | [`PivotItemData[]`](../controls/navigation-items.md#pivotitemdata) | | | +| `selectedIndex` | [`Optional`](../components/Optional.md) or `int` or `int?` | | | +| `onSelectedIndexChanged` | `Action?` | `null` | | + +## `PivotItem` + +```csharp +PivotItemData PivotItem(string header, Element content) +``` + +**Returns:** [`PivotItemData`](../controls/navigation-items.md#pivotitemdata). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `header` | `string` | | +| `content` | [`Element`](../elements/Element.md) | | + +## `SelectorBar` + +Creates a [`SelectorBarElement`](../elements/navigation.md#selectorbarelement). `selectedIndex` defaults to [`Optional.Unset`](../components/Optional.md#unset) — omit it to let the control own its selection. + +```csharp +SelectorBarElement SelectorBar(SelectorBarItemData[] items, Optional selectedIndex = default, Action? onSelectedIndexChanged = null) +``` + +**Returns:** [`SelectorBarElement`](../elements/navigation.md#selectorbarelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `items` | [`SelectorBarItemData[]`](../controls/navigation-items.md#selectorbaritemdata) | | | +| `selectedIndex` | [`Optional`](../components/Optional.md) | `default` | | +| `onSelectedIndexChanged` | `Action?` | `null` | | + +## `SelectorBarItem` + +```csharp +SelectorBarItemData SelectorBarItem(string text, string? icon = null) +``` + +**Returns:** [`SelectorBarItemData`](../controls/navigation-items.md#selectorbaritemdata). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `text` | `string` | | | +| `icon` | `string?` | `null` | | + +## `Tab` + +```csharp +TabViewItemData Tab(string header, Element content) +``` + +**Returns:** [`TabViewItemData`](../controls/navigation-items.md#tabviewitemdata). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `header` | `string` | | +| `content` | [`Element`](../elements/Element.md) | | + +## `TabView` + +Creates a tab view whose selected index is controlled only when `selectedIndex` has a value. + +```csharp +TabViewElement TabView(params TabViewItemData[] tabs) +TabViewElement TabView(Optional selectedIndex, Action? onSelectedIndexChanged = null, params TabViewItemData[] tabs) +TabViewElement TabView(int selectedIndex, Action? onSelectedIndexChanged = null, params TabViewItemData[] tabs) +TabViewElement TabView(int? selectedIndex, Action? onSelectedIndexChanged = null, params TabViewItemData[] tabs) +``` + +| Overload | Description | +| --- | --- | +| `TabView(TabViewItemData[])` | | +| `TabView(Optional, Action?, TabViewItemData[])` | Creates a tab view whose selected index is controlled only when `selectedIndex` has a value. | +| `TabView(int, Action?, TabViewItemData[])` | Creates a tab view with a controlled selected index. Disambiguates a plain [`Int32`](https://learn.microsoft.com/dotnet/api/system.int32) argument, which converts equally well to [`Nullable`](https://learn.microsoft.com/dotnet/api/system.nullable-1) and [`Optional`](../components/Optional.md). Any [`Int32`](https://learn.microsoft.com/dotnet/api/system.int32) — including `default`, which is `0` — selects that index; pass `(int?)null` or [`Optional.Unset`](../components/Optional.md#unset) to leave the selection uncontrolled. | +| `TabView(int?, Action?, TabViewItemData[])` | Creates a tab view whose selected index is unset when `selectedIndex` is `null`. | + +**Returns:** [`TabViewElement`](../elements/navigation.md#tabviewelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `tabs` | [`TabViewItemData[]`](../controls/navigation-items.md#tabviewitemdata) | | | +| `selectedIndex` | [`Optional`](../components/Optional.md) or `int` or `int?` | | | +| `onSelectedIndexChanged` | `Action?` | `null` | | diff --git a/docs/guide/reference/factories/shapes.md b/docs/guide/reference/factories/shapes.md new file mode 100644 index 0000000000..a9face8130 --- /dev/null +++ b/docs/guide/reference/factories/shapes.md @@ -0,0 +1,71 @@ +# Factories: Shapes + +Rectangles, ellipses, lines, paths and brushes. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Styling and Theming](../../styling.md) + +## `AcrylicBrush` + +Creates a new AcrylicBrush. This allocates a WinRT DependencyObject on every call. On hot paths (e.g., inside Render methods), cache the result with `UseMemo`: + +```csharp +var brush = ctx.UseMemo(() => AcrylicBrush(color, 0.8), color); +``` + +```csharp +AcrylicBrush AcrylicBrush(Color tintColor, double tintOpacity = 0.8, Color? fallbackColor = null, double? tintLuminosityOpacity = null) +``` + +**Returns:** [`AcrylicBrush`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.media.acrylicbrush). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `tintColor` | `Color` | | | +| `tintOpacity` | `double` | `0.8` | | +| `fallbackColor` | `Color?` | `null` | | +| `tintLuminosityOpacity` | `double?` | `null` | | + +## `Ellipse` + +```csharp +EllipseElement Ellipse() +``` + +**Returns:** [`EllipseElement`](../elements/shapes.md#ellipseelement). + +## `Line` + +```csharp +LineElement Line(double x1, double y1, double x2, double y2) +``` + +**Returns:** [`LineElement`](../elements/shapes.md#lineelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `x1` | `double` | | +| `y1` | `double` | | +| `x2` | `double` | | +| `y2` | `double` | | + +## `Path2D` + +```csharp +PathElement Path2D() +``` + +**Returns:** [`PathElement`](../elements/shapes.md#pathelement). + +## `Rectangle` + +```csharp +RectangleElement Rectangle() +``` + +**Returns:** [`RectangleElement`](../elements/shapes.md#rectangleelement). diff --git a/docs/guide/reference/factories/status-and-info.md b/docs/guide/reference/factories/status-and-info.md new file mode 100644 index 0000000000..8262788480 --- /dev/null +++ b/docs/guide/reference/factories/status-and-info.md @@ -0,0 +1,86 @@ +# Factories: Status and info + +Info bars, badges and progress indicators. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Status and Info](../../status-and-info.md) + +## `InfoBadge` + +```csharp +InfoBadgeElement InfoBadge() +InfoBadgeElement InfoBadge(int value) +``` + +**Returns:** [`InfoBadgeElement`](../elements/status-and-info.md#infobadgeelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `value` | `int` | | + +## `InfoBar` + +```csharp +InfoBarElement InfoBar(string? title = null, string? message = null) +``` + +**Returns:** [`InfoBarElement`](../elements/status-and-info.md#infobarelement). + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `title` | `string?` | `null` | | +| `message` | `string?` | `null` | | + +## `Progress` + +Creates a determinate [`ProgressElement`](../elements/status-and-info.md#progresselement) at the given value. + +```csharp +ProgressElement Progress(double value) +``` + +**Returns:** [`ProgressElement`](../elements/status-and-info.md#progresselement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `value` | `double` | | + +**Remarks** + +The element reconciles to a WinUI `ProgressBar`. The Reactor name `Progress` is the short, intent-naming spelling — the WinUI name includes the visual shape (`Bar`) the way agents reach for a rendering primitive; Reactor calls it by what it does. [`ProgressRing`](#progressring) is the circular variant. (spec 039 §5 / §16) + +## `ProgressIndeterminate` + +Creates an indeterminate [`ProgressElement`](../elements/status-and-info.md#progresselement) (animated bar with no value). The reconciler maps this to `ProgressBar.IsIndeterminate`. + +```csharp +ProgressElement ProgressIndeterminate() +``` + +**Returns:** [`ProgressElement`](../elements/status-and-info.md#progresselement). + +**Remarks** + +Reactor-original convenience for the indeterminate-bar case; see [`Progress`](#progress) for the naming rationale. (spec 039 §5 / §16) + +## `ProgressRing` + +```csharp +ProgressRingElement ProgressRing() +ProgressRingElement ProgressRing(double value) +``` + +**Returns:** [`ProgressRingElement`](../elements/status-and-info.md#progressringelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `value` | `double` | | diff --git a/docs/guide/reference/factories/text.md b/docs/guide/reference/factories/text.md new file mode 100644 index 0000000000..8fb88715c9 --- /dev/null +++ b/docs/guide/reference/factories/text.md @@ -0,0 +1,304 @@ +# Factories: Text + +Text blocks, rich text and the typography factories. + +Each factory method returns an element record. Call them through `using static Microsoft.UI.Reactor.Factories;`. + +**Learn more:** [Text and Media](../../text-and-media.md) + +## `Body` + +WinUI 3 `BodyTextBlockStyle` — 14px regular body text. + +```csharp +TextBlockElement Body(string content) +``` + +**Returns:** [`TextBlockElement`](../elements/text.md#textblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | + +## `BodyLarge` + +WinUI 3 `BodyLargeTextBlockStyle` — 18px regular body text. + +```csharp +TextBlockElement BodyLarge(string content) +``` + +**Returns:** [`TextBlockElement`](../elements/text.md#textblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | + +## `BodyStrong` + +WinUI 3 `BodyStrongTextBlockStyle` — 14px Semibold body text. + +```csharp +TextBlockElement BodyStrong(string content) +``` + +**Returns:** [`TextBlockElement`](../elements/text.md#textblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | + +## `Caption` + +Creates a caption-styled [`TextBlockElement`](../elements/text.md#textblockelement) (12px). + +```csharp +TextBlockElement Caption(string content) +``` + +**Returns:** [`TextBlockElement`](../elements/text.md#textblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | + +**Remarks** + +Reactor-original convenience wrapper — there is no WinUI control named `Caption`. Sized for the WinUI Caption type-ramp slot; use for secondary metadata (timestamps, helper text, hints) below primary copy. (spec 039 §0.3) + +## `Display` + +WinUI 3 `DisplayTextBlockStyle` — 68px Semibold hero text. Use sparingly: hero banners and splash screens, at most one per page. + +```csharp +TextBlockElement Display(string content) +``` + +**Returns:** [`TextBlockElement`](../elements/text.md#textblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | + +## `Heading` + +Creates a heading-styled [`TextBlockElement`](../elements/text.md#textblockelement) (28px, bold, automation heading level 1). + +```csharp +TextBlockElement Heading(string content) +``` + +**Returns:** [`TextBlockElement`](../elements/text.md#textblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | + +**Remarks** + +Reactor-original convenience wrapper — there is no WinUI control named `Heading`. Sized for the WinUI Title type-ramp slot, with the accessibility heading level set so screen readers announce it as a landmark. Prefer this over hand-styled [`TextBlock`](#textblock) for page / section titles. (spec 039 §0.3) + +## `Hyperlink` + +Issue #479 — clickable inline hyperlink: fires `onClick` on click and suppresses platform navigation. Use for in-flow interactive fragments (open a flyout, enter edit mode) inside a virtualized list of [`RichTextBlock`](#richtextblock) rows where giving each fragment its own `UIElement` would be too heavy. + +```csharp +RichTextHyperlink Hyperlink(string text, Action onClick) +RichTextHyperlink Hyperlink(string text, Uri navigateUri) +``` + +**Returns:** [`RichTextHyperlink`](../controls/rich-text.md#richtexthyperlink). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `text` | `string` | | +| `onClick` | `Action` | | +| `navigateUri` | `Uri` | | + +## `InlineUI` + +Issue #480 — embeds a Reactor `child` element inline inside a [`RichTextBlock`](#richtextblock). Mirrors WinUI's `InlineUIContainer`. The child is reconciled as any other Reactor element — descendant hooks, event wiring, and pooling all work as expected. Re-renders use the incremental update path: structurally compatible inlines are mutated in place and embedded children retain their WinUI control identity (Slider drag, focus, and animation state survive). Only structural changes (paragraph count change, inline type change, Route A↔B swap) fall back to a full block rebuild. + +```csharp +RichTextInlineUIContainer InlineUI(Element child) +RichTextInlineUIContainer InlineUI(Func factory) +``` + +| Overload | Description | +| --- | --- | +| `InlineUI(Element)` | Issue #480 — embeds a Reactor `child` element inline inside a [`RichTextBlock`](#richtextblock). Mirrors WinUI's `InlineUIContainer`. The child is reconciled as any other Reactor element — descendant hooks, event wiring, and pooling all work as expected. Re-renders use the incremental update path: structurally compatible inlines are mutated in place and embedded children retain their WinUI control identity (Slider drag, focus, and animation state survive). Only structural changes (paragraph count change, inline type change, Route A↔B swap) fall back to a full block rebuild. | +| `InlineUI(Func)` | Issue #480 — embeds a native WinUI control (produced by `factory`) inline inside a [`RichTextBlock`](#richtextblock). Escape hatch for controls without a Reactor element counterpart. The factory is re-invoked only when its delegate identity changes; passing the same factory across renders preserves the control instance. | + +**Returns:** [`RichTextInlineUIContainer`](../controls/rich-text.md#richtextinlineuicontainer). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `child` | [`Element`](../elements/Element.md) | | +| `factory` | `Func` | | + +## `Paragraph` + +```csharp +RichTextParagraph Paragraph(params RichTextInline[] inlines) +``` + +**Returns:** [`RichTextParagraph`](../controls/rich-text.md#richtextparagraph). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `inlines` | [`RichTextInline[]`](../controls/rich-text.md#richtextinline) | | + +## `RichTextBlock` + +Creates a [`RichTextBlockElement`](../elements/text.md#richtextblockelement) from an array of typed paragraphs. Each paragraph contains a sequence of inline runs / hyperlinks / line breaks built with [`Paragraph`](#paragraph), [`Run`](#run), and [`Hyperlink`](#hyperlink). + +```csharp +RichTextBlockElement RichTextBlock(RichTextParagraph[] paragraphs) +RichTextBlockElement RichTextBlock(string text) +``` + +| Overload | Description | +| --- | --- | +| `RichTextBlock(RichTextParagraph[])` | Creates a [`RichTextBlockElement`](../elements/text.md#richtextblockelement) from an array of typed paragraphs. Each paragraph contains a sequence of inline runs / hyperlinks / line breaks built with [`Paragraph`](#paragraph), [`Run`](#run), and [`Hyperlink`](#hyperlink). | +| `RichTextBlock(string)` | Creates a [`RichTextBlockElement`](../elements/text.md#richtextblockelement) wrapping a single string of plain text. Use the [`RichTextBlock`](#richtextblock) overload to compose runs, hyperlinks, and inline formatting. | + +**Returns:** [`RichTextBlockElement`](../elements/text.md#richtextblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `paragraphs` | [`RichTextParagraph[]`](../controls/rich-text.md#richtextparagraph) | | +| `text` | `string` | | + +**Remarks** + +Named for parity with WinUI's `Microsoft.UI.Xaml.Controls.RichTextBlock`. (spec 039 §1.3 / §14 #8) + +## `Run` + +```csharp +RichTextRun Run(string text) +``` + +**Returns:** [`RichTextRun`](../controls/rich-text.md#richtextrun). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `text` | `string` | | + +## `SubHeading` + +Creates a sub-heading styled [`TextBlockElement`](../elements/text.md#textblockelement) (20px, semi-bold, automation heading level 2). + +```csharp +TextBlockElement SubHeading(string content) +``` + +**Returns:** [`TextBlockElement`](../elements/text.md#textblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | + +**Remarks** + +Reactor-original convenience wrapper — there is no WinUI control named `SubHeading`. Pairs with [`Heading`](#heading) for the secondary section level; sized for the WinUI Subtitle type-ramp slot. (spec 039 §0.3) + +## `Subtitle` + +WinUI 3 `SubtitleTextBlockStyle` — 20px Semibold sub-heading. + +```csharp +TextBlockElement Subtitle(string content) +``` + +**Returns:** [`TextBlockElement`](../elements/text.md#textblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | + +## `TextBlock` + +```csharp +TextBlockElement TextBlock(string content) +``` + +**Returns:** [`TextBlockElement`](../elements/text.md#textblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | + +## `Title` + +WinUI 3 `TitleTextBlockStyle` — 28px Semibold heading. + +```csharp +TextBlockElement Title(string content) +``` + +**Returns:** [`TextBlockElement`](../elements/text.md#textblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | + +## `TitleBar` + +```csharp +TitleBarElement TitleBar(string title) +``` + +**Returns:** [`TitleBarElement`](../elements/navigation.md#titlebarelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `title` | `string` | | + +## `TitleLarge` + +WinUI 3 `TitleLargeTextBlockStyle` — 40px Semibold large title. Use for primary page titles on feature or landing pages. + +```csharp +TextBlockElement TitleLarge(string content) +``` + +**Returns:** [`TextBlockElement`](../elements/text.md#textblockelement). + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `content` | `string` | | diff --git a/docs/guide/reference/hooks/Announce.md b/docs/guide/reference/hooks/Announce.md deleted file mode 100644 index d8b5361772..0000000000 --- a/docs/guide/reference/hooks/Announce.md +++ /dev/null @@ -1,45 +0,0 @@ -# Announce - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.AnnounceHandle.Announce(System.String)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Overloads - -- [`Announce(string)`](#announcestring) -- [`Announce(string, bool)`](#announcestring-bool) - -## `Announce(string)` - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.AnnounceHandle.Announce(System.String)` - -### Summary - -Announces a message to screen readers (polite — queued after current speech). - -## `Announce(string, bool)` - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.AnnounceHandle.Announce(System.String,System.Boolean)` - -### Summary - -Announces a message to screen readers. - -### Parameters - -- **message** — The text to announce. -- **assertive** — If true, interrupts current speech immediately. -If false (default), queued after current speech finishes. - -### Discussion - -Thread-safe. When called on the UI thread the announcement is raised -synchronously. When called from any other thread it is marshalled to the -captured UI `DispatcherQueue` and runs asynchronously -(fire-and-forget) — it may complete after this method returns. Calls made -before the live-region [Region](Region.md) ([guide](../../hooks.md)) has mounted are ignored. - - diff --git a/docs/guide/reference/hooks/AnnounceHandle.md b/docs/guide/reference/hooks/AnnounceHandle.md deleted file mode 100644 index 0ae00f0ba4..0000000000 --- a/docs/guide/reference/hooks/AnnounceHandle.md +++ /dev/null @@ -1,15 +0,0 @@ -# AnnounceHandle - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.AnnounceHandle` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Handle returned by [UseAnnounce](UseAnnounce.md#useannouncerendercontext) ([guide](../../hooks.md)). -Provides an imperative [Announce](Announce.md#announcestring) ([guide](../../hooks.md)) method for screen reader -live-region announcements plus a zero-size [Region](Region.md) ([guide](../../hooks.md)) element -that must be included somewhere in the component's rendered tree. - - diff --git a/docs/guide/reference/hooks/AnnounceRegionElement.md b/docs/guide/reference/hooks/AnnounceRegionElement.md deleted file mode 100644 index 745feaacb5..0000000000 --- a/docs/guide/reference/hooks/AnnounceRegionElement.md +++ /dev/null @@ -1,12 +0,0 @@ -# AnnounceRegionElement - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.AnnounceRegionElement` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Internal Reactor element that mounts a hidden TextBlock with LiveSetting for announcements. - - diff --git a/docs/guide/reference/hooks/AnyLoading.md b/docs/guide/reference/hooks/AnyLoading.md deleted file mode 100644 index 80c6e9ea1f..0000000000 --- a/docs/guide/reference/hooks/AnyLoading.md +++ /dev/null @@ -1,12 +0,0 @@ -# AnyLoading - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.PendingScope.AnyLoading` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -True iff any tracked token is currently `Loading`. - - diff --git a/docs/guide/reference/hooks/CacheKey.md b/docs/guide/reference/hooks/CacheKey.md deleted file mode 100644 index 3815f81723..0000000000 --- a/docs/guide/reference/hooks/CacheKey.md +++ /dev/null @@ -1,15 +0,0 @@ -# CacheKey - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.ResourceOptions.CacheKey` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Overrides the generated cache key; null uses a key derived from deps. -When set, the key identifies the query; deps changes alone do not cancel -an in-flight request or start a new fetch. Include values that select -different data in the key, for example `$"user:{userId}"`. - - diff --git a/docs/guide/reference/hooks/CacheTime.md b/docs/guide/reference/hooks/CacheTime.md deleted file mode 100644 index 835137b1d1..0000000000 --- a/docs/guide/reference/hooks/CacheTime.md +++ /dev/null @@ -1,12 +0,0 @@ -# CacheTime - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.ResourceOptions.CacheTime` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Retention after the last subscriber leaves; null uses five minutes. - - diff --git a/docs/guide/reference/hooks/Changed.md b/docs/guide/reference/hooks/Changed.md deleted file mode 100644 index 4edd5a620f..0000000000 --- a/docs/guide/reference/hooks/Changed.md +++ /dev/null @@ -1,12 +0,0 @@ -# Changed - -`event` -_cref_: `E:Microsoft.UI.Reactor.Hooks.PendingScope.Changed` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Fires when a resource joins, leaves, or changes its loading state. - - diff --git a/docs/guide/reference/hooks/Clear.md b/docs/guide/reference/hooks/Clear.md deleted file mode 100644 index be18e10eb0..0000000000 --- a/docs/guide/reference/hooks/Clear.md +++ /dev/null @@ -1,12 +0,0 @@ -# Clear - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusManager.Clear` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Clears all registrations. - - diff --git a/docs/guide/reference/hooks/ComponentUseMemoCellsExtensions.md b/docs/guide/reference/hooks/ComponentUseMemoCellsExtensions.md deleted file mode 100644 index ff8727cfa5..0000000000 --- a/docs/guide/reference/hooks/ComponentUseMemoCellsExtensions.md +++ /dev/null @@ -1,19 +0,0 @@ -# ComponentUseMemoCellsExtensions - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.ComponentUseMemoCellsExtensions` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -`Component`-class shims for [UseMemoCellsExtensions](UseMemoCellsExtensions.md) ([guide](../../hooks.md)) -so subclasses can call `UseMemoCells` without going through -`this.Context`. Same semantics as the `RenderContext` -extension methods. - -## Discussion - -Spec 034 §C. - - diff --git a/docs/guide/reference/hooks/Count.md b/docs/guide/reference/hooks/Count.md deleted file mode 100644 index 108408f47d..0000000000 --- a/docs/guide/reference/hooks/Count.md +++ /dev/null @@ -1,12 +0,0 @@ -# Count - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.PendingScope.Count` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Snapshot the number of registered tokens (loading or not). Diagnostic only. - - diff --git a/docs/guide/reference/hooks/CursorFromPageIndex.md b/docs/guide/reference/hooks/CursorFromPageIndex.md deleted file mode 100644 index c4ee8c1d48..0000000000 --- a/docs/guide/reference/hooks/CursorFromPageIndex.md +++ /dev/null @@ -1,15 +0,0 @@ -# CursorFromPageIndex - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.InfiniteHookState`2.CursorFromPageIndex` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Optional: computes the cursor for an arbitrary page index directly, bypassing the -"wait for page N-1" constraint. Used by `UseDataSource` to expose the offset -semantics of `IDataSource`'s `ContinuationToken`, so deep -scrolls fetch pages in parallel instead of walking the chain one round-trip at a time. - - diff --git a/docs/guide/reference/hooks/Customize.md b/docs/guide/reference/hooks/Customize.md deleted file mode 100644 index 30c0731168..0000000000 --- a/docs/guide/reference/hooks/Customize.md +++ /dev/null @@ -1,12 +0,0 @@ -# Customize - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.AnnounceRegionElement.Customize(Microsoft.UI.Reactor.Core.V1Protocol.Descriptor.ControlDescriptor{Microsoft.UI.Reactor.Hooks.AnnounceRegionElement,Microsoft.UI.Xaml.Controls.TextBlock})` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Author hook — add the bespoke descriptor entries for the `[WrapManual]` props. - - diff --git a/docs/guide/reference/hooks/Descriptor.md b/docs/guide/reference/hooks/Descriptor.md deleted file mode 100644 index d550d203f5..0000000000 --- a/docs/guide/reference/hooks/Descriptor.md +++ /dev/null @@ -1,12 +0,0 @@ -# Descriptor - -`field` -_cref_: `F:Microsoft.UI.Reactor.Hooks.AnnounceRegionElement.Descriptor` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -The descriptor the engine interprets for every [AnnounceRegionElement](AnnounceRegionElement.md) ([guide](../../hooks.md)). - - diff --git a/docs/guide/reference/hooks/Error.md b/docs/guide/reference/hooks/Error.md deleted file mode 100644 index ba9f086458..0000000000 --- a/docs/guide/reference/hooks/Error.md +++ /dev/null @@ -1,12 +0,0 @@ -# Error - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.Mutation`2.Error` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Most recent error, or null if the last completion was a success or [Reset](Reset.md) ([guide](../../hooks.md)) was called. - - diff --git a/docs/guide/reference/hooks/Fields.md b/docs/guide/reference/hooks/Fields.md deleted file mode 100644 index e78edab96a..0000000000 --- a/docs/guide/reference/hooks/Fields.md +++ /dev/null @@ -1,12 +0,0 @@ -# Fields - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.FocusManager.Fields` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Registered field names in order. - - diff --git a/docs/guide/reference/hooks/Focus.md b/docs/guide/reference/hooks/Focus.md deleted file mode 100644 index 1e4805ef4b..0000000000 --- a/docs/guide/reference/hooks/Focus.md +++ /dev/null @@ -1,31 +0,0 @@ -# Focus - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusExtensions.Focus(Microsoft.UI.Reactor.Core.NumberBoxElement,Microsoft.UI.Reactor.Hooks.FocusManager,System.String,System.Boolean)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Overloads - -- [`Focus(NumberBoxElement, FocusManager, string, bool)`](#focusnumberboxelement-focusmanager-string-bool) -- [`Focus(TextBoxElement, FocusManager, string, bool)`](#focustextboxelement-focusmanager-string-bool) - -## `Focus(NumberBoxElement, FocusManager, string, bool)` - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusExtensions.Focus(Microsoft.UI.Reactor.Core.NumberBoxElement,Microsoft.UI.Reactor.Hooks.FocusManager,System.String,System.Boolean)` - -### Summary - -Registers this NumberBox with a FocusManager for programmatic focus control. - -## `Focus(TextBoxElement, FocusManager, string, bool)` - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusExtensions.Focus(Microsoft.UI.Reactor.Core.TextBoxElement,Microsoft.UI.Reactor.Hooks.FocusManager,System.String,System.Boolean)` - -### Summary - -Registers this TextBox with a FocusManager for programmatic focus control. - - diff --git a/docs/guide/reference/hooks/FocusAttached.md b/docs/guide/reference/hooks/FocusAttached.md deleted file mode 100644 index 94f3d42d6b..0000000000 --- a/docs/guide/reference/hooks/FocusAttached.md +++ /dev/null @@ -1,12 +0,0 @@ -# FocusAttached - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.FocusAttached` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Attached metadata for focus registration on elements. - - diff --git a/docs/guide/reference/hooks/FocusExtensions.md b/docs/guide/reference/hooks/FocusExtensions.md deleted file mode 100644 index 073c722be7..0000000000 --- a/docs/guide/reference/hooks/FocusExtensions.md +++ /dev/null @@ -1,13 +0,0 @@ -# FocusExtensions - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.FocusExtensions` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Fluent extensions for attaching focus management to elements. -Uses .Set() to capture the WinUI control reference during mount/update. - - diff --git a/docs/guide/reference/hooks/FocusField.md b/docs/guide/reference/hooks/FocusField.md deleted file mode 100644 index 4043a8e81d..0000000000 --- a/docs/guide/reference/hooks/FocusField.md +++ /dev/null @@ -1,12 +0,0 @@ -# FocusField - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusManager.FocusField(System.String)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Focuses a specific field by name. - - diff --git a/docs/guide/reference/hooks/FocusFirst.md b/docs/guide/reference/hooks/FocusFirst.md deleted file mode 100644 index 507fa90d77..0000000000 --- a/docs/guide/reference/hooks/FocusFirst.md +++ /dev/null @@ -1,13 +0,0 @@ -# FocusFirst - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusManager.FocusFirst(System.Collections.Generic.IReadOnlyList{System.String})` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Focuses the first field from the given list that exists in this manager. -Useful with ValidationContext.InvalidFields. - - diff --git a/docs/guide/reference/hooks/FocusManager.md b/docs/guide/reference/hooks/FocusManager.md deleted file mode 100644 index ad1bc3a598..0000000000 --- a/docs/guide/reference/hooks/FocusManager.md +++ /dev/null @@ -1,13 +0,0 @@ -# FocusManager - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.FocusManager` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Manages focus for a set of registered form fields. -Supports programmatic focus control, enter-to-advance, and field ordering. - - diff --git a/docs/guide/reference/hooks/FocusMeta.md b/docs/guide/reference/hooks/FocusMeta.md deleted file mode 100644 index c99c681b48..0000000000 --- a/docs/guide/reference/hooks/FocusMeta.md +++ /dev/null @@ -1,12 +0,0 @@ -# FocusMeta - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusExtensions.FocusMeta``1(``0,Microsoft.UI.Reactor.Hooks.FocusManager,System.String,System.Boolean)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Registers any element with a FocusManager via attached metadata (for custom types). - - diff --git a/docs/guide/reference/hooks/FocusNext.md b/docs/guide/reference/hooks/FocusNext.md deleted file mode 100644 index 3ed3bca139..0000000000 --- a/docs/guide/reference/hooks/FocusNext.md +++ /dev/null @@ -1,13 +0,0 @@ -# FocusNext - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusManager.FocusNext(System.String)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Focuses the field after the given field in registration order. -If the current field is the last one, triggers submit. - - diff --git a/docs/guide/reference/hooks/FocusPrevious.md b/docs/guide/reference/hooks/FocusPrevious.md deleted file mode 100644 index b2a3b0ec63..0000000000 --- a/docs/guide/reference/hooks/FocusPrevious.md +++ /dev/null @@ -1,12 +0,0 @@ -# FocusPrevious - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusManager.FocusPrevious(System.String)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Focuses the field before the given field in registration order. - - diff --git a/docs/guide/reference/hooks/FocusTrap.md b/docs/guide/reference/hooks/FocusTrap.md deleted file mode 100644 index a6d23572b7..0000000000 --- a/docs/guide/reference/hooks/FocusTrap.md +++ /dev/null @@ -1,13 +0,0 @@ -# FocusTrap - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusTrapElementExtensions.FocusTrap``1(``0,Microsoft.UI.Reactor.Hooks.FocusTrapHandle)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Attaches a focus trap to this element. When the trap is active, -Tab/Shift+Tab cycles within this element's visual subtree. - - diff --git a/docs/guide/reference/hooks/FocusTrapElementExtensions.md b/docs/guide/reference/hooks/FocusTrapElementExtensions.md deleted file mode 100644 index 3b6ff75daa..0000000000 --- a/docs/guide/reference/hooks/FocusTrapElementExtensions.md +++ /dev/null @@ -1,13 +0,0 @@ -# FocusTrapElementExtensions - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.FocusTrapElementExtensions` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Fluent extension to attach a FocusTrapHandle to an element. -The handle captures the mounted WinUI element for focus trapping. - - diff --git a/docs/guide/reference/hooks/FocusTrapHandle.md b/docs/guide/reference/hooks/FocusTrapHandle.md deleted file mode 100644 index 19b9b0daad..0000000000 --- a/docs/guide/reference/hooks/FocusTrapHandle.md +++ /dev/null @@ -1,14 +0,0 @@ -# FocusTrapHandle - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.FocusTrapHandle` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Handle returned by UseFocusTrap. When active, traps keyboard focus within -the container element so Tab/Shift+Tab cycles within the trapped scope. -Essential for modal dialogs and flyouts. - - diff --git a/docs/guide/reference/hooks/GetFocus.md b/docs/guide/reference/hooks/GetFocus.md deleted file mode 100644 index a17cc29d98..0000000000 --- a/docs/guide/reference/hooks/GetFocus.md +++ /dev/null @@ -1,12 +0,0 @@ -# GetFocus - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusExtensions.GetFocus``1(``0)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Gets the FocusAttached metadata from an element. - - diff --git a/docs/guide/reference/hooks/IHookDispatcher.md b/docs/guide/reference/hooks/IHookDispatcher.md deleted file mode 100644 index 45d39b61d4..0000000000 --- a/docs/guide/reference/hooks/IHookDispatcher.md +++ /dev/null @@ -1,19 +0,0 @@ -# IHookDispatcher - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.IHookDispatcher` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Abstraction for marshalling continuations back to the render thread. Null-safe — -if the callback is absent the continuation runs inline on the thread-pool -completion thread (tests and headless hosts). - -## Discussion - -The production implementation wraps `DispatcherQueue.TryEnqueue`; tests typically -install a synchronous stub that records invocations. - - diff --git a/docs/guide/reference/hooks/InfiniteHookState.md b/docs/guide/reference/hooks/InfiniteHookState.md deleted file mode 100644 index ca914f0d4a..0000000000 --- a/docs/guide/reference/hooks/InfiniteHookState.md +++ /dev/null @@ -1,13 +0,0 @@ -# InfiniteHookState - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.InfiniteHookState`2` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Per-hook state for `UseInfiniteResource`. Coordinates in-flight page fetches, -cache subscriptions, deps-change restart, and unmount teardown. - - diff --git a/docs/guide/reference/hooks/IsActive.md b/docs/guide/reference/hooks/IsActive.md deleted file mode 100644 index 8c45bbeba1..0000000000 --- a/docs/guide/reference/hooks/IsActive.md +++ /dev/null @@ -1,12 +0,0 @@ -# IsActive - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.FocusTrapHandle.IsActive` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Whether the focus trap is currently active. - - diff --git a/docs/guide/reference/hooks/IsFirstField.md b/docs/guide/reference/hooks/IsFirstField.md deleted file mode 100644 index efd224b6dc..0000000000 --- a/docs/guide/reference/hooks/IsFirstField.md +++ /dev/null @@ -1,12 +0,0 @@ -# IsFirstField - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusManager.IsFirstField(System.String)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Returns true if the given field is the first registered field. - - diff --git a/docs/guide/reference/hooks/IsLastField.md b/docs/guide/reference/hooks/IsLastField.md deleted file mode 100644 index 32dc298238..0000000000 --- a/docs/guide/reference/hooks/IsLastField.md +++ /dev/null @@ -1,12 +0,0 @@ -# IsLastField - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusManager.IsLastField(System.String)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Returns true if the given field is the last registered field. - - diff --git a/docs/guide/reference/hooks/IsPending.md b/docs/guide/reference/hooks/IsPending.md deleted file mode 100644 index 128059aa71..0000000000 --- a/docs/guide/reference/hooks/IsPending.md +++ /dev/null @@ -1,12 +0,0 @@ -# IsPending - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.Mutation`2.IsPending` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -True while at least one [RunAsync](RunAsync.md) ([guide](../../hooks.md)) call is in-flight. - - diff --git a/docs/guide/reference/hooks/LastResult.md b/docs/guide/reference/hooks/LastResult.md deleted file mode 100644 index 2a8d748d37..0000000000 --- a/docs/guide/reference/hooks/LastResult.md +++ /dev/null @@ -1,12 +0,0 @@ -# LastResult - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.Mutation`2.LastResult` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Most recent successful result, or default if none yet. - - diff --git a/docs/guide/reference/hooks/Mutation.md b/docs/guide/reference/hooks/Mutation.md deleted file mode 100644 index 16867dc31e..0000000000 --- a/docs/guide/reference/hooks/Mutation.md +++ /dev/null @@ -1,31 +0,0 @@ -# Mutation - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.Mutation`2` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Handle returned by the `UseMutation` hook. Carries -the pending/error/last-result state and the [RunAsync](RunAsync.md) ([guide](../../hooks.md)) entry point. - -## Discussion - - - -**Concurrency.** Overlapping [RunAsync](RunAsync.md) ([guide](../../hooks.md)) calls each get their own -cancellation token; both complete and fire their callbacks in completion order. -[LastResult](LastResult.md) ([guide](../../hooks.md)) is whichever finishes last. If you want strictly-serialized -mutations, wrap [RunAsync](RunAsync.md) ([guide](../../hooks.md)) behind your own gate (or disable the trigger -control while [IsPending](IsPending.md) ([guide](../../hooks.md)) is true). - - - -**Reset.**[Reset](Reset.md) ([guide](../../hooks.md)) clears [Error](Error.md) ([guide](../../hooks.md)) and -[LastResult](LastResult.md) ([guide](../../hooks.md)) but does **not** cancel in-flight work — this is an explicit -choice so a "dismiss the error banner" action doesn't abort the user's retry. - - - - diff --git a/docs/guide/reference/hooks/MutationHookState.md b/docs/guide/reference/hooks/MutationHookState.md deleted file mode 100644 index b7146e16d7..0000000000 --- a/docs/guide/reference/hooks/MutationHookState.md +++ /dev/null @@ -1,13 +0,0 @@ -# MutationHookState - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.MutationHookState`2` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Mutable state backing a single `UseMutation` hook instance. Owned per-component, -per-hook-slot; disposed on unmount. - - diff --git a/docs/guide/reference/hooks/MutationOptions.md b/docs/guide/reference/hooks/MutationOptions.md deleted file mode 100644 index df42a6706e..0000000000 --- a/docs/guide/reference/hooks/MutationOptions.md +++ /dev/null @@ -1,31 +0,0 @@ -# MutationOptions - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.MutationOptions`2` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Callbacks and side-effects for the `UseMutation` hook. -All callbacks are optional; all run on the dispatcher thread except [OnOptimistic](MutationOptions.md) -which runs synchronously on the caller of [RunAsync](RunAsync.md) ([guide](../../hooks.md)) -— the typical case is a render-thread click handler, so the optimistic update lands in the -very next frame without a dispatcher hop. - -## Discussion - - - -**InvalidateKeys.** On success, each key is passed to -`QueryCache.Invalidate`. Sibling `UseResource` hooks subscribed to -those keys will observe the invalidation and refetch on their next render. - - - -Error path: [OnError](MutationOptions.md) fires but [InvalidateKeys](MutationOptions.md) does -**not** — the assumption is the server state didn't change, so the cache is still valid. - - - - diff --git a/docs/guide/reference/hooks/NotifyPending.md b/docs/guide/reference/hooks/NotifyPending.md deleted file mode 100644 index 01ddfa0c74..0000000000 --- a/docs/guide/reference/hooks/NotifyPending.md +++ /dev/null @@ -1,12 +0,0 @@ -# NotifyPending - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.InfiniteHookState`2.NotifyPending` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Called from RequestPage / page-completion paths to keep the Pending scope in sync. - - diff --git a/docs/guide/reference/hooks/Pending.md b/docs/guide/reference/hooks/Pending.md index 182d9df04e..92a3b55c0f 100644 --- a/docs/guide/reference/hooks/Pending.md +++ b/docs/guide/reference/hooks/Pending.md @@ -1,33 +1,209 @@ # Pending -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.PendingFactory.Pending(Microsoft.UI.Reactor.Core.Element,Microsoft.UI.Reactor.Core.Element)` +The Pending element that shows a fallback while resources below it load. -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +**Learn more:** [Hooks](../../hooks.md) -## Summary +## `PendingComponent` -Wraps `child` with a fresh [PendingScope](PendingScope.md) ([guide](../../hooks.md)). Renders -`fallback` instead of `child` while any -`UseResource`/`UseInfiniteResource` in the subtree is in the -`Loading` state. `Reloading(previous)` does **not** trigger the -fallback — spec §10.1. +Component backing the `Pending` element. Hosts a [`PendingScope`](#pendingscope), subscribes to its [`PendingScope.Changed`](#changed) event, and chooses between [`PendingProps.Fallback`](#fallback) and [`PendingProps.Child`](#child). -## Discussion +```csharp +public sealed class PendingComponent +``` -The child subtree is always mounted so its hooks register with the scope. The -element simply chooses which rendered tree to show — there is no unwinding -of rendering, and no reconciler involvement. +Namespace: `Microsoft.UI.Reactor.Hooks`. +### Remarks -Marked `[ReactorSourceTransparent]` (see -`ReactorSourceTransparentAttribute`, spec 010) because it is a -pure forwarder: the element is really built by the `Component<,>` call -on the next line, inside Reactor's own assembly, where no consumer call site -exists to intercept. Without the annotation a `Pending(...)` element reports -no location at all. With it, the interceptor in the consumer's compilation stamps -the line they wrote `Pending(` on, which is the answer they were looking for. +The child subtree is always rendered. When the scope reports any loading resource, the child's `Visibility` is flipped to `Collapsed` and the fallback is shown instead. Because the subtree stays mounted, its hooks keep running, their fetches complete in the background, and the UI swaps to the real content on the next render frame after the scope reports clean. +### Constructors +#### `PendingComponent` +```csharp +public PendingComponent() +``` +### Methods + +#### `Render` + +```csharp +public override Element Render() +``` + +## `PendingFactory` + +Entry-point factory for the `Pending` bubble-up element. See `docs/specs/020-async-resources-design.md` §10 for the full mechanism. + +```csharp +public static class PendingFactory +``` + +Namespace: `Microsoft.UI.Reactor.Hooks`. + +### Methods + +#### `Pending` + +Wraps `child` with a fresh [`PendingScope`](#pendingscope). Renders `fallback` instead of `child` while any `UseResource`/`UseInfiniteResource` in the subtree is in the `Loading` state. `Reloading(previous)` does **not** trigger the fallback — spec §10.1. + +```csharp +public static Element Pending(Element fallback, Element child) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `fallback` | [`Element`](../elements/Element.md) | | +| `child` | [`Element`](../elements/Element.md) | | + +**Remarks** + +The child subtree is always mounted so its hooks register with the scope. The element simply chooses which rendered tree to show — there is no unwinding of rendering, and no reconciler involvement. + +Marked `[ReactorSourceTransparent]` (see [`ReactorSourceTransparentAttribute`](../diagnostics/ReactorSourceTransparentAttribute.md), spec 010) because it is a pure forwarder: the element is really built by the `Component<,>` call on the next line, inside Reactor's own assembly, where no consumer call site exists to intercept. Without the annotation a `Pending(...)` element reports no location at all. With it, the interceptor in the consumer's compilation stamps the line they wrote `Pending(` on, which is the answer they were looking for. + +## `PendingProps` + +Props for [`PendingComponent`](#pendingcomponent). + +```csharp +public sealed record PendingProps(Element Fallback, Element Child) +``` + +Namespace: `Microsoft.UI.Reactor.Hooks`. + +### Constructors + +#### `PendingProps` + +Props for [`PendingComponent`](#pendingcomponent). + +```csharp +public PendingProps(Element Fallback, Element Child) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `Fallback` | [`Element`](../elements/Element.md) | | +| `Child` | [`Element`](../elements/Element.md) | | + +### Properties + +#### `Child` + +```csharp +public Element Child // get, init +``` + +#### `Fallback` + +```csharp +public Element Fallback // get, init +``` + +## `PendingScope` + +Shared loading-state ref-count consumed by the `Pending` element and populated by `UseResource` / `UseInfiniteResource` hooks inside the scope. When the scope observes **any** registered resource in the `Loading` state (not `Reloading`), the owning `Pending` element renders its fallback instead of the child subtree. + +```csharp +public sealed class PendingScope +``` + +Namespace: `Microsoft.UI.Reactor.Hooks`. + +### Remarks + +**Semantics.** Only `Loading` triggers the fallback — spec §10.1. A `Reloading(previous)` is "we already have something to show" and the subtree continues to render normally. + +**Threading.** All members are thread-safe. [`PendingScope.Changed`](#changed) fires on the thread that caused the mutation — consumers (typically `Pending`'s re-render trigger) marshal it to the dispatcher themselves. + +**Scope nesting.** Each `Pending` provides a fresh scope to its subtree, so nested `Pending`s are independent. A hook registers only with its nearest ancestor scope. + +### Constructors + +#### `PendingScope` + +```csharp +public PendingScope() +``` + +### Properties + +#### `AnyLoading` + +True iff any tracked token is currently `Loading`. + +```csharp +public bool AnyLoading // get +``` + +#### `Count` + +Snapshot the number of registered tokens (loading or not). Diagnostic only. + +```csharp +public int Count // get +``` + +### Methods + +#### `Register` + +Start tracking `token` with the given initial `isLoading` state. A hook typically uses its own `this`-equivalent as the token. + +```csharp +public void Register(object token, bool isLoading) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `token` | `object` | | +| `isLoading` | `bool` | | + +#### `SetLoading` + +Update `token`'s loading state. Silently ignored if the token was never registered (defensive — avoids forcing the caller to track whether they registered). + +```csharp +public void SetLoading(object token, bool isLoading) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `token` | `object` | | +| `isLoading` | `bool` | | + +#### `Unregister` + +Stop tracking `token`. Idempotent. + +```csharp +public void Unregister(object token) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `token` | `object` | | + +### Events + +#### `Changed` + +Fires when a resource joins, leaves, or changes its loading state. + +```csharp +public event Action? Changed +``` diff --git a/docs/guide/reference/hooks/PendingComponent.md b/docs/guide/reference/hooks/PendingComponent.md deleted file mode 100644 index 66db77f04f..0000000000 --- a/docs/guide/reference/hooks/PendingComponent.md +++ /dev/null @@ -1,22 +0,0 @@ -# PendingComponent - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.PendingComponent` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Component backing the `Pending` element. Hosts a [PendingScope](PendingScope.md) ([guide](../../hooks.md)), -subscribes to its [Changed](Changed.md) ([guide](../../hooks.md)) event, and chooses between -[Fallback](PendingProps.md) and [Child](PendingProps.md). - -## Discussion - -The child subtree is always rendered. When the scope reports any loading resource, -the child's `Visibility` is flipped to `Collapsed` and the fallback is -shown instead. Because the subtree stays mounted, its hooks keep running, their -fetches complete in the background, and the UI swaps to the real content on the -next render frame after the scope reports clean. - - diff --git a/docs/guide/reference/hooks/PendingFactory.md b/docs/guide/reference/hooks/PendingFactory.md deleted file mode 100644 index c415a2c4d7..0000000000 --- a/docs/guide/reference/hooks/PendingFactory.md +++ /dev/null @@ -1,13 +0,0 @@ -# PendingFactory - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.PendingFactory` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Entry-point factory for the `Pending` bubble-up element. See -`docs/specs/020-async-resources-design.md` §10 for the full mechanism. - - diff --git a/docs/guide/reference/hooks/PendingProps.md b/docs/guide/reference/hooks/PendingProps.md deleted file mode 100644 index 5115bdf4cd..0000000000 --- a/docs/guide/reference/hooks/PendingProps.md +++ /dev/null @@ -1,12 +0,0 @@ -# PendingProps - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.PendingProps` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Props for [PendingComponent](PendingComponent.md) ([guide](../../hooks.md)). - - diff --git a/docs/guide/reference/hooks/PendingScope.md b/docs/guide/reference/hooks/PendingScope.md deleted file mode 100644 index fb50650510..0000000000 --- a/docs/guide/reference/hooks/PendingScope.md +++ /dev/null @@ -1,37 +0,0 @@ -# PendingScope - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.PendingScope` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Shared loading-state ref-count consumed by the `Pending` element and populated by -`UseResource` / `UseInfiniteResource` hooks inside the scope. When the scope -observes **any** registered resource in the `Loading` state (not `Reloading`), -the owning `Pending` element renders its fallback instead of the child subtree. - -## Discussion - - - -**Semantics.** Only `Loading` triggers the fallback — spec §10.1. A -`Reloading(previous)` is "we already have something to show" and the subtree -continues to render normally. - - - -**Threading.** All members are thread-safe. [Changed](Changed.md) ([guide](../../hooks.md)) fires on the -thread that caused the mutation — consumers (typically `Pending`'s re-render -trigger) marshal it to the dispatcher themselves. - - - -**Scope nesting.** Each `Pending` provides a fresh scope to its subtree, -so nested `Pending`s are independent. A hook registers only with its nearest -ancestor scope. - - - - diff --git a/docs/guide/reference/hooks/Post.md b/docs/guide/reference/hooks/Post.md deleted file mode 100644 index b401c04d20..0000000000 --- a/docs/guide/reference/hooks/Post.md +++ /dev/null @@ -1,12 +0,0 @@ -# Post - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.IHookDispatcher.Post(System.Action)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Enqueue `action` to run on the dispatcher thread. - - diff --git a/docs/guide/reference/hooks/RefetchOnMount.md b/docs/guide/reference/hooks/RefetchOnMount.md deleted file mode 100644 index 07a01d9889..0000000000 --- a/docs/guide/reference/hooks/RefetchOnMount.md +++ /dev/null @@ -1,12 +0,0 @@ -# RefetchOnMount - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.ResourceOptions.RefetchOnMount` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Whether to fetch on a cache miss. - - diff --git a/docs/guide/reference/hooks/RefetchOnWindowFocus.md b/docs/guide/reference/hooks/RefetchOnWindowFocus.md deleted file mode 100644 index 23aca32de0..0000000000 --- a/docs/guide/reference/hooks/RefetchOnWindowFocus.md +++ /dev/null @@ -1,12 +0,0 @@ -# RefetchOnWindowFocus - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.ResourceOptions.RefetchOnWindowFocus` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Whether to opt into window-focus revalidation. - - diff --git a/docs/guide/reference/hooks/Region.md b/docs/guide/reference/hooks/Region.md deleted file mode 100644 index 47db111203..0000000000 --- a/docs/guide/reference/hooks/Region.md +++ /dev/null @@ -1,13 +0,0 @@ -# Region - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.AnnounceHandle.Region` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -A zero-size, invisible Reactor element that acts as the live-region anchor. -Include this anywhere in your component tree (it renders nothing visible). - - diff --git a/docs/guide/reference/hooks/Register.md b/docs/guide/reference/hooks/Register.md deleted file mode 100644 index 54ba6bdb87..0000000000 --- a/docs/guide/reference/hooks/Register.md +++ /dev/null @@ -1,34 +0,0 @@ -# Register - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusManager.Register(System.String)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Members - -> These members share a name but are declared on unrelated types. They are not overloads of one another. - -- [`Register(string)`](#registerstring) — `Microsoft.UI.Reactor.Hooks.FocusManager` -- [`Register(object, bool)`](#registerobject-bool) — `Microsoft.UI.Reactor.Hooks.PendingScope` - -## `Register(string)` - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusManager.Register(System.String)` - -### Summary - -Registers a field name in ordering. Call on every render to maintain order. - -## `Register(object, bool)` - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.PendingScope.Register(System.Object,System.Boolean)` - -### Summary - -Start tracking `token` with the given initial `isLoading` -state. A hook typically uses its own `this`-equivalent as the token. - - diff --git a/docs/guide/reference/hooks/Reset.md b/docs/guide/reference/hooks/Reset.md deleted file mode 100644 index 8828efe497..0000000000 --- a/docs/guide/reference/hooks/Reset.md +++ /dev/null @@ -1,13 +0,0 @@ -# Reset - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.Mutation`2.Reset` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Clear [Error](Error.md) ([guide](../../hooks.md)) and [LastResult](LastResult.md) ([guide](../../hooks.md)). Does not cancel or affect any -in-flight [RunAsync](RunAsync.md) ([guide](../../hooks.md)) call. - - diff --git a/docs/guide/reference/hooks/ResourceHookState.md b/docs/guide/reference/hooks/ResourceHookState.md deleted file mode 100644 index 2c43386ecd..0000000000 --- a/docs/guide/reference/hooks/ResourceHookState.md +++ /dev/null @@ -1,13 +0,0 @@ -# ResourceHookState - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.ResourceHookState`1` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Mutable state backing a single `UseResource` hook instance. Instances are -owned per-component, per-hook-slot, and are disposed on unmount. - - diff --git a/docs/guide/reference/hooks/ResourceOptions.md b/docs/guide/reference/hooks/ResourceOptions.md deleted file mode 100644 index 3320c2a36c..0000000000 --- a/docs/guide/reference/hooks/ResourceOptions.md +++ /dev/null @@ -1,26 +0,0 @@ -# ResourceOptions - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.ResourceOptions` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Tuning for the `UseResource` hook. Defaults mirror -TanStack Query — zero [StaleTime](StaleTime.md) ([guide](../../hooks.md)) (always refetch-on-mount but dedup -concurrent requests), five-minute [CacheTime](CacheTime.md) ([guide](../../hooks.md)). - -## Parameters - -- **StaleTime** — Freshness interval; null uses zero. -- **CacheTime** — Retention after the last subscriber leaves; null uses five minutes. -- **RetryCount** — Number of retries after a failed fetch. -- **RefetchOnMount** — Whether to fetch on a cache miss. -- **CacheKey** — Overrides the generated cache key; null uses a key derived from deps. -When set, the key identifies the query; deps changes alone do not cancel -an in-flight request or start a new fetch. Include values that select -different data in the key, for example `$"user:{userId}"`. -- **RefetchOnWindowFocus** — Whether to opt into window-focus revalidation. - - diff --git a/docs/guide/reference/hooks/RetryCount.md b/docs/guide/reference/hooks/RetryCount.md deleted file mode 100644 index 578fffcd81..0000000000 --- a/docs/guide/reference/hooks/RetryCount.md +++ /dev/null @@ -1,12 +0,0 @@ -# RetryCount - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.ResourceOptions.RetryCount` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Number of retries after a failed fetch. - - diff --git a/docs/guide/reference/hooks/RunAsync.md b/docs/guide/reference/hooks/RunAsync.md deleted file mode 100644 index 340d25c49d..0000000000 --- a/docs/guide/reference/hooks/RunAsync.md +++ /dev/null @@ -1,31 +0,0 @@ -# RunAsync - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.Mutation`2.RunAsync(`0)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Kick off the mutator with `input`. Returns a task that completes -with the mutator's result or fault. - -## Discussion - - - -Ordering: [OnOptimistic](MutationOptions.md) fires -synchronously before the mutator starts. [OnSuccess](MutationOptions.md) -or [OnError](MutationOptions.md) fires on the hook's dispatcher -thread after completion. - - - -If [OnOptimistic](MutationOptions.md) throws, the -mutator is never invoked and the returned task is faulted with the optimistic -exception — prevents half-applied state where the optimistic patch ran but the -real request can't. - - - - diff --git a/docs/guide/reference/hooks/SetControl.md b/docs/guide/reference/hooks/SetControl.md deleted file mode 100644 index 672eb40839..0000000000 --- a/docs/guide/reference/hooks/SetControl.md +++ /dev/null @@ -1,12 +0,0 @@ -# SetControl - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusManager.SetControl(System.String,Microsoft.UI.Xaml.Controls.Control)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Associates a WinUI control with a field name. Called from .Set() during mount/update. - - diff --git a/docs/guide/reference/hooks/SetLoading.md b/docs/guide/reference/hooks/SetLoading.md deleted file mode 100644 index ff0a6363bb..0000000000 --- a/docs/guide/reference/hooks/SetLoading.md +++ /dev/null @@ -1,14 +0,0 @@ -# SetLoading - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.PendingScope.SetLoading(System.Object,System.Boolean)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Update `token`'s loading state. Silently ignored if the token -was never registered (defensive — avoids forcing the caller to track whether they -registered). - - diff --git a/docs/guide/reference/hooks/SetSubmitHandler.md b/docs/guide/reference/hooks/SetSubmitHandler.md deleted file mode 100644 index 58c2e9b2ea..0000000000 --- a/docs/guide/reference/hooks/SetSubmitHandler.md +++ /dev/null @@ -1,12 +0,0 @@ -# SetSubmitHandler - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.FocusManager.SetSubmitHandler(System.Action)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Sets the callback for submit (Enter on last field). - - diff --git a/docs/guide/reference/hooks/StaleTime.md b/docs/guide/reference/hooks/StaleTime.md deleted file mode 100644 index c6de03c029..0000000000 --- a/docs/guide/reference/hooks/StaleTime.md +++ /dev/null @@ -1,12 +0,0 @@ -# StaleTime - -`property` -_cref_: `P:Microsoft.UI.Reactor.Hooks.ResourceOptions.StaleTime` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Freshness interval; null uses zero. - - diff --git a/docs/guide/reference/hooks/Unregister.md b/docs/guide/reference/hooks/Unregister.md deleted file mode 100644 index c098bd39e9..0000000000 --- a/docs/guide/reference/hooks/Unregister.md +++ /dev/null @@ -1,12 +0,0 @@ -# Unregister - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.PendingScope.Unregister(System.Object)` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Stop tracking `token`. Idempotent. - - diff --git a/docs/guide/reference/hooks/UseAnnounce.md b/docs/guide/reference/hooks/UseAnnounce.md index 04d7d754e5..55cd1c5fbd 100644 --- a/docs/guide/reference/hooks/UseAnnounce.md +++ b/docs/guide/reference/hooks/UseAnnounce.md @@ -1,41 +1,30 @@ # UseAnnounce -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.UseAnnounceExtensions.UseAnnounce(Microsoft.UI.Reactor.Core.Component)` +Creates an [`AnnounceHandle`](hook-types.md#announcehandle) for making screen reader announcements. The handle persists across re-renders. -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +You must include [`AnnounceHandle.Region`](hook-types.md#region) in your rendered tree: -## Overloads - -- [`UseAnnounce(Component)`](#useannouncecomponent) -- [`UseAnnounce(RenderContext)`](#useannouncerendercontext) - -## `UseAnnounce(Component)` - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.UseAnnounceExtensions.UseAnnounce(Microsoft.UI.Reactor.Core.Component)` - -### Summary +```csharp +var announce = UseAnnounce(); +return VStack( + announce.Region, + Button("Save", () => { Save(); announce.Announce("Document saved"); }), +); +``` -Creates an [AnnounceHandle](AnnounceHandle.md) ([guide](../../hooks.md)) for making screen reader announcements. +```csharp +public static AnnounceHandle UseAnnounce(this RenderContext ctx) +``` -## `UseAnnounce(RenderContext)` +An extension method on [`RenderContext`](../components/RenderContext.md), declared in `UseAnnounceExtensions`. -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.UseAnnounceExtensions.UseAnnounce(Microsoft.UI.Reactor.Core.RenderContext)` +**Learn more:** [Accessibility](../../accessibility.md), [Hooks](../../hooks.md) -### Summary +## Use from a class component -Creates an [AnnounceHandle](AnnounceHandle.md) ([guide](../../hooks.md)) for making screen reader announcements. -The handle persists across re-renders. +Class components can call the same hook directly. These overloads forward to the ones above: -You must include [Region](Region.md) ([guide](../../hooks.md)) in your rendered tree: ```csharp -var announce = UseAnnounce(); -return VStack( -announce.Region, -Button("Save", () => { Save(); announce.Announce("Document saved"); }), -); +protected AnnounceHandle UseAnnounce() +public static AnnounceHandle UseAnnounce(this Component component) ``` - - diff --git a/docs/guide/reference/hooks/UseAnnounceExtensions.md b/docs/guide/reference/hooks/UseAnnounceExtensions.md deleted file mode 100644 index 06471dc5cb..0000000000 --- a/docs/guide/reference/hooks/UseAnnounceExtensions.md +++ /dev/null @@ -1,12 +0,0 @@ -# UseAnnounceExtensions - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.UseAnnounceExtensions` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Extension methods for the UseAnnounce hook. - - diff --git a/docs/guide/reference/hooks/UseBreakpoint.md b/docs/guide/reference/hooks/UseBreakpoint.md index cbde9e6816..c0a7380572 100644 --- a/docs/guide/reference/hooks/UseBreakpoint.md +++ b/docs/guide/reference/hooks/UseBreakpoint.md @@ -1,35 +1,57 @@ # UseBreakpoint -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseBreakpoint(System.Double)` +Returns true when the given window's width is \>= minWidth. Re-renders when the window resizes across the breakpoint. -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +```csharp +public bool UseBreakpoint(double minWidth) +public bool UseBreakpoint(Window window, double minWidth) +``` + +Declared on [`RenderContext`](../components/RenderContext.md). + +**Learn more:** [Layout](../../layout.md), [Hooks](../../hooks.md) ## Overloads -- [`UseBreakpoint(double)`](#usebreakpointdouble) -- [`UseBreakpoint(Window, double)`](#usebreakpointwindow-double) +| Overload | Description | +| --- | --- | +| [`UseBreakpoint(double)`](#usebreakpointdouble) | Window-inferring overload — takes only `minWidth` and resolves the window whose host renders this component (see the parameterless `UseWindowSize`). | +| [`UseBreakpoint(Window, double)`](#usebreakpointwindow-double) | Returns true when the given window's width is \>= minWidth. | + +### `UseBreakpoint(double)` + +Window-inferring overload — takes only `minWidth` and resolves the window whose host renders this component (see the parameterless [`UseWindowSize`](UseWindowSize.md#usewindowsize_1)). Returns false when the component has no owning window. (spec 036 §5.2) + +```csharp +public bool UseBreakpoint(double minWidth) +``` -## `UseBreakpoint(double)` +**Parameters** -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseBreakpoint(System.Double)` +| Name | Type | Description | +| --- | --- | --- | +| `minWidth` | `double` | | -### Summary +### `UseBreakpoint(Window, double)` -Window-inferring overload — takes only `minWidth` and -resolves the window whose host renders this component (see the parameterless -[UseWindowSize](UseWindowSize.md#usewindowsize) ([guide](../../hooks.md))). Returns false when the component has no owning -window. (spec 036 §5.2) +Returns true when the given window's width is \>= minWidth. Re-renders when the window resizes across the breakpoint. -## `UseBreakpoint(Window, double)` +```csharp +public bool UseBreakpoint(Window window, double minWidth) +``` -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseBreakpoint(Microsoft.UI.Xaml.Window,System.Double)` +**Parameters** -### Summary +| Name | Type | Description | +| --- | --- | --- | +| `window` | `Window` | | +| `minWidth` | `double` | | -Returns true when the given window's width is >= minWidth. -Re-renders when the window resizes across the breakpoint. +## Use from a class component +Class components can call the same hook directly. These overloads forward to the ones above: +```csharp +protected bool UseBreakpoint(double minWidth) +protected bool UseBreakpoint(Window window, double minWidth) +``` diff --git a/docs/guide/reference/hooks/UseCallback.md b/docs/guide/reference/hooks/UseCallback.md index 0b57712f33..de1935eae2 100644 --- a/docs/guide/reference/hooks/UseCallback.md +++ b/docs/guide/reference/hooks/UseCallback.md @@ -1,67 +1,101 @@ # UseCallback -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseCallback(System.Action,System.Object[])` +Returns a stable callback reference that doesn't change between renders. -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +```csharp +public Action UseCallback(Action callback, params object[] dependencies) +public Action UseCallback(Action callback, T1 d1) +public Action UseCallback(Action callback, T1 d1, T2 d2) +public Action UseCallback(Action callback, T1 d1, T2 d2, T3 d3) +``` -## Overloads +Declared on [`RenderContext`](../components/RenderContext.md). -- [`UseCallback(Action, object[])`](#usecallbackaction-object) -- [`UseCallback(Action, T1)`](#usecallbackt1action-t1) -- [`UseCallback(Action, T1, T2)`](#usecallbackt1-t2action-t1-t2) -- [`UseCallback(Action, T1, T2, T3)`](#usecallbackt1-t2-t3action-t1-t2-t3) +**Learn more:** [Hooks](../../hooks.md), [Performance](../../performance.md) -## `UseCallback(Action, object[])` +## Overloads -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseCallback(System.Action,System.Object[])` +| Overload | Description | +| --- | --- | +| [`UseCallback(Action, object[])`](#usecallbackaction-object) | Returns a stable callback reference that doesn't change between renders. | +| [`UseCallback(Action, T1)`](#usecallbackt1action-t1) | Single-dependency `UseCallback` overload that avoids the `params object[]` allocation (and value-type boxing) on the deps-unchanged path. | +| [`UseCallback(Action, T1, T2)`](#usecallbackt1-t2action-t1-t2) | Two-dependency `UseCallback` overload that avoids the `params object[]` allocation on the deps-unchanged path. | +| [`UseCallback(Action, T1, T2, T3)`](#usecallbackt1-t2-t3action-t1-t2-t3) | Three-dependency `UseCallback` overload that avoids the `params object[]` allocation on the deps-unchanged path. | -### Summary +### `UseCallback(Action, object[])` Returns a stable callback reference that doesn't change between renders. -## `UseCallback(Action, T1)` +```csharp +public Action UseCallback(Action callback, params object[] dependencies) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `callback` | `Action` | | +| `dependencies` | `object[]` | | + +### `UseCallback(Action, T1)` + +Single-dependency `UseCallback` overload that avoids the `params object[]` allocation (and value-type boxing) on the deps-unchanged path. Returns a stable reference until `d1` changes. + +```csharp +public Action UseCallback(Action callback, T1 d1) +``` + +**Parameters** -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseCallback``1(System.Action,``0)` +| Name | Type | Description | +| --- | --- | --- | +| `callback` | `Action` | | +| `d1` | `T1` | | -### Summary +**Remarks** -Single-dependency `UseCallback` overload that avoids the -`params object[]` allocation (and value-type boxing) on the -deps-unchanged path. Returns a stable reference until `d1` -changes. +If `d1`'s compile-time type is an array of reference types (e.g. `string[]`), it is treated as a dependency *list* and compared element-wise — matching the `params object[]` overload — not as a single reference-compared value. A dependency whose static type is not an array is always compared as one value, even if its runtime value happens to be an array. -### Discussion +### `UseCallback(Action, T1, T2)` -If `d1`'s compile-time type is an array of reference types -(e.g. `string[]`), it is treated as a dependency list and compared -element-wise — matching the `params object[]` overload — not as a single -reference-compared value. A dependency whose static type is not an array is -always compared as one value, even if its runtime value happens to be an array. +Two-dependency `UseCallback` overload that avoids the `params object[]` allocation on the deps-unchanged path. -## `UseCallback(Action, T1, T2)` +```csharp +public Action UseCallback(Action callback, T1 d1, T2 d2) +``` -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseCallback``2(System.Action,``0,``1)` +**Parameters** -### Summary +| Name | Type | Description | +| --- | --- | --- | +| `callback` | `Action` | | +| `d1` | `T1` | | +| `d2` | `T2` | | -Two-dependency `UseCallback` overload that avoids the -`params object[]` allocation on the deps-unchanged path. +### `UseCallback(Action, T1, T2, T3)` -## `UseCallback(Action, T1, T2, T3)` +Three-dependency `UseCallback` overload that avoids the `params object[]` allocation on the deps-unchanged path. -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseCallback``3(System.Action,``0,``1,``2)` +```csharp +public Action UseCallback(Action callback, T1 d1, T2 d2, T3 d3) +``` -### Summary +**Parameters** -Three-dependency `UseCallback` overload that avoids the -`params object[]` allocation on the deps-unchanged path. +| Name | Type | Description | +| --- | --- | --- | +| `callback` | `Action` | | +| `d1` | `T1` | | +| `d2` | `T2` | | +| `d3` | `T3` | | -## Featured in +## Use from a class component -- [Hooks](../../hooks.md) +Class components can call the same hook directly. These overloads forward to the ones above: +```csharp +protected Action UseCallback(Action callback, params object[] dependencies) +protected Action UseCallback(Action callback, T1 d1) +protected Action UseCallback(Action callback, T1 d1, T2 d2) +protected Action UseCallback(Action callback, T1 d1, T2 d2, T3 d3) +``` diff --git a/docs/guide/reference/hooks/UseChildValidationContext.md b/docs/guide/reference/hooks/UseChildValidationContext.md new file mode 100644 index 0000000000..0b205433a5 --- /dev/null +++ b/docs/guide/reference/hooks/UseChildValidationContext.md @@ -0,0 +1,19 @@ +# UseChildValidationContext + +Creates a child validation context independent from any parent. Returns both the child context and the parent (if one exists). The child collects its own messages; use the parent reference to bubble manually. + +```csharp +public static (ValidationContext Child, ValidationContext Parent) UseChildValidationContext(this RenderContext ctx) +``` + +An extension method on [`RenderContext`](../components/RenderContext.md), declared in `ValidationContextHookExtensions`. + +**Learn more:** [Forms and Input](../../forms.md), [Hooks](../../hooks.md) + +## Use from a class component + +Class components can call the same hook directly. These overloads forward to the ones above: + +```csharp +public static (ValidationContext Child, ValidationContext Parent) UseChildValidationContext(this Component component) +``` diff --git a/docs/guide/reference/hooks/UseClosingGuard.md b/docs/guide/reference/hooks/UseClosingGuard.md index d1457e63ef..b7a306586f 100644 --- a/docs/guide/reference/hooks/UseClosingGuard.md +++ b/docs/guide/reference/hooks/UseClosingGuard.md @@ -1,16 +1,25 @@ # UseClosingGuard -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseClosingGuard(System.Func{System.Boolean})` +Registers a synchronous "can the window close right now?" predicate. Multiple guards stack — any returning `false` cancels the close. Runs on the UI thread; for async confirmation, return `false` and re-trigger [`ReactorWindow.Close`](../hosting/ReactorWindow.md#close) from the dialog callback. No-op outside a window. (spec 036 §7 / §13.4) -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +```csharp +public void UseClosingGuard(Func canClose) +``` -## Summary +Declared on [`RenderContext`](../components/RenderContext.md). -Registers a synchronous "can the window close right now?" predicate. -Multiple guards stack — any returning `false` cancels the close. -Runs on the UI thread; for async confirmation, return `false` and -re-trigger `ReactorWindow.Close` from -the dialog callback. No-op outside a window. (spec 036 §7 / §13.4) +**Learn more:** [Windows](../../windows.md), [Hooks](../../hooks.md) +## Parameters +| Name | Type | Description | +| --- | --- | --- | +| `canClose` | `Func` | | + +## Use from a class component + +Class components can call the same hook directly. These overloads forward to the ones above: + +```csharp +protected void UseClosingGuard(Func canClose) +``` diff --git a/docs/guide/reference/hooks/UseCollection.md b/docs/guide/reference/hooks/UseCollection.md index bda84b430c..4ae5255fd4 100644 --- a/docs/guide/reference/hooks/UseCollection.md +++ b/docs/guide/reference/hooks/UseCollection.md @@ -1,13 +1,25 @@ # UseCollection -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseCollection``1(System.Collections.ObjectModel.ObservableCollection{``0})` +Subscribes to an ObservableCollection and re-renders on Add/Remove/Reset. Returns the collection as IReadOnlyList. -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +```csharp +public IReadOnlyList UseCollection(ObservableCollection collection) +``` -## Summary +Declared on [`RenderContext`](../components/RenderContext.md). -Subscribes to an ObservableCollection and re-renders on Add/Remove/Reset. -Returns the collection as IReadOnlyList. +**Learn more:** [Collections](../../collections.md), [Hooks](../../hooks.md) +## Parameters +| Name | Type | Description | +| --- | --- | --- | +| `collection` | `ObservableCollection` | | + +## Use from a class component + +Class components can call the same hook directly. These overloads forward to the ones above: + +```csharp +protected IReadOnlyList UseCollection(ObservableCollection collection) +``` diff --git a/docs/guide/reference/hooks/UseColorScheme.md b/docs/guide/reference/hooks/UseColorScheme.md index 82530d0660..b74c586c40 100644 --- a/docs/guide/reference/hooks/UseColorScheme.md +++ b/docs/guide/reference/hooks/UseColorScheme.md @@ -1,29 +1,23 @@ # UseColorScheme -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseColorScheme` +Returns the app-global [`ColorScheme`](../theming/enums.md#colorscheme) — [`ColorScheme.Light`](../theming/enums.md#values_1) or [`ColorScheme.Dark`](../theming/enums.md#values_1), read from `Application.Current.RequestedTheme`. -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +The value is re-evaluated on every render — when the app theme changes, [`ReactorHost`](../hosting/ReactorHost.md) triggers a re-render so this hook naturally picks up the new value. -## Summary +This hook does **not** observe per-element `RequestedTheme` overrides: it consults the application, not the calling component's position in the tree, so a component inside a `.RequestedTheme(Dark)` subtree still reports the app theme. It also never returns [`ColorScheme.HighContrast`](../theming/enums.md#values_1) in a running app — use [`UseHighContrast`](UseHighContrast.md) for forced-colors mode. -Returns the app-global `ColorScheme` — `ColorScheme.Light` -or `ColorScheme.Dark`, read from -`Application.Current.RequestedTheme`. +```csharp +public ColorScheme UseColorScheme() +``` +Declared on [`RenderContext`](../components/RenderContext.md). -The value is re-evaluated on every render — when the app theme changes, -`ReactorHost` triggers a re-render so this hook -naturally picks up the new value. - - - -This hook does **not** observe per-element `RequestedTheme` overrides: it -consults the application, not the calling component's position in the tree, so a -component inside a `.RequestedTheme(Dark)` subtree still reports the app theme. -It also never returns `ColorScheme.HighContrast` in a running app — use -[UseHighContrast](UseHighContrast.md) ([guide](../../hooks.md)) for forced-colors mode. - +**Learn more:** [Theming Tokens](../../theming-tokens.md), [Hooks](../../hooks.md) +## Use from a class component +Class components can call the same hook directly. These overloads forward to the ones above: +```csharp +protected ColorScheme UseColorScheme() +``` diff --git a/docs/guide/reference/hooks/UseCommand.md b/docs/guide/reference/hooks/UseCommand.md index 4069e4970f..da7a9925d1 100644 --- a/docs/guide/reference/hooks/UseCommand.md +++ b/docs/guide/reference/hooks/UseCommand.md @@ -1,45 +1,56 @@ # UseCommand -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseCommand(Microsoft.UI.Reactor.Core.Command)` +Processes a Command for use in a component. Always consumes a **stable hook shape** (independent of whether the command is sync/async or debounced), so a command at a given call site can flip between sync↔async or [`Command.DebounceMs`](../input/Command.md#debouncems) 0↔N across renders without ever reordering hook slots. For a pure sync command with no [`Command.DebounceMs`](../input/Command.md#debouncems) the original command is returned unchanged (identity preserved). For async commands, wraps ExecuteAsync with automatic IsExecuting tracking and re-entrance guards. When [`Command.DebounceMs`](../input/Command.md#debouncems) \> 0, wraps the dispatch with a leading-edge debounce: a fire within the window of the prior accepted fire is dropped and [`Command.IsDebouncing`](../input/Command.md#isdebouncing) (hence [`Command.IsEnabled`](../input/Command.md#isenabled)=false) reflects the window so the bound control disables, re-enabling when the window elapses. The returned command has a sync Execute action, ExecuteAsync = null, and preserves the authored DebounceMs value (re-passing it through UseCommand is a no-op — debounce is never applied twice). -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +```csharp +public Command UseCommand(Command command) +public Command UseCommand(Command command) +``` + +Declared on [`RenderContext`](../components/RenderContext.md). + +**Learn more:** [Commanding](../../commanding.md), [Hooks](../../hooks.md) ## Overloads -- [`UseCommand(Command)`](#usecommandcommand) -- [`UseCommand(Command)`](#usecommandt1commandt1) +| Overload | Description | +| --- | --- | +| [`UseCommand(Command)`](#usecommandcommand) | Processes a Command for use in a component. | +| [`UseCommand(Command)`](#usecommandtcommandt) | Processes a parameterized Command for use in a component. | + +### `UseCommand(Command)` + +Processes a Command for use in a component. Always consumes a **stable hook shape** (independent of whether the command is sync/async or debounced), so a command at a given call site can flip between sync↔async or [`Command.DebounceMs`](../input/Command.md#debouncems) 0↔N across renders without ever reordering hook slots. For a pure sync command with no [`Command.DebounceMs`](../input/Command.md#debouncems) the original command is returned unchanged (identity preserved). For async commands, wraps ExecuteAsync with automatic IsExecuting tracking and re-entrance guards. When [`Command.DebounceMs`](../input/Command.md#debouncems) \> 0, wraps the dispatch with a leading-edge debounce: a fire within the window of the prior accepted fire is dropped and [`Command.IsDebouncing`](../input/Command.md#isdebouncing) (hence [`Command.IsEnabled`](../input/Command.md#isenabled)=false) reflects the window so the bound control disables, re-enabling when the window elapses. The returned command has a sync Execute action, ExecuteAsync = null, and preserves the authored DebounceMs value (re-passing it through UseCommand is a no-op — debounce is never applied twice). + +```csharp +public Command UseCommand(Command command) +``` -## `UseCommand(Command)` +**Parameters** -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseCommand(Microsoft.UI.Reactor.Core.Command)` +| Name | Type | Description | +| --- | --- | --- | +| `command` | [`Command`](../input/Command.md) | | -### Summary +### `UseCommand(Command)` -Processes a Command for use in a component. Always consumes a **stable hook shape** -(independent of whether the command is sync/async or debounced), so a command at a given -call site can flip between sync↔async or `Command.DebounceMs` 0↔N across -renders without ever reordering hook slots. For a pure sync command with no -`Command.DebounceMs` the original command is returned unchanged (identity -preserved). For async commands, wraps ExecuteAsync with automatic IsExecuting tracking and -re-entrance guards. When `Command.DebounceMs` > 0, wraps the dispatch with a -leading-edge debounce: a fire within the window of the prior accepted fire is dropped and -`Command.IsDebouncing` (hence `Command.IsEnabled`=false) reflects -the window so the bound control disables, re-enabling when the window elapses. The returned -command has a sync Execute action, ExecuteAsync = null, and preserves the authored -DebounceMs value (re-passing it through UseCommand is a no-op — debounce is never applied -twice). +Processes a parameterized Command for use in a component. Consumes the same **stable hook shape** as the non-generic [`UseCommand`](#usecommandcommand) and applies the same async tracking and leading-edge [`Command.DebounceMs`](../input/Command-1.md#debouncems) debounce. -## `UseCommand(Command)` +```csharp +public Command UseCommand(Command command) +``` -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseCommand``1(Microsoft.UI.Reactor.Core.Command{``0})` +**Parameters** -### Summary +| Name | Type | Description | +| --- | --- | --- | +| `command` | [`Command`](../input/Command-1.md) | | -Processes a parameterized Command for use in a component. Consumes the same -**stable hook shape** as the non-generic [UseCommand](UseCommand.md#usecommandcommand) ([guide](../../hooks.md)) and applies -the same async tracking and leading-edge `Command.DebounceMs` debounce. +## Use from a class component +Class components can call the same hook directly. These overloads forward to the ones above: +```csharp +protected Command UseCommand(Command command) +protected Command UseCommand(Command command) +``` diff --git a/docs/guide/reference/hooks/UseCommandState.md b/docs/guide/reference/hooks/UseCommandState.md deleted file mode 100644 index b85f57dfc7..0000000000 --- a/docs/guide/reference/hooks/UseCommandState.md +++ /dev/null @@ -1,16 +0,0 @@ -# UseCommandState - -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseCommandState` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Allocates the stable hook shape shared by both [UseCommand](UseCommand.md#usecommandcommand) ([guide](../../hooks.md)) overloads: -the IsExecuting / IsDebouncing state, the re-entrance guard and debounce-slot refs, and an -unmount effect that disposes any live re-enable timer so it cannot fire -`setIsDebouncing` / request a re-render against a torn-down context. These hooks are -allocated unconditionally so the hook order is identical regardless of the command's shape. - - diff --git a/docs/guide/reference/hooks/UseContext.md b/docs/guide/reference/hooks/UseContext.md index 7d5fc079a6..daf0e7da42 100644 --- a/docs/guide/reference/hooks/UseContext.md +++ b/docs/guide/reference/hooks/UseContext.md @@ -1,17 +1,25 @@ # UseContext -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseContext``1(Microsoft.UI.Reactor.Core.Context{``0})` +Reads the nearest ancestor's provided value for the given context. Returns the context's DefaultValue if no provider exists in the ancestor chain. Follows hook rules — must be called in the same order every render. -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +```csharp +public T UseContext(Context context) +``` -## Summary +Declared on [`RenderContext`](../components/RenderContext.md). -Reads the nearest ancestor's provided value for the given context. -Returns the context's DefaultValue if no provider exists in the ancestor chain. -Follows hook rules — must be called in the same order every render. +**Learn more:** [Context](../../context.md), [Hooks](../../hooks.md) -## Featured in +## Parameters -- [Hooks](../../hooks.md) +| Name | Type | Description | +| --- | --- | --- | +| `context` | [`Context`](../components/Context.md) | | +## Use from a class component + +Class components can call the same hook directly. These overloads forward to the ones above: + +```csharp +protected T UseContext(Context context) +``` diff --git a/docs/guide/reference/hooks/UseDataSource.md b/docs/guide/reference/hooks/UseDataSource.md new file mode 100644 index 0000000000..2136d55569 --- /dev/null +++ b/docs/guide/reference/hooks/UseDataSource.md @@ -0,0 +1,84 @@ +# UseDataSource + +Projects an [`IDataSource`](../data/IDataSource.md) through `UseInfiniteResource`, surfacing its pages as an [`InfiniteResource`](../data/paging.md#infiniteresourcetitem). Deps are identity-based on `source` and value-based on the request descriptors, so a new sort/filter/search restarts the pagination cleanly. + +```csharp +public static InfiniteResource UseDataSource(this RenderContext ctx, IDataSource source, DataRequest request, InfiniteResourceOptions? options = null, IHookDispatcher? dispatcher = null) +public static InfiniteResource UseDataSource(this RenderContext ctx, IDataSource source, DataRequest request, QueryCache cache, InfiniteResourceOptions? options = null, IHookDispatcher? dispatcher = null) +protected InfiniteResource UseDataSource(IDataSource source, DataRequest request, InfiniteResourceOptions? options = null) +``` + +An extension method on [`RenderContext`](../components/RenderContext.md), declared in `DataSourceResourceExtensions`. + +**Learn more:** [Data System](../../data-system.md), [Hooks](../../hooks.md) + +## Overloads + +| Overload | Description | +| --- | --- | +| [`UseDataSource(RenderContext, IDataSource, DataRequest, InfiniteResourceOptions?, IHookDispatcher?)`](#usedatasourcetrendercontext-idatasourcet-datarequest-infiniteresourceoptions-ihookdispatcher) | Overload that reads the ambient `QueryCache` from `AppContexts.QueryCache`. | +| [`UseDataSource(RenderContext, IDataSource, DataRequest, QueryCache, InfiniteResourceOptions?, IHookDispatcher?)`](#usedatasourcetrendercontext-idatasourcet-datarequest-querycache-infiniteresourceoptions-ihookdispatcher) | Projects an `IDataSource` through `UseInfiniteResource`, surfacing its pages as an `InfiniteResource`. | +| [`UseDataSource(IDataSource, DataRequest, InfiniteResourceOptions?)`](#usedatasourcetitemidatasourcetitem-datarequest-infiniteresourceoptions) | Projects a data source into a paged resource using the ambient query cache. | + +### `UseDataSource(RenderContext, IDataSource, DataRequest, InfiniteResourceOptions?, IHookDispatcher?)` + +Overload that reads the ambient [`QueryCache`](../data/query-cache.md#querycache) from [`AppContexts.QueryCache`](../components/AppContexts.md#querycache). [`ReactorHost`](../hosting/ReactorHost.md) installs a process-wide default cache at startup; tests or subtrees may override it via `.Provide(AppContexts.QueryCache, customCache)`. + +```csharp +public static InfiniteResource UseDataSource(this RenderContext ctx, IDataSource source, DataRequest request, InfiniteResourceOptions? options = null, IHookDispatcher? dispatcher = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `source` | [`IDataSource`](../data/IDataSource.md) | | | +| `request` | [`DataRequest`](../data/descriptors.md#datarequest) | | | +| `options` | [`InfiniteResourceOptions?`](../data/paging.md#infiniteresourceoptions) | `null` | | +| `dispatcher` | [`IHookDispatcher?`](hook-types.md#ihookdispatcher) | `null` | | + +**Remarks** + +The initial page size comes from `options.PageSize` (default 50) when `options` is supplied, or `request.PageSize` otherwise, and is clamped to at least 1. This size stays fixed across renders and query restarts. To change it, have the parent remount the calling component with a different key, e.g. `.WithKey($"tasks:{pageSize}")`, or increment a parent-owned reset version used by `.WithKey($"tasks:{resetVersion}")`. + +### `UseDataSource(RenderContext, IDataSource, DataRequest, QueryCache, InfiniteResourceOptions?, IHookDispatcher?)` + +Projects an [`IDataSource`](../data/IDataSource.md) through `UseInfiniteResource`, surfacing its pages as an [`InfiniteResource`](../data/paging.md#infiniteresourcetitem). Deps are identity-based on `source` and value-based on the request descriptors, so a new sort/filter/search restarts the pagination cleanly. + +```csharp +public static InfiniteResource UseDataSource(this RenderContext ctx, IDataSource source, DataRequest request, QueryCache cache, InfiniteResourceOptions? options = null, IHookDispatcher? dispatcher = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `source` | [`IDataSource`](../data/IDataSource.md) | | | +| `request` | [`DataRequest`](../data/descriptors.md#datarequest) | | | +| `cache` | [`QueryCache`](../data/query-cache.md#querycache) | | | +| `options` | [`InfiniteResourceOptions?`](../data/paging.md#infiniteresourceoptions) | `null` | | +| `dispatcher` | [`IHookDispatcher?`](hook-types.md#ihookdispatcher) | `null` | | + +**Remarks** + +The initial page size comes from `options.PageSize` (default 50) when `options` is supplied, or `request.PageSize` otherwise, and is clamped to at least 1. This size stays fixed across renders and query restarts. To change it, have the parent remount the calling component with a different key, e.g. `.WithKey($"tasks:{pageSize}")`, or increment a parent-owned reset version used by `.WithKey($"tasks:{resetVersion}")`. + +### `UseDataSource(IDataSource, DataRequest, InfiniteResourceOptions?)` + +Projects a data source into a paged resource using the ambient query cache. + +```csharp +protected InfiniteResource UseDataSource(IDataSource source, DataRequest request, InfiniteResourceOptions? options = null) +``` + +**Parameters** + +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `source` | [`IDataSource`](../data/IDataSource.md) | | | +| `request` | [`DataRequest`](../data/descriptors.md#datarequest) | | | +| `options` | [`InfiniteResourceOptions?`](../data/paging.md#infiniteresourceoptions) | `null` | | + +**Remarks** + +The initial page size comes from `options.PageSize` (default 50) when `options` is supplied, or `request.PageSize` otherwise, and is clamped to at least 1. This size stays fixed across renders and query restarts. To change it, have the parent remount the calling component with a different key, e.g. `.WithKey($"tasks:{pageSize}")`, or increment a parent-owned reset version used by `.WithKey($"tasks:{resetVersion}")`. diff --git a/docs/guide/reference/hooks/UseDevtools.md b/docs/guide/reference/hooks/UseDevtools.md index ccd8cbe017..eaac178fad 100644 --- a/docs/guide/reference/hooks/UseDevtools.md +++ b/docs/guide/reference/hooks/UseDevtools.md @@ -1,27 +1,21 @@ # UseDevtools -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.UseDevtoolsExtensions.UseDevtools(Microsoft.UI.Reactor.Core.RenderContext)` +Returns `true` when the current process is running with the in-app devtools UI enabled. This is the AND of two independent signals: -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +1. The binary was built with `Reactor.DevtoolsSupport` enabled (build-time capability gate). +2. The process was launched with `--devtools app` or `--devtools run` (session-scoped opt-in by the user running the app). -## Summary +The value is frozen for the session; this call does not consume a hook slot and does not cause re-renders. Components use it to gate dev-only UX so the subtree is never constructed in retail sessions: -Returns `true` when the current process is running with the in-app -devtools UI enabled. This is the AND of two independent signals: - -- The binary was built with `Reactor.DevtoolsSupport` -enabled (build-time capability gate). -- The process was launched with `--devtools app` or -`--devtools run` (session-scoped opt-in by the user running the app). - - -The value is frozen for the session; this call does not consume a hook -slot and does not cause re-renders. Components use it to gate dev-only -UX so the subtree is never constructed in retail sessions: ```csharp var dev = ctx.UseDevtools(); return VStack(Content(), dev ? DebugOverlay() : null); ``` +```csharp +public static bool UseDevtools(this RenderContext ctx) +``` + +An extension method on [`RenderContext`](../components/RenderContext.md), declared in `UseDevtoolsExtensions`. +**Learn more:** [Devtools](../../devtools.md), [Hooks](../../hooks.md) diff --git a/docs/guide/reference/hooks/UseDisplays.md b/docs/guide/reference/hooks/UseDisplays.md index cc28f2ce9d..eb19fb6970 100644 --- a/docs/guide/reference/hooks/UseDisplays.md +++ b/docs/guide/reference/hooks/UseDisplays.md @@ -1,12 +1,19 @@ # UseDisplays -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseDisplays` +Returns the current display snapshot and re-renders when the display layout changes. -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +```csharp +public IReadOnlyList UseDisplays() +``` -## Summary +Declared on [`RenderContext`](../components/RenderContext.md). -Returns the current display snapshot and re-renders when the display layout changes. +**Learn more:** [Advanced Windowing](../../windowing-advanced.md), [Hooks](../../hooks.md) + +## Use from a class component +Class components can call the same hook directly. These overloads forward to the ones above: +```csharp +protected IReadOnlyList UseDisplays() +``` diff --git a/docs/guide/reference/hooks/UseDpi.md b/docs/guide/reference/hooks/UseDpi.md index cf3befef11..b9d557a039 100644 --- a/docs/guide/reference/hooks/UseDpi.md +++ b/docs/guide/reference/hooks/UseDpi.md @@ -1,14 +1,19 @@ # UseDpi -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseDpi` +Returns the current per-window DPI ([`ReactorWindow.Dpi`](../hosting/ReactorWindow.md#dpi)) and re-renders on DPI change. Returns the system primary-monitor DPI when called outside a window. (spec 036 §5.2) -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +```csharp +public uint UseDpi() +``` -## Summary +Declared on [`RenderContext`](../components/RenderContext.md). -Returns the current per-window DPI (`ReactorWindow.Dpi`) -and re-renders on DPI change. Returns the system primary-monitor DPI when -called outside a window. (spec 036 §5.2) +**Learn more:** [Advanced Windowing](../../windowing-advanced.md), [Hooks](../../hooks.md) +## Use from a class component +Class components can call the same hook directly. These overloads forward to the ones above: + +```csharp +protected uint UseDpi() +``` diff --git a/docs/guide/reference/hooks/UseEffect.md b/docs/guide/reference/hooks/UseEffect.md index c319ae6f3d..318fba9625 100644 --- a/docs/guide/reference/hooks/UseEffect.md +++ b/docs/guide/reference/hooks/UseEffect.md @@ -1,125 +1,180 @@ # UseEffect -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseEffect(System.Action,System.Object[])` +Runs a side effect after render. The effect re-runs when any dependency changes. Pass an empty array for "run once on mount" semantics. Returns a cleanup action that runs before the next effect or on unmount. -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +```csharp +public void UseEffect(Action effect, params object[] dependencies) +public void UseEffect(Func effectWithCleanup, params object[] dependencies) +public void UseEffect(Action effect, T1 d1) +public void UseEffect(Func effectWithCleanup, T1 d1) +public void UseEffect(Action effect, T1 d1, T2 d2) +public void UseEffect(Func effectWithCleanup, T1 d1, T2 d2) +public void UseEffect(Action effect, T1 d1, T2 d2, T3 d3) +public void UseEffect(Func effectWithCleanup, T1 d1, T2 d2, T3 d3) +``` -## Overloads +Declared on [`RenderContext`](../components/RenderContext.md). + +**Learn more:** [Effects and Lifecycle](../../effects.md), [Effects Scheduling](../../effects-scheduling.md), [Hooks](../../hooks.md) -- [`UseEffect(Action, object[])`](#useeffectaction-object) -- [`UseEffect(Func, object[])`](#useeffectfuncaction-object) -- [`UseEffect(Action, T1)`](#useeffectt1action-t1) -- [`UseEffect(Func, T1)`](#useeffectt1funcaction-t1) -- [`UseEffect(Action, T1, T2)`](#useeffectt1-t2action-t1-t2) -- [`UseEffect(Func, T1, T2)`](#useeffectt1-t2funcaction-t1-t2) -- [`UseEffect(Action, T1, T2, T3)`](#useeffectt1-t2-t3action-t1-t2-t3) -- [`UseEffect(Func, T1, T2, T3)`](#useeffectt1-t2-t3funcaction-t1-t2-t3) +## Overloads -## `UseEffect(Action, object[])` +| Overload | Description | +| --- | --- | +| [`UseEffect(Action, object[])`](#useeffectaction-object) | Runs a side effect after render. | +| [`UseEffect(Func, object[])`](#useeffectfuncaction-object) | Like UseEffect but the effect returns a cleanup function. | +| [`UseEffect(Action, T1)`](#useeffectt1action-t1) | Single-dependency `UseEffect` overload that avoids the `params object[]` allocation (and value-type boxing) on the deps-unchanged path. | +| [`UseEffect(Func, T1)`](#useeffectt1funcaction-t1) | Single-dependency cleanup-flavor `UseEffect` overload that avoids the `params object[]` allocation on the deps-unchanged path. | +| [`UseEffect(Action, T1, T2)`](#useeffectt1-t2action-t1-t2) | Two-dependency `UseEffect` overload that avoids the `params object[]` allocation on the deps-unchanged path. | +| [`UseEffect(Func, T1, T2)`](#useeffectt1-t2funcaction-t1-t2) | Two-dependency cleanup-flavor `UseEffect` overload that avoids the `params object[]` allocation on the deps-unchanged path. | +| [`UseEffect(Action, T1, T2, T3)`](#useeffectt1-t2-t3action-t1-t2-t3) | Three-dependency `UseEffect` overload that avoids the `params object[]` allocation on the deps-unchanged path. | +| [`UseEffect(Func, T1, T2, T3)`](#useeffectt1-t2-t3funcaction-t1-t2-t3) | Three-dependency cleanup-flavor `UseEffect` overload that avoids the `params object[]` allocation on the deps-unchanged path. | -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseEffect(System.Action,System.Object[])` +### `UseEffect(Action, object[])` -### Summary +Runs a side effect after render. The effect re-runs when any dependency changes. Pass an empty array for "run once on mount" semantics. Returns a cleanup action that runs before the next effect or on unmount. -Runs a side effect after render. The effect re-runs when any dependency changes. -Pass an empty array for "run once on mount" semantics. -Returns a cleanup action that runs before the next effect or on unmount. +```csharp +public void UseEffect(Action effect, params object[] dependencies) +``` -## `UseEffect(Func, object[])` +**Parameters** -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseEffect(System.Func{System.Action},System.Object[])` +| Name | Type | Description | +| --- | --- | --- | +| `effect` | `Action` | | +| `dependencies` | `object[]` | | -### Summary +### `UseEffect(Func, object[])` Like UseEffect but the effect returns a cleanup function. -## `UseEffect(Action, T1)` +```csharp +public void UseEffect(Func effectWithCleanup, params object[] dependencies) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `effectWithCleanup` | `Func` | | +| `dependencies` | `object[]` | | + +### `UseEffect(Action, T1)` + +Single-dependency `UseEffect` overload that avoids the `params object[]` allocation (and value-type boxing) on the deps-unchanged path. Semantically identical to the params overload called with one dependency: the effect re-runs only when `d1` changes. + +```csharp +public void UseEffect(Action effect, T1 d1) +``` + +**Parameters** + +| Name | Type | Description | +| --- | --- | --- | +| `effect` | `Action` | | +| `d1` | `T1` | | + +**Remarks** + +If `d1`'s compile-time type is an array of reference types (e.g. `string[]`), it is treated as a dependency *list* and compared element-wise — matching the `params object[]` overload — not as a single reference-compared value. A dependency whose static type is not an array is always compared as one value, even if its runtime value happens to be an array. -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseEffect``1(System.Action,``0)` +### `UseEffect(Func, T1)` -### Summary +Single-dependency cleanup-flavor `UseEffect` overload that avoids the `params object[]` allocation on the deps-unchanged path. Semantically identical to the params overload called with one dependency. -Single-dependency `UseEffect` overload that avoids the -`params object[]` allocation (and value-type boxing) on the -deps-unchanged path. Semantically identical to the params overload called -with one dependency: the effect re-runs only when `d1` -changes. +```csharp +public void UseEffect(Func effectWithCleanup, T1 d1) +``` -### Discussion +**Parameters** -If `d1`'s compile-time type is an array of reference types -(e.g. `string[]`), it is treated as a dependency list and compared -element-wise — matching the `params object[]` overload — not as a single -reference-compared value. A dependency whose static type is not an array is -always compared as one value, even if its runtime value happens to be an array. +| Name | Type | Description | +| --- | --- | --- | +| `effectWithCleanup` | `Func` | | +| `d1` | `T1` | | -## `UseEffect(Func, T1)` +**Remarks** -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseEffect``1(System.Func{System.Action},``0)` +If `d1`'s compile-time type is an array of reference types (e.g. `string[]`), it is treated as a dependency *list* and compared element-wise — matching the `params object[]` overload — not as a single reference-compared value. A dependency whose static type is not an array is always compared as one value, even if its runtime value happens to be an array. -### Summary +### `UseEffect(Action, T1, T2)` -Single-dependency cleanup-flavor `UseEffect` overload that avoids the -`params object[]` allocation on the deps-unchanged path. Semantically -identical to the params overload called with one dependency. +Two-dependency `UseEffect` overload that avoids the `params object[]` allocation on the deps-unchanged path. Re-runs when either dependency changes. -### Discussion +```csharp +public void UseEffect(Action effect, T1 d1, T2 d2) +``` -If `d1`'s compile-time type is an array of reference types -(e.g. `string[]`), it is treated as a dependency list and compared -element-wise — matching the `params object[]` overload — not as a single -reference-compared value. A dependency whose static type is not an array is -always compared as one value, even if its runtime value happens to be an array. +**Parameters** -## `UseEffect(Action, T1, T2)` +| Name | Type | Description | +| --- | --- | --- | +| `effect` | `Action` | | +| `d1` | `T1` | | +| `d2` | `T2` | | -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseEffect``2(System.Action,``0,``1)` +### `UseEffect(Func, T1, T2)` -### Summary +Two-dependency cleanup-flavor `UseEffect` overload that avoids the `params object[]` allocation on the deps-unchanged path. -Two-dependency `UseEffect` overload that avoids the -`params object[]` allocation on the deps-unchanged path. Re-runs when -either dependency changes. +```csharp +public void UseEffect(Func effectWithCleanup, T1 d1, T2 d2) +``` -## `UseEffect(Func, T1, T2)` +**Parameters** -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseEffect``2(System.Func{System.Action},``0,``1)` +| Name | Type | Description | +| --- | --- | --- | +| `effectWithCleanup` | `Func` | | +| `d1` | `T1` | | +| `d2` | `T2` | | -### Summary +### `UseEffect(Action, T1, T2, T3)` -Two-dependency cleanup-flavor `UseEffect` overload that avoids the -`params object[]` allocation on the deps-unchanged path. +Three-dependency `UseEffect` overload that avoids the `params object[]` allocation on the deps-unchanged path. Re-runs when any dependency changes. -## `UseEffect(Action, T1, T2, T3)` +```csharp +public void UseEffect(Action effect, T1 d1, T2 d2, T3 d3) +``` -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseEffect``3(System.Action,``0,``1,``2)` +**Parameters** -### Summary +| Name | Type | Description | +| --- | --- | --- | +| `effect` | `Action` | | +| `d1` | `T1` | | +| `d2` | `T2` | | +| `d3` | `T3` | | -Three-dependency `UseEffect` overload that avoids the -`params object[]` allocation on the deps-unchanged path. Re-runs when -any dependency changes. +### `UseEffect(Func, T1, T2, T3)` -## `UseEffect(Func, T1, T2, T3)` +Three-dependency cleanup-flavor `UseEffect` overload that avoids the `params object[]` allocation on the deps-unchanged path. -`method` -_cref_: `M:Microsoft.UI.Reactor.Core.RenderContext.UseEffect``3(System.Func{System.Action},``0,``1,``2)` +```csharp +public void UseEffect(Func effectWithCleanup, T1 d1, T2 d2, T3 d3) +``` -### Summary +**Parameters** -Three-dependency cleanup-flavor `UseEffect` overload that avoids the -`params object[]` allocation on the deps-unchanged path. +| Name | Type | Description | +| --- | --- | --- | +| `effectWithCleanup` | `Func` | | +| `d1` | `T1` | | +| `d2` | `T2` | | +| `d3` | `T3` | | -## Featured in +## Use from a class component -- [Effects](../../effects.md) -- [Hooks](../../hooks.md) +Class components can call the same hook directly. These overloads forward to the ones above: +```csharp +protected void UseEffect(Action effect, params object[] dependencies) +protected void UseEffect(Func effectWithCleanup, params object[] dependencies) +protected void UseEffect(Action effect, T1 d1) +protected void UseEffect(Func effectWithCleanup, T1 d1) +protected void UseEffect(Action effect, T1 d1, T2 d2) +protected void UseEffect(Func effectWithCleanup, T1 d1, T2 d2) +protected void UseEffect(Action effect, T1 d1, T2 d2, T3 d3) +protected void UseEffect(Func effectWithCleanup, T1 d1, T2 d2, T3 d3) +``` diff --git a/docs/guide/reference/hooks/UseElementFocus.md b/docs/guide/reference/hooks/UseElementFocus.md index 9c57209ab2..7031b34414 100644 --- a/docs/guide/reference/hooks/UseElementFocus.md +++ b/docs/guide/reference/hooks/UseElementFocus.md @@ -1,44 +1,22 @@ # UseElementFocus -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.UseElementFocusExtensions.UseElementFocus(Microsoft.UI.Reactor.Core.Component,Microsoft.UI.Xaml.FocusState)` +Creates (or retrieves) a component-scoped [`ElementRef`](../input/element-refs.md#elementref) and pairs it with a `RequestFocus` action. Bind the ref to an element via `.Ref(ref)`. Calling `RequestFocus` schedules [`FocusManager.Focus`](../input/FocusManager.md#focus) on the UI dispatcher; if the ref's target has not mounted yet the call is a no-op. -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Overloads - -- [`UseElementFocus(Component, FocusState)`](#useelementfocuscomponent-focusstate) -- [`UseElementFocus(RenderContext, FocusState)`](#useelementfocusrendercontext-focusstate) - -## `UseElementFocus(Component, FocusState)` - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.UseElementFocusExtensions.UseElementFocus(Microsoft.UI.Reactor.Core.Component,Microsoft.UI.Xaml.FocusState)` - -### Summary - -Component-extension overload of [UseElementFocus](UseElementFocus.md#useelementfocusrendercontext-focusstate) ([guide](../../hooks.md)). -Equivalent to calling the `RenderContext`-extension form against -`component.Context`; see that overload for the full contract. - -### Parameters - -- **component** — The component whose render context owns the hook slot. -- **state** — The focus state used by the imperative request. +```csharp +public static (ElementRef Ref, Action RequestFocus) UseElementFocus(this RenderContext ctx, FocusState state = (FocusState)3) +``` -## `UseElementFocus(RenderContext, FocusState)` +An extension method on [`RenderContext`](../components/RenderContext.md), declared in `UseElementFocusExtensions`. -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.UseElementFocusExtensions.UseElementFocus(Microsoft.UI.Reactor.Core.RenderContext,Microsoft.UI.Xaml.FocusState)` +**Learn more:** [Input and gestures](../../input-and-gestures.md), [Hooks](../../hooks.md) -### Summary +## Parameters -Creates (or retrieves) a component-scoped `ElementRef` and pairs it -with a `RequestFocus` action. Bind the ref to an element via `.Ref(ref)`. -Calling `RequestFocus` schedules `Input.FocusManager.Focus` on the UI -dispatcher; if the ref's target has not mounted yet the call is a no-op. +| Name | Type | Default | Description | +| --- | --- | --- | --- | +| `state` | `FocusState` | `(FocusState)3` | | -### Examples +## Example ```csharp var (inputRef, requestFocus) = ctx.UseElementFocus(); @@ -46,4 +24,10 @@ ctx.UseEffect(() => requestFocus(), Array.Empty()); // focus on first re return TextBox(value, setValue).Ref(inputRef); ``` +## Use from a class component +Class components can call the same hook directly. These overloads forward to the ones above: + +```csharp +public static (ElementRef Ref, Action RequestFocus) UseElementFocus(this Component component, FocusState state = (FocusState)3) +``` diff --git a/docs/guide/reference/hooks/UseElementFocusExtensions.md b/docs/guide/reference/hooks/UseElementFocusExtensions.md deleted file mode 100644 index 2eab6e0b9e..0000000000 --- a/docs/guide/reference/hooks/UseElementFocusExtensions.md +++ /dev/null @@ -1,16 +0,0 @@ -# UseElementFocusExtensions - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.UseElementFocusExtensions` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Hook for imperative element focus (spec 027 Tier 5). Returns a stable -`ElementRef` (survives re-renders) plus a `RequestFocus` action -that schedules `Input.FocusManager.Focus` on the UI dispatcher. Scheduling -defers focus past the current reconcile pass so callers can safely request focus -from effects or event handlers without racing against layout. - - diff --git a/docs/guide/reference/hooks/UseElementRef.md b/docs/guide/reference/hooks/UseElementRef.md index 9647c5b61c..4cb96064c3 100644 --- a/docs/guide/reference/hooks/UseElementRef.md +++ b/docs/guide/reference/hooks/UseElementRef.md @@ -1,37 +1,25 @@ # UseElementRef -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.UseElementRefExtensions.UseElementRef``1(Microsoft.UI.Reactor.Core.Component)` +Returns a stable [`ElementRef`](../input/element-refs.md#elementreft) for the current component scope. -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) +```csharp +public static ElementRef UseElementRef(this RenderContext ctx) where T : FrameworkElement +``` -## Overloads +An extension method on [`RenderContext`](../components/RenderContext.md), declared in `UseElementRefExtensions`. -- [`UseElementRef(Component)`](#useelementreftcomponent) -- [`UseElementRef(RenderContext)`](#useelementreftrendercontext) +**Learn more:** [Input and gestures](../../input-and-gestures.md), [Hooks](../../hooks.md) -## `UseElementRef(Component)` +## Type parameters -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.UseElementRefExtensions.UseElementRef``1(Microsoft.UI.Reactor.Core.Component)` +| Name | Description | +| --- | --- | +| `T` | The concrete control type the ref will attach to. | -### Summary - -Component-extension overload of [UseElementRef](UseElementRef.md#useelementreftrendercontext) ([guide](../../hooks.md)). -Equivalent to calling the `RenderContext`-extension form against -`component.Context`. - -### Parameters - -- **component** — The component whose render context owns the hook slot. - -## `UseElementRef(RenderContext)` - -`method` -_cref_: `M:Microsoft.UI.Reactor.Hooks.UseElementRefExtensions.UseElementRef``1(Microsoft.UI.Reactor.Core.RenderContext)` - -### Summary - -Returns a stable `ElementRef` for the current component scope. +## Use from a class component +Class components can call the same hook directly. These overloads forward to the ones above: +```csharp +public static ElementRef UseElementRef(this Component component) where T : FrameworkElement +``` diff --git a/docs/guide/reference/hooks/UseElementRefExtensions.md b/docs/guide/reference/hooks/UseElementRefExtensions.md deleted file mode 100644 index 2322f262dd..0000000000 --- a/docs/guide/reference/hooks/UseElementRefExtensions.md +++ /dev/null @@ -1,28 +0,0 @@ -# UseElementRefExtensions - -`type` -_cref_: `T:Microsoft.UI.Reactor.Hooks.UseElementRefExtensions` - -> **Learn more:** [Hooks](../../hooks.md), [Effects](../../effects.md) - -## Summary - -Hook that returns a strongly-typed `ElementRef` for binding to a -concrete WinUI control via the `.Ref(...)` modifier. The typed ref removes -the `(Button)ref.Current` cast at consumers (Composition, Ink, focus, …). - -## Discussion - -Spec 033 §3. The same `ElementRef` instance is returned across -re-renders (identity stable), so storing the ref in a deps array or comparing -with `Object.ReferenceEquals` is safe. - -## Examples - -```csharp -var btn = ctx.UseElementRef