From f00bed880c3c0c92732a22075bfec22497845d79 Mon Sep 17 00:00:00 2001 From: Maxime Westhoven Date: Thu, 1 Oct 2026 20:30:57 +0200 Subject: [PATCH 001/303] feat(dms): port the v2 design across the dashboard Bring the dashboard, its settings and its building blocks to the v2 design, and add the features the redesign relies on. - Shell: v2 tokens and themes (light and dark), sidebar with user menu, header, command palette, page header actions, widgets dock. - Table view: v2 grid and toolbar, filter chips, cards display, kanban as a display, expandable rows, density and sticky header, archive mode, reduced chrome options, bulk actions fixed, row rules and permissions per table. - Settings: new shell and navigation, overview with account summary and recent activity, profile (export and delete account), language and region, security, notifications, appearance (accessibility), shortcuts, members and invitations on the table view, roles editor with preview as role. - Generic components and backend blocks: icon well, status pill, section header, empty state, check list, list row, stat strip, key-value list, activity feed, meter, section and field row, save bar, banner, card, nav card grid, permission veil. - Primitives themed to v2, charts, auth pages, onboarding, error page, modules catalog with a module store preview. - Playground: design system showcase, blocks demos, welcome page. Co-Authored-By: Claude Opus 5.5 --- .../06.built-in-dashboard.md | 11 +- .../02.building/03.pages-and-components.md | 2 +- .../dms/docs/02.building/04.navigation.md | 5 +- .../docs/02.building/06.backend-services.md | 1 + .../dms/docs/02.building/07.localization.md | 10 + .../dms/docs/04.components/01.overview.md | 2 + packages/dms/docs/04.components/05.forms.md | 3 +- packages/dms/docs/04.components/06.tables.md | 121 ++- .../docs/04.components/11.display-blocks.md | 213 ++++++ .../04.components/12.lists-and-settings.md | 172 +++++ .../02.dashboard-chrome.md | 4 +- .../03.theming-and-branding.md | 23 +- .../04.custom-data-types.md | 15 +- .../02.authenticated-requests.md | 2 +- .../04.page-context.md | 20 + .../07.interfaces/3.base/1.introduction.md | 7 + .../07.interfaces/3.base/10.display-blocks.md | 79 ++ .../dms/docs/07.interfaces/3.base/4.tables.md | 24 +- .../dms/docs/07.interfaces/3.base/6.layout.md | 33 + .../2.categories-and-subjects.md | 4 +- .../4.notifications/3.sending.md | 3 +- packages/dms/frontend-vue/deferred-plugins.ts | 2 + packages/dms/frontend-vue/dms.frontend.ts | 4 + .../dms-auth/app/components/AuthBackLink.vue | 21 + .../dms-auth/app/components/AuthCodeInput.vue | 39 + .../dms-auth/app/components/AuthFormAlert.vue | 26 + .../app/components/AuthNewPasswordField.vue | 50 ++ .../app/components/AuthPasswordInput.vue | 61 ++ .../app/components/AuthResendCode.vue | 51 ++ .../dms-auth/app/components/OAuthButtons.vue | 11 +- .../app/composables/useAuthFormError.ts | 27 + .../dms-auth/app/custom-pages/auth/2fa.vue | 164 ++--- .../app/custom-pages/auth/accounts.vue | 188 ++--- .../dms-auth/app/custom-pages/auth/backup.vue | 108 +-- .../custom-pages/auth/forgot-validation.vue | 147 ++-- .../dms-auth/app/custom-pages/auth/forgot.vue | 95 +-- .../dms-auth/app/custom-pages/auth/login.vue | 207 +++--- .../app/custom-pages/auth/recover-success.vue | 33 +- .../app/custom-pages/auth/recover.vue | 114 +-- .../dms-auth/app/custom-pages/auth/signup.vue | 189 +++-- .../app/custom-pages/auth/validate.vue | 129 ++-- .../layers/dms-auth/app/utils/accountsFlow.ts | 5 +- .../layers/dms-auth/app/utils/authStyles.ts | 3 + .../dms-auth/i18n/locales/auth-en-GB.json | 271 ++++++- .../dms-auth/i18n/locales/auth-fr-FR.json | 277 ++++++- .../composables/auth/usePermissionPreview.ts | 361 +++++++++ .../app/composables/data-types/useDataType.ts | 10 + .../composables/period/compareResolvers.ts | 36 +- .../user/useUserRegionalPreferences.ts | 57 ++ .../layers/dms-core/app/types/menu.ts | 12 + .../layers/dms-core/app/types/row-action.ts | 33 + .../layers/dms-core/app/utils/formatter.ts | 47 +- .../dms-core/app/utils/permission-preview.ts | 296 ++++++++ .../layers/dms-core/app/utils/regional.ts | 269 +++++++ .../dms-core/app/utils/url-interpolation.ts | 6 +- .../dms-core/i18n/locales/core-en-GB.json | 28 +- .../dms-core/i18n/locales/core-fr-FR.json | 28 +- .../layers/dms-layout/app/app.config.ts | 221 ++---- .../layers/dms-layout/app/assets/css/main.css | 411 +++++++++-- .../components/layout/DashboardBanners.vue | 27 +- .../components/layout/DashboardHeader.vue | 199 +++-- .../components/layout/DashboardSidebar.vue | 80 +- .../app/build/components/layout/Footer.vue | 161 +++- .../build/components/layout/PageHeader.vue | 13 +- .../components/layout/PageHeaderActionBar.vue | 210 ++++++ .../components/layout/QuickActionsPopover.vue | 48 +- .../components/layout/RolePreviewBar.vue | 149 ++++ .../components/layout/SidebarUserMenu.vue | 143 ++++ .../build/components/layout/sidebarState.ts | 6 +- .../notification/NotificationPopover.vue | 72 +- .../pages/modules/ModuleCatalogTile.vue | 114 +++ .../pages/modules/ModuleCategoryChips.vue | 49 ++ .../pages/modules/ModuleStoreTile.vue | 90 +++ .../settings/members/InviteEmailsInput.vue | 117 +++ .../settings/members/InviteOwnerSwitch.vue | 42 ++ .../settings/members/InviteRolePicker.vue | 115 +++ .../notification/NotificationInboxItem.vue | 114 +++ .../NotificationMatrixCategory.vue | 85 +++ .../NotificationMatrixSubject.vue | 87 +++ .../NotificationPreferencesForm.vue | 418 ++++------- .../notification/NotificationsList.vue | 467 +++++++----- .../notification/notificationDisplay.ts | 96 +++ .../settings/profile/ProfileAccountData.vue | 45 ++ .../pages/settings/profile/ProfileAvatar.vue | 61 ++ .../settings/profile/ProfilePersonalInfo.vue | 283 ++++++++ .../profile/ProfileSecuritySummary.vue | 77 ++ .../pages/settings/roles/RoleEditor.vue | 336 +++++++++ .../settings/roles/RoleMemberAvatars.vue | 43 ++ .../pages/settings/roles/RoleOwnerPanel.vue | 55 ++ .../settings/roles/RolePermissionArea.vue | 132 ++++ .../settings/roles/RolePermissionBranch.vue | 81 +++ .../settings/roles/RolePermissionGroup.vue | 59 ++ .../settings/roles/RolePermissionLeaf.vue | 202 ++++++ .../settings/roles/RolePermissionTree.vue | 182 +++++ .../pages/settings/roles/RolesList.vue | 156 ++++ .../pages/settings/roles/RolesListItem.vue | 95 +++ .../pages/settings/roles/role-permissions.ts | 483 ++++++++++++ .../pages/settings/roles/role-types.ts | 83 +++ .../pages/settings/roles/useRoleEditor.ts | 203 ++++++ .../pages/settings/roles/useRolesApi.ts | 67 ++ .../security/SecurityBackupCodesModal.vue | 159 ++++ .../settings/security/SecurityCodeModal.vue | 122 ++++ .../pages/settings/security/SecurityEmail.vue | 200 +++++ .../settings/security/SecurityPassword.vue | 264 +++++++ .../security/SecurityPasswordInput.vue | 50 ++ .../settings/security/SecuritySessions.vue | 335 +++++++++ .../settings/security/SecurityStatus.vue | 155 ++++ .../security/SecurityTotpSetupModal.vue | 173 +++++ .../settings/security/SecurityTwoFactor.vue | 465 ++++++++++++ .../settings/shell/SettingsAccountSummary.vue | 112 +++ .../settings/shell/SettingsActivityCard.vue | 197 +++++ .../pages/settings/shell/SettingsNav.vue | 243 +++++++ .../pages/settings/shell/SettingsShell.vue | 19 + .../settings/shortcut/KeyboardShortcut.vue | 11 +- .../settings/theme/AppearanceOptionTile.vue | 74 ++ .../pages/settings/theme/CssVariablesList.vue | 447 +++++++----- .../app/components/AppWidgetsDock.vue | 4 +- .../app/components/layout/DashboardSearch.vue | 19 +- .../app/components/layout/StageCard.vue | 85 +++ .../navigation/CollapsedMenuItem.vue | 71 +- .../components/navigation/NavigationMenu.vue | 103 ++- .../components/profile/ProfileLanguage.vue | 51 -- .../components/profile/ProfileSessions.vue | 321 -------- .../components/profile/ProfileTwoFactor.vue | 501 ------------- .../general/useAccessibilityPreferences.ts | 52 ++ .../general/useSidebarStartCollapsed.ts | 14 + .../layout/usePageHeaderActions.ts | 42 ++ .../notification/useNotificationCatalog.ts | 85 +++ .../useNotificationPreferences.ts | 131 ++++ .../notification/useNotifications.ts | 295 +++++--- .../app/composables/page/useModuleHistory.ts | 72 +- .../app/composables/page/useModulesListing.ts | 88 ++- .../settings/activity/buildAccountActivity.ts | 336 +++++++++ .../settings/activity/useAccountActivity.ts | 55 ++ .../settings/profile/useAccountData.ts | 229 ++++++ .../settings/profile/useProfileAvatar.ts | 95 +++ .../composables/settings/region/timeZones.ts | 96 +++ .../settings/region/useRegionSettings.ts | 90 +++ .../settings/security/useSecurityFormat.ts | 95 +++ .../settings/security/useSecurityOverview.ts | 136 ++++ .../settings/useSettingsNavIndicators.ts | 108 +++ .../settings/useSettingsNavTrails.ts | 52 ++ .../settings/useSettingsNavigation.ts | 236 ++++++ .../app/composables/useFooterLinks.ts | 21 +- .../app/custom-layouts/DefaultLayout.vue | 80 +- .../app/custom-layouts/EmptyLayout.vue | 46 +- .../dms-layout/app/custom-pages/modules.vue | 613 ++++++++++++++-- .../app/custom-pages/settings/appearance.vue | 322 ++++---- .../app/custom-pages/settings/index.vue | 216 ++---- .../custom-pages/settings/notifications.vue | 10 +- .../app/custom-pages/settings/region.vue | 365 ++++++++++ .../app/custom-pages/settings/roles.vue | 296 ++++++++ .../app/custom-pages/settings/shortcuts.vue | 259 ++++--- .../layers/dms-layout/app/error.vue | 159 ++-- .../layers/dms-layout/app/pages/[...slug].vue | 1 + .../dms-layout/app/plugins/accessibility.ts | 22 + .../app/plugins/notification-stream.client.ts | 12 +- .../app/plugins/permission-preview.client.ts | 18 + .../app/plugins/regional-preferences.ts | 19 + .../layers/dms-layout/app/theme/actions.ts | 366 ++++++++++ .../layers/dms-layout/app/theme/data.ts | 174 +++++ .../dms-layout/app/theme/form-controls.ts | 654 +++++++++++++++++ .../layers/dms-layout/app/theme/navigation.ts | 293 ++++++++ .../layers/dms-layout/app/theme/surfaces.ts | 321 ++++++++ .../layers/dms-layout/app/types/page.ts | 22 + .../dms-layout/app/utils/account-menu.ts | 2 +- .../app/utils/module-store-catalog.ts | 137 ++++ .../dms-layout/app/utils/modules-catalog.ts | 193 +++++ .../dms-layout/i18n/locales/layout-en-GB.json | 667 +++++++++++++++-- .../dms-layout/i18n/locales/layout-fr-FR.json | 667 +++++++++++++++-- .../public/images/antelope-logo/dark.svg | 24 +- .../public/images/antelope-logo/light.svg | 24 +- .../components/onboarding/StepIndicator.vue | 42 ++ .../app/components/onboarding/StepMeta.vue | 38 + .../components/onboarding/steps/platform.vue | 138 ++++ .../app/components/onboarding/steps/ready.vue | 191 +++++ .../components/onboarding/steps/register.vue | 248 ++++--- .../app/composables/onboarding/steps.ts | 16 + .../app/custom-pages/onboarding.vue | 61 +- .../i18n/locales/onboarding-en-GB.json | 61 +- .../i18n/locales/onboarding-fr-FR.json | 61 +- .../build/components/containers/constants.ts | 2 + .../containers/drawer/DynamicDrawer.vue | 53 +- .../containers/modal/DynamicModal.vue | 84 ++- .../app/build/components/table/Actions.vue | 366 +++++++++- .../app/build/components/table/Empty.vue | 122 ++-- .../app/build/components/table/FiltersRow.vue | 191 +++-- .../app/build/components/table/Pagination.vue | 170 ++++- .../build/components/table/RowSelection.vue | 165 ++++- .../app/build/components/table/Table.vue | 476 ++++++++++-- .../app/build/components/table/Tabs.vue | 116 ++- .../data-types/registerDefaults.ts | 368 +++++++++- .../data-types/useColumnValueRenderer.ts | 117 +++ .../table-view/useTableViewConfig.ts | 12 +- .../table-view/useTableViewRowActions.ts | 192 ++++- .../table-view/utils/bulkActions.ts | 127 ++++ .../composables/table-view/utils/chrome.ts | 78 ++ .../table-view/utils/columnVisibility.ts | 15 +- .../table-view/utils/expandedRows.ts | 51 ++ .../table-view/utils/quickFilters.ts | 125 ++++ .../app/build/composables/table/constants.ts | 8 +- .../app/build/composables/table/useTable.ts | 16 +- .../composables/table/useTableColumns.ts | 419 +++++++++-- .../layers/dms-ui/app/build/types/tree.ts | 1 + .../app/components/RecursiveComponent.vue | 117 ++- .../components/activity-feed/ActivityFeed.vue | 215 ++++++ .../activity-feed/activityFeedDays.ts | 115 +++ .../app/components/activity/ActivityItem.vue | 126 ++-- .../dms-ui/app/components/banner/Banner.vue | 148 ++-- .../app/components/blocks/BannerBlock.vue | 112 +++ .../app/components/blocks/BlockActions.vue | 73 ++ .../app/components/blocks/BlockStatus.vue | 56 ++ .../app/components/blocks/CardBlock.vue | 94 +++ .../app/components/blocks/EmptyStateBlock.vue | 63 ++ .../components/blocks/KeyValueListBlock.vue | 104 +++ .../components/blocks/NavCardGridBlock.vue | 143 ++++ .../app/components/blocks/StatStripBlock.vue | 83 +++ .../dms-ui/app/components/card/Card.vue | 70 +- .../dms-ui/app/components/card/NavCard.vue | 115 ++- .../app/components/chart/ApexChartHost.vue | 99 ++- .../dms-ui/app/components/chart/Chart.vue | 49 +- .../dms-ui/app/components/chart/ChartCard.vue | 64 +- .../components/chart/internal/Sparkline.vue | 176 ++--- .../components/chart/internal/TrendBadge.vue | 93 ++- .../app/components/check-list/CheckList.vue | 228 ++++++ .../components/check-list/PasswordRules.vue | 140 ++++ .../app/components/confirm/ConfirmModal.vue | 214 +++++- .../dms-ui/app/components/copy/CopyButton.vue | 10 +- .../app/components/empty-state/EmptyState.vue | 139 ++++ .../app/components/field-row/FieldRow.vue | 101 +++ .../dms-ui/app/components/form/Form.vue | 432 +++++++---- .../components/form/components/Calendar.vue | 8 +- .../components/form/components/Cascader.vue | 10 +- .../components/form/components/Checkbox.vue | 10 +- .../components/form/components/DatePicker.vue | 29 +- .../app/components/form/components/File.vue | 14 +- .../app/components/form/components/Image.vue | 18 +- .../components/form/components/InputColor.vue | 7 +- .../form/components/InputNumber.vue | 4 + .../form/components/InputPercentage.vue | 24 +- .../components/form/components/Relation.vue | 2 + .../components/form/components/RichText.vue | 18 +- .../app/components/form/components/Select.vue | 2 + .../dms-ui/app/components/grid/GridRow.vue | 4 +- .../app/components/icon-well/IconWell.vue | 85 +++ .../key-value-list/KeyValueList.vue | 214 ++++++ .../dms-ui/app/components/kpi/KpiCard.vue | 240 ++++-- .../dms-ui/app/components/link/AutoLink.vue | 33 + .../app/components/list-row/ListRow.vue | 288 ++++++++ .../dms-ui/app/components/meter/Meter.vue | 240 ++++++ .../app/components/meter/MeterBlock.vue | 126 ++++ .../components/period/PeriodRangeCalendar.vue | 294 ++++++++ .../app/components/period/PeriodSelector.vue | 672 ++++++++++++----- .../components/permission/PermissionVeil.vue | 118 +++ .../app/components/save-bar/SaveBar.vue | 84 +++ .../app/components/save-bar/SaveStatus.vue | 32 + .../app/components/section-header/Eyebrow.vue | 68 ++ .../section-header/SectionHeader.vue | 118 +++ .../dms-ui/app/components/section/Section.vue | 93 +++ .../dms-ui/app/components/section/context.ts | 10 + .../app/components/segmented/Segmented.vue | 148 +++- .../app/components/stat-strip/StatStrip.vue | 258 +++++++ .../app/components/status-pill/StatusPill.vue | 168 +++++ .../app/components/status/StatusSummary.vue | 186 +++-- .../layers/dms-ui/app/components/tab/Tab.vue | 20 +- .../components/table-view/CardsDisplay.vue | 153 ++++ .../table-view/ExpandedRowDetail.vue | 122 ++++ .../app/components/table-view/FilePreview.vue | 2 +- .../components/table-view/IdentityCell.vue | 125 ++++ .../app/components/table-view/KanbanBoard.vue | 134 +++- .../components/table-view/KanbanDisplay.vue | 1 + .../app/components/table-view/TableView.vue | 406 +++++++++-- .../app/components/top-list/TopListCard.vue | 170 +++-- .../top-list/internal/TopListRow.vue | 59 +- .../dms-ui/app/components/tree/Tree.vue | 16 +- .../app/composables/blocks/useBlockItems.ts | 67 ++ .../app/composables/chart/apexPlotOptions.ts | 43 +- .../dms-ui/app/composables/chart/apexTheme.ts | 168 +++++ .../app/composables/chart/apexTypeConfigs.ts | 7 +- .../chart/resolveSparklineAccent.ts | 9 +- .../app/composables/chart/sparklinePath.ts | 81 +++ .../app/composables/chart/useApexChart.ts | 241 +++--- .../app/composables/chart/useChartTheme.ts | 67 +- .../dms-ui/app/composables/confirm/index.ts | 1 + .../dms-ui/app/composables/confirm/types.ts | 46 ++ .../app/composables/confirm/useConfirm.ts | 14 +- .../app/composables/containers/types.ts | 13 + .../app/composables/form/types/props.ts | 5 + .../dms-ui/app/composables/form/useForm.ts | 40 + .../app/composables/global/shortcuts.ts | 24 + .../composables/navigation/useNavBadges.ts | 23 + .../app/composables/period/periodDisplay.ts | 146 ++++ .../app/composables/period/usePeriodDraft.ts | 127 ++++ .../app/composables/table-view/kanban.ts | 2 + .../table-view/types/action-target.ts | 6 + .../composables/table-view/types/column.ts | 12 + .../composables/table-view/types/config.ts | 79 +- .../table-view/types/custom-button.ts | 5 + .../composables/table-view/types/display.ts | 8 + .../table-view/useTableViewDisplays.ts | 1 + .../dms-ui/app/config/shortcuts-registry.ts | 5 + .../app/plugins/table-view-displays.client.ts | 13 + .../layers/dms-ui/app/types/modal.ts | 4 +- .../layers/dms-ui/app/types/row-action.ts | 9 + .../app/utils/accessibilityPreferences.ts | 138 ++++ .../layers/dms-ui/app/utils/fieldTrigger.ts | 23 + .../layers/dms-ui/app/utils/link.ts | 33 + .../layers/dms-ui/app/utils/relativeDate.ts | 67 ++ .../layers/dms-ui/app/utils/semanticTint.ts | 2 +- .../layers/dms-ui/app/utils/tone.ts | 86 +++ .../layers/dms-ui/i18n/locales/ui-en-GB.json | 100 ++- .../layers/dms-ui/i18n/locales/ui-fr-FR.json | 100 ++- .../tests/accessibility-preferences.test.ts | 320 ++++++++ .../tests/account-activity.test.ts | 157 ++++ .../tests/activity-feed-days.test.ts | 84 +++ .../frontend-vue/tests/chart-colors.test.ts | 2 +- .../tests/chart-series-styles.test.ts | 18 +- .../tests/error-page-message.test.ts | 15 + .../image-reference-preservation.test.ts | 2 +- .../tests/module-store-catalog.test.ts | 145 ++++ .../tests/modules-catalog.test.ts | 152 ++++ .../tests/notification-popover-errors.test.ts | 13 +- .../tests/onboarding-register.test.ts | 99 +-- .../tests/page-fill-height.test.ts | 33 +- .../frontend-vue/tests/period-draft.test.ts | 120 +++ .../frontend-vue/tests/period-presets.test.ts | 12 + .../tests/permission-preview-partial.test.ts | 301 ++++++++ .../tests/permission-preview.test.ts | 241 ++++++ .../permission-veil-stable-content.test.ts | 191 +++++ .../tests/regional-preferences.test.ts | 209 ++++++ .../tests/role-permission-tree.test.ts | 453 ++++++++++++ .../tests/role-permissions.test.ts | 546 ++++++++++++++ .../tests/settings-activity-card.test.ts | 192 +++++ .../tests/settings-navigation.test.ts | 204 ++++++ .../tests/sidebar-footer-navigation.test.ts | 9 + .../tests/signup-invitation-link.test.ts | 8 +- .../tests/tab-slot-spacing.test.ts | 2 +- .../tests/table-view-bulk-actions.test.ts | 166 +++++ .../tests/table-view-chrome.test.ts | 116 +++ .../tests/table-view-expanded-rows.test.ts | 55 ++ .../tests/url-interpolation.test.ts | 20 + .../frontend-vue/tests/vue-inventory.test.ts | 21 +- .../app/components/OrderLinesDetail.vue | 114 +++ .../app/components/PrimitivesShowcase.vue | 579 +++++++++++++++ .../app/components/TaskCardsDisplay.vue | 183 +++-- .../foundations/FoundationsFeedback.vue | 467 ++++++++++++ .../foundations/FoundationsLabels.vue | 315 ++++++++ .../foundations/FoundationsLists.vue | 393 ++++++++++ .../foundations/FoundationsOverlays.vue | 229 ++++++ .../foundations/FoundationsSurfaces.vue | 386 ++++++++++ .../components/foundations/ShowcaseDemo.vue | 26 + .../foundations/ShowcaseSection.vue | 37 + .../welcome/PlaygroundCodeBlock.vue | 108 +++ .../welcome/PlaygroundEcosystem.vue | 232 ++++++ .../welcome/PlaygroundWelcomeHero.vue | 236 ++++++ .../dms/playground/src/blocks/activity.ts | 98 +++ packages/dms/playground/src/blocks/api.ts | 101 +++ .../dms/playground/src/blocks/category.ts | 11 + .../dms/playground/src/blocks/feed-api.ts | 141 ++++ .../dms/playground/src/blocks/feedback.ts | 161 ++++ packages/dms/playground/src/blocks/index.ts | 10 + .../dms/playground/src/blocks/key-value.ts | 166 +++++ packages/dms/playground/src/blocks/meters.ts | 85 +++ .../dms/playground/src/blocks/nav-cards.ts | 112 +++ .../dms/playground/src/blocks/settings.ts | 168 +++++ .../dms/playground/src/blocks/stat-strip.ts | 116 +++ .../dms/playground/src/demo-module/index.ts | 18 + packages/dms/playground/src/examples/index.ts | 1 + packages/dms/playground/src/examples/page.ts | 210 +++++- .../playground/src/examples/welcome-api.ts | 90 +++ .../src/examples/welcome-content.ts | 326 +++++++++ .../playground/src/foundations/category.ts | 11 + .../dms/playground/src/foundations/index.ts | 2 + .../dms/playground/src/foundations/pages.ts | 99 +++ packages/dms/playground/src/index.ts | 3 + .../src/navigation/dynamic-provider.ts | 3 + .../src/page-extension/members-extension.ts | 15 + .../dms/playground/src/plain-module/index.ts | 7 + .../dms/playground/src/primitives/category.ts | 10 + .../dms/playground/src/primitives/index.ts | 2 + .../dms/playground/src/primitives/page.ts | 23 + packages/dms/playground/src/sections.ts | 13 + .../src/table-view/archive-mode/page.ts | 3 +- .../src/table-view/cascader-mode/page.ts | 4 +- .../src/table-view/defaultValues.ts | 6 +- .../playground/src/table-view/density/page.ts | 46 ++ .../src/table-view/drawer-mode/page.ts | 3 +- .../table-view/expandable-rows/data-api.ts | 186 +++++ .../table-view/expandable-rows/database.ts | 326 +++++++++ .../src/table-view/expandable-rows/page.ts | 72 ++ .../src/table-view/gate-bypass/page.ts | 2 +- .../src/table-view/grouped-fields/page.ts | 3 +- .../dms/playground/src/table-view/index.ts | 4 + .../src/table-view/modal-mode/page.ts | 3 +- .../src/table-view/page-mode/page.ts | 6 +- .../table-view/relation-dms-member/page.ts | 2 +- .../src/table-view/relation-key/page.ts | 2 +- .../playground/src/table-view/users/page.ts | 2 +- .../userNotificationPreferences.model.ts | 26 + .../src/db/models/userNotifications.model.ts | 163 +++-- .../dms/src/db/tables/systemState.table.ts | 6 + .../src/db/tables/userNotifications.table.ts | 5 + .../src/dev/module-update-notifications.ts | 1 + .../dms/src/implementations/dms-auth/index.ts | 3 +- .../implementations/dms-base/search-route.ts | 34 +- .../implementations/dms-base/table-view.ts | 19 +- .../dms-notifications/index.ts | 28 +- .../dms-notifications/registry.ts | 24 + packages/dms/src/implementations/dms/page.ts | 686 +++++++++++++++++- .../implementations/dms/permission-preview.ts | 272 +++++++ .../settings/users/account-activity-store.ts | 142 ++++ .../pages/settings/users/account-activity.ts | 334 +++++++++ .../settings/users/account-credentials.ts | 253 +++++++ .../settings/users/account-data-store.ts | 279 +++++++ .../src/pages/settings/users/account-data.ts | 250 +++++++ .../dms/src/pages/settings/users/index.ts | 2 + .../settings/users/invite-email-list-type.ts | 33 + .../src/pages/settings/users/invite-resend.ts | 65 ++ .../dms/src/pages/settings/users/invites.ts | 298 ++++++-- .../settings/users/member-invite-batch.ts | 169 +++++ .../settings/users/member-invite-form.ts | 134 ++-- .../pages/settings/users/member-management.ts | 181 +++++ .../settings/users/member-role-options.ts | 56 ++ .../dms/src/pages/settings/users/members.ts | 494 ++++++++----- .../src/pages/settings/users/notifications.ts | 162 ++++- .../settings/users/permission-tree-nodes.ts | 69 +- .../pages/settings/users/profile-helpers.ts | 6 +- .../dms/src/pages/settings/users/profile.ts | 465 +++++------- .../dms/src/pages/settings/users/region.ts | 66 ++ .../settings/users/regional-preferences.ts | 60 ++ .../pages/settings/users/role-editor-store.ts | 236 ++++++ .../src/pages/settings/users/role-editor.ts | 270 +++++++ .../src/pages/settings/users/role-preview.ts | 254 +++++++ .../dms/src/pages/settings/users/roles.ts | 402 +++++++++- .../dms/src/pages/settings/users/security.ts | 183 +++++ .../settings/users/two-factor-operations.ts | 309 ++++++++ .../dms/src/routes/auth/reset-password.ts | 1 + packages/dms/src/routes/onboarding.ts | 38 +- packages/dms/src/routes/system-state.ts | 4 +- .../test/unit/db/notification-inbox.test.ts | 86 +++ .../unit/db/notification-preferences.test.ts | 22 + .../dms/permission-preview-aggregate.test.ts | 155 ++++ .../dms/permission-preview-header.test.ts | 106 +++ .../dms/permission-preview-menu.test.ts | 164 +++++ .../notification-subject-lock.test.ts | 38 + .../dms-base/display-blocks-catalog.test.ts | 82 +++ .../dms-base/layout-header-actions.test.ts | 102 +++ .../lists-and-settings-catalog.test.ts | 68 ++ .../table-view-bulk-operations.test.ts | 304 ++++++++ .../table-view-export-permission.test.ts | 64 ++ .../table-view-reduced-chrome.test.ts | 252 +++++++ ...e-view-route-param-filter-defaults.test.ts | 5 +- .../table-view-row-rules-per-table.test.ts | 375 ++++++++++ ...view-shared-controller-permissions.test.ts | 120 +++ .../src/test/unit/onboarding-platform.test.ts | 121 +++ .../pages/settings/account-activity.test.ts | 322 ++++++++ .../unit/pages/settings/account-data.test.ts | 281 +++++++ .../pages/settings/account-security.test.ts | 270 +++++++ .../settings/invite-email-delivery.test.ts | 40 +- .../unit/pages/settings/members-page.test.ts | 311 ++++++++ .../settings/regional-preferences.test.ts | 76 ++ .../unit/pages/settings/role-editor.test.ts | 314 ++++++++ .../unit/pages/settings/role-preview.test.ts | 311 ++++++++ .../src/test/unit/utils/user-activity.test.ts | 105 +++ .../onboarding/register-admin.schema.test.ts | 74 +- ...er-notification-preferences.schema.test.ts | 29 +- packages/dms/src/types/2fa.d.ts | 14 + .../dms/src/utils/account-notifications.ts | 17 +- packages/dms/src/utils/user-activity.ts | 46 ++ .../src/validation/account-deletion.schema.ts | 18 + .../src/validation/member-invite.schema.ts | 170 +++-- .../src/validation/member-ownership.schema.ts | 6 + .../onboarding/register-admin.schema.ts | 43 +- .../validation/regional-preferences.schema.ts | 49 ++ .../dms/src/validation/role-editor.schema.ts | 50 ++ .../dms/src/validation/security.schema.ts | 29 + .../user-notification-preferences.schema.ts | 14 + .../src/auth/db/tables/users.table.ts | 53 ++ .../interface-dms/src/base/activity-feed.ts | 196 +++++ packages/interface-dms/src/base/banner.ts | 129 ++++ .../interface-dms/src/base/block-types.ts | 9 + packages/interface-dms/src/base/card.ts | 116 +++ packages/interface-dms/src/base/display.ts | 113 +++ .../interface-dms/src/base/empty-state.ts | 147 ++++ .../src/base/form-block-schema.ts | 9 + packages/interface-dms/src/base/form-types.ts | 7 + packages/interface-dms/src/base/index.ts | 10 + .../interface-dms/src/base/key-value-list.ts | 165 +++++ packages/interface-dms/src/base/layouts.ts | 90 ++- packages/interface-dms/src/base/meter.ts | 208 ++++++ .../interface-dms/src/base/nav-card-grid.ts | 142 ++++ packages/interface-dms/src/base/section.ts | 164 +++++ packages/interface-dms/src/base/stat-strip.ts | 152 ++++ packages/interface-dms/src/base/table-view.ts | 16 +- .../interface-dms/src/base/table-view/auth.ts | 135 +++- .../src/base/table-view/factory-helpers.ts | 225 +++++- .../src/base/table-view/factory.ts | 97 ++- .../src/base/table-view/files.ts | 6 +- .../interface-dms/src/base/table-view/meta.ts | 109 ++- .../src/base/table-view/options.ts | 224 +++++- .../src/base/table-view/routes.ts | 7 +- .../src/base/table-view/row-rules.ts | 114 ++- .../src/base/table-view/schema.ts | 146 +++- .../interface-dms/src/base/top-list-card.ts | 7 + .../src/base/types/action-target.ts | 30 + .../src/base/types/custom-button.ts | 6 + .../src/base/types/row-action.ts | 63 ++ .../src/data-controllers/members.ts | 134 +++- .../src/db/tables/roles.table.ts | 4 + .../src/db/tables/user_invites.table.ts | 7 + packages/interface-dms/src/hooks.ts | 16 + packages/interface-dms/src/index.ts | 4 + packages/interface-dms/src/invites.ts | 7 + .../src/notifications/builder.ts | 7 + .../interface-dms/src/notifications/types.ts | 14 + .../interface-dms/src/page/layout-filter.ts | 35 + packages/interface-dms/src/page/metadata.ts | 31 +- packages/interface-dms/src/page/types.ts | 63 ++ 518 files changed, 54808 insertions(+), 6411 deletions(-) create mode 100644 packages/dms/docs/04.components/11.display-blocks.md create mode 100644 packages/dms/docs/04.components/12.lists-and-settings.md create mode 100644 packages/dms/docs/07.interfaces/3.base/10.display-blocks.md create mode 100644 packages/dms/frontend-vue/layers/dms-auth/app/components/AuthBackLink.vue create mode 100644 packages/dms/frontend-vue/layers/dms-auth/app/components/AuthCodeInput.vue create mode 100644 packages/dms/frontend-vue/layers/dms-auth/app/components/AuthFormAlert.vue create mode 100644 packages/dms/frontend-vue/layers/dms-auth/app/components/AuthNewPasswordField.vue create mode 100644 packages/dms/frontend-vue/layers/dms-auth/app/components/AuthPasswordInput.vue create mode 100644 packages/dms/frontend-vue/layers/dms-auth/app/components/AuthResendCode.vue create mode 100644 packages/dms/frontend-vue/layers/dms-auth/app/composables/useAuthFormError.ts create mode 100644 packages/dms/frontend-vue/layers/dms-auth/app/utils/authStyles.ts create mode 100644 packages/dms/frontend-vue/layers/dms-core/app/composables/auth/usePermissionPreview.ts create mode 100644 packages/dms/frontend-vue/layers/dms-core/app/composables/user/useUserRegionalPreferences.ts create mode 100644 packages/dms/frontend-vue/layers/dms-core/app/utils/permission-preview.ts create mode 100644 packages/dms/frontend-vue/layers/dms-core/app/utils/regional.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/layout/PageHeaderActionBar.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/layout/RolePreviewBar.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/layout/SidebarUserMenu.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/modules/ModuleCatalogTile.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/modules/ModuleCategoryChips.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/modules/ModuleStoreTile.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/members/InviteEmailsInput.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/members/InviteOwnerSwitch.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/members/InviteRolePicker.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/NotificationInboxItem.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/NotificationMatrixCategory.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/NotificationMatrixSubject.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/notification/notificationDisplay.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/profile/ProfileAccountData.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/profile/ProfileAvatar.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/profile/ProfilePersonalInfo.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/profile/ProfileSecuritySummary.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/RoleEditor.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/RoleMemberAvatars.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/RoleOwnerPanel.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/RolePermissionArea.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/RolePermissionBranch.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/RolePermissionGroup.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/RolePermissionLeaf.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/RolePermissionTree.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/RolesList.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/RolesListItem.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/role-permissions.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/role-types.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/useRoleEditor.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/roles/useRolesApi.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/security/SecurityBackupCodesModal.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/security/SecurityCodeModal.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/security/SecurityEmail.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/security/SecurityPassword.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/security/SecurityPasswordInput.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/security/SecuritySessions.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/security/SecurityStatus.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/security/SecurityTotpSetupModal.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/security/SecurityTwoFactor.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/shell/SettingsAccountSummary.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/shell/SettingsActivityCard.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/shell/SettingsNav.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/shell/SettingsShell.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/build/components/pages/settings/theme/AppearanceOptionTile.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/components/layout/StageCard.vue delete mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/components/profile/ProfileLanguage.vue delete mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/components/profile/ProfileSessions.vue delete mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/components/profile/ProfileTwoFactor.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/general/useAccessibilityPreferences.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/general/useSidebarStartCollapsed.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/layout/usePageHeaderActions.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotificationCatalog.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotificationPreferences.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/activity/buildAccountActivity.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/activity/useAccountActivity.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/profile/useAccountData.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/profile/useProfileAvatar.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/region/timeZones.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/region/useRegionSettings.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/security/useSecurityFormat.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/security/useSecurityOverview.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavIndicators.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavTrails.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavigation.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/custom-pages/settings/region.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/custom-pages/settings/roles.vue create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/plugins/accessibility.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/plugins/permission-preview.client.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/plugins/regional-preferences.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/theme/actions.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/theme/data.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/theme/form-controls.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/theme/navigation.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/theme/surfaces.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/utils/module-store-catalog.ts create mode 100644 packages/dms/frontend-vue/layers/dms-layout/app/utils/modules-catalog.ts create mode 100644 packages/dms/frontend-vue/layers/dms-onboarding/app/components/onboarding/StepIndicator.vue create mode 100644 packages/dms/frontend-vue/layers/dms-onboarding/app/components/onboarding/StepMeta.vue create mode 100644 packages/dms/frontend-vue/layers/dms-onboarding/app/components/onboarding/steps/platform.vue create mode 100644 packages/dms/frontend-vue/layers/dms-onboarding/app/components/onboarding/steps/ready.vue create mode 100644 packages/dms/frontend-vue/layers/dms-onboarding/app/composables/onboarding/steps.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/build/components/containers/constants.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/build/composables/data-types/useColumnValueRenderer.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/utils/bulkActions.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/utils/chrome.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/utils/expandedRows.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/utils/quickFilters.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/activity-feed/ActivityFeed.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/activity-feed/activityFeedDays.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/BannerBlock.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/BlockActions.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/BlockStatus.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/CardBlock.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/EmptyStateBlock.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/KeyValueListBlock.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/NavCardGridBlock.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/StatStripBlock.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/check-list/CheckList.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/check-list/PasswordRules.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/empty-state/EmptyState.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/field-row/FieldRow.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/icon-well/IconWell.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/key-value-list/KeyValueList.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/link/AutoLink.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/list-row/ListRow.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/meter/Meter.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/meter/MeterBlock.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/period/PeriodRangeCalendar.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/permission/PermissionVeil.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/save-bar/SaveBar.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/save-bar/SaveStatus.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/section-header/Eyebrow.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/section-header/SectionHeader.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/section/Section.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/section/context.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/stat-strip/StatStrip.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/status-pill/StatusPill.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/table-view/CardsDisplay.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/table-view/ExpandedRowDetail.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/components/table-view/IdentityCell.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/composables/blocks/useBlockItems.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/composables/chart/apexTheme.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/composables/chart/sparklinePath.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/composables/confirm/types.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/composables/global/shortcuts.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/composables/navigation/useNavBadges.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/composables/period/periodDisplay.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/composables/period/usePeriodDraft.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/utils/accessibilityPreferences.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/utils/fieldTrigger.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/utils/link.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/utils/relativeDate.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/utils/tone.ts create mode 100644 packages/dms/frontend-vue/tests/accessibility-preferences.test.ts create mode 100644 packages/dms/frontend-vue/tests/account-activity.test.ts create mode 100644 packages/dms/frontend-vue/tests/activity-feed-days.test.ts create mode 100644 packages/dms/frontend-vue/tests/module-store-catalog.test.ts create mode 100644 packages/dms/frontend-vue/tests/modules-catalog.test.ts create mode 100644 packages/dms/frontend-vue/tests/period-draft.test.ts create mode 100644 packages/dms/frontend-vue/tests/permission-preview-partial.test.ts create mode 100644 packages/dms/frontend-vue/tests/permission-preview.test.ts create mode 100644 packages/dms/frontend-vue/tests/permission-veil-stable-content.test.ts create mode 100644 packages/dms/frontend-vue/tests/regional-preferences.test.ts create mode 100644 packages/dms/frontend-vue/tests/role-permission-tree.test.ts create mode 100644 packages/dms/frontend-vue/tests/role-permissions.test.ts create mode 100644 packages/dms/frontend-vue/tests/settings-activity-card.test.ts create mode 100644 packages/dms/frontend-vue/tests/settings-navigation.test.ts create mode 100644 packages/dms/frontend-vue/tests/table-view-bulk-actions.test.ts create mode 100644 packages/dms/frontend-vue/tests/table-view-chrome.test.ts create mode 100644 packages/dms/frontend-vue/tests/table-view-expanded-rows.test.ts create mode 100644 packages/dms/frontend-vue/tests/url-interpolation.test.ts create mode 100644 packages/dms/playground/frontend-vue/app/components/OrderLinesDetail.vue create mode 100644 packages/dms/playground/frontend-vue/app/components/PrimitivesShowcase.vue create mode 100644 packages/dms/playground/frontend-vue/app/components/foundations/FoundationsFeedback.vue create mode 100644 packages/dms/playground/frontend-vue/app/components/foundations/FoundationsLabels.vue create mode 100644 packages/dms/playground/frontend-vue/app/components/foundations/FoundationsLists.vue create mode 100644 packages/dms/playground/frontend-vue/app/components/foundations/FoundationsOverlays.vue create mode 100644 packages/dms/playground/frontend-vue/app/components/foundations/FoundationsSurfaces.vue create mode 100644 packages/dms/playground/frontend-vue/app/components/foundations/ShowcaseDemo.vue create mode 100644 packages/dms/playground/frontend-vue/app/components/foundations/ShowcaseSection.vue create mode 100644 packages/dms/playground/frontend-vue/app/components/welcome/PlaygroundCodeBlock.vue create mode 100644 packages/dms/playground/frontend-vue/app/components/welcome/PlaygroundEcosystem.vue create mode 100644 packages/dms/playground/frontend-vue/app/components/welcome/PlaygroundWelcomeHero.vue create mode 100644 packages/dms/playground/src/blocks/activity.ts create mode 100644 packages/dms/playground/src/blocks/api.ts create mode 100644 packages/dms/playground/src/blocks/category.ts create mode 100644 packages/dms/playground/src/blocks/feed-api.ts create mode 100644 packages/dms/playground/src/blocks/feedback.ts create mode 100644 packages/dms/playground/src/blocks/index.ts create mode 100644 packages/dms/playground/src/blocks/key-value.ts create mode 100644 packages/dms/playground/src/blocks/meters.ts create mode 100644 packages/dms/playground/src/blocks/nav-cards.ts create mode 100644 packages/dms/playground/src/blocks/settings.ts create mode 100644 packages/dms/playground/src/blocks/stat-strip.ts create mode 100644 packages/dms/playground/src/examples/welcome-api.ts create mode 100644 packages/dms/playground/src/examples/welcome-content.ts create mode 100644 packages/dms/playground/src/foundations/category.ts create mode 100644 packages/dms/playground/src/foundations/index.ts create mode 100644 packages/dms/playground/src/foundations/pages.ts create mode 100644 packages/dms/playground/src/primitives/category.ts create mode 100644 packages/dms/playground/src/primitives/index.ts create mode 100644 packages/dms/playground/src/primitives/page.ts create mode 100644 packages/dms/playground/src/table-view/density/page.ts create mode 100644 packages/dms/playground/src/table-view/expandable-rows/data-api.ts create mode 100644 packages/dms/playground/src/table-view/expandable-rows/database.ts create mode 100644 packages/dms/playground/src/table-view/expandable-rows/page.ts create mode 100644 packages/dms/src/implementations/dms/permission-preview.ts create mode 100644 packages/dms/src/pages/settings/users/account-activity-store.ts create mode 100644 packages/dms/src/pages/settings/users/account-activity.ts create mode 100644 packages/dms/src/pages/settings/users/account-credentials.ts create mode 100644 packages/dms/src/pages/settings/users/account-data-store.ts create mode 100644 packages/dms/src/pages/settings/users/account-data.ts create mode 100644 packages/dms/src/pages/settings/users/invite-email-list-type.ts create mode 100644 packages/dms/src/pages/settings/users/invite-resend.ts create mode 100644 packages/dms/src/pages/settings/users/member-invite-batch.ts create mode 100644 packages/dms/src/pages/settings/users/member-management.ts create mode 100644 packages/dms/src/pages/settings/users/member-role-options.ts create mode 100644 packages/dms/src/pages/settings/users/region.ts create mode 100644 packages/dms/src/pages/settings/users/regional-preferences.ts create mode 100644 packages/dms/src/pages/settings/users/role-editor-store.ts create mode 100644 packages/dms/src/pages/settings/users/role-editor.ts create mode 100644 packages/dms/src/pages/settings/users/role-preview.ts create mode 100644 packages/dms/src/pages/settings/users/security.ts create mode 100644 packages/dms/src/pages/settings/users/two-factor-operations.ts create mode 100644 packages/dms/src/test/unit/db/notification-inbox.test.ts create mode 100644 packages/dms/src/test/unit/implementations/dms/permission-preview-aggregate.test.ts create mode 100644 packages/dms/src/test/unit/implementations/dms/permission-preview-header.test.ts create mode 100644 packages/dms/src/test/unit/implementations/dms/permission-preview-menu.test.ts create mode 100644 packages/dms/src/test/unit/implementations/notification-subject-lock.test.ts create mode 100644 packages/dms/src/test/unit/interfaces/dms-base/display-blocks-catalog.test.ts create mode 100644 packages/dms/src/test/unit/interfaces/dms-base/layout-header-actions.test.ts create mode 100644 packages/dms/src/test/unit/interfaces/dms-base/lists-and-settings-catalog.test.ts create mode 100644 packages/dms/src/test/unit/interfaces/dms-base/table-view-bulk-operations.test.ts create mode 100644 packages/dms/src/test/unit/interfaces/dms-base/table-view-export-permission.test.ts create mode 100644 packages/dms/src/test/unit/interfaces/dms-base/table-view-reduced-chrome.test.ts create mode 100644 packages/dms/src/test/unit/interfaces/dms-base/table-view-row-rules-per-table.test.ts create mode 100644 packages/dms/src/test/unit/interfaces/dms-base/table-view-shared-controller-permissions.test.ts create mode 100644 packages/dms/src/test/unit/onboarding-platform.test.ts create mode 100644 packages/dms/src/test/unit/pages/settings/account-activity.test.ts create mode 100644 packages/dms/src/test/unit/pages/settings/account-data.test.ts create mode 100644 packages/dms/src/test/unit/pages/settings/account-security.test.ts create mode 100644 packages/dms/src/test/unit/pages/settings/members-page.test.ts create mode 100644 packages/dms/src/test/unit/pages/settings/regional-preferences.test.ts create mode 100644 packages/dms/src/test/unit/pages/settings/role-editor.test.ts create mode 100644 packages/dms/src/test/unit/pages/settings/role-preview.test.ts create mode 100644 packages/dms/src/test/unit/utils/user-activity.test.ts create mode 100644 packages/dms/src/utils/user-activity.ts create mode 100644 packages/dms/src/validation/account-deletion.schema.ts create mode 100644 packages/dms/src/validation/member-ownership.schema.ts create mode 100644 packages/dms/src/validation/regional-preferences.schema.ts create mode 100644 packages/dms/src/validation/role-editor.schema.ts create mode 100644 packages/dms/src/validation/security.schema.ts create mode 100644 packages/interface-dms/src/base/activity-feed.ts create mode 100644 packages/interface-dms/src/base/banner.ts create mode 100644 packages/interface-dms/src/base/card.ts create mode 100644 packages/interface-dms/src/base/display.ts create mode 100644 packages/interface-dms/src/base/empty-state.ts create mode 100644 packages/interface-dms/src/base/key-value-list.ts create mode 100644 packages/interface-dms/src/base/meter.ts create mode 100644 packages/interface-dms/src/base/nav-card-grid.ts create mode 100644 packages/interface-dms/src/base/section.ts create mode 100644 packages/interface-dms/src/base/stat-strip.ts diff --git a/packages/dms/docs/01.getting-started/06.built-in-dashboard.md b/packages/dms/docs/01.getting-started/06.built-in-dashboard.md index c72b462d7..79f4ef649 100644 --- a/packages/dms/docs/01.getting-started/06.built-in-dashboard.md +++ b/packages/dms/docs/01.getting-started/06.built-in-dashboard.md @@ -11,8 +11,8 @@ Load the DMS with zero pages of your own and you already have a working product: Every page renders inside the same chrome: -- **Sidebar** — the search / command palette trigger and the navigation tree built from the three root groups (**Pages**, **Modules**, **Settings**) and whatever categories and modules your code registers ([Navigation](/docs/building/navigation)). Users can pin pages as **favorites**, and the sidebar collapses to icons. -- **Header** — the sidebar-collapse toggle, quick actions, the notification bell, and the user-avatar menu. +- **Sidebar** — the search / command palette trigger and the navigation tree built from the three root groups (**Pages**, **Modules**, **Settings**) and whatever categories and modules your code registers ([Navigation](/docs/building/navigation)). Its footer holds Settings, Modules and the user menu, opened from the signed-in user's row. Users can pin pages as **favorites**, and the sidebar collapses to icons. +- **Header** — the sidebar-collapse toggle, the breadcrumb with its favorite star, quick actions and the notification bell (the light / dark / system choice lives in the user menu of the sidebar footer). - **Footer** — copyright, locale switcher, and registered links. A frontend layer extends every part of this shell through registries — header buttons, layout banners, sidebar widgets, footer links, app widgets and overlays ([Dashboard chrome](/docs/extending-the-dashboard/dashboard-chrome)) — and reskins it through app config ([Theming & branding](/docs/extending-the-dashboard/theming-and-branding)). @@ -34,7 +34,7 @@ The bell surfaces in-app notifications with an unread badge, live over the user' ## First run: the onboarding wizard -A fresh instance has no users. Until one exists, every route funnels to `/onboarding`, a wizard that registers the **first admin** — created as **platform owner**, attached to the default tenant — and marks the instance onboarded. From then on the wizard locks itself (it answers `412` to anyone who returns) and new users arrive by [invitation](/docs/auth-and-tenancy/authentication#how-users-enter-the-platform) — or by [self-registration](/docs/auth-and-tenancy/saas-mode) when the optional `dms-saas` module is loaded. +A fresh instance has no users. Until one exists, every route funnels to `/onboarding`, a three-step wizard: **Platform** (the platform name, which then titles the browser tab and the sign-in page over the configured `meta.title`, and the administrator's language), **Administrator** (first and last name, e-mail and a password checked live against the five password rules), then **Ready** (next steps, then the dashboard). It registers the **first admin** — created as **platform owner**, attached to the default tenant — and marks the instance onboarded. From then on the wizard locks itself (it answers `412` to anyone who returns) and new users arrive by [invitation](/docs/auth-and-tenancy/authentication#how-users-enter-the-platform) — or by [self-registration](/docs/auth-and-tenancy/saas-mode) when the optional `dms-saas` module is loaded. ![First-run administrator account form on a fresh demo database](../images/template-onboarding.png) @@ -48,13 +48,14 @@ The **Settings** root group ships a user section out of the box: | Page | What it does | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| **Profile** | Name, email, password, and interface language; **two-factor** enrollment (authenticator app, email codes, backup codes); the **sessions** list with per-device revocation and a "log out everywhere" switch. | +| **Profile** | Name, email, password; **two-factor** enrollment (authenticator app, email codes, backup codes); the **sessions** list with per-device revocation and a "log out everywhere" switch. A **Your data** block (its own permission, `settings.user.profile.accountDataComponent`) lets the user download a JSON file of everything the DMS keeps about them — profile, preferences, memberships and roles, notifications, sessions, linked sign-in providers, invitations sent; never a password, two-factor secret or token — and delete their account behind their password and their typed e-mail. Deletion refuses the last owner of a workspace or of the platform, signs out every device, removes memberships, notifications, provider links and two-factor data, keeps the invitations the user sent, and fires `USER_DELETED` ([Backend services](/docs/building/backend-services#lifecycle-hooks)). | +| **Language & region** | Interface language, time zone (automatic from the browser, or any IANA zone), first day of the week, 12- or 24-hour clock and numeric or written dates. Stored on the account, so every device follows them, and applied by every date the dashboard writes ([Localization](/docs/building/localization#dates-and-times)). Permission `settings.user.region`, granted to roles like any page. | | **Notifications** | Toggle received notification subjects; browse, read, and delete past notifications. | | **Shortcuts** | The keyboard-shortcut reference, aggregated from every loaded layer. | | **Members** | The tenant's member table — invite by email (role, language, owner flag, optional first/last name — required when skipping email validation), promote/demote tenant owners, force email validation, remove members. Owner-safety guards prevent removing the last owner. | | **Invites** | Pending invitations, with resend and cancel. | | **Roles** | Create roles and grant permissions from the permission tree that your pages, components, and actions register ([Auth & permissions](/docs/auth-and-tenancy/auth-and-permissions)). | -| **Appearance** | Color mode and interface density (small / normal / large). | +| **Appearance** | Color mode, interface density (small / normal / large), the sidebar's starting state, and accessibility options: reduce motion, increase contrast, always underline links. All per device. | Your project can add its own settings pages by registering pages under `settingsCategory` ([Navigation](/docs/building/navigation#the-root-groups)). diff --git a/packages/dms/docs/02.building/03.pages-and-components.md b/packages/dms/docs/02.building/03.pages-and-components.md index e53911978..5c0fb96c1 100644 --- a/packages/dms/docs/02.building/03.pages-and-components.md +++ b/packages/dms/docs/02.building/03.pages-and-components.md @@ -64,7 +64,7 @@ The optional third argument to `PageController` wraps the page in a **layout**. Three built-in layouts ship: -- **`DefaultLayout(options?)`** — the standard dashboard frame. `fullWidth` controls the content max-width and defaults to `true`; `hideHeader` suppresses the page header; `fillHeight` makes the page fill the height of the panel, for a tool that scrolls inside itself ([Pages that fill the panel](/docs/interfaces/base/layout#pages-that-fill-the-panel)). +- **`DefaultLayout(options?)`** — the standard dashboard frame. `fullWidth` controls the content max-width and defaults to `true`; `hideHeader` suppresses the page header; `fillHeight` makes the page fill the height of the panel, for a tool that scrolls inside itself ([Pages that fill the panel](/docs/interfaces/base/layout#pages-that-fill-the-panel)). `headerActions` puts buttons next to the page title — links or quick actions, each optionally behind a permission ([Header actions](/docs/interfaces/base/layout#header-actions)). - **`FormPageLayout(options?)`** — the same frame with `fullWidth: false`, for a page that only holds a form. - **`EmptyLayout()`** — no chrome at all; the built-in auth and onboarding pages use it. Reach for it when a page must fill the viewport on its own. diff --git a/packages/dms/docs/02.building/04.navigation.md b/packages/dms/docs/02.building/04.navigation.md index 2eaa94fbe..3a588cfee 100644 --- a/packages/dms/docs/02.building/04.navigation.md +++ b/packages/dms/docs/02.building/04.navigation.md @@ -96,14 +96,15 @@ The signal carries no data: connected clients re-fetch their own `/sitelayout` a ## Entry appearance -Two semantic fields shape how an entry renders — both on pages (`MenuOptions`) and on dynamic entries. They are deliberately semantic, not classes: the theme decides the colors. +Three semantic fields shape how an entry renders — both on pages (`MenuOptions`) and on dynamic entries. They are deliberately semantic, not classes: the theme decides the colors. | Field | Values | Renders as | | --------- | -------------------------------------------------- | ----------------------------------------------------------------------------- | | `variant` | `"default"` (implicit) or `"accent"` | An accent entry uses the theme's primary color — for a call to action ("New project"). | | `status` | `"success"`, `"warning"`, `"error"`, `"neutral"` | A colored state dot at the end of the entry (on the icon's corner when the sidebar is collapsed). | +| `badge` | A short string (`"3"`, `"new"`) | A small neutral pill with a mono label at the end of the entry — counts, "new" markers. | -A status dot renders on leaf entries only: an entry with children uses that slot for its expand chevron. +A status dot or a badge takes the end of the entry, the slot an entry with children uses for its expand chevron: a status dot shows on leaf entries only, and when a leaf has both, the badge wins. ## Quick actions: the command palette diff --git a/packages/dms/docs/02.building/06.backend-services.md b/packages/dms/docs/02.building/06.backend-services.md index 15b619860..10a652c4f 100644 --- a/packages/dms/docs/02.building/06.backend-services.md +++ b/packages/dms/docs/02.building/06.backend-services.md @@ -48,6 +48,7 @@ The current `Hook` enum: | `INVITE_BEING_CREATED` / `INVITE_CREATED` / `INVITE_DELETED` | invite lifecycle | | `MEMBER_BEING_ADDED` / `MEMBER_ADDED` / `MEMBER_REMOVED` | tenant-membership lifecycle | | `USER_REGISTERED` | a user completed registration — `{ tenantId, userId, email, name }` | +| `USER_DELETED` | a user deleted their own account, after the DMS removed its rows — `{ userId, email }`; delete the per-user rows your module keeps. A failing handler is logged, it does not bring the account back | `UnregisterHook(hook, handler)` removes a handler, for a module that stops listening while it stays loaded. diff --git a/packages/dms/docs/02.building/07.localization.md b/packages/dms/docs/02.building/07.localization.md index 53cd728e9..32b2c0336 100644 --- a/packages/dms/docs/02.building/07.localization.md +++ b/packages/dms/docs/02.building/07.localization.md @@ -44,3 +44,13 @@ Drop one JSON file per language under `i18n/locales/` in your frontend module; t ``` Reference a key as `"$my_app.report.title"` in backend metadata, or `t("my_app.report.title")` in a Vue template. When a key must exist in several files (one per language), grep a neighboring key to find them all quickly. + +## Dates and times + +Each user picks, on **Settings › Language & region**, a time zone, a first day of the week, a clock (12- or 24-hour) and a date format (numeric `01/10/2026` or written `1 Oct 2026`). Every one of them defaults to automatic: the browser's time zone, and the week and clock of the interface language. They are stored on the user row (`timeZone`, `weekStart`, `timeFormat`, `dateFormat`, all optional) and travel with the session user, so the server-rendered page already uses them. + +The shared formatters apply them for you — `formatDate`, `formatTime`, `formatDateTime` and `formatRelativeTime` from `dms-core/app/utils/formatter`, the `date` and `relative_date` table data types, notification and activity times, the members' "Last active", and the calendars of date pickers and the period selector. Format through them rather than with a bare `Intl.DateTimeFormat`, or through `regionalDateTimeFormat(locale, options)` from `dms-core/app/utils/regional`, which takes the same options and adds the user's preferences. Explicit options win: a `timeZone`, `hour12` or `hourCycle` you pass is kept, and the date format only rewrites full dates (day, month and year). For a value that is a calendar day computed in the browser, pass `{ keepLocalZone: true }` so it does not move to another zone. + +A screen that needs the values themselves — a calendar's `weekStartsOn`, the zone to show next to a time — reads them from `useUserRegionalPreferences()` ([Page context](/docs/frontend-composables/page-context#useuserregionalpreferences)). + +Amounts keep the currency of their data: there is no display-currency preference, since showing an amount in another currency would need a conversion the DMS cannot make. diff --git a/packages/dms/docs/04.components/01.overview.md b/packages/dms/docs/04.components/01.overview.md index ccc258359..cd84ed3d7 100644 --- a/packages/dms/docs/04.components/01.overview.md +++ b/packages/dms/docs/04.components/01.overview.md @@ -25,6 +25,8 @@ The component chapters follow the same shape, so you can scan them the same way | ----------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------- | | **Charts & widgets** | Dashboard data-viz: charts, KPI cards, top lists, period selector | [Charts & widgets](/docs/components/charts-and-widgets) | | **Layout & containers** | Arrange components: grids, stacks, tabs, placeholders | [Layout & containers](/docs/components/layout-and-containers) | +| **Lists & settings** | Activity feeds, x-of-y meters, settings sections and their field rows | [Lists & settings](/docs/components/lists-and-settings) | +| **Display blocks** | Stat strips, key/value facts, nav-card grids, empty states, banners, cards | [Display blocks](/docs/components/display-blocks) | | **Custom component** | The escape hatch to a freeform Vue component when the builders don't fit | [Custom component](/docs/components/custom-component) | | **Form** | Data entry / edit screens, validated and submitted to a route | [Forms](/docs/components/forms) | | **Tables** | Paginated, filterable, sortable lists & CRUD, backed by a `DataController` | [Tables](/docs/components/tables) | diff --git a/packages/dms/docs/04.components/05.forms.md b/packages/dms/docs/04.components/05.forms.md index 6a555a383..a157fceb3 100644 --- a/packages/dms/docs/04.components/05.forms.md +++ b/packages/dms/docs/04.components/05.forms.md @@ -18,7 +18,7 @@ The frontend renders a titled card. From the top: - An optional **title** and **description** header. - The **fields**, each a labelled input chosen from its DataType (text box, select, date picker, file upload, rich text, …), with the field's `description` as helper text. A required field carries an asterisk after its label (a group's label when one of its fields is required), and a `* Required fields` legend closes the form; a disabled or hidden field is never marked. Invalid fields show an inline message and an error state. - **Field groups**, whose members render together under a shared label, laid out horizontally or vertically (`orientation`). -- A **submit button** at the bottom. On submit the form validates against its schema; on success it shows `successMessage` (and optionally navigates via `redirectOnSuccess`), on failure `errorMessage`. A submit that went through but left something for the user to act on answers with a `warning` field (an i18n key or plain text) in its JSON response: the form then shows that warning instead of `successMessage`, and still redirects. +- A **submit button** at the bottom. On submit the form validates against its schema; on success it shows `successMessage` (and optionally navigates via `redirectOnSuccess`), on failure `errorMessage`. A submit that went through but left something for the user to act on answers with a `warning` field (an i18n key or plain text) in its JSON response: the form then shows that warning instead of `successMessage`, and still redirects. A submit response carrying `notice: { title, description?, color?, params? }` adds a toast of its own — a partial success such as "2 invitations sent, 1 address skipped" (`$` keys pluralized on a numeric `params.count`). When `fetchUrl` is set the form first loads existing values and pre-fills the inputs (an edit form); without it the form starts empty (a create form). @@ -89,6 +89,7 @@ The routes behind `submitUrl` (and `fetchUrl`) are normal API controllers — se | `submitLabel` | `string` | — | Label of the submit button (i18n key or literal). Defaults to the generic "Save changes". | | `successMessage` | `string` | — | Toast shown after a successful submit. | | `errorMessage` | `string` | — | Toast shown when a submit fails. | +| `saveBar` | `boolean` | `false` | Replaces the footer buttons with a sticky save bar that shows while there are unsaved changes, names the changed fields and offers Discard and Save. See [Settings sections](/docs/components/lists-and-settings#a-form-in-a-section). | | `fieldsOrientation` | `"horizontal" \| "vertical"` | — | Overall layout direction of the field list. | | `redirectOnSuccess` | `string` | — | Path to navigate to after a successful submit. Supports token substitution. | | `submitDefaults` | `Record` | — | Extra values merged into the submit payload. String values support token substitution. | diff --git a/packages/dms/docs/04.components/06.tables.md b/packages/dms/docs/04.components/06.tables.md index 57680843a..e2f449a63 100644 --- a/packages/dms/docs/04.components/06.tables.md +++ b/packages/dms/docs/04.components/06.tables.md @@ -67,6 +67,13 @@ A frontend layer can add **alternate displays** (kanban, cards, calendar…) bey | Option | Type | Default | Purpose | | ---------------------- | ----------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------- | | `caption` | `string` | — | Heading above the table. | +| `chrome` | `"full" \| "minimal" \| TableViewChromeOptions` | `"full"` | Which controls surround the rows: caption, search, filters, sort, refresh, table menu, column menus, page size picker (see [Reduced chrome](#reduced-chrome)). | +| `searchPlaceholder` | `string` | — | Placeholder of the search field (`$`-prefixed: i18n key). | +| `quickFilters` | `TableViewQuickFilter[]` | — | One-click dropdown filters in the toolbar over a column's values (see [Quick filters](#quick-filters)). | +| `hiddenColumns` | `string[]` | — | Columns hidden from the grid by default, still listed (a cell, a detail band or a form reads them). | +| `pageSize` | `number` | `10` | Rows per page while the user picked none. | +| `footer` | `{ countLabel?; hint? }` | — | Footer texts: the row count (`$` key pluralized on `{ count }`, e.g. "7 members") and a hint at its right. | +| `expandable` | `TableViewExpandableOptions` | — | A caret column opens a detail band under each row, listing `fields` and/or rendering a `component` (see [Expandable rows](#expandable-rows)). | | `rowIdKey` | `string` | `"_id"` | Field used as row identity for actions and realtime. | | `labelKey` | `string` | — | Field that titles the form container ("Edit _Buy milk_"). | | `rowActions` | `TableViewRowActionOptions` | — | Which per-row actions to show and their rules (see [Row actions](#row-actions)). | @@ -111,6 +118,105 @@ Wrapping keeps secondary text such as scope hints visible without changing the d Standalone `TableColumn` definitions accept the same option. A custom `-cell` slot replaces the default wrapper and owns its layout. `TableView` does not forward these slots. Alternate displays such as kanban are unaffected. +### Reduced chrome + +`chrome` decides which controls a table draws around its rows. The default, `"full"`, is the dashboard grid: caption and count, a search button, filters, sort, refresh, the ⋯ table menu, column header menus and resizing, and a footer with the page size picker. `"minimal"` is the reduced list of a settings page: no caption (the page header names it), an always-open search field, quick filters, custom buttons, sortable headers, the row menu and a footer without the page size picker. Toggles lay over a preset: + +```ts [src/pages/members.ts] +static members = TableView(memberAPI, { + chrome: "minimal", // or { preset: "minimal", caption: true, refresh: true } + searchPlaceholder: "$page.members.search", + quickFilters: [{ field: "roleIds", label: "$page.members.role" }], + hiddenColumns: ["email"], // drawn inside the member cell instead + pageSize: 25, + footer: { countLabel: "$page.members.count", hint: "$page.members.hint" }, +}); +``` + +| Toggle | Values | Full | Minimal | Control | +| ------------- | -------------------------- | -------- | -------- | ----------------------------------------------------------------------- | +| `caption` | `boolean` | `true` | `false` | Caption and count. Without it, the tabs move up into the header band. | +| `search` | `boolean \| "field"` | `true` | `"field"`| A button opening a field, an always-open field, or nothing. | +| `filters` | `boolean` | `true` | `false` | Filter button and filters row. | +| `sorting` | `boolean` | `true` | `false` | Sort popover (sortable headers stay clickable). | +| `refresh` | `boolean` | `true` | `false` | Refresh button. | +| `menu` | `boolean` | `true` | `false` | The ⋯ table menu: columns, density, export, import, page size. | +| `columnMenus` | `boolean` | `true` | `false` | Column header menus (sort, hide, pin) and column resizing. | +| `pageSize` | `boolean` | `true` | `false` | Footer page size picker; the pager then shows only past one page. | + +A display's capabilities still apply on top (a kanban hides the tabs whatever the chrome). Keyboard shortcuts, row actions, selection, presence, density and the sticky header are unaffected. + +### Quick filters + +`quickFilters` draws one dropdown button per entry in the toolbar, listing the values of a `filterable` column: a select's items, a boolean's two labels, or the rows a relation points to (read from its `select` endpoint). Picking a value filters the list (mode `array_contains_string` for a multiple select or relation, `is` otherwise, or the declared `mode`); "All" (`allLabel`) clears it. A quick filter is not persisted, does not show in the filters row and leaves the tab counters alone. Registration throws for an unknown or non-filterable column. + +### Link tabs + +A tab can open another page instead of filtering — sibling lists such as Members ↔ Invitations. Give it `to` (a page controller, whose URL and permission it follows, or a dashboard path with an optional `permission` id) and `countFrom` (a data controller, or its location) for its counter. A tab with the id `"all"` stands in for the implicit "all" tab, at its own position, with its own label and icon. `badge: true` publishes the tab's counter as the navigation badge of the page it stands for (the settings nav shows it): + +```ts +tabs: [ + { id: "all", label: "$page.members.tabs.members", icon: "i-ph-users", badge: true }, + { id: "invites", label: "$page.members.tabs.invites", icon: "i-ph-envelope-simple", + to: "/settings/user/members/invites", permission: "settings.user.invites", + countFrom: "/api/tables/admin-invites" }, +], +``` + +A link tab the caller may not open is left out when the layout is served; one whose list the caller may not read shows no counter. + +### Cells drawn by a display data type + +A column renders its cells through its data type's formatter. `display` on `@Column` borrows another registered frontend data type for the grid (and expanded-row fields) only — forms, filters, validation and exports keep `type` — and `display.label` renames the grid header. The formatter receives the whole row, so a cell can compose sibling fields. `size` sets the column's default width in px (150 otherwise; room left is spread in proportion): + +```ts +@Column({ + name: "Full name", + type: new DefaultDataTypes.StringType(), + size: 300, + display: { + type: "identity", + label: "Member", + options: { avatarField: "avatar", subtitleField: "email", selfField: "userId" }, + }, +}) +declare name: string; +``` + +The DMS registers four reusable cell types (options in [Custom data types](/docs/extending-the-dashboard/custom-data-types#cell-data-types)): `identity` (avatar or icon tile, name, "You" tag, badges, secondary line), `pills` (v2 role pills, or one filled pill such as an owner's crown), `relative_date` ("2 hr. ago", "Active now", "In 5 days", "Sep 27 · by Camille") and `indicator` (an on/off icon and word). The `status` type draws a v2 status pill. + +### Expandable rows + +`expandable` adds a caret column in front of the content. Opening a row shows a detail band under it, on the muted surface: the configured `fields` as a label/value list, a registered frontend `component`, or both side by side (the component on the left, the fields on the right on wide screens). + +```ts [src/pages/orders.ts] +static orders = TableView(orderDataAPI, { + caption: "Orders", + expandable: { + // Column keys, or { key, label } to relabel one. Each value renders + // through its column's data type, exactly like a grid cell. + fields: [{ key: "shippingAddress", label: "Ship to" }, "carrier", "payment"], + fieldsLabel: "Shipping & payment", + // Resolved by name from the global frontend registry. + component: CustomComponent("OrderLinesDetail"), + defaultExpanded: "first", // "none" (default) | "first" | "all" + single: true, // opening a row closes the previous one + }, +}); +``` + +| Option | Type | Default | Purpose | +| ----------------- | --------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------- | +| `fields` | `Array` | — | Columns listed in the band. A field must name a declared `@Column` (registration throws otherwise) and be `@Listable` to carry a value. | +| `fieldsLabel` | `string` | — | Eyebrow above the field list (`$`-prefixed: i18n key). | +| `component` | `Component` | — | Frontend component rendered in the band. It receives `row` (the listed row), `rowId` and `columns` (the column metadata), plus its own options. | +| `defaultExpanded` | `"none" \| "first" \| "all"` | `"none"` | Rows open on arrival, and again whenever a new set is listed: page, page size, filter, search, sort, tab or archive view. | +| `single` | `boolean` | `false` | At most one row open at a time. | + +A field the grid should not show stays listed and takes `isVisible: false` on its `@Column`: it is then read off the row for the band only (the column manager can still show it). Data a component needs that is no column at all — order lines, a timeline — only has to be `@Listable` on the controller. + +A refresh of the same set (the refresh button, a realtime update) keeps the rows the user opened, minus those no longer listed. The caret is a real button (`aria-expanded`, and `aria-controls` naming the band while it is open), so it works from the keyboard. It sits next to the selection checkbox and stays pinned with it, and the band spans the presence rail, the row actions and pinned columns; density, sticky header, archive mode and tabs apply as usual. Alternate displays (kanban, cards, custom displays) are unaffected. + ### Filtering, search, and sorting Filtering, search, and sorting need no page-side configuration — they come from the controller's decorators ([Data controller](/docs/components/data-controller)): a `filterable` column gets a filter offering its `DataType`'s operators, `@Searchable` fields feed the search box, and `@Sortable` columns get sortable headers. @@ -170,7 +276,7 @@ Rules are enforced **server-side** as well as in the UI: - A delete/edit/archive/restore request for an ineligible row is filtered out. - A non-strict edit whose single row is ineligible returns `403`. - With `strictRuleValidation: true`, the whole request is rejected `400`. -- A rule declared on a row action is registered once per controller and applies to every table view on it. +- A rule belongs to the table view declaring it. Several table views may share one controller (and its routes): each write names the table it comes from (`?tableView=`, sent by the frontend), and only that table's rules — and its permission — apply. A request naming no table is checked against the tables whose action the caller holds, and passes a row when one of them allows it. **Custom row actions** add menu entries that fire an `ActionTarget` rather than a built-in CRUD operation — the `custom` array below sits inside the `TableView`'s `rowActions`: @@ -186,9 +292,15 @@ custom: [ ], ``` +A custom row action can also take a `permission` (like a custom button below: stripped for a caller without it), a `color`, and — inline (`isVisible: true`) — a `variant` and `showLabel` to draw a labelled button ("Resend", "Revoke") rather than an icon. In the ⋯ menu, the row's own actions (details, edit, duplicate) come first, then the custom ones, then the destructive ones (delete, archive, restore) after a separator. + +A built-in action's `RowActionConfig` can rename and re-icon it (`label`, `icon`: "Change roles" for `edit`), give it a `successMessage`, and — for delete, archive and restore of one row — a `confirmFrom` URL (`{id}` filled in) answering a `RowActionConfirmDescriptor`: the confirmation the server words for that row, with its impact list, or a `blocked` explanation (the last owner of a workspace) that only offers to close. + +An `api` target may send a JSON `body`, copy a field of its response to the clipboard (`copy: "url"` for a share link), and word its `confirm` with an `icon` and a `confirmLabel`; on a row action the confirm texts receive the row's fields as i18n parameters (`"Remove {name}?"`). + A target can open a component in a drawer or a modal, navigate to an internal page or an external URL, call an API endpoint (with an optional confirmation dialog), or run an async export job — each `ActionTarget` type and its fields are in [Actions & reactivity](/docs/building/actions-and-reactivity#action-targets). Custom toolbar buttons (`customButtons`) take the same target, plus a `variant` and a `color`. -A custom toolbar button can also declare a `permission`: either the id of one of the table's own actions (e.g. `"add"`) or an `Action` from another component (`otherTable.getAction("add")`). The button is stripped from the serialized options when the caller lacks the permission — same mechanism as the built-in actions. The route the button calls still needs its own guard (`@AuthUserWithPermission(...)`). Give the button an `id` to expose it as a [quick action](/docs/building/navigation#quick-actions-the-command-palette) (`{ type: "button", page, button: "" }`), which inherits this permission. +A custom toolbar button can also declare a `permission`: either the id of one of the table's own actions (e.g. `"add"`) or an `Action` from another component (`otherTable.getAction("add")`). The button is stripped from the serialized options when the caller lacks the permission — same mechanism as the built-in actions. The route the button calls still needs its own guard (`@AuthUserWithPermission(...)`). Mark it `hidden` to leave it out of the toolbar while keeping it pressable by id — from a quick action or a page header action (`DefaultLayout({ headerActions: [{ id, button: "" }] })`), which mirrors its permission and availability. Give the button an `id` to expose it as a [quick action](/docs/building/navigation#quick-actions-the-command-palette) (`{ type: "button", page, button: "" }`), which inherits this permission. A custom toolbar button can also declare an `availability` resolver, called per request with `{ tenantId, user }` while the page layout is filtered. When it returns `{ reason }`, the button reaches the client disabled, with the reason (a string or a `$` i18n key) in its tooltip; a quick action pressing it shows the reason instead of opening the target. Returning `undefined` leaves it enabled, and a resolver that throws is logged and leaves it enabled too. It only shapes the UI: the operation behind the button must still refuse on its own. @@ -200,7 +312,7 @@ Set `archiveMode: true` **and** decorate a boolean field with `@ArchiveField()`; - An `@ArchiveField` without `archiveMode` is accepted: it enables the archive filter on list without swapping the actions. - Archive mode registers three permissions — `archive`, `restore`, `viewArchived`. -It also injects default rules so the right action shows per row: `edit`/`duplicate`/`archive` apply only when the archive field is **not** `true`; `restore`/`delete` apply only when it **is** `true`. Your own rule on any of these wins. +It also injects default rules so the right action shows per row: `edit`/`duplicate`/`archive` apply only when the archive field is **not** `true`; `restore`/`delete` apply only when it **is** `true`. Your own rule on any of these wins. These defaults are enforced server-side like any rule, and a row whose archive field was never written (created by a form that leaves it out) counts as active. The `viewArchived` permission is enforced server-side: a client sending `showArchived=true` without it gets a hard **403**, not a silent empty list. Archive and restore are bulk PUT operations over selected `ids`. @@ -278,6 +390,9 @@ Guards exist for `edit`, `delete`, `archive`, `restore`, and `new`, each receivi ## Permissions +Several table views may share one data controller (a demo table on many pages, a list and its page extension): its data routes are shared, so each action is guarded by the permission of **every** table view mounting it — a caller holding `list` on any of those tables may list, exactly what that table already exposes. A table view no page mounted carries no permission and is ignored; a controller with a single table view behaves as before. + + Every table action registers its own permission, named `.`. The component permission id is the page's permission id (its full id, unless the page declares `permission.id`) followed by every field/child id in the table's position; each action appends its id — `list`, `select` (granted by default), `add`, `edit`, `view`, `delete`, `export`, plus `archive`/`restore`/`viewArchived` in archive mode. These same per-action permissions gate the row actions. The table is **filtered per user**: it strips the forms and row actions the caller lacks before the page renders, and the matching routes reject unauthorized calls server-side. As a special case, if the `edit` action has no rule, the table force-disables `details` (the edit form already covers viewing). See [Auth & permissions](/docs/auth-and-tenancy/auth-and-permissions). diff --git a/packages/dms/docs/04.components/11.display-blocks.md b/packages/dms/docs/04.components/11.display-blocks.md new file mode 100644 index 000000000..3bb08cf4e --- /dev/null +++ b/packages/dms/docs/04.components/11.display-blocks.md @@ -0,0 +1,213 @@ +--- +title: "Display blocks" +description: StatStrip, KeyValueList, NavCardGrid, EmptyState, Banner and Card — the summary and notice blocks a page is assembled from. +--- + +# Display blocks + +These blocks carry the summaries and notices around a page's data: a strip of headline figures, label / value facts, a grid of cards linking elsewhere, an empty state, a banner, and a titled card holding other blocks. Each is a builder you declare on a page like any other ([Pages & components](/docs/building/pages-and-components)), and each is registered in the block catalog with its options described, so the page builder can place and configure it. The playground shows all of them under **Blocks**. + +```ts [src/pages/overview.ts] +import { + Banner, + Card, + EmptyState, + KeyValueList, + NavCardGrid, + StatStrip, +} from "@antelopejs/interface-dms/base"; +``` + +Every text option — titles, labels, details, button labels — follows the [`$`-prefix convention](/docs/frontend-composables/utilities#usetranslation--the--prefix-convention): `"$my_module.billing.title"` is translated, anything else is shown as written. Links (`to`, `href`) take a DMS route, an `#anchor` on the page, or an absolute URL, which opens in a new tab. + +Tones are `neutral`, `primary`, `secondary`, `success`, `warning`, `error` and `info`; an icon well also takes `muted`, the quiet well of a settings row. + +## Live items + +`StatStrip`, `KeyValueList` and `NavCardGrid` list items. The items are written in the options, or read from a route with `fetchUrl`, which answers `{ items: [...] }` in the block's own item shape. While the first answer loads the block draws skeletons; when it fails it shows an error with a retry; when the list is empty it shows `emptyLabel`. Like the KPI cards, the block refetches when a [watched event](/docs/building/actions-and-reactivity) changes its state. + +| Option | Type | Purpose | +| ---------------- | ------------ | --------------------------------------------------------- | +| `fetchUrl` | `string` | Route answering `{ items }`; replaces the static `items`. | +| `fetchUrlMethod` | `HttpMethod` | Method of the fetch (`GET` by default). | +| `emptyLabel` | `string` | Title of the empty state. | + +```ts +@Get("billing-stats") +stats() { + return { + items: [ + { icon: "i-ph-receipt", eyebrow: "Invoices sent", value: 1284 }, + { icon: "i-ph-warning-octagon", tone: "error", eyebrow: "Overdue", value: 6, + detail: "Oldest 41 days", detailTone: "error" }, + ], + }; +} +``` + +## StatStrip + +**What it renders.** A row of headline figures, each a cell with an icon well, a mono label, the value and a detail line. `joined` draws one card split by hairlines (the security status strip); `cards` draws one compact stat card per figure (the modules summary). A cell with `href` links to where the figure is managed. Columns drop on narrow screens: a joined strip goes to one column on phones, the compact cards keep two. + +```ts +static status = StatStrip({ + layout: "joined", + items: [ + { icon: "i-ph-shield-check", tone: "success", eyebrow: "Two-factor", + value: "On", detail: "Authenticator app", href: "/settings/user/security" }, + { icon: "i-ph-devices", eyebrow: "Sessions", value: "3 active", + detail: "This device + 2 others" }, + ], +}); +``` + +| Option | Type | Default | Purpose | +| --------- | --------------------- | ----------- | ------------------------------------------ | +| `items` | `StatStripItem[]` | — | The cells, in order. | +| `layout` | `"joined" \| "cards"` | `joined` | One card split in cells, or one card each. | +| `columns` | `number` (1–6) | items count | Columns on wide screens. | +| `label` | `string` | — | Accessible name of the strip. | + +A `StatStripItem` carries `eyebrow` and `value` (a number is formatted for the locale), plus optional `icon`, `tone` (well tone; `muted` by default when joined, `primary` as cards), `detail`, `detailTone` and `href`. + +## KeyValueList + +**What it renders.** Label / value rows split by hairlines, the label on the left and the value right-aligned, each value drawn by its `type`: `text`, `status` (a tinted pill), `money` (a currency amount), `date` (a localized date), `link` (an accent link) or `mono` (an identifier). A `detail` adds a dim note after the value. The list sits in a card by default, with `title` as the card's eyebrow; turn `card` off to place it inside a [Card](#card). + +```ts +static subscription = KeyValueList({ + title: "Subscription", + items: [ + { label: "Plan", value: "Business" }, + { label: "Status", value: "Past due", type: "status", tone: "error" }, + { label: "Next invoice", value: 588, type: "money", detail: "Oct 31" }, + { label: "Customer ID", value: "cus_Q8f2LmXv01", type: "mono" }, + ], +}); +``` + +| Option | Type | Default | Purpose | +| ---------- | -------------------- | ------- | ---------------------------------------- | +| `items` | `KeyValueListItem[]` | — | The rows, in order. | +| `title` | `string` | — | Eyebrow title of the card. | +| `card` | `boolean` | `true` | Card surface around the list. | +| `dense` | `boolean` | `false` | Tighter rows, for side panels. | +| `columns` | `number` (1–3) | `1` | Columns on wide screens. | +| `currency` | `string` | `EUR` | Default ISO 4217 code of `money` values. | + +A `KeyValueListItem` carries a `label` and a `value` (an ISO date for `date`, a number for `money`; an empty value shows a dash), plus optional `type`, `tone` (text colour, or the pill tone of a `status`), `href`, `detail` and `currency`. + +## NavCardGrid + +**What it renders.** A grid of navigation cards: an icon well, the title with an arrow that slides in on hover, a description, and optionally the target's live `state` in mono, a small uppercase `badge` after the title (the module a page comes from) and mono `readout` lines. An optional `title` and `description` head the grid. + +```ts +static workspace = NavCardGrid({ + title: "Workspace", + items: [ + { icon: "i-ph-users", title: "Members", to: "/settings/user/members", + description: "People with access and pending invitations.", + state: "8 of 10 seats used" }, + { icon: "i-ph-credit-card", title: "Billing", to: "/billing", + state: "Payment failed", stateTone: "error", badge: "SaaS" }, + ], +}); +``` + +| Option | Type | Default | Purpose | +| ------------- | --------------- | ------- | ----------------------------- | +| `items` | `NavCardItem[]` | — | The cards, in order. | +| `columns` | `number` (1–4) | `3` | Columns on wide screens. | +| `title` | `string` | — | Section title above the grid. | +| `description` | `string` | — | Line under the section title. | + +A `NavCardItem` carries `title`, `icon` and `to`, plus optional `description`, `iconTone`, `state`, `stateTone`, `badge` and `readout`. + +The cards are items of one block rather than blocks of their own: a grid of nav cards is one list, configured in one place, reflowed as one grid, and — with `fetchUrl` — fed by one route that computes every card's state. A single card is a one-item grid. + +## EmptyState + +**What it renders.** An icon well, a title, a short explanation and the link buttons that fit the case, centred. The `variant` says why it is empty and sets the icon, the tone and how it is announced (`error` as an alert, the others as a status). In a card by default. + +```ts +static noInvoices = EmptyState({ + title: "No invoices yet", + description: "Invoices appear here once a customer is billed.", + actions: [{ label: "Create an invoice", to: "/invoices/new", icon: "i-ph-plus" }], +}); +``` + +| Option | Type | Default | Purpose | +| ------------- | ---------------------------------------------------- | --------- | -------------------------------------- | +| `title` | `string` | — | Title. | +| `description` | `string` | — | Short explanation. | +| `variant` | `"no-data" \| "no-result" \| "no-access" \| "error"` | `no-data` | Why it is empty. | +| `icon` | `string` | variant's | Overrides the icon. | +| `tone` | tone | variant's | Overrides the well tone. | +| `size` | `"sm" \| "md" \| "lg"` | `md` | `sm` compact, `lg` with a larger well. | +| `framed` | `boolean` | `false` | Hatched panel behind it. | +| `actions` | `BlockLinkAction[]` | — | Link buttons; the first one leads. | +| `card` | `boolean` | `true` | Card surface around it. | + +A `BlockLinkAction` is `{ label, to, icon?, variant?, color? }`. The block picks each button's look from its place; `variant` (`solid`, `outline`, `soft`, `subtle`, `ghost`, `link`) and `color` (a tone) override it. + +## Banner + +**What it renders.** A notice: a tinted wash fading from the left, a boxed icon in the tone, the title and a line of explanation, link buttons on the right (the last one is the main action) and an optional close button. `size: "sm"` is the compact one-line banner for cards and side panels. + +A dismissed banner stays dismissed: the dismissal is kept in a cookie for a year, so the server render already leaves it out. It is remembered under `dismissKey`, or the block's position on its page without one; change the key to show the banner again (a new beta, a new notice). + +This is a block placed on one page. For a strip shown under the dashboard header on every page, use `RegisterLayoutBanner` ([Dashboard chrome](/docs/extending-the-dashboard/dashboard-chrome)). + +```ts +static beta = Banner({ + tone: "warning", + title: "Sales analytics is in beta", + description: "Numbers refresh every 15 minutes.", + actions: [{ label: "Send feedback", to: "#feedback" }], + dismissible: true, + dismissKey: "sales-beta-2026", +}); +``` + +| Option | Type | Default | Purpose | +| ------------- | ---------------------------------------------------------- | ------- | ------------------------------------------- | +| `title` | `string` | — | Title. | +| `description` | `string` | — | Line of explanation. | +| `tone` | `"info" \| "success" \| "warning" \| "error" \| "primary"` | `info` | Colour of the wash and the icon. | +| `icon` | `string` | tone's | Overrides the icon. | +| `size` | `"md" \| "sm"` | `md` | `sm` is the compact one-line banner. | +| `actions` | `BlockLinkAction[]` | — | Link buttons on the right. | +| `dismissible` | `boolean` | `false` | Adds a close button; the dismissal is kept. | +| `dismissKey` | `string` | — | Key the dismissal is kept under. | + +## Card + +**What it renders.** A titled card holding other blocks: the head with the eyebrow `title`, a mono `count`, a dim `description` line and link buttons on the right; the body, where the children stack; and an optional muted foot band. + +`Card` is a container. Children added with `.child()` and no slot stack in the body. A child added with `{ slot: "actions" }` joins the head's link buttons, one with `{ slot: "footer" }` fills the foot band; each of those two slots holds one child, so several go in an `HStack`. + +```ts +static connectors = Card({ + title: "Connectors", + count: 4, + padded: false, + actions: [{ label: "View all", to: "/integrations", icon: "i-ph-arrow-right" }], + footer: "Last sync 10:15", +}) + .child("list", KeyValueList({ card: false, dense: true, items: [/* … */] })); +``` + +| Option | Type | Default | Purpose | +| ------------- | ------------------------- | --------- | ----------------------------------------------------- | +| `title` | `string` | — | Eyebrow title of the head. | +| `count` | `number \| string` | — | Mono count after the title. | +| `description` | `string` | — | Dim line under the title. | +| `actions` | `BlockLinkAction[]` | — | Link buttons on the right of the head. | +| `footer` | `string` | — | Muted text in the foot band. | +| `padded` | `boolean` | `true` | Body padding; off for a list or a table edge to edge. | +| `variant` | `"default" \| "elevated"` | `default` | `elevated`: stronger shadow on an empty backdrop. | + +## Permissions + +These blocks hold no data of their own beyond their options; a block with a `fetchUrl` reads it with the viewer's session, so the route applies its own checks. Like every block, each one is a position in the page layout that a role must be granted to see ([Auth & permissions](/docs/auth-and-tenancy/auth-and-permissions)), and a `Card`'s children each carry their own position under it. diff --git a/packages/dms/docs/04.components/12.lists-and-settings.md b/packages/dms/docs/04.components/12.lists-and-settings.md new file mode 100644 index 000000000..4ff96ca6e --- /dev/null +++ b/packages/dms/docs/04.components/12.lists-and-settings.md @@ -0,0 +1,172 @@ +--- +title: "Lists & settings" +description: ActivityFeed, Meter, and the Section / FieldRow blocks that compose a settings-like page from the backend. +--- + +# Lists & settings + +The blocks on this page cover what a settings screen or an overview is made of beyond charts and tables: a feed of recent events, a bar telling how much of a quota is used, and the titled sections whose rows hold a label, its help text and a control. Each is a builder you declare on a page like any other ([Pages & components](/docs/building/pages-and-components)); the playground shows all of them under **Blocks**. + +```ts [src/pages/workspace.ts] +import { + ActivityFeed, + FieldRow, + Meter, + Section, +} from "@antelopejs/interface-dms/base"; +``` + +## ActivityFeed + +**What it renders.** A card with an eyebrow title and an optional "View all" link, then one row per event: a tinted icon well, the title, dimmed details joined by "·", the time on the right and an accent dot for an unread event. Events are filed under day separators — "Today · Sep 29", "Yesterday · Sep 28", the weekday within the week, then the date — each row showing its time; with `groupByDay: false` the rows say how long ago instead. A skeleton shows while the first answer loads, an empty state when there is nothing, and an error state with a retry when the source fails. + +```ts +static activity = ActivityFeed({ + title: "Activity", + fetchUrl: "/api/activity", + maxItems: 8, + viewAllTo: "/audit", +}); +``` + +The source answers the entries newest first, as an array or as `{ items }`: + +```ts +@Get("activity") +list() { + return { + items: [ + { + icon: "i-ph-check-circle", + tone: "success", + title: "Order #10481 paid", + meta: ["Globex Logistics", "€860.50", "Stripe"], + date: "2026-09-29T09:18:00Z", + to: "/orders/10481", + }, + ], + }; +} +``` + +| Option | Type | Default | Purpose | +| ------------------ | -------------------- | ------- | --------------------------------------------------------------------------- | +| `title` | `string` | — | Eyebrow title of the card head. | +| `items` | `ActivityFeedItem[]` | — | Entries shown when no source is set. | +| `fetchUrl` | `string` | — | Route answering `ActivityFeedItem[]` or `{ items }`. | +| `fetchUrlMethod` | `HttpMethod` | `GET` | Method of the fetch. | +| `groupByDay` | `boolean` | `true` | Day separators with times; off, relative times ("14 min ago"). | +| `maxItems` | `number` | — | Shows at most this many entries. | +| `viewAllTo` | `string` | — | Path of the "View all" link in the card head. | +| `viewAllLabel` | `string` | — | Its label; defaults to "View all". | +| `emptyTitle` | `string` | — | Empty state title; defaults to "No activity yet". | +| `emptyDescription` | `string` | — | Empty state text. | +| `mono` | `boolean` | `false` | Mono titles and details, for paths, queries and request logs. | +| `framed` | `boolean` | `true` | The card frame and its head; off, the bare list (inside a `Section`, say). | + +An entry (`ActivityFeedItem`) has a `title` and optionally an `icon`, a `tone` (`neutral`, `accent`, `secondary`, `success`, `warning`, `error`, `info`), `meta` (details), `date` (ISO, for the day and the time), `time` (literal text in place of the time), `unread` and `to` (makes the row a link). Titles and details are translated when they are `$`-prefixed i18n keys. + +On the frontend each row is a `DmsActivityItem`, the feed preset of the generic `DmsListRow` (icon well or avatar, title, "·"-joined meta, trailing slot, unread and current states) that the settings pages also use for sessions and notifications. + +## Meter + +**What it renders.** An "x of y" bar (v2 `.c-meter`): the label, a dimmed hint and the value on one line, the bar under it, then an optional legend. One value fills the bar in its tone; `segments` stack several fills — members and pending invites in the seats meter — each with its legend label. `warnAt` and `errorAt` turn a single fill and the value text warning or error past a percentage of `max`. + +```ts +static seats = Meter({ + label: "Seats", + hint: "8 in use · 2 free", + max: 10, + segments: [ + { value: 6, label: "6 members" }, + { value: 2, tone: "soft", label: "2 pending invites" }, + ], + legend: true, + linkLabel: "Manage members", + linkTo: "/settings/members", +}); +``` + +| Option | Type | Default | Purpose | +| ------------------------ | ------------------------------------------------ | ---------- | ------------------------------------------------------------------- | +| `label` | `string` | — | Name of the measure. | +| `hint` | `string` | — | Dimmed note after the label. | +| `value` | `number` | `0` | Filled amount; ignored when `segments` is set. | +| `max` | `number` | `100` | Total the bar stands for. | +| `segments` | `MeterSegment[]` | — | Stacked fills: `{ value, tone?, label? }`. | +| `legend` | `boolean` | `false` | Shows the segment labels under the bar. | +| `format` | `"fraction" \| "percent" \| "value" \| "none"` | `fraction` | Value text: `8 / 10`, `80%`, `8` or nothing. | +| `valueLabel` | `string` | — | Replaces the formatted value text ("38.2 / 50 GB"). | +| `tone` | `MeterTone` | `accent` | Fill of a single value: `accent`, `soft`, `neutral`, `success`, … | +| `warnAt` / `errorAt` | `number` | — | Percent of `max` from which the fill turns warning / error. | +| `size` | `"xs" \| "sm" \| "md"` | `sm` | Bar height: 4, 6 or 8 px. | +| `fetchUrl` | `string` | — | Route answering any of `{ value, max, segments, hint, valueLabel }`. | +| `framed` | `boolean` | `false` | Wraps the meter in a padded card. | +| `linkLabel` / `linkTo` | `string` | — | A link at the end of the legend line. | + +Figures that change per request — seats used, quota left — come from `fetchUrl`: a page layout is built once, when the page registers. + +## Section and FieldRow + +**What they render.** `Section` is the v2 settings block (`.st-block`): a 15px title and one line of description above a card. `FieldRow` is one row of that card (`.st-row`): a label with its help text and a control, set apart from the next row by a hairline. Together they compose a settings page from the backend, the way the core settings pages are drawn. + +```ts +static plan = Section({ + title: "Plan & usage", + description: "Seats, storage and API calls of the workspace.", +}) + .child( + "seats", + FieldRow({ label: "Seats", description: "Billed monthly.", layout: "form" }) + .child("meter", Meter({ max: 10, value: 8 })), + ) + .child( + "storage", + FieldRow({ label: "Storage", layout: "form" }) + .child("meter", Meter({ value: 38.2, max: 50, valueLabel: "38.2 / 50 GB" })), + ); +``` + +| `Section` option | Type | Purpose | +| ---------------- | --------- | ----------------------------------------------------------------- | +| `title` | `string` | Heading above the card. | +| `description` | `string` | One line under the heading. | +| `danger` | `boolean` | A block of destructive actions: red frame and title. | +| `bare` | `boolean` | The children without the card frame (a grid, a framed feed). | + +| `FieldRow` option | Type | Default | Purpose | +| ----------------- | ------------------------------- | -------- | --------------------------------------------------------------------------------------------- | +| `label` | `string` | — | Row label. | +| `description` | `string` | — | Help text under the label. | +| `layout` | `"inline" \| "form" \| "stack"` | `inline` | `inline`: compact control on the right. `form`: 240px label column. `stack`: label above. | +| `required` | `boolean` | `false` | Red asterisk after the label. | +| `disabled` | `boolean` | `false` | Dims the row. | + +Both are containers. A field row holds one block that stands on its own — a meter, a banner, a status. Fields someone fills in and submits do not go in field rows: they belong to a [`Form`](/docs/components/forms), which owns their values, validation and submit, and which lays them out as section rows by itself (below). This keeps one way to declare a field. + +On the frontend the same pieces are the generic `DmsSection`, `DmsFieldRow`, `DmsSaveBar` and `DmsSaveStatus` components, usable in any custom page. + +### A form in a section + +A `Form` placed in a framed `Section` drops its own card: its fields become the section's rows, with the 240px label column of a `form` field row. With `saveBar: true` the footer buttons give way to the sticky save bar (v2 `.st-savebar`): it appears once a field differs from what the form loaded, names the changed fields, and offers Discard and Save; saving hides it again. + +```ts +static profile = Section({ title: "Workspace profile" }).child( + "form", + Form({ + fetchUrl: "/api/workspace", + submitUrl: "/api/workspace", + saveBar: true, + fields: [ + { id: "name", label: "Name", type: new DefaultDataTypes.StringType(), required: true }, + { id: "description", label: "Description", type: new DefaultDataTypes.StringType({ textarea: true }) }, + ], + }), +); +``` + +`saveBar` works on a form outside a section too — in its own card, or in a modal — in place of the reset and submit buttons. + +## Permissions + +These blocks follow the page's [Auth & permissions](/docs/auth-and-tenancy/auth-and-permissions) like any component: each child of a section or a field row has its own permission, and a child the user may not see is left out of the layout. The routes behind `fetchUrl` guard themselves. diff --git a/packages/dms/docs/05.extending-the-dashboard/02.dashboard-chrome.md b/packages/dms/docs/05.extending-the-dashboard/02.dashboard-chrome.md index 2a416b6e5..c9206bf54 100644 --- a/packages/dms/docs/05.extending-the-dashboard/02.dashboard-chrome.md +++ b/packages/dms/docs/05.extending-the-dashboard/02.dashboard-chrome.md @@ -11,7 +11,7 @@ One piece of chrome is registered from the **backend** instead: [layout banners] ## Header actions -`registerHeaderAction` adds an icon-only button to the right of the dashboard header navbar — the strip that already holds quick actions, notifications, and the user avatar. +`registerHeaderAction` adds an icon-only button to the right of the dashboard header navbar — the strip that already holds quick actions and notifications. **Signature** @@ -293,6 +293,8 @@ Three registries mount a component of yours; they differ in where it lands and w `registerFooterLink` adds a link to the footer's link row (next to the copyright and the locale switcher). +The row starts with two Antelope links, `dms:documentation` and `dms:website` (orders 10 and 20), followed by a GitHub star button for the DMS repository. Register an entry under one of these ids to replace it. URL targets (`https://…`) open in a new tab. + **Signature** ```ts diff --git a/packages/dms/docs/05.extending-the-dashboard/03.theming-and-branding.md b/packages/dms/docs/05.extending-the-dashboard/03.theming-and-branding.md index d8ece42c0..5edd36df4 100644 --- a/packages/dms/docs/05.extending-the-dashboard/03.theming-and-branding.md +++ b/packages/dms/docs/05.extending-the-dashboard/03.theming-and-branding.md @@ -85,7 +85,7 @@ Beyond the palette, four surfaces give finer control. All of them are standard N **Component theme slots.** The `ui` app-config key also carries per-component overrides (`ui.card.slots`, `ui.navigationMenu`, …). Use one to restyle a component family everywhere. To see what the DMS already overrides, read the base layer's `app.config.ts`. -**CSS variables.** The base layer's stylesheet defines the surface system as CSS variables, each with a dark-mode variant: `--ui-bg*` for canvas and elevated surfaces, `--ui-border*` for hairlines, `--ui-radius` for corner rounding, `--dms-surface-card` for card frames, plus the shadow tokens. Override them in your own unlayered `:root` CSS to shift the whole surface palette at once. +**CSS variables.** The base layer's stylesheet defines the surface system as CSS variables, each with a dark-mode variant: `--ui-bg*` for canvas and elevated surfaces, `--ui-border*` for hairlines, `--ui-text*` for the text tiers, `--ui-radius` for corner rounding, `--dms-surface-card` and `--dms-radius-card` for card frames, `--dms-bg-sidebar` and `--dms-bg-field` for the sidebar and form fields, `--dms-canvas-glow` for the background image behind the page (a cyan glow in dark mode, `none` in light), plus the shadow tokens. Solid primary buttons use `--dms-accent-fill`, `--dms-accent-fill-hover` and `--dms-accent-on-fill` rather than `--ui-primary`, which is the accent for text and icons. Override them in your own unlayered `:root` CSS to shift the whole surface palette at once. DMS defaults live in the `dms` cascade layer. Unlayered consumer `:root` and `.dark` declarations override those defaults in either stylesheet order, without doubled selectors or `!important`. The primary switch uses shade 600 in dark mode for thumb contrast; other switch colors retain their semantic tokens. Glow and live-edit highlights follow `--dms-accent` (primary shade 500 in light mode, 400 in dark mode), replacing the internal `--dms-accent-rgb` channel token. @@ -113,6 +113,25 @@ Because everything is `rem`-based, custom components inherit the scaling for fre ## Color mode -Users pick light, dark or system on the same **Appearance** page. The choice lives in the `dms-color-mode` cookie, so an explicit `light` or `dark` class is already on `` in the server-rendered page; `system` follows the operating system and resolves in the browser before the first paint. Your code reads or sets it through the `useColorModePreference()` cookie ref ([Page context](/docs/frontend-composables/page-context#usecolormodepreference)). +Users pick light, dark or system on the same **Appearance** page, or from the Theme submenu of the user menu in the sidebar footer. The choice lives in the `dms-color-mode` cookie, so an explicit `light` or `dark` class is already on `` in the server-rendered page; `system` follows the operating system and resolves in the browser before the first paint. Your code reads or sets it through the `useColorModePreference()` cookie ref ([Page context](/docs/frontend-composables/page-context#usecolormodepreference)). Nuxt UI's color-mode components (`UColorModeSelect`, `UColorModeButton`, the theme group of the dashboard search) stay in sync with it both ways. Style dark mode with Tailwind's `dark:` variant, which keys on the `dark` class. + +## Accessibility + +The **Accessibility** block of the same **Appearance** page holds three options. Like the theme and the density they are per device: they live in the `dms-accessibility` cookie, which the server reads, so their classes are already on `` in the first paint. Your code reads or sets them through `useAccessibilityPreferences()` ([Page context](/docs/frontend-composables/page-context#useaccessibilitypreferences)). + +| Option | Values | On `` | Effect | +| ---------------------- | ------------------------------ | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Reduce motion | Automatic (default) / On / Off | `dms-reduce-motion` (On), `dms-full-motion` (Off) | Animations and transitions run in about 0 ms and play once. Spinners (`animate-spin`) keep turning. Charts are drawn without animation. Automatic sets no class and follows the operating system's `prefers-reduced-motion`. | +| Increase contrast | On / Off | `dms-increase-contrast` | Darker (light theme) or lighter (dark theme) `--ui-text*`, `--ui-border*` and `--dms-*` line tokens. Muted and dimmed text clear WCAG AA (4.5:1) on cards and the canvas, and field borders clear 3:1. | +| Always underline links | On / Off | `dms-underline-links` | Underlines content links: the text links that underline on hover (`ULink`, table link cells, inline links) and anything with the `dms-text-link` class. Menu items, tabs, cards and buttons are left alone. | + +There is no text-size option: the interface density already scales the text with the rest of the interface. + +To keep your module in line: + +- Use Tailwind's `motion-safe:` and `motion-reduce:` variants for decorative motion. The DMS redefines them so they follow the device setting first and the system setting under Automatic. +- In JavaScript-driven motion (a canvas, a chart library, a count-up), call `isReducedMotionActive()` (from the dms-ui layer's `utils/accessibilityPreferences`) before animating. +- Style secondary text and borders with the `text-muted`, `text-dimmed` and `border-*` tokens rather than fixed colors, so high contrast reaches them. +- Give a content link built on a bare `` or `` the `dms-text-link` class (or the v2 `hover:underline` text-link classes) so the underline option covers it. diff --git a/packages/dms/docs/05.extending-the-dashboard/04.custom-data-types.md b/packages/dms/docs/05.extending-the-dashboard/04.custom-data-types.md index 8e7718941..efb61f982 100644 --- a/packages/dms/docs/05.extending-the-dashboard/04.custom-data-types.md +++ b/packages/dms/docs/05.extending-the-dashboard/04.custom-data-types.md @@ -27,7 +27,7 @@ From a plugin in your layer, register the same `id` with `useDataTypes().registe | Field | Purpose | | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `formatter` | A map of `(value, locale, options?) => string \| VNode` functions, keyed by compare mode with a required `default`. Renders table cells; per-mode entries format filter chips. | +| `formatter` | A map of `(value, locale, options?, row?) => string \| VNode` functions, keyed by compare mode with a required `default`. Renders table cells; per-mode entries format filter chips. Two more keys: `cell` (a shorter grid rendering) and `empty` (drawn for a null value instead of the fallback). `row` is the listed row in a table, absent elsewhere. | | `displayComponent` | A read-only Vue component for the form's read view — it receives `:model-value` and takes precedence over `formatter` there. Any component works; wrap a heavy one in `defineAsyncComponent` to keep its code out of the startup bundle. | | `beforeStateMapper` | `(value, options?) => value` — reshapes the server value before the form state is seeded. Must be idempotent: the form reset re-applies it to values that may already be mapped. The built-in `relation` type uses it to turn populated objects back into bare ids. | @@ -37,6 +37,19 @@ The frontend object carries **no** `inputComponent` or `filterComponents` — in One subtlety on `formatter`: in table cells its `options` argument is the field's backend options, but in the form read view the render site passes its own props object instead — don't write a formatter that relies on backend options being present. +## Cell data types + +A frontend data type does not need a backend class to draw cells: a column names it with `display` (see [Tables](/docs/components/tables#cells-drawn-by-a-display-data-type)) and keeps its own `type` for forms and filters. The DMS registers these, for any table: + +| Id | Options | Draws | +| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------- | +| `identity` | `avatarField` (image value or URL), `icon` (tile instead of an avatar), `subtitleField`, `selfField` + `selfLabel` (tag of the signed-in user's row), `badges: [{ field, equals?, notEquals?, label, color? }]`, `storage` | Avatar, name, "You" tag, badges, secondary line. | +| `pills` | `labelKey` (relation label, `name` by default), `exclusive: { field, label, icon? }` (one filled pill when the row's field is set), `emptyLabel` | Mono outline pills; unresolved relation ids are skipped. | +| `relative_date` | `style` (`relative` \| `day`), `tone`, `nowWithinMs` + `nowLabel`, `emptyLabel` + `emptyTone`, `soonWithinMs` + `soonTone`, `pastStyle` + `pastTone`, `byField` + `byLabel` (`{ date, name }`) | "2 hr. ago", "Active now", "Never signed in", "In 5 days", "Sep 27 · by Camille". | +| `indicator` | `onLabel`, `offLabel`, `onIcon`, `offIcon`, `onTone` (`success`), `offTone` (`dimmed`) | An icon and a word; on for a set flag or a non-empty list. | + +Tones are `default`, `muted`, `dimmed`, `highlighted`, `success`, `warning`, `error`, `info` and `primary`; labels are `$`-prefixed i18n keys or literals. + ## Worked example: a rating type A 0–5 star rating. The backend declares the type and reuses the built-in numeric input; the frontend renders filled stars in cells and read views. diff --git a/packages/dms/docs/06.frontend-composables/02.authenticated-requests.md b/packages/dms/docs/06.frontend-composables/02.authenticated-requests.md index d5c509c24..ad7b66765 100644 --- a/packages/dms/docs/06.frontend-composables/02.authenticated-requests.md +++ b/packages/dms/docs/06.frontend-composables/02.authenticated-requests.md @@ -131,7 +131,7 @@ Both probing and switching go through the backend's `/api/auth/refresh`, which * ## `useLogout` — the shared logout -`useLogout()` returns `{ logout }`, the logout behavior shared by every surface that offers it (the header user menu, the command palette's session group). `logout()` clears the session, drops the current user from the multi-account list, then routes to the account switcher (`/auth/accounts`) when other stored accounts remain — or to `/auth` otherwise. The session is cleared even when the user object is malformed, so logout never silently no-ops. Call it instead of hand-rolling `clearSession` + navigation: +`useLogout()` returns `{ logout }`, the logout behavior shared by every surface that offers it (the sidebar user menu, the command palette's session group). `logout()` clears the session, drops the current user from the multi-account list, then routes to the account switcher (`/auth/accounts`) when other stored accounts remain — or to `/auth` otherwise. The session is cleared even when the user object is malformed, so logout never silently no-ops. Call it instead of hand-rolling `clearSession` + navigation: ```ts const { logout } = useLogout(); diff --git a/packages/dms/docs/06.frontend-composables/04.page-context.md b/packages/dms/docs/06.frontend-composables/04.page-context.md index 19cb50f33..1b8de55ad 100644 --- a/packages/dms/docs/06.frontend-composables/04.page-context.md +++ b/packages/dms/docs/06.frontend-composables/04.page-context.md @@ -162,6 +162,26 @@ const size = getPreference("tables.contacts.pageSize", 25); `() → CookieRef` — the color mode as a writable cookie ref (`dms-color-mode`, values `"light" | "dark" | "system"`, default `"system"`). Assign to `.value` to change it; Nuxt UI's color-mode components follow, and a change made through them updates the cookie. +### `useAccessibilityPreferences()` + +`() → { preferences, reduceMotion, increaseContrast, underlineLinks }` — the accessibility options of the **Appearance** page, from the `dms-accessibility` cookie (URI-encoded JSON, kept a year). `preferences` is the complete, read-only object; the three others are writable refs: `reduceMotion` is `"auto" | "on" | "off"` (default `"auto"`, which follows `prefers-reduced-motion`), `increaseContrast` and `underlineLinks` are booleans (default `false`). Assigning one rewrites the cookie and updates the `` classes ([Theming](/docs/extending-the-dashboard/theming-and-branding#accessibility)). + +### `useUserRegionalPreferences()` + +`() → { preferences, detectedTimeZone, timeZone, weekStartsOn, timeFormat }` — the signed-in user's choices from **Settings › Language & region**. Unlike the cookie-backed composables above, these are stored on the user and follow them on every device. `preferences` holds what the user chose (`timeZone`, `weekStart`, `timeFormat`, `dateFormat`; an unset field is automatic); `timeZone`, `weekStartsOn` (0 Sunday … 6 Saturday) and `timeFormat` (`"h23" | "h12"`) are computed refs with the automatic ones resolved — the browser's zone (`detectedTimeZone`), the language's first day and clock. The shared date formatters already apply them ([Localization](/docs/building/localization#dates-and-times)); reach for this for a component of your own, such as a calendar: + +```vue + + + +``` + ### `useFavoritePages()` `useFavoritePages` tracks the user's pinned pages, persisted to the `dms-favorite-pages` cookie and mirrored in shared state. A `FavoritePage` records the page's `id`, `path`, `title`, and optional `icon`. It returns: diff --git a/packages/dms/docs/07.interfaces/3.base/1.introduction.md b/packages/dms/docs/07.interfaces/3.base/1.introduction.md index f1bd3c030..0bd04ce22 100644 --- a/packages/dms/docs/07.interfaces/3.base/1.introduction.md +++ b/packages/dms/docs/07.interfaces/3.base/1.introduction.md @@ -29,6 +29,13 @@ The DMS documentation carries task-shaped chapters on the same components, organ | `tab` | `Tab` | yes | [Layout and Containers](./6.layout.md) | | `layouts` | `DefaultLayout`, `EmptyLayout` | yes | [Layout and Containers](./6.layout.md) | | `placeholder` | `Placeholder` | yes | [Layout and Containers](./6.layout.md) | +| `display` | `DISPLAY_TONES`, `IconTone`, `BlockLinkAction`, `BlockItemsSource` | yes | [Display Blocks](./10.display-blocks.md) | +| `stat-strip` | `StatStrip` | yes | [Display Blocks](./10.display-blocks.md) | +| `key-value-list` | `KeyValueList` | yes | [Display Blocks](./10.display-blocks.md) | +| `nav-card-grid` | `NavCardGrid` | yes | [Display Blocks](./10.display-blocks.md) | +| `empty-state` | `EmptyState` | yes | [Display Blocks](./10.display-blocks.md) | +| `banner` | `Banner` | yes | [Display Blocks](./10.display-blocks.md) | +| `card` | `Card` | yes | [Display Blocks](./10.display-blocks.md) | | `custom` | `CustomComponent` | no | [Layout and Containers](./6.layout.md) | | `tree` | `Tree`, `TreeNode`, `TreeEvents` | yes | [Tree](./7.tree.md) | | `data-types` | `DataType`, the registration decorators, `DefaultDataTypes`, `DefaultDataCompareTypes`, `StatusType` | no | [Data Types](./8.data-types.md) | diff --git a/packages/dms/docs/07.interfaces/3.base/10.display-blocks.md b/packages/dms/docs/07.interfaces/3.base/10.display-blocks.md new file mode 100644 index 000000000..851ac9e78 --- /dev/null +++ b/packages/dms/docs/07.interfaces/3.base/10.display-blocks.md @@ -0,0 +1,79 @@ +# Display Blocks + +## Overview + +Six builders cover the summaries and notices around a page's data: `StatStrip`, `KeyValueList`, `NavCardGrid`, `EmptyState`, `Banner` and `Card`. Each returns a `ComponentBuilder` and registers its block type with an options schema, so `ListBlockTypes()` describes it to a page builder. `Card` is a container; the others are leaves. The task-shaped chapter is [Display blocks](/docs/components/display-blocks). + +```typescript +import { + Banner, + Card, + EmptyState, + KeyValueList, + NavCardGrid, + StatStrip, +} from "@antelopejs/interface-dms/base"; +``` + +| Builder | Subpath | Block type | Component name | Group | +| -------------- | ---------------- | -------------- | -------------------------- | --------------- | +| `StatStrip` | `stat-strip` | `StatStrip` | `dms-stat-strip-block` | `visualization` | +| `KeyValueList` | `key-value-list` | `KeyValueList` | `dms-key-value-list-block` | `content` | +| `NavCardGrid` | `nav-card-grid` | `NavCardGrid` | `dms-nav-card-grid-block` | `content` | +| `EmptyState` | `empty-state` | `EmptyState` | `dms-empty-state-block` | `content` | +| `Banner` | `banner` | `Banner` | `dms-banner-block` | `content` | +| `Card` | `card` | `Card` | `dms-card-block` | `layout` | + +Every factory takes its options as optional, so a block placed before it is configured is the bare call `StatStrip()`. + +## Shared Vocabulary + +`display` holds what the six share. + +| Symbol | Kind | Value | +| ------------------------- | --------- | ------------------------------------------------------------------------------------------------ | +| `DISPLAY_TONES` | constant | `neutral`, `primary`, `secondary`, `success`, `warning`, `error`, `info` | +| `DisplayTone` | type | One of `DISPLAY_TONES`. | +| `ICON_TONES` / `IconTone` | constant | `DISPLAY_TONES` plus `muted`, the quiet icon well. | +| `BlockLinkAction` | interface | `{ label, to, icon?, variant?, color? }`: a link button; `to` is a route, an `#anchor` or a URL. | +| `BLOCK_ACTION_VARIANTS` | constant | `solid`, `outline`, `soft`, `subtle`, `ghost`, `link`. | +| `BlockItemsSource` | interface | `{ fetchUrl?, fetchUrlMethod?, emptyLabel? }`: where a list block reads `{ items }` from. | +| `BlockLinkActionSchema` | schema | The zod schema of one action, with its `ui()` hints. | + +## List Blocks + +`StatStripProps`, `KeyValueListProps` and `NavCardGridProps` extend `BaseComponentProps` and `BlockItemsSource`. Their `items` are static; a `fetchUrl` replaces them with the `items` of its answer, `{ items: T[] }`, in the same item shape. + +| Item interface | Required | Optional | +| ------------------ | --------------------- | ---------------------------------------------------------------------------- | +| `StatStripItem` | `eyebrow`, `value` | `id`, `icon`, `tone` (`IconTone`), `detail`, `detailTone`, `href` | +| `KeyValueListItem` | `label` | `id`, `value`, `type` (`KeyValueType`), `href`, `tone`, `detail`, `currency` | +| `NavCardItem` | `title`, `icon`, `to` | `id`, `description`, `iconTone`, `state`, `stateTone`, `badge`, `readout` | + +| Props | Own options | +| ------------------- | --------------------------------------------------------- | +| `StatStripProps` | `items`, `layout` (`StatStripLayout`), `columns`, `label` | +| `KeyValueListProps` | `items`, `title`, `card`, `dense`, `columns`, `currency` | +| `NavCardGridProps` | `items`, `title`, `description`, `columns` | + +`STAT_STRIP_LAYOUTS` is `joined`, `cards`; `KEY_VALUE_TYPES` is `text`, `status`, `money`, `date`, `link`, `mono`. + +## Static Blocks + +| Props | Options | +| ----------------- | ----------------------------------------------------------------------------------------------------- | +| `EmptyStateProps` | `title`, `description`, `variant`, `icon`, `tone`, `framed`, `size`, `actions`, `card` | +| `BannerProps` | `title`, `description`, `tone` (`BannerTone`), `icon`, `size`, `actions`, `dismissible`, `dismissKey` | +| `CardProps` | `title`, `count`, `description`, `actions`, `footer`, `padded`, `variant` | + +`EMPTY_STATE_VARIANTS` is `no-data`, `no-result`, `no-access`, `error`; `EMPTY_STATE_SIZES` is `sm`, `md`, `lg`. `BANNER_TONES` is `info`, `success`, `warning`, `error`, `primary`; `BANNER_SIZES` is `md`, `sm`. `CARD_VARIANTS` is `default`, `elevated`. + +## Card Slots + +`Card` registers `container: true` and two slots, `CARD_ACTIONS_SLOT` (`"actions"`, next to the head's link buttons) and `CARD_FOOTER_SLOT` (`"footer"`, the foot band). Children without a slot render in the body; each slot holds one child. + +```typescript +Card({ title: "Connectors", count: 4 }) + .child("list", KeyValueList({ card: false, items })) + .child("foot", HStack(), { slot: CARD_FOOTER_SLOT }); +``` diff --git a/packages/dms/docs/07.interfaces/3.base/4.tables.md b/packages/dms/docs/07.interfaces/3.base/4.tables.md index 18805cfe8..6bb0b22aa 100644 --- a/packages/dms/docs/07.interfaces/3.base/4.tables.md +++ b/packages/dms/docs/07.interfaces/3.base/4.tables.md @@ -128,6 +128,9 @@ These are not the plain data-api defaults. Every route asserts tenant access and | `filterable` | `boolean` | Register the type's filter and allow column filtering. | | `inputComponent` | `Component` | Overrides the input component the data type supplies. | | `group` | `string` | Identifier of the `ColumnGroup` this column belongs to in the generated forms. | +| `cellWrap` | `boolean` | Wrap the grid cell without a line limit. | +| `size` | `number` | Default width of the grid column in px (150 when omitted). | +| `display` | `ColumnDisplay` | `{ type, options?, label? }`: a frontend data type the grid cells (and expanded-row fields) render with, its options, and a grid header in place of `name`. `type` keeps driving forms, filters, validation and exports; the formatter also receives the row. | A read-only field whose `readonlyBehavior` resolves to `hidden` for a mode is dropped from that mode's form; a field whose data type has no input component is dropped from every form. @@ -217,6 +220,13 @@ Typing `TableViewOptions` by `InstanceType` is what makes row-action rules fi | Option | Type | Description | | --- | --- | --- | | `caption` | `string` | Table caption; also the component's display name, defaulting to `"TableView"`. | +| `chrome` | `TableViewChromePreset \| TableViewChromeOptions` | `"full"` (default) or `"minimal"`, or per-control toggles over a preset: `caption`, `search` (`boolean \| "field"`), `filters`, `sorting`, `refresh`, `menu`, `columnMenus`, `pageSize`. | +| `searchPlaceholder` | `string` | Placeholder of the search field. | +| `quickFilters` | `TableViewQuickFilter[]` | `{ field, label?, icon?, allLabel?, mode? }` dropdown filters over a filterable column's values; not persisted. Unknown or non-filterable columns throw. | +| `hiddenColumns` | `string[]` | Columns hidden from the grid by default (still listed). Unknown columns throw. | +| `pageSize` | `number` | Rows per page while the user picked none (default 10). | +| `footer` | `TableViewFooterOptions` | `{ countLabel?, hint? }`: the footer's row count (`$` key pluralized on `{ count }`) and hint. | +| `expandable` | `TableViewExpandableOptions` | Expandable rows: `fields` (column keys or `{ key, label? }`, each rendered by its column's data type), `fieldsLabel`, `component` (receives `row`, `rowId`, `columns`), `defaultExpanded` (`"none"` \| `"first"` \| `"all"`) and `single`. Fields must name declared columns. Serialized as `TableViewExpandableSerialized`. | | `rowIdKey` | `string` | Field holding the row id. Defaults to `DEFAULT_ROW_ID_FIELD`. | | `labelKey` | `string` | Field used to name a row in container titles. | | `rowActions` | `TableViewRowActionOptions` | Built-in and custom row actions. | @@ -228,7 +238,7 @@ Typing `TableViewOptions` by `InstanceType` is what makes row-action rules fi | `queryParamFilters` | `QueryParamFilters` | Maps URL query parameters onto hidden filters. | | `routeParamFilters` | `RouteParamFilters` | Maps DMS route parameters onto hidden filters. | | `strictRuleValidation` | `boolean` | Reject the whole request when any row fails rule validation, instead of processing only the eligible rows. | -| `tabs` | `TableViewTab[]` | Tabs above the table, each applying a set of hidden filters. | +| `tabs` | `TableViewTab[]` | Tabs above the table, each applying a set of hidden filters (`filters` optional). A tab may link to another page instead (`to`: page controller or path, `permission` for a path, `countFrom`: data controller or location for its counter); a tab with id `"all"` replaces the implicit one; `badge` publishes its counter as the page's nav badge. Serialized as `TableViewTabSerialized` (`to` resolved per request, `toPage`). | | `realtime` | `boolean` | Set to `false` to disable realtime broadcast and presence for this resource. Realtime is on by default. | | `kanban` | `KanbanOptions` | Enable the kanban display. | | `displays` | `TableViewDisplayOption[]` | Additional displays beyond the built-in `table`. | @@ -303,7 +313,7 @@ custom: [ ], ``` -Rules are enforced on both sides. When any action carries a `rule`, `TableView` stores the whole `rowActions` object on the controller metadata as the controller's rule set, and the `edit`, `delete`, `archive` and `restore` routes validate the affected ids against it before running. Rows that fail the rule are dropped from the operation; with `strictRuleValidation` the whole request is rejected instead. Because the rules live on the controller, a second table view on the same controller that declares no rule of its own still gets the controller's rule merged into its serialized row actions, so its menu matches what the server accepts. +Rules are enforced on both sides, per table view. `TableView` records its own `rowActions` (archive-mode defaults included) against its builder (`setRowScope`), and the `edit`, `delete`, `archive` and `restore` routes validate the affected ids against the rules of the table the request comes from before running. The frontend names it on every write with the `tableView` query parameter (`TABLE_VIEW_QUERY_KEY`), holding the table's `tableViewKey` (its component permission id, served in its options); the request is then held to that table's permission alone, and a key naming no table view with the action is refused `403`. A request naming no table acts through every mounted table view whose action the caller holds: a row passes when one of them allows it. Rows that fail the rule are dropped from the operation; with `strictRuleValidation` the whole request is rejected instead. Another table view over the same controller is never constrained by these rules. Permissions are applied on top. The table view registers `list` and `select` as component actions always, `add`, `edit` and `view` when the matching generated form exists, `delete` when the controller declares the delete endpoint, `archive`, `restore` and `viewArchived` under `archiveMode`, and `export` when the three export endpoints are registered. Each action carries a permission id of the form `.`. When the viewer lacks the permission the corresponding row action is forced to `false` and the corresponding generated form is withheld. The rule algebra itself — leaf operators, `and` / `or` / `not`, and `RowActionConfig` — is documented in [Shared Types](./2.types.md). @@ -313,6 +323,12 @@ A `new` or `edit` `ResourceForm` block over the controller submits to the same r `TableViewRowActionOptionsSerialized` is the transported shape: rules and flags untyped, `custom` as `CustomRowActionSerialized[]`, plus a `showArchived?: boolean` field the builder fills from the `viewArchived` permission. +### Row action extras + +`RowActionConfig` (built-in actions) also takes `label`, `icon`, `successMessage` and `confirmFrom` — a URL (`{id}` and the row-id field filled in) answering a `RowActionConfirmDescriptor` (`title`, `description`, `params`, `icon`, `confirmColor`, `confirmLabel`, `confirmIcon`, `cancelLabel`, `impact[]`, `blocked`) used for delete, archive and restore of a single row. `CustomRowAction` also takes `permission` (`ButtonPermission`, stripped per request like a custom button), `color`, `variant` and `showLabel`. The `api` action target also takes `body`, `copy` (response field copied to the clipboard) and `confirm.icon` / `confirm.confirmLabel`. `CustomButton` takes `hidden`: served and pressable by id, not drawn in the toolbar. + +When several table views share a data controller, each action of its routes is guarded by the permission ids of every mounted table view (`TableViewMeta.actionPermissionIds(action)`; any one suffices), unless the request names its table view with `tableView`, which holds it to that table's id alone. `TableViewMeta.componentBuilders` lists them; `componentBuilder` is the last one. + ## Archive Mode With `archiveMode: true`, the archive and restore actions replace deletion. The builder calls `applyArchiveModeDefaultRules` (see [Helpers](./9.helpers.md)) to give every relevant action a default rule against the `@ArchiveField` column, so archived rows offer restore and delete while live rows offer edit, duplicate and archive. Actions you configured explicitly keep your settings; only actions left undefined, set to `true`, or given without a rule receive the default. @@ -504,17 +520,19 @@ The routes reach the DMS through two interface functions it implements, `interna | `groups` | `Record` keyed by group id. | | `options` | The `TableViewOptions` the last `TableView` call set. | | `archiveField` | Field name recorded by `@ArchiveField`. | -| `controllerRowActionRules` | Row actions promoted to controller-wide rules. | +| `controllerRowActionRules` | Controller-wide rules applied on top of each table view's own, set only by an explicit `setControllerRowActionRules`. | | `controllerGuards` | Guards promoted to controller-wide guards. | | `componentBuilders` | Every live `TableView` builder built on the controller, in build order. | | `actionPermissionIds(actionId)` | The permission id the action carries on each mounted table view of the controller. | | `addComponentBuilder` | Writer the builder calls to record itself. | +| `componentBuilder` | The live table view built last. Assigning it records a builder like `addComponentBuilder`: it joins the others, never replaces them. | | `resourceFormBuilders` | Every live `new` / `edit` form built over the controller, in build order: the `ResourceForm` blocks and the forms each table view opens. | | `addResourceFormBuilder` | Writer the form builder calls to record a form that submits to the controller. | | `writingComponents` | Every live component that submits to the controller's write routes: its table views and its `new` / `edit` forms, including the ones a page-mode table view mounts on its form sub-pages. A native file staged by any of them is accepted on save; one staged by any other component is refused. | | `config` | Getter returning `{ location, columns }`, the serialized column list plus the controller's route location. | | `getFormFields(mode)` | Builds the `FormFieldOrGroup[]` for `"view"`, `"edit"` or `"new"`. | | `setColumn`, `setGroup`, `setOptions`, `setArchiveField`, `setControllerRowActionRules`, `setControllerGuards` | Writers used by the decorators and the builder. | +| `setRowScope`, `rowScopeOf`, `tableViewFor` | The row rules each table view enforces, and the mounted table view a `tableView` key names. | Each entry of `config.columns` carries `id`, `header`, `isVisible`, `type` (the serialized data type), `accessorKey`, `listable`, `enableSorting`, `enableColumnFilter`, `defaultValue`, `accessMode` and `readonlyBehavior`. diff --git a/packages/dms/docs/07.interfaces/3.base/6.layout.md b/packages/dms/docs/07.interfaces/3.base/6.layout.md index ee9f5c077..2ac01820b 100644 --- a/packages/dms/docs/07.interfaces/3.base/6.layout.md +++ b/packages/dms/docs/07.interfaces/3.base/6.layout.md @@ -177,6 +177,7 @@ export class OverviewPage extends PageController( | `fullWidth` | `boolean` | Let the content span the whole panel instead of a constrained column. Defaults to `true`. | | `hideHeader` | `boolean` | Omit the page header. | | `fillHeight` | `boolean` | Let the page fill the height of the panel instead of growing with its content, for a tool that scrolls inside itself — see [Pages that fill the panel](#pages-that-fill-the-panel). Defaults to `false`. | +| `headerActions` | `PageHeaderAction[]` | Buttons right of the page title, in order — see [Header actions](#header-actions). | Dashboard pages are full-width unless they opt out, which is what a table, a grid of cards or a chart wants. Set `fullWidth: false` for a page that only holds a form, where a constrained column stays readable — or use `FormPageLayout`, which is exactly that: @@ -194,6 +195,38 @@ The generated `new` and `edit` pages of a table view use it, so a form page you Because they return a plain `ComponentInfo` rather than a `ComponentBuilder`, the page layouts have no `.child()`, `.meta()` or `.watch()`. +### Header actions + +A page puts its main actions next to its title — a primary "New invoice", an "Export", a link to the docs — with `headerActions`. Each button opens a path or runs a [quick action](/docs/interfaces/core/quick-actions): + +```typescript +import { DefaultLayout } from "@antelopejs/interface-dms/base/layouts"; +import { newInvoiceAction } from "./quick-actions"; + +DefaultLayout({ + headerActions: [ + { id: "docs", label: "Documentation", icon: "i-ph-book-open", to: "https://antelopejs.com/docs", external: true }, + { id: "new", quickAction: newInvoiceAction, color: "primary" }, + { id: "audit", label: "Audit log", icon: "i-ph-scroll", to: "/audit", permission: "billing.audit" }, + ], +}); +``` + +| Field | Type | Description | +| --- | --- | --- | +| `id` | `string` | Key of the action, unique in the header. | +| `label` | `string` | Button text (i18n key with `$` or literal). A quick action lends its own name. | +| `icon` | `string` | Icon name. A quick action lends its own icon. | +| `to` | `string` | DMS path the button opens, or a full URL with `external`. | +| `external` | `boolean` | Opens `to` in a new tab, with an outbound-link icon. | +| `quickAction` | `string \| QuickActionInfo` | The quick action the button runs: what `QuickAction()` returned, or its key (`category:id`, or the bare id). | +| `button` | `string` | Presses the custom button of this `id` a component of the page declares (a table view's `customButtons`, typically `hidden`). Left out when the button is not served to the user, disabled with its reason when its `availability` refuses. | +| `color` | `"primary" \| "neutral" \| …` | Defaults to `neutral`, an outline button; any other color is solid. | +| `variant` | `"solid" \| "outline" \| "soft" \| "subtle" \| "ghost"` | Overrides the fill derived from the color. | +| `permission` | `string` | Permission id the user must hold to see the button. | + +Who sees a button is settled on the server when the layout is served: an action whose `permission` the user lacks is left out of the layout, and a quick-action button only shows to the users the quick action is served to — that is, the users its page admits. A page drawn by a Vue page component can add its own buttons next to these with `usePageHeaderActions`. + ### Pages that fill the panel A page built around one tool — a file explorer, a data grid, a graph canvas — usually wants that tool to take the height of the panel and scroll inside itself, rather than make the whole page scroll. Set `fillHeight` on its layout: diff --git a/packages/dms/docs/07.interfaces/4.notifications/2.categories-and-subjects.md b/packages/dms/docs/07.interfaces/4.notifications/2.categories-and-subjects.md index faf70c459..b744b202e 100644 --- a/packages/dms/docs/07.interfaces/4.notifications/2.categories-and-subjects.md +++ b/packages/dms/docs/07.interfaces/4.notifications/2.categories-and-subjects.md @@ -36,6 +36,7 @@ export const shopCategory = NotificationCategory("shop", { | `descriptionKey` | `string` (optional) | Translation key for a longer description. | | `icon` | `string` | Icon name, in the icon syntax used across the dashboard (for example `i-ph-shopping-cart`). | | `togglePermission` | [`TogglePermission`](#toggle-permissions) (optional) | Parent toggle stance applied when evaluating this category's subjects. It does not lock the category's own switch. | +| `tagKey` | `string` (optional) | Translation key of a short module tag (for example `SaaS`) shown next to the category in the settings screen and on each of its notifications in the inbox. Without it, the inbox tags a notification with its subject's label. | Registering a second category with an `id` that is already taken is ignored: the first declaration wins. @@ -82,6 +83,7 @@ export const stockSubject = NotificationSubject("stock", { | `labelKey` | `string` | Translation key for the subject name. | | `descriptionKey` | `string` (optional) | Translation key for a longer description. | | `togglePermission` | [`TogglePermission`](#toggle-permissions) (optional) | Whether users may turn this subject off, read together with the category's value. | +| `badgeKey` | `string` (optional) | Translation key of a badge shown next to the subject label in the settings screen (for example `Developer mode`). | A subject carries the whole category object, not just its id, so `subject.category.id` is always reachable from a subject you hold. That is how a send resolves the preference key from nothing but the subject you passed to the builder. @@ -186,7 +188,7 @@ The declaration functions and the built-in constants are exported from the inter | Symbol | Import from | | ------ | ----------- | | `NotificationCategory`, `NotificationSubject`, `SystemCategory`, `GeneralSubject`, `SecuritySubject`, `AccountSubject`, `CollaborationSubject`, `AutomationSubject` | `@antelopejs/interface-dms/notifications` | -| `NotificationCategoryInfo`, `NotificationSubjectInfo`, `TogglePermission`, `ReadScope` | `@antelopejs/interface-dms/notifications/types` | +| `NotificationCategoryInfo`, `NotificationSubjectInfo`, `NotificationTone`, `TogglePermission`, `ReadScope` | `@antelopejs/interface-dms/notifications/types` | ```typescript import type { NotificationSubjectInfo } from "@antelopejs/interface-dms/notifications/types"; diff --git a/packages/dms/docs/07.interfaces/4.notifications/3.sending.md b/packages/dms/docs/07.interfaces/4.notifications/3.sending.md index 63752012f..591bb3e49 100644 --- a/packages/dms/docs/07.interfaces/4.notifications/3.sending.md +++ b/packages/dms/docs/07.interfaces/4.notifications/3.sending.md @@ -55,6 +55,7 @@ const shipped = Notification() | `.subject(subject)` | `NotificationSubjectInfo` | The subject the notification is filed under, which decides the category and the user preference it is gated on. Required. | | `.linkTo(value)` | `string` | Destination the notification links to, such as `/settings/user/profile`. Optional. | | `.params(value)` | `Record` | Interpolation values carried alongside the notification. Optional. | +| `.tone(value)` | `NotificationTone` (`"neutral"`, `"accent"`, `"success"`, `"warning"`, `"error"`) | Colour of the icon well the inbox lists the notification with. Optional: without it the well is accented while unread and neutral once read. | The subject comes from [Categories and Subjects](./2.categories-and-subjects.md) — either one you declared with `NotificationSubject()` or one of the built-in constants. @@ -92,7 +93,7 @@ So a chain that skips one of the four does not compile — `this` is typed `neve const broken = Notification().icon("i-ph-bell").title("Hello").build(); ``` -The check is purely static and happens at the call site. Nothing is validated again at runtime, and `.linkTo()` and `.params()` never affect it. +The check is purely static and happens at the call site. Nothing is validated again at runtime, and `.linkTo()` and `.params()` never affect it, and neither does `.tone()`. `build()` returns a `SendableNotification` holding a frozen copy of the data, so reusing the builder afterwards cannot change a notification you already built. diff --git a/packages/dms/frontend-vue/deferred-plugins.ts b/packages/dms/frontend-vue/deferred-plugins.ts index f5de67d00..7c02e1758 100644 --- a/packages/dms/frontend-vue/deferred-plugins.ts +++ b/packages/dms/frontend-vue/deferred-plugins.ts @@ -8,6 +8,7 @@ import commandPalettePersonalPagesPlugin from "./layers/dms-layout/app/plugins/c import commandPaletteQuickActionsPlugin from "./layers/dms-layout/app/plugins/command-palette-quick-actions.client"; import commandPaletteSessionPlugin from "./layers/dms-layout/app/plugins/command-palette-session.client"; import notificationStreamPlugin from "./layers/dms-layout/app/plugins/notification-stream.client"; +import permissionPreviewPlugin from "./layers/dms-layout/app/plugins/permission-preview.client"; import profileSyncPlugin from "./layers/dms-layout/app/plugins/profile-sync.client"; const deferredPlugins: DmsPluginSetup[] = [ @@ -17,6 +18,7 @@ const deferredPlugins: DmsPluginSetup[] = [ commandPaletteQuickActionsPlugin, commandPaletteSessionPlugin, notificationStreamPlugin, + permissionPreviewPlugin, profileSyncPlugin, ]; diff --git a/packages/dms/frontend-vue/dms.frontend.ts b/packages/dms/frontend-vue/dms.frontend.ts index 4654074b0..f2f80280d 100644 --- a/packages/dms/frontend-vue/dms.frontend.ts +++ b/packages/dms/frontend-vue/dms.frontend.ts @@ -10,9 +10,11 @@ import authMiddleware from "./layers/dms-auth/app/middleware/auth"; import homepageRedirectMiddleware from "./layers/dms-layout/app/middleware/homepage-redirect.global"; import moduleRoutingMiddleware from "./layers/dms-layout/app/middleware/module-routing.global"; import pageLeaveGuardMiddleware from "./layers/dms-layout/app/middleware/page-leave-guard.global"; +import accessibilityPlugin from "./layers/dms-layout/app/plugins/accessibility"; import colorModePlugin from "./layers/dms-layout/app/plugins/color-mode"; import interfaceScalePlugin from "./layers/dms-layout/app/plugins/interface-scale"; import languageSyncPlugin from "./layers/dms-layout/app/plugins/language-sync"; +import regionalPreferencesPlugin from "./layers/dms-layout/app/plugins/regional-preferences"; import seoPlugin from "./layers/dms-layout/app/plugins/seo"; import onboardingMiddleware from "./layers/dms-onboarding/app/middleware/onboarding.global"; import registerPlugin from "./layers/dms-ui/app/plugins/register"; @@ -147,7 +149,9 @@ function registerPlugins(sdk: Parameters[0]): void { } sdk.registerPlugin(colorModePlugin); sdk.registerPlugin(interfaceScalePlugin); + sdk.registerPlugin(accessibilityPlugin); sdk.registerPlugin(languageSyncPlugin); + sdk.registerPlugin(regionalPreferencesPlugin); sdk.registerPlugin(seoPlugin); sdk.registerPlugin(registerPlugin); sdk.registerPlugin(shortcutsPlugin); diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthBackLink.vue b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthBackLink.vue new file mode 100644 index 000000000..9b10bb53f --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthBackLink.vue @@ -0,0 +1,21 @@ + + + diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthCodeInput.vue b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthCodeInput.vue new file mode 100644 index 000000000..f9c9837b0 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthCodeInput.vue @@ -0,0 +1,39 @@ + + + diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthFormAlert.vue b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthFormAlert.vue new file mode 100644 index 000000000..c67cd7732 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthFormAlert.vue @@ -0,0 +1,26 @@ + + + diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthNewPasswordField.vue b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthNewPasswordField.vue new file mode 100644 index 000000000..8d7d53a0e --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthNewPasswordField.vue @@ -0,0 +1,50 @@ + + + diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthPasswordInput.vue b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthPasswordInput.vue new file mode 100644 index 000000000..2c34ded25 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthPasswordInput.vue @@ -0,0 +1,61 @@ + + + diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthResendCode.vue b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthResendCode.vue new file mode 100644 index 000000000..9f23d4c99 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-auth/app/components/AuthResendCode.vue @@ -0,0 +1,51 @@ + + + diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/components/OAuthButtons.vue b/packages/dms/frontend-vue/layers/dms-auth/app/components/OAuthButtons.vue index e49016d82..4afcd3238 100644 --- a/packages/dms/frontend-vue/layers/dms-auth/app/components/OAuthButtons.vue +++ b/packages/dms/frontend-vue/layers/dms-auth/app/components/OAuthButtons.vue @@ -31,7 +31,8 @@ function startUrl(providerId: string): string { diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/composables/useAuthFormError.ts b/packages/dms/frontend-vue/layers/dms-auth/app/composables/useAuthFormError.ts new file mode 100644 index 000000000..613c6496c --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-auth/app/composables/useAuthFormError.ts @@ -0,0 +1,27 @@ +export interface AuthFormError { + title: string; + description: string; +} + +/** + * The error an auth form shows inline, above its fields, instead of a toast + * that disappears before it is read. Translated when set, so it can be set + * after an `await` without the i18n context. + */ +export function useAuthFormError() { + const { t } = useI18n(); + const formError = ref(null); + + function showFormError(error: unknown, titleKey: string): void { + formError.value = { + title: t(titleKey), + description: resolveApiMessage(t, resolveApiErrorMessage(error)), + }; + } + + function clearFormError(): void { + formError.value = null; + } + + return { formError, showFormError, clearFormError }; +} diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/2fa.vue b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/2fa.vue index e62908ffb..493432aa6 100644 --- a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/2fa.vue +++ b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/2fa.vue @@ -1,28 +1,46 @@ diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/accounts.vue b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/accounts.vue index 62856e9f3..e72c65b7a 100644 --- a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/accounts.vue +++ b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/accounts.vue @@ -1,4 +1,8 @@ diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/backup.vue b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/backup.vue index ffb216450..ca5551fce 100644 --- a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/backup.vue +++ b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/backup.vue @@ -1,8 +1,14 @@ diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/forgot-validation.vue b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/forgot-validation.vue index 5cb8df7aa..b80593093 100644 --- a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/forgot-validation.vue +++ b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/forgot-validation.vue @@ -1,13 +1,19 @@ diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/forgot.vue b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/forgot.vue index 0e3f56a02..d5de5c988 100644 --- a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/forgot.vue +++ b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/forgot.vue @@ -1,13 +1,19 @@ diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/login.vue b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/login.vue index 43c9820eb..c63a9a796 100644 --- a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/login.vue +++ b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/login.vue @@ -1,17 +1,23 @@ + + + + + + + + + + + - - {{ $t(link.label) }} - + + + + + + + + + +
+ + +
- - +
+ +
+ + {{ $t(link.label) }} + +
+ diff --git a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/recover-success.vue b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/recover-success.vue index 7c9c34a90..192efea1f 100644 --- a/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/recover-success.vue +++ b/packages/dms/frontend-vue/layers/dms-auth/app/custom-pages/auth/recover-success.vue @@ -1,15 +1,22 @@ - diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/components/layout/StageCard.vue b/packages/dms/frontend-vue/layers/dms-layout/app/components/layout/StageCard.vue new file mode 100644 index 000000000..ed0f95ad5 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/components/layout/StageCard.vue @@ -0,0 +1,85 @@ + + + diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/components/navigation/CollapsedMenuItem.vue b/packages/dms/frontend-vue/layers/dms-layout/app/components/navigation/CollapsedMenuItem.vue index 9518b86d6..3ff3750b0 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/components/navigation/CollapsedMenuItem.vue +++ b/packages/dms/frontend-vue/layers/dms-layout/app/components/navigation/CollapsedMenuItem.vue @@ -20,6 +20,12 @@ const theme = tv({ childList: "space-y-0.5", collapsibleTrigger: "w-full justify-between", collapsibleContent: "mt-0.5 space-y-0.5", + // "Preview as role" only: the badge the rail puts on a locked entry's + // icon, and the lock a nested locked entry ends with (toned by state). + topLevelLock: + "absolute -top-0.5 -right-0.5 size-3.5 rounded-full bg-default", + lock: "ml-auto size-3.5 shrink-0", + groupLock: "size-3.5 shrink-0", }, variants: { isTopLevel: { @@ -32,8 +38,30 @@ const theme = tv({ isAccent: { true: { topLevelButton: "text-primary", link: "text-primary" }, }, + // Same hatches as the expanded menu (NavigationMenu.vue): red for an + // entry the role could not open, orange for one it opens partially. + previewState: { + hidden: { + topLevelButton: + "text-muted bg-[repeating-linear-gradient(-45deg,color-mix(in_srgb,var(--ui-error)_9%,transparent)_0_6px,transparent_6px_12px)]", + link: "text-muted bg-[repeating-linear-gradient(-45deg,color-mix(in_srgb,var(--ui-error)_9%,transparent)_0_6px,transparent_6px_12px)]", + topLevelLock: "text-error", + lock: "text-error", + groupLock: "text-error", + }, + partial: { + topLevelButton: + "bg-[repeating-linear-gradient(-45deg,color-mix(in_srgb,var(--ui-warning)_12%,transparent)_0_6px,transparent_6px_12px)]", + link: "bg-[repeating-linear-gradient(-45deg,color-mix(in_srgb,var(--ui-warning)_12%,transparent)_0_6px,transparent_6px_12px)]", + topLevelLock: "text-warning", + lock: "text-warning", + groupLock: "text-warning", + }, + }, }, }); + +const PREVIEW_LOCK_ICON = "i-ph-lock-simple"; - - diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/components/profile/ProfileSessions.vue b/packages/dms/frontend-vue/layers/dms-layout/app/components/profile/ProfileSessions.vue deleted file mode 100644 index 36b0b9257..000000000 --- a/packages/dms/frontend-vue/layers/dms-layout/app/components/profile/ProfileSessions.vue +++ /dev/null @@ -1,321 +0,0 @@ - - - diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/components/profile/ProfileTwoFactor.vue b/packages/dms/frontend-vue/layers/dms-layout/app/components/profile/ProfileTwoFactor.vue deleted file mode 100644 index de1ca9db2..000000000 --- a/packages/dms/frontend-vue/layers/dms-layout/app/components/profile/ProfileTwoFactor.vue +++ /dev/null @@ -1,501 +0,0 @@ - - - diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/general/useAccessibilityPreferences.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/general/useAccessibilityPreferences.ts new file mode 100644 index 000000000..f7106b14e --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/general/useAccessibilityPreferences.ts @@ -0,0 +1,52 @@ +import { computed, type ComputedRef, type WritableComputedRef } from "vue"; +import { + ACCESSIBILITY_COOKIE, + DEFAULT_ACCESSIBILITY_PREFERENCES, + parseAccessibilityPreferences, + type AccessibilityPreferences, + type ReduceMotionPreference, +} from "#dms-ui/app/utils/accessibilityPreferences"; + +const ACCESSIBILITY_COOKIE_MAX_AGE = 60 * 60 * 24 * 365; + +export interface AccessibilityPreferencesRefs { + /** The complete preferences, read from the cookie. */ + preferences: ComputedRef; + reduceMotion: WritableComputedRef; + increaseContrast: WritableComputedRef; + underlineLinks: WritableComputedRef; +} + +/** + * The accessibility preferences of this device, from the `dms-accessibility` + * cookie shared by every caller. Each field is a writable ref: assigning it + * rewrites the cookie, and the `` classes follow. The server reads the + * same cookie, so the first paint already has them. + */ +export const useAccessibilityPreferences = (): AccessibilityPreferencesRefs => { + const cookie = useDmsCookie(ACCESSIBILITY_COOKIE, { + default: () => ({ ...DEFAULT_ACCESSIBILITY_PREFERENCES }), + maxAge: ACCESSIBILITY_COOKIE_MAX_AGE, + }); + const preferences = computed(() => + parseAccessibilityPreferences(cookie.value), + ); + + function field( + key: K, + ): WritableComputedRef { + return computed({ + get: () => preferences.value[key], + set: (value) => { + cookie.value = { ...preferences.value, [key]: value }; + }, + }); + } + + return { + preferences, + reduceMotion: field("reduceMotion"), + increaseContrast: field("increaseContrast"), + underlineLinks: field("underlineLinks"), + }; +}; diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/general/useSidebarStartCollapsed.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/general/useSidebarStartCollapsed.ts new file mode 100644 index 000000000..c70a9e5da --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/general/useSidebarStartCollapsed.ts @@ -0,0 +1,14 @@ +export const SIDEBAR_START_COLLAPSED_COOKIE = "dms-sidebar-start-collapsed"; +const SIDEBAR_START_COLLAPSED_COOKIE_MAX_AGE = 60 * 60 * 24 * 365; + +/** + * Whether the dashboard opens with the sidebar collapsed on this device, as a + * cookie ref shared by every caller. The server reads the same cookie, so the + * first render already has the right sidebar width. + */ +export const useSidebarStartCollapsed = () => { + return useDmsCookie(SIDEBAR_START_COLLAPSED_COOKIE, { + default: () => false, + maxAge: SIDEBAR_START_COLLAPSED_COOKIE_MAX_AGE, + }); +}; diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/layout/usePageHeaderActions.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/layout/usePageHeaderActions.ts new file mode 100644 index 000000000..e492073cd --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/layout/usePageHeaderActions.ts @@ -0,0 +1,42 @@ +import { + inject, + onBeforeUnmount, + provide, + shallowRef, + type InjectionKey, + type ShallowRef, + type VNodeChild, +} from "vue"; + +/** Renders the actions shown on the right of the page header. */ +export type PageHeaderActionsRender = () => VNodeChild; + +const PAGE_HEADER_ACTIONS_KEY: InjectionKey< + ShallowRef +> = Symbol("dms:page-header-actions"); + +/** + * Called by a layout that renders a page header: returns the render function + * the page in its slot asked for, if any. + */ +export const providePageHeaderActions = (): ShallowRef => { + const actions = shallowRef(null); + provide(PAGE_HEADER_ACTIONS_KEY, actions); + return actions; +}; + +/** + * Puts actions in the page header (a primary button, a status pill…) from a + * page rendered inside a layout. The actions are removed when the page + * unmounts. Outside such a layout the call does nothing. + * + * @param render Render function of the actions, e.g. `() => h(UButton, …)` + */ +export const usePageHeaderActions = (render: PageHeaderActionsRender): void => { + const actions = inject(PAGE_HEADER_ACTIONS_KEY, null); + if (!actions) return; + actions.value = render; + onBeforeUnmount(() => { + if (actions.value === render) actions.value = null; + }); +}; diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotificationCatalog.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotificationCatalog.ts new file mode 100644 index 000000000..f468e701a --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotificationCatalog.ts @@ -0,0 +1,85 @@ +export type NotificationTogglePermission = "allowed" | "forbidden" | "default"; + +export interface NotificationCategory { + id: string; + labelKey: string; + descriptionKey?: string; + icon: string; + togglePermission?: NotificationTogglePermission; + /** Short module tag (`SaaS`) shown on the category and its notifications. */ + tagKey?: string; +} + +export interface NotificationSubject { + id: string; + category: NotificationCategory; + labelKey: string; + descriptionKey?: string; + togglePermission?: NotificationTogglePermission; + badgeKey?: string; + /** Set by the server: the user may not turn the subject off. */ + locked?: boolean; +} + +interface NotificationCatalogResponse { + categories: NotificationCategory[]; + subjects: NotificationSubject[]; +} + +export const buildPreferenceKey = (categoryId: string, subjectId: string) => + `${categoryId}:${subjectId}`; + +export const subjectPreferenceKey = (subject: NotificationSubject) => + buildPreferenceKey(subject.category.id, subject.id); + +/** + * The registered notification categories and subjects, loaded once and + * shared by the preferences matrix and the inbox (which tags each + * notification with its source). + */ +export const useNotificationCatalog = () => { + const { $authFetch } = useAuthFetch(); + const categories = useDmsState( + "notification-catalog-categories", + () => [], + ); + const subjects = useDmsState( + "notification-catalog-subjects", + () => [], + ); + const isLoaded = useDmsState( + "notification-catalog-loaded", + () => false, + ); + + const loadCatalog = async () => { + const response = await $authFetch( + "/settings/user/notifications/categories", + ); + categories.value = response.categories; + subjects.value = response.subjects; + isLoaded.value = true; + }; + + const subjectsOf = (categoryId: string) => + subjects.value.filter((subject) => subject.category.id === categoryId); + + const findCategory = (categoryId: string) => + categories.value.find((category) => category.id === categoryId); + + const findSubject = (categoryId: string, subjectId?: string) => + subjects.value.find( + (subject) => + subject.category.id === categoryId && subject.id === subjectId, + ); + + return { + categories, + subjects, + isLoaded, + loadCatalog, + subjectsOf, + findCategory, + findSubject, + }; +}; diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotificationPreferences.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotificationPreferences.ts new file mode 100644 index 000000000..2786fe862 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotificationPreferences.ts @@ -0,0 +1,131 @@ +import { + type NotificationCategory, + type NotificationSubject, + subjectPreferenceKey, + useNotificationCatalog, +} from "./useNotificationCatalog"; + +/** Instant-save feedback of one matrix row. */ +export type PreferenceRowState = "idle" | "saving" | "saved"; + +type PreferenceMap = Record; + +const PREFERENCES_URL = "/settings/user/notifications/preferences"; +/** How long a row keeps its "Saved" tick. */ +const SAVED_STATE_DURATION_MS = 2000; + +/** + * State of the notification preferences matrix. Each switch saves on its + * own (PATCH of the keys it changes); a failed save puts the switches back + * and keeps the attempted change so it can be retried. + */ +export const useNotificationPreferences = () => { + const { $authFetch } = useAuthFetch(); + const catalog = useNotificationCatalog(); + const preferences = ref({}); + const rowStates = ref>({}); + const failedChanges = ref(null); + const isLoading = ref(true); + const loadFailed = ref(false); + const savedTimers = new Map>(); + + const isEnabled = (subject: NotificationSubject) => + preferences.value[subjectPreferenceKey(subject)] ?? true; + + const rowState = (subject: NotificationSubject): PreferenceRowState => + rowStates.value[subjectPreferenceKey(subject)] ?? "idle"; + + const toggleableSubjectsOf = (category: NotificationCategory) => + catalog.subjectsOf(category.id).filter((subject) => !subject.locked); + + const setRowStates = (keys: string[], state: PreferenceRowState) => { + const next = { ...rowStates.value }; + for (const key of keys) { + clearTimeout(savedTimers.get(key)); + next[key] = state; + } + rowStates.value = next; + }; + + const markSaved = (keys: string[]) => { + setRowStates(keys, "saved"); + for (const key of keys) { + savedTimers.set( + key, + setTimeout(() => setRowStates([key], "idle"), SAVED_STATE_DURATION_MS), + ); + } + }; + + const save = async (changes: PreferenceMap) => { + const keys = Object.keys(changes); + if (keys.length === 0) return; + const previous = Object.fromEntries( + keys.map((key) => [key, preferences.value[key] ?? true]), + ); + failedChanges.value = null; + preferences.value = { ...preferences.value, ...changes }; + setRowStates(keys, "saving"); + try { + await $authFetch(PREFERENCES_URL, { method: "PATCH", body: changes }); + markSaved(keys); + } catch { + preferences.value = { ...preferences.value, ...previous }; + setRowStates(keys, "idle"); + failedChanges.value = changes; + } + }; + + const toggleSubject = (subject: NotificationSubject, enabled: boolean) => + save({ [subjectPreferenceKey(subject)]: enabled }); + + const toggleCategory = (category: NotificationCategory, enabled: boolean) => + save( + Object.fromEntries( + toggleableSubjectsOf(category).map((subject) => [ + subjectPreferenceKey(subject), + enabled, + ]), + ), + ); + + const retry = async () => { + if (failedChanges.value) await save(failedChanges.value); + }; + + const load = async () => { + isLoading.value = true; + loadFailed.value = false; + try { + const [stored] = await Promise.all([ + $authFetch(PREFERENCES_URL), + catalog.loadCatalog(), + ]); + preferences.value = stored ?? {}; + } catch { + loadFailed.value = true; + } finally { + isLoading.value = false; + } + }; + + onBeforeUnmount(() => { + for (const timer of savedTimers.values()) clearTimeout(timer); + }); + + return { + categories: catalog.categories, + subjectsOf: catalog.subjectsOf, + preferences, + failedChanges, + isLoading, + loadFailed, + isEnabled, + rowState, + toggleableSubjectsOf, + toggleSubject, + toggleCategory, + retry, + load, + }; +}; diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotifications.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotifications.ts index e302663db..c158c9ccf 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotifications.ts +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/notification/useNotifications.ts @@ -1,5 +1,13 @@ import { NotificationEvents } from "./types/events"; +/** Icon well colour a sender may set on a notification. */ +export type NotificationTone = + | "neutral" + | "accent" + | "success" + | "warning" + | "error"; + export interface UserNotification { _id: string; userId: string; @@ -10,17 +18,51 @@ export interface UserNotification { linkTo: string | null; isRead: boolean; categoryId: string; + subjectId?: string; + tone?: NotificationTone | null; createdAt: string; updatedAt: string; } +/** Tabs of the settings inbox. */ +export type NotificationInboxFilter = "all" | "unread"; + +/** Totals behind the All and Unread inbox tabs. */ +export interface NotificationCounts { + all: number; + unread: number; +} + +interface MarkAllReadResponse { + success: boolean; + ids?: string[]; +} + +const API_BASE = "/settings/user/notifications"; const NOTIFICATION_COMPONENT_ID = "global-notifications"; const NOTIFICATIONS_PAGE_SIZE = 20; +const buildListUrl = (offset: number, filter: NotificationInboxFilter) => { + const query = new URLSearchParams({ + limit: String(NOTIFICATIONS_PAGE_SIZE), + offset: String(offset), + }); + if (filter === "unread") query.set("filter", "unread"); + return `${API_BASE}/list?${query.toString()}`; +}; + +/** + * Shared notification state: the header bell (unread count, popover feed) + * and the settings inbox (its own filtered feed and tab totals) read and + * update the same rows, so a change made in one shows in the other. + */ export const useNotifications = () => { const { $authFetch } = useAuthFetch(); const { sendComponentEvent } = useComponentEvent(); - const unreadCount = useDmsState("notifications-unread-count", () => 0); + const unreadCount = useDmsState( + "notifications-unread-count", + () => 0, + ); const unreadPreview = useDmsState( "notifications-unread-preview", () => [], @@ -31,19 +73,86 @@ export const useNotifications = () => { ); const offset = useDmsState("notifications-offset", () => 0); const hasMore = useDmsState("notifications-has-more", () => true); + const inboxFilter = useDmsState( + "notifications-inbox-filter", + () => "all", + ); + const inboxItems = useDmsState( + "notifications-inbox-items", + () => [], + ); + const inboxHasMore = useDmsState( + "notifications-inbox-has-more", + () => true, + ); + const inboxCounts = useDmsState( + "notifications-inbox-counts", + () => ({ all: 0, unread: 0 }), + ); + + const lists = [notifications, unreadPreview, inboxItems]; + + const setReadState = (ids: string[], isRead: boolean) => { + const idsSet = new Set(ids); + for (const list of lists) { + list.value = list.value.map((n) => + idsSet.has(n._id) ? { ...n, isRead } : n, + ); + } + }; + + const setAllRead = () => { + for (const list of lists) { + list.value = list.value.map((n) => ({ ...n, isRead: true })); + } + unreadPreview.value = []; + }; + + const removeFromLists = (ids: string[]) => { + const idsSet = new Set(ids); + for (const list of lists) { + list.value = list.value.filter((n) => !idsSet.has(n._id)); + } + }; + + const emitRead = (ids: string[]) => { + for (const notificationId of ids) { + sendComponentEvent( + NotificationEvents.NOTIFICATION_READ, + NOTIFICATION_COMPONENT_ID, + { notificationId }, + ); + } + }; + + const emitCount = () => { + sendComponentEvent( + NotificationEvents.COUNT_CHANGED, + NOTIFICATION_COMPONENT_ID, + { count: unreadCount.value }, + ); + }; const fetchUnreadCount = async () => { const data = await $authFetch<{ count: number }>( - "/settings/user/notifications/unread-count", + `${API_BASE}/unread-count`, ); if (data) { unreadCount.value = data.count; } }; + /** Refreshes the inbox tab totals, and the bell count with them. */ + const fetchCounts = async () => { + const data = await $authFetch(`${API_BASE}/counts`); + if (!data) return; + inboxCounts.value = data; + unreadCount.value = data.unread; + }; + const fetchUnreadPreview = async () => { const data = await $authFetch( - "/settings/user/notifications/unread-preview", + `${API_BASE}/unread-preview`, ); if (data) { unreadPreview.value = data; @@ -58,7 +167,7 @@ export const useNotifications = () => { } const data = await $authFetch( - `/settings/user/notifications/list?limit=${NOTIFICATIONS_PAGE_SIZE}&offset=${offset.value}`, + buildListUrl(offset.value, "all"), ); if (data) { @@ -68,46 +177,55 @@ export const useNotifications = () => { } }; - const markAsRead = async (notificationId: string) => { - await $authFetch( - `/settings/user/notifications/mark-read/${notificationId}`, - { - method: "PUT", - }, + /** Loads the next page of the settings inbox, or its first one on `reset`. */ + const fetchInbox = async (reset = false) => { + if (reset) { + inboxItems.value = []; + inboxHasMore.value = true; + } + + const data = await $authFetch( + buildListUrl(inboxItems.value.length, inboxFilter.value), ); - const updateNotification = (n: UserNotification) => { - if (n._id === notificationId) { - return { ...n, isRead: true }; - } - return n; - }; + if (data) { + const known = new Set(inboxItems.value.map((n) => n._id)); + const fresh = data.filter((n) => !known.has(n._id)); + inboxItems.value = [...inboxItems.value, ...fresh]; + inboxHasMore.value = data.length === NOTIFICATIONS_PAGE_SIZE; + } + }; - notifications.value = notifications.value.map(updateNotification); - unreadPreview.value = unreadPreview.value.map(updateNotification); + const setInboxFilter = async (filter: NotificationInboxFilter) => { + inboxFilter.value = filter; + await Promise.all([fetchInbox(true), fetchCounts()]); + }; - await fetchUnreadCount(); + const markAsRead = async (notificationId: string) => { + await $authFetch(`${API_BASE}/mark-read/${notificationId}`, { + method: "PUT", + }); + setReadState([notificationId], true); + unreadPreview.value = unreadPreview.value.filter((n) => !n.isRead); + await fetchCounts(); + emitRead([notificationId]); + }; - sendComponentEvent( - NotificationEvents.NOTIFICATION_READ, - NOTIFICATION_COMPONENT_ID, - { notificationId }, - ); + const markAsUnread = async (notificationId: string) => { + await $authFetch(`${API_BASE}/mark-unread/${notificationId}`, { + method: "PUT", + }); + setReadState([notificationId], false); + await fetchCounts(); + emitCount(); }; const deleteNotification = async (notificationId: string) => { - await $authFetch(`/settings/user/notifications/delete/${notificationId}`, { + await $authFetch(`${API_BASE}/delete/${notificationId}`, { method: "DELETE", }); - - notifications.value = notifications.value.filter( - (n) => n._id !== notificationId, - ); - unreadPreview.value = unreadPreview.value.filter( - (n) => n._id !== notificationId, - ); - - await fetchUnreadCount(); + removeFromLists([notificationId]); + await fetchCounts(); sendComponentEvent( NotificationEvents.NOTIFICATION_DELETED, @@ -116,72 +234,62 @@ export const useNotifications = () => { ); }; - const markAllAsRead = async () => { - await $authFetch("/settings/user/notifications/mark-all-read", { + /** Marks everything read and returns the ids it changed, for an undo. */ + const markAllAsRead = async (): Promise => { + const response = await $authFetch( + `${API_BASE}/mark-all-read`, + { method: "PUT" }, + ); + setAllRead(); + await fetchCounts(); + emitCount(); + return response?.ids ?? []; + }; + + /** Reopens the notifications a "mark all as read" changed. */ + const undoMarkAllAsRead = async (ids: string[]) => { + if (ids.length === 0) return; + await $authFetch(`${API_BASE}/mark-unread`, { method: "PUT", + body: { ids }, }); - - notifications.value = notifications.value.map((n) => ({ - ...n, - isRead: true, - })); - unreadPreview.value = []; - - await fetchUnreadCount(); - - sendComponentEvent( - NotificationEvents.COUNT_CHANGED, - NOTIFICATION_COMPONENT_ID, - { count: 0 }, - ); + setReadState(ids, false); + await fetchCounts(); + emitCount(); }; const deleteAll = async () => { - await $authFetch("/settings/user/notifications/delete-all", { + await $authFetch(`${API_BASE}/delete-all`, { method: "DELETE", }); - notifications.value = []; - unreadPreview.value = []; + for (const list of lists) list.value = []; unreadCount.value = 0; + inboxCounts.value = { all: 0, unread: 0 }; hasMore.value = false; - - sendComponentEvent( - NotificationEvents.COUNT_CHANGED, - NOTIFICATION_COMPONENT_ID, - { count: 0 }, - ); + inboxHasMore.value = false; + emitCount(); }; const handleRemoteRead = async (ids: string[]) => { if (ids.length === 0) return; - const idsSet = new Set(ids); - const updateNotification = (n: UserNotification) => - idsSet.has(n._id) ? { ...n, isRead: true } : n; - notifications.value = notifications.value.map(updateNotification); - unreadPreview.value = unreadPreview.value.map(updateNotification); - await fetchUnreadCount(); - for (const notificationId of ids) { - sendComponentEvent( - NotificationEvents.NOTIFICATION_READ, - NOTIFICATION_COMPONENT_ID, - { notificationId }, - ); - } + setReadState(ids, true); + unreadPreview.value = unreadPreview.value.filter((n) => !n.isRead); + await fetchCounts(); + emitRead(ids); + }; + + const handleRemoteUnread = async (ids: string[]) => { + if (ids.length === 0) return; + setReadState(ids, false); + await fetchCounts(); + emitCount(); }; const handleRemoteAllRead = async () => { - notifications.value = notifications.value.map((n) => ({ - ...n, - isRead: true, - })); - unreadPreview.value = []; - await fetchUnreadCount(); - sendComponentEvent( - NotificationEvents.COUNT_CHANGED, - NOTIFICATION_COMPONENT_ID, - { count: 0 }, - ); + setAllRead(); + await fetchCounts(); + emitCount(); }; const handleIncomingNotification = (incoming: UserNotification) => { @@ -191,17 +299,18 @@ export const useNotifications = () => { if (isAlreadyKnown) return; notifications.value = [incoming, ...notifications.value]; unreadPreview.value = [incoming, ...unreadPreview.value]; + inboxItems.value = [incoming, ...inboxItems.value]; unreadCount.value += 1; + inboxCounts.value = { + all: inboxCounts.value.all + 1, + unread: inboxCounts.value.unread + 1, + }; sendComponentEvent( NotificationEvents.NOTIFICATION_RECEIVED, NOTIFICATION_COMPONENT_ID, { notification: incoming }, ); - sendComponentEvent( - NotificationEvents.COUNT_CHANGED, - NOTIFICATION_COMPONENT_ID, - { count: unreadCount.value }, - ); + emitCount(); }; return { @@ -209,15 +318,25 @@ export const useNotifications = () => { unreadPreview, notifications, hasMore, + inboxFilter, + inboxItems, + inboxHasMore, + inboxCounts, fetchUnreadCount, + fetchCounts, fetchUnreadPreview, fetchNotifications, + fetchInbox, + setInboxFilter, markAsRead, + markAsUnread, deleteNotification, markAllAsRead, + undoMarkAllAsRead, deleteAll, handleIncomingNotification, handleRemoteRead, + handleRemoteUnread, handleRemoteAllRead, }; }; diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/page/useModuleHistory.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/page/useModuleHistory.ts index f10b78e46..c7f91c4e2 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/composables/page/useModuleHistory.ts +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/page/useModuleHistory.ts @@ -1,40 +1,88 @@ -const MODULE_HISTORY_STATE_KEY = "dms-moduleHistory"; +const MODULE_HISTORY_COOKIE = "dms-module-history"; +// Kept for a year and bounded, so the cookie stays small on every request. +const MODULE_HISTORY_MAX_AGE_SECONDS = 60 * 60 * 24 * 365; +const MODULE_HISTORY_MAX_ENTRIES = 12; +const MODULE_HISTORY_MAX_PATH_LENGTH = 300; export interface ModuleHistoryEntry { moduleId: string; path: string; + /** Epoch milliseconds of the last visit; 0 when unknown. */ + visitedAt: number; } export interface ModuleHistoryApi { record: (moduleId: string, path: string) => void; getLast: (moduleId: string) => string | null; + /** Visited modules with their last path, ordered oldest to newest visit. */ entries: ComputedRef; } +interface StoredVisit { + path: string; + at: number; +} + +type StoredHistory = Record; + +/** + * Reads whatever the cookie holds into a clean history, dropping anything + * malformed: a hand-edited cookie or an older shape must never break the + * modules page or the command palette. + */ +function normalizeHistory(raw: unknown): StoredHistory { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; + const result: StoredHistory = {}; + for (const [moduleId, value] of Object.entries(raw)) { + if (!value || typeof value !== "object") continue; + const { path, at } = value as Partial; + if (typeof path !== "string" || !path.startsWith("/")) continue; + result[moduleId] = { path, at: typeof at === "number" ? at : 0 }; + } + return result; +} + +/** + * Last page visited in each module, kept in a cookie so it survives reloads + * and the server renders the same catalog links and "recently used" order as + * the browser. + */ export const useModuleHistory = (): ModuleHistoryApi => { - const history = useDmsState>( - MODULE_HISTORY_STATE_KEY, - () => ({}), - ); + const cookie = useDmsCookie(MODULE_HISTORY_COOKIE, { + default: () => ({}), + maxAge: MODULE_HISTORY_MAX_AGE_SECONDS, + sameSite: "lax", + }); + + const history = computed(() => normalizeHistory(cookie.value)); function record(moduleId: string, path: string): void { - if (!moduleId || !path) return; + if (!moduleId || !path || path.length > MODULE_HISTORY_MAX_PATH_LENGTH) { + return; + } // Re-insert the key so a revisited module moves to the end: a plain // spread would keep its first-visit position and break the - // oldest-to-newest ordering `entries` guarantees. + // oldest-to-newest ordering `entries` guarantees. The oldest visits + // fall off once the history is full. const { [moduleId]: _previous, ...others } = history.value; - history.value = { ...others, [moduleId]: path }; + const kept = Object.entries(others).slice( + -(MODULE_HISTORY_MAX_ENTRIES - 1), + ); + cookie.value = { + ...Object.fromEntries(kept), + [moduleId]: { path, at: Date.now() }, + }; } function getLast(moduleId: string): string | null { - return history.value[moduleId] ?? null; + return history.value[moduleId]?.path ?? null; } - /** Visited modules with their last path, ordered oldest to newest visit. */ const entries = computed(() => - Object.entries(history.value).map(([moduleId, path]) => ({ + Object.entries(history.value).map(([moduleId, visit]) => ({ moduleId, - path, + path: visit.path, + visitedAt: visit.at, })), ); diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/page/useModulesListing.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/page/useModulesListing.ts index 858da4112..2c2a25a85 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/composables/page/useModulesListing.ts +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/page/useModulesListing.ts @@ -1,39 +1,49 @@ -type ModulesListingEntry = ModuleInfo & { - hasAccess: boolean; - landingSlug: string; -}; +import type { ModuleCatalogEntry } from "../../types/page"; + +/** + * Why the catalog could not be loaded: `forbidden` when the server refused + * the caller (not a platform owner), `failed` for anything else. `status` is + * the HTTP status when the server answered at all. + */ +export interface ModulesListingError { + kind: "forbidden" | "failed"; + status?: number; +} const STATE_KEY_MODULES = "dms-modulesListing"; const STATE_KEY_LOADING = "dms-modulesListingLoading"; const STATE_KEY_ERROR = "dms-modulesListingError"; +const STATE_KEY_FETCHED_AT = "dms-modulesListingFetchedAt"; +// A listing younger than this is fresh enough to show without refetching: +// it also covers the hydration right after a server render. +const REVALIDATE_AFTER_MS = 30_000; +export const ENDPOINT_MODULES_LISTING = "/dms/modules-listing"; const IN_FLIGHT_MODULES_LISTING_KEY = "__dmsInFlightModulesListing"; -const ENDPOINT_MODULES_LISTING = "/dms/modules-listing"; -const ERROR_FORBIDDEN_MESSAGE = "Forbidden: only owners can list modules"; -const ERROR_UNKNOWN_MESSAGE = "Unknown error loading modules listing"; -function isForbiddenError(error: unknown): boolean { - const status = error as - | { response?: { status?: number }; statusCode?: number } +function readStatus(error: unknown): number | undefined { + const details = error as + | { response?: { status?: number }; statusCode?: number; status?: number } | undefined; - if (!status) return false; - if (status.response?.status === HTTP_FORBIDDEN) return true; - if (status.statusCode === HTTP_FORBIDDEN) return true; - return false; + return details?.response?.status ?? details?.statusCode ?? details?.status; } -function extractErrorMessage(error: unknown): string { - if (isForbiddenError(error)) return ERROR_FORBIDDEN_MESSAGE; - if (error instanceof Error) return error.message; - return ERROR_UNKNOWN_MESSAGE; +function toListingError(error: unknown): ModulesListingError { + const status = readStatus(error); + if (status === HTTP_FORBIDDEN) return { kind: "forbidden", status }; + return { kind: "failed", status }; } export const useModulesListing = () => { - const modules = useDmsState( + const modules = useDmsState( STATE_KEY_MODULES, () => undefined, ); const isLoading = useDmsState(STATE_KEY_LOADING, () => false); - const loadingError = useDmsState(STATE_KEY_ERROR, () => null); + const loadingError = useDmsState( + STATE_KEY_ERROR, + () => null, + ); + const fetchedAt = useDmsState(STATE_KEY_FETCHED_AT, () => 0); // Held on the DMS app, like the in-flight fetches of useSiteLayout: every // caller writes the same listing state, so they share one fetch. Not module @@ -50,17 +60,26 @@ export const useModulesListing = () => { }, }; - function fetchModulesListing(): Promise { + /** + * Fetches the catalog. With `keepOnFailure`, a failed request leaves the + * modules already on screen in place (a background revalidation must not + * blank the page); otherwise the failure replaces them with the error. + */ + function fetchModulesListing(keepOnFailure = false): Promise { const { $authFetch } = useAuthFetch(); isLoading.value = true; - loadingError.value = null; + if (!keepOnFailure) loadingError.value = null; - const promise = $authFetch(ENDPOINT_MODULES_LISTING) + const promise = $authFetch(ENDPOINT_MODULES_LISTING) .then((result) => { modules.value = result; + loadingError.value = null; + fetchedAt.value = Date.now(); }) .catch((error: unknown) => { - loadingError.value = extractErrorMessage(error); + const listingError = toListingError(error); + if (keepOnFailure && listingError.kind === "failed") return; + loadingError.value = listingError; modules.value = undefined; }) .finally(() => { @@ -83,20 +102,37 @@ export const useModulesListing = () => { await fetchModulesListing(); } + /** + * Loads the catalog again on request (Refresh, Try again): the current list + * stays on screen while loading, and a failure is shown, not swallowed. + */ async function refresh(): Promise { if (inFlightLoadingPromise.value) { await inFlightLoadingPromise.value; } - modules.value = undefined; - loadingError.value = null; await fetchModulesListing(); } + /** + * Reloads statuses and readouts while keeping the current list on screen, + * unless the listing is only a few seconds old: readouts are live figures, + * so a later revisit should not show stale ones. + */ + async function revalidate(): Promise { + if (inFlightLoadingPromise.value) { + await inFlightLoadingPromise.value; + return; + } + if (Date.now() - fetchedAt.value < REVALIDATE_AFTER_MS) return; + await fetchModulesListing(true); + } + return { modules, isLoading, loadingError, loadModulesListing, refresh, + revalidate, }; }; diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/activity/buildAccountActivity.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/activity/buildAccountActivity.ts new file mode 100644 index 000000000..0b2b60bbe --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/activity/buildAccountActivity.ts @@ -0,0 +1,336 @@ +import type { DmsTone } from "#dms-ui/app/utils/tone"; + +/** Events the backend lists (`GET /settings/user/profile/activity`). */ +export type AccountActivityType = + | "session_started" + | "sign_in" + | "password_changed" + | "password_reset" + | "email_changed" + | "two_factor_enabled" + | "two_factor_disabled" + | "backup_codes_generated" + | "login_method_added" + | "account_created" + | "workspace_joined" + | "invite_sent" + | "collaborator_joined"; + +/** One event of the viewer's own account, as the backend answers it. */ +export interface AccountActivityEvent { + id: string; + type: AccountActivityType | string; + /** ISO date. */ + date: string; + browser?: string; + os?: string; + deviceType?: string; + /** Sign-in alert: "Chrome on Windows". */ + device?: string; + ip?: string; + location?: string; + current?: boolean; + method?: string; + provider?: string; + email?: string; + workspace?: string; + actor?: string; + owner?: boolean; +} + +/** A literal, or an i18n key whose params may be texts themselves. */ +export type ActivityText = + | { literal: string } + | { key: string; params?: Record }; + +type Translate = (key: string, params?: Record) => string; + +/** One row of the card, before translation. */ +export interface AccountActivityRow { + id: string; + type: string; + icon: string; + tone: DmsTone; + title: ActivityText; + /** Dimmed details, joined by "·". */ + meta: ActivityText[]; + date: string; + /** Page the row leads to, when the viewer can open it. */ + to?: string; + /** Id of that page, which the role preview veils the row by. */ + pageId?: string; +} + +/** Pages the rows and the "View all" link lead to. */ +export const ACTIVITY_SECURITY_PAGE_ID = "settings.user.security"; +export const ACTIVITY_PROFILE_PAGE_ID = "settings.user.profile"; +export const ACTIVITY_NOTIFICATIONS_PAGE_ID = "settings.user.notifications"; +export const ACTIVITY_MEMBERS_PAGE_ID = "settings.user.members"; +export const ACTIVITY_INVITES_PAGE_ID = "settings.user.members.invites"; + +const KEY = "page.settings.overview.activity"; +// "Chrome 150.0.7871.250" reads as "Chrome": the version is noise here. +const BROWSER_VERSION = /\s+[\d.]+$/; +// What the sign-in records when the user agent names no browser or OS. +const UNKNOWN_PART = "unknown"; +const DEVICE_ICONS: Record = { + desktop: "i-ph-desktop", + mobile: "i-ph-device-mobile", + tablet: "i-ph-device-tablet", +}; +const TWO_FACTOR_METHODS = new Set(["totp", "email"]); + +interface EventLook { + icon: string; + tone: DmsTone; + pageId: string; + /** Section of the page the row scrolls to. */ + anchor?: string; +} + +const LOOKS: Record = { + session_started: { + icon: DEVICE_ICONS.desktop!, + tone: "info", + pageId: ACTIVITY_SECURITY_PAGE_ID, + anchor: "sessions", + }, + sign_in: { + icon: "i-ph-sign-in", + tone: "info", + pageId: ACTIVITY_SECURITY_PAGE_ID, + anchor: "sessions", + }, + password_changed: { + icon: "i-ph-password", + tone: "neutral", + pageId: ACTIVITY_SECURITY_PAGE_ID, + anchor: "password", + }, + password_reset: { + icon: "i-ph-key", + tone: "warning", + pageId: ACTIVITY_SECURITY_PAGE_ID, + anchor: "password", + }, + email_changed: { + icon: "i-ph-envelope-simple", + tone: "neutral", + pageId: ACTIVITY_SECURITY_PAGE_ID, + anchor: "email", + }, + two_factor_enabled: { + icon: "i-ph-shield-check", + tone: "success", + pageId: ACTIVITY_SECURITY_PAGE_ID, + anchor: "two-factor", + }, + two_factor_disabled: { + icon: "i-ph-shield-warning", + tone: "warning", + pageId: ACTIVITY_SECURITY_PAGE_ID, + anchor: "two-factor", + }, + backup_codes_generated: { + icon: "i-ph-lifebuoy", + tone: "success", + pageId: ACTIVITY_SECURITY_PAGE_ID, + anchor: "two-factor", + }, + login_method_added: { + icon: "i-ph-plugs-connected", + tone: "info", + pageId: ACTIVITY_SECURITY_PAGE_ID, + }, + account_created: { + icon: "i-ph-user-circle-plus", + tone: "accent", + pageId: ACTIVITY_PROFILE_PAGE_ID, + }, + workspace_joined: { + icon: "i-ph-buildings", + tone: "accent", + pageId: ACTIVITY_MEMBERS_PAGE_ID, + }, + invite_sent: { + icon: "i-ph-paper-plane-tilt", + tone: "secondary", + pageId: ACTIVITY_INVITES_PAGE_ID, + }, + collaborator_joined: { + icon: "i-ph-user-plus", + tone: "secondary", + pageId: ACTIVITY_MEMBERS_PAGE_ID, + }, +}; + +const isKnownType = (type: string): type is AccountActivityType => + Object.hasOwn(LOOKS, type); + +const text = ( + key: string, + params?: Record, +): ActivityText => + params ? { key: `${KEY}.${key}`, params } : { key: `${KEY}.${key}` }; + +const literal = (value: string | undefined): ActivityText | undefined => + value ? { literal: value } : undefined; + +const present = ( + entries: Array, +): ActivityText[] => entries.filter((entry): entry is ActivityText => !!entry); + +const devicePart = (value: string | undefined): string => { + const part = (value ?? "").trim(); + return part.toLowerCase() === UNKNOWN_PART ? "" : part; +}; + +/** "Chrome on Windows" from a session's browser and OS, if either is known. */ +function sessionDevice(event: AccountActivityEvent): ActivityText | undefined { + const browser = devicePart(event.browser?.replace(BROWSER_VERSION, "")); + const os = devicePart(event.os); + if (!browser && !os) return undefined; + if (browser && os) return text("device", { browser, os }); + return text("device_single", { device: browser || os }); +} + +function titleOf(event: AccountActivityEvent): ActivityText { + switch (event.type) { + case "session_started": { + const device = sessionDevice(event); + return device + ? text("event.signed_in_on", { device }) + : text("event.signed_in"); + } + case "sign_in": + return event.device + ? text("event.signed_in_on", { device: event.device }) + : text("event.signed_in"); + case "login_method_added": + return event.provider + ? text("event.login_method_added", { provider: event.provider }) + : text("event.login_method_added_unnamed"); + case "workspace_joined": + return event.workspace + ? text("event.workspace_joined", { workspace: event.workspace }) + : text("event.workspace_joined_unnamed"); + case "invite_sent": + return event.email + ? text("event.invite_sent", { email: event.email }) + : text("event.invite_sent_unnamed"); + case "collaborator_joined": + return event.actor + ? text("event.collaborator_joined", { name: event.actor }) + : text("event.collaborator_joined_unnamed"); + default: + return text(`event.${event.type}`); + } +} + +function metaOf(event: AccountActivityEvent): ActivityText[] { + switch (event.type) { + case "session_started": + return present([ + literal(event.location), + literal(event.ip), + event.current && text("this_device"), + ]); + case "sign_in": + return present([literal(event.ip)]); + case "email_changed": + return present([literal(event.email)]); + case "two_factor_enabled": + case "two_factor_disabled": + return present([ + !!event.method && + TWO_FACTOR_METHODS.has(event.method) && + text(`method.${event.method}`), + ]); + case "workspace_joined": + return present([ + event.owner + ? text("as_owner") + : !!event.actor && text("invited_by", { name: event.actor }), + ]); + case "invite_sent": + return present([literal(event.workspace)]); + default: + return []; + } +} + +/** Translates a text, its nested texts first. */ +export function translateActivityText( + value: ActivityText, + t: Translate, +): string { + if ("literal" in value) return value.literal; + if (!value.params) return t(value.key); + const params = Object.fromEntries( + Object.entries(value.params).map(([name, param]) => [ + name, + typeof param === "string" ? param : translateActivityText(param, t), + ]), + ); + return t(value.key, params); +} + +/** + * The card's rows, in the order the backend sent them (newest first). + * Unknown event types are skipped. A row links to its page only when the + * viewer can open it. + * + * @param events Events of the viewer's own account + * @param pages Route of each settings page the viewer can open, by page id + */ +export function buildAccountActivityRows( + events: readonly AccountActivityEvent[], + pages: Readonly>, +): AccountActivityRow[] { + const rows: AccountActivityRow[] = []; + for (const event of events) { + if (!isKnownType(event.type)) continue; + const look = LOOKS[event.type]; + const route = pages[look.pageId]; + const icon = + event.type === "session_started" + ? (DEVICE_ICONS[event.deviceType ?? ""] ?? look.icon) + : look.icon; + rows.push({ + id: event.id, + type: event.type, + icon, + tone: + event.type === "session_started" && event.current + ? "accent" + : look.tone, + title: titleOf(event), + meta: metaOf(event), + date: event.date, + ...(route + ? { + to: look.anchor ? `${route}#${look.anchor}` : route, + pageId: look.pageId, + } + : {}), + }); + } + return rows; +} + +/** + * Where "View all" leads: the notifications inbox, else the Security page, + * whichever the viewer can open first. + */ +export function activityViewAllPage( + pages: Readonly>, +): { to: string; pageId: string } | undefined { + for (const pageId of [ + ACTIVITY_NOTIFICATIONS_PAGE_ID, + ACTIVITY_SECURITY_PAGE_ID, + ]) { + const to = pages[pageId]; + if (to) return { to, pageId }; + } + return undefined; +} diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/activity/useAccountActivity.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/activity/useAccountActivity.ts new file mode 100644 index 000000000..1e9868c7b --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/activity/useAccountActivity.ts @@ -0,0 +1,55 @@ +import { computed, onMounted, ref } from "vue"; +import { useSettingsNavigation } from "../useSettingsNavigation"; +import { + type AccountActivityEvent, + type AccountActivityRow, + activityViewAllPage, + buildAccountActivityRows, +} from "./buildAccountActivity"; + +/** The signed-in user's own events, merged and sorted by the backend. */ +export const ACCOUNT_ACTIVITY_ENDPOINT = "/settings/user/profile/activity"; + +/** + * The rows of the settings overview's "Recent account activity" card. + * + * One request: the backend merges the viewer's sessions, account + * notifications, credential timestamps, memberships and sent invitations, and + * leaves out a source it could not read. A failed request reads as no + * activity. Rows link only to the settings pages the viewer can open. + */ +export function useAccountActivity() { + const { groups } = useSettingsNavigation(); + const { $authFetch } = useAuthFetch(); + + const pages = computed>(() => + Object.fromEntries( + groups.value.flatMap((group) => + group.pages.map((page) => [page.fullId, page.to]), + ), + ), + ); + + const events = ref([]); + const isLoading = ref(true); + + onMounted(async () => { + try { + const response = await $authFetch( + ACCOUNT_ACTIVITY_ENDPOINT, + ); + events.value = Array.isArray(response) ? response : []; + } catch { + events.value = []; + } finally { + isLoading.value = false; + } + }); + + const rows = computed(() => + buildAccountActivityRows(events.value, pages.value), + ); + const viewAll = computed(() => activityViewAllPage(pages.value)); + + return { rows, viewAll, isLoading }; +} diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/profile/useAccountData.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/profile/useAccountData.ts new file mode 100644 index 000000000..aac0ee30d --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/profile/useAccountData.ts @@ -0,0 +1,229 @@ +import UFormField from "@nuxt/ui/components/FormField.vue"; +import UInput from "@nuxt/ui/components/Input.vue"; +import type { Component, Ref } from "vue"; +import { downloadFile } from "#dms-core/app/utils/downloadFile"; +import { useConfirm } from "#dms-ui/app/composables/confirm"; +import type { ConfirmImpact } from "#dms-ui/app/composables/confirm/types"; +import { useSecurityFormat } from "../security/useSecurityFormat"; + +const PROFILE_ENDPOINT = "/settings/user/profile"; +const EXPORT_ENDPOINT = `${PROFILE_ENDPOINT}/account-export`; +const DELETION_ENDPOINT = `${PROFILE_ENDPOINT}/account-deletion`; +const EXPORT_FILE_PREFIX = "dms-account-export"; +const JSON_INDENT = 2; +const ISO_DATE_LENGTH = 10; +const AUTH_ROUTE = "/auth"; +const I18N = "page.settings.profile.data"; + +/** Why the account cannot be deleted yet, as the API answers it. */ +export interface DeletionBlocker { + kind: "tenant" | "platform"; + tenantId?: string; + tenantName?: string; +} + +/** What deleting the account would remove, as the API answers it. */ +export interface AccountDeletionImpact { + email: string; + hasPassword: boolean; + memberships: number; + sessions: number; + notifications: number; + externalIdentities: number; + invitesSent: number; + blockers: DeletionBlocker[]; +} + +/** The export file name: `dms-account-export-2026-10-01.json`. */ +export function accountExportFilename(at: Date = new Date()): string { + return `${EXPORT_FILE_PREFIX}-${at.toISOString().slice(0, ISO_DATE_LENGTH)}.json`; +} + +/** + * "Your data" on the profile page: download everything the DMS keeps about + * the signed-in user, or delete the account after a password and a typed + * e-mail, then sign out. + */ +export function useAccountData() { + const { $authFetch } = useAuthFetch(); + const { confirm } = useConfirm(); + const { user, clear } = useUserSession(); + const { removeAccount } = useMultiAccount(); + const { processI18n } = useTranslation(); + const { errorMessage, errorCode } = useSecurityFormat(); + const toast = useToast(); + const { t } = useI18n(); + + const isExporting = ref(false); + const isCheckingDeletion = ref(false); + + /** A message key the API answers with (`$…`), else a known error code. */ + function describeError(error: unknown, fallbackKey: string): string { + const code = errorCode(error); + if (code?.startsWith("$")) return processI18n(code); + return errorMessage(error, fallbackKey); + } + + async function exportData(): Promise { + isExporting.value = true; + try { + const file = await $authFetch(EXPORT_ENDPOINT); + const blob = new Blob([JSON.stringify(file, null, JSON_INDENT)], { + type: "application/json", + }); + const url = URL.createObjectURL(blob); + downloadFile(url, accountExportFilename()); + URL.revokeObjectURL(url); + toast.add({ + color: "success", + icon: "i-ph-check-circle", + title: t(`${I18N}.export_done`), + }); + } catch (error) { + toast.add({ + color: "error", + icon: "i-ph-warning-circle", + title: describeError(error, `${I18N}.export_error`), + }); + } finally { + isExporting.value = false; + } + } + + function impactList(impact: AccountDeletionImpact): ConfirmImpact[] { + return [ + { + icon: "i-ph-users-three", + label: t(`${I18N}.impact_memberships`), + count: impact.memberships, + }, + { + icon: "i-ph-devices", + label: t(`${I18N}.impact_sessions`), + count: impact.sessions, + }, + { + icon: "i-ph-bell", + label: t(`${I18N}.impact_notifications`), + count: impact.notifications, + }, + { + icon: "i-ph-link", + label: t(`${I18N}.impact_identities`), + count: impact.externalIdentities, + }, + { + icon: "i-ph-envelope-simple", + label: t(`${I18N}.impact_invites`), + count: impact.invitesSent, + }, + ]; + } + + function passwordField(password: Ref) { + return () => + h(UFormField, { label: t(`${I18N}.delete_password`) }, () => + // Generic in its value type, which `h` cannot infer. + h(UInput as Component, { + modelValue: password.value, + type: "password", + autocomplete: "current-password", + class: "w-full", + "onUpdate:modelValue": (value: unknown) => { + password.value = typeof value === "string" ? value : ""; + }, + }), + ); + } + + function blockerNames(blockers: DeletionBlocker[]): string { + return blockers + .map((blocker) => + blocker.kind === "platform" + ? t(`${I18N}.blocker_platform`) + : (blocker.tenantName ?? blocker.tenantId ?? ""), + ) + .join(", "); + } + + async function explainBlockers(blockers: DeletionBlocker[]): Promise { + await confirm({ + title: t(`${I18N}.blocked_title`), + description: t(`${I18N}.blocked_description`, { + names: blockerNames(blockers), + }), + icon: "i-ph-crown-simple", + confirmColor: "warning", + hideConfirm: true, + cancelLabel: t(`${I18N}.blocked_close`), + }); + } + + async function signOutDeleted(): Promise { + const userId = user.value?._id; + await clear().catch(() => undefined); + if (userId) await removeAccount(userId).catch(() => undefined); + toast.add({ + color: "success", + icon: "i-ph-check-circle", + title: t(`${I18N}.delete_done_title`), + description: t(`${I18N}.delete_done_description`), + }); + await navigateDms(AUTH_ROUTE); + } + + async function submitDeletion( + impact: AccountDeletionImpact, + password: string, + ): Promise { + try { + await $authFetch(DELETION_ENDPOINT, { + method: "POST", + body: { + password: impact.hasPassword ? password : undefined, + confirmation: impact.email, + }, + }); + } catch (error) { + throw new Error(describeError(error, `${I18N}.delete_error`)); + } + } + + async function confirmDeletion(impact: AccountDeletionImpact): Promise { + const password = ref(""); + const confirmed = await confirm({ + title: t(`${I18N}.delete_confirm_title`), + description: t(`${I18N}.delete_confirm_description`), + icon: "i-ph-warning", + confirmColor: "error", + confirmIcon: "i-ph-trash", + confirmLabel: t(`${I18N}.delete_confirm_button`), + impact: impactList(impact), + body: impact.hasPassword ? passwordField(password) : undefined, + confirmText: impact.email, + onConfirm: () => submitDeletion(impact, password.value), + }); + if (confirmed) await signOutDeleted(); + } + + async function deleteAccount(): Promise { + isCheckingDeletion.value = true; + let impact: AccountDeletionImpact; + try { + impact = await $authFetch(DELETION_ENDPOINT); + } catch (error) { + toast.add({ + color: "error", + icon: "i-ph-warning-circle", + title: describeError(error, `${I18N}.delete_error`), + }); + return; + } finally { + isCheckingDeletion.value = false; + } + if (impact.blockers.length > 0) return explainBlockers(impact.blockers); + return confirmDeletion(impact); + } + + return { isExporting, isCheckingDeletion, exportData, deleteAccount }; +} diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/profile/useProfileAvatar.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/profile/useProfileAvatar.ts new file mode 100644 index 000000000..5de5023e1 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/profile/useProfileAvatar.ts @@ -0,0 +1,95 @@ +import { + type PresignResponse, + useUploadWithProgress, +} from "#dms-ui/app/composables/form/useUploadWithProgress"; +import { + type FileFieldConstraints, + matchMimetype, +} from "#dms-ui/app/utils/fileConstraints"; +import { + type ImageResizeBounds, + resizeImageToBounds, +} from "#dms-ui/app/utils/imageResize"; + +const PRESIGN_URL = "/api/files/presign"; +const METADATA_URL = "/api/files/metadata"; + +/** Upload options the backend serialized for the avatar image field. */ +export interface AvatarFieldOptions { + uploadToken?: string; + storage?: string; + constraints?: FileFieldConstraints; + resize?: ImageResizeBounds; +} + +/** Why a picked file was refused before any upload. */ +export type AvatarRejection = "mimetype" | "size"; + +interface FileMetadataResponse { + url: string; +} + +/** Outcome of an avatar upload: a staged key, or why it was refused. */ +export interface AvatarUploadResult { + key?: string; + rejection?: AvatarRejection; +} + +/** + * The profile avatar's upload flow, the same one the image form field uses: + * resize to the field's bounds, presign with the field's upload token, then + * PUT to storage. The returned key is staged until the profile is saved. + * + * @param options Serialized options of the avatar image field + */ +export function useProfileAvatar(options: () => AvatarFieldOptions) { + const { $authFetch } = useAuthFetch(); + const { uploadWithProgress } = useUploadWithProgress(); + const progress = ref(0); + + const isAccepted = (file: File): boolean => { + const mimetypes = options().constraints?.allowedMimetypes; + if (!mimetypes?.length) return file.type.startsWith("image/"); + return mimetypes.some((pattern) => matchMimetype(file.type, pattern)); + }; + + const prepare = (file: File): Promise => { + const bounds = options().resize; + return bounds ? resizeImageToBounds(file, bounds) : Promise.resolve(file); + }; + + async function upload(file: File): Promise { + if (!isAccepted(file)) return { rejection: "mimetype" }; + const prepared = await prepare(file); + const maxSize = options().constraints?.maxSize; + if (maxSize && prepared.size > maxSize) return { rejection: "size" }; + progress.value = 0; + const presign = await $authFetch(PRESIGN_URL, { + method: "POST", + body: { + filename: prepared.name, + size: prepared.size, + mimetype: prepared.type, + uploadToken: options().uploadToken, + }, + }); + await uploadWithProgress(presign, prepared, (value) => { + progress.value = value; + }); + return { key: presign.resourceKey }; + } + + /** @returns A short-lived URL to display a stored avatar */ + async function resolveUrl(key: string): Promise { + try { + const metadata = await $authFetch(METADATA_URL, { + query: { resourceKey: key, storage: options().storage }, + }); + return metadata.url; + } catch { + return null; + } + } + + return { progress, upload, resolveUrl }; +} diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/region/timeZones.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/region/timeZones.ts new file mode 100644 index 000000000..eb735c5aa --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/region/timeZones.ts @@ -0,0 +1,96 @@ +/** One entry of the time zone picker. */ +export interface TimeZoneOption { + /** IANA identifier (`Europe/Brussels`). */ + value: string; + /** `Europe / Brussels`. */ + label: string; + /** `UTC+02:00`, at the moment the list was built. */ + offset: string; +} + +type IntlWithSupportedValues = typeof Intl & { + supportedValuesOf?: (key: "timeZone") => string[]; +}; + +/** Offered when the runtime cannot list its zones. */ +const FALLBACK_TIME_ZONES = [ + "UTC", + "Europe/London", + "Europe/Paris", + "Europe/Brussels", + "Europe/Berlin", + "America/New_York", + "America/Chicago", + "America/Denver", + "America/Los_Angeles", + "America/Sao_Paulo", + "Africa/Johannesburg", + "Asia/Dubai", + "Asia/Kolkata", + "Asia/Singapore", + "Asia/Tokyo", + "Australia/Sydney", + "Pacific/Auckland", +]; + +const UTC_LABEL = "UTC"; +const GMT_PREFIX = /^GMT/; +const OFFSET_PATTERN = /^UTC([+-])(\d{2}):(\d{2})$/; +const MINUTES_PER_HOUR = 60; + +/** Every IANA zone the runtime knows. */ +export function listTimeZones(): string[] { + return ( + (Intl as IntlWithSupportedValues).supportedValuesOf?.("timeZone") ?? + FALLBACK_TIME_ZONES + ); +} + +/** `UTC+02:00`: the offset of `timeZone` at `at`. */ +export function timeZoneOffset(timeZone: string, at: Date): string { + const name = new Intl.DateTimeFormat("en-US", { + timeZone, + timeZoneName: "longOffset", + }) + .formatToParts(at) + .find((part) => part.type === "timeZoneName")?.value; + if (!name || name === "GMT") return `${UTC_LABEL}+00:00`; + return name.replace(GMT_PREFIX, UTC_LABEL); +} + +/** Minutes east of UTC an offset label stands for, to sort by it. */ +function offsetMinutes(offset: string): number { + const match = OFFSET_PATTERN.exec(offset); + if (!match) return 0; + const [, sign, hours, minutes] = match; + const total = Number(hours) * MINUTES_PER_HOUR + Number(minutes); + return sign === "-" ? -total : total; +} + +/** `America/Argentina/Buenos_Aires` → `America / Argentina / Buenos Aires`. */ +export function timeZoneLabel(timeZone: string): string { + return timeZone.replaceAll("_", " ").split("/").join(" / "); +} + +/** + * The picker's entries, west to east then by name. `extra` adds zones the + * runtime does not list but the user may hold (an alias the browser reports). + */ +export function buildTimeZoneOptions( + zones: string[], + at: Date, + extra: string[] = [], +): TimeZoneOption[] { + const unique = [...new Set([...zones, ...extra.filter(Boolean)])]; + return unique + .map((value) => ({ + value, + label: timeZoneLabel(value), + offset: timeZoneOffset(value, at), + })) + .sort( + (a, b) => + offsetMinutes(a.offset) - offsetMinutes(b.offset) || + a.label.localeCompare(b.label), + ); +} diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/region/useRegionSettings.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/region/useRegionSettings.ts new file mode 100644 index 000000000..1f64a4e66 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/region/useRegionSettings.ts @@ -0,0 +1,90 @@ +import type { SaveStatusState } from "#dms-ui/app/components/save-bar/SaveStatus.vue"; +import type { + DateFormatPreference, + TimeFormatPreference, + WeekStartPreference, +} from "#dms-core/app/utils/regional"; + +export const REGION_PREFERENCES_ENDPOINT = "/settings/user/region/preferences"; +const SAVED_STAMP_MS = 2500; + +/** What the Language & region page saves, as the API takes it. */ +export interface RegionSettingsValues { + language: string; + timeZone: string | null; + weekStart: WeekStartPreference | null; + timeFormat: TimeFormatPreference | null; + dateFormat: DateFormatPreference | null; +} + +export type RegionSettingsField = keyof RegionSettingsValues; + +type SessionUser = Partial & Record; + +/** + * Instant save of the Language & region page: each control saves on its own, + * with its own "Saved" stamp. The session user is patched first, so dates + * across the dashboard follow before the request returns, and put back if + * it fails. + */ +export function useRegionSettings() { + const dmsApp = useDmsApp(); + const { $authFetch } = useAuthFetch(); + const { user } = useUserSession(); + const { refresh } = useCurrentUser(); + const toast = useToast(); + const { t } = useI18n(); + + const states = reactive< + Partial> + >({}); + const timers = new Map>(); + + function stamp(field: RegionSettingsField, state: SaveStatusState): void { + clearTimeout(timers.get(field)); + states[field] = state; + if (state !== "saved") return; + timers.set( + field, + setTimeout(() => (states[field] = "idle"), SAVED_STAMP_MS), + ); + } + + function patchUser(values: Partial): void { + if (user.value) user.value = { ...user.value, ...values }; + } + + async function save( + field: K, + value: RegionSettingsValues[K], + ): Promise { + const previous = user.value?.[field] ?? null; + if (previous === value) return; + stamp(field, "saving"); + patchUser({ [field]: value }); + if (field === "language") await dmsApp.$i18n.setLocale(value as string); + try { + await $authFetch(REGION_PREFERENCES_ENDPOINT, { + method: "POST", + body: { [field]: value }, + }); + stamp(field, "saved"); + await refresh().catch(() => undefined); + } catch { + patchUser({ [field]: previous }); + if (field === "language" && typeof previous === "string") { + await dmsApp.$i18n.setLocale(previous); + } + stamp(field, "idle"); + toast.add({ + color: "error", + icon: "i-ph-warning-circle", + title: t("page.settings.region.save_error"), + }); + } + } + + onBeforeUnmount(() => timers.forEach((timer) => clearTimeout(timer))); + + return { states, save }; +} diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/security/useSecurityFormat.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/security/useSecurityFormat.ts new file mode 100644 index 000000000..34f4f47e9 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/security/useSecurityFormat.ts @@ -0,0 +1,95 @@ +import { regionalDateTimeFormat } from "#dms-core/app/utils/regional"; + +const MS_PER_SECOND = 1000; +const MS_PER_MINUTE = 60 * MS_PER_SECOND; +const MS_PER_HOUR = 60 * MS_PER_MINUTE; +const MS_PER_DAY = 24 * MS_PER_HOUR; +const MS_PER_MONTH = 30 * MS_PER_DAY; +const MS_PER_YEAR = 365 * MS_PER_DAY; +const ERROR_CODE_PREFIX = "error."; +const SECURITY_ERRORS_PREFIX = "page.settings.security.errors."; + +interface RelativeUnit { + unit: Intl.RelativeTimeFormatUnit; + ms: number; +} + +/** Largest unit first: the first one that fits at least once is used. */ +const RELATIVE_UNITS: RelativeUnit[] = [ + { unit: "year", ms: MS_PER_YEAR }, + { unit: "month", ms: MS_PER_MONTH }, + { unit: "day", ms: MS_PER_DAY }, + { unit: "hour", ms: MS_PER_HOUR }, + { unit: "minute", ms: MS_PER_MINUTE }, +]; + +interface FetchErrorLike { + data?: unknown; +} + +type DateInput = string | Date; + +/** + * Locale-aware dates for the Security and Profile settings, plus the + * translation of API error codes into sentences. + */ +export function useSecurityFormat() { + const { locale, t, te } = useI18n(); + + const formatDate = (value: DateInput): string => + regionalDateTimeFormat(locale.value, { dateStyle: "medium" }).format( + new Date(value), + ); + + const formatDateTime = (value: DateInput): string => + regionalDateTimeFormat(locale.value, { + dateStyle: "medium", + timeStyle: "short", + }).format(new Date(value)); + + const daysSince = (value: DateInput): number => + Math.max( + 0, + Math.floor((Date.now() - new Date(value).getTime()) / MS_PER_DAY), + ); + + /** "3 days ago", "in an hour"… or "now" under a minute. */ + const formatRelative = (value: DateInput): string => { + const elapsed = new Date(value).getTime() - Date.now(); + const formatter = new Intl.RelativeTimeFormat(locale.value, { + numeric: "auto", + }); + const fit = RELATIVE_UNITS.find(({ ms }) => Math.abs(elapsed) >= ms); + if (!fit) return formatter.format(0, "second"); + return formatter.format(Math.round(elapsed / fit.ms), fit.unit); + }; + + /** + * @param error What `$authFetch` threw + * @param fallbackKey Message used when the error carries no known code + */ + const errorMessage = (error: unknown, fallbackKey: string): string => { + const code = (error as FetchErrorLike | undefined)?.data; + if (typeof code !== "string" || !code.startsWith(ERROR_CODE_PREFIX)) { + return t(fallbackKey); + } + const ownKey = `${SECURITY_ERRORS_PREFIX}${code.slice(ERROR_CODE_PREFIX.length)}`; + if (te(ownKey)) return t(ownKey); + return te(code) ? t(code) : t(fallbackKey); + }; + + /** @returns The error code (`error.xxx`) the API answered with, if any */ + const errorCode = (error: unknown): string | undefined => { + const code = (error as FetchErrorLike | undefined)?.data; + return typeof code === "string" ? code : undefined; + }; + + return { + formatDate, + formatDateTime, + formatRelative, + daysSince, + errorMessage, + errorCode, + }; +} diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/security/useSecurityOverview.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/security/useSecurityOverview.ts new file mode 100644 index 000000000..00b016a84 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/security/useSecurityOverview.ts @@ -0,0 +1,136 @@ +import { useSettingsNavTrails } from "../useSettingsNavTrails"; + +/** Base URL of the Security page API. */ +export const SECURITY_ENDPOINT = "/settings/user/security"; +/** Route of the Security page. */ +export const SECURITY_PAGE_PATH = "/settings/user/security"; +const SECURITY_PAGE_ID = "settings.user.security"; +/** At or below this many backup codes left, the page asks for a new set. */ +const LOW_BACKUP_CODES = 3; + +/** Two-factor state as the API reports it. */ +export interface TwoFactorStatus { + methods: string[]; + hasBackupCodes: boolean; + backupCodesLeft: number; + backupCodesTotal: number; + backupCodesGeneratedAt: string | null; + backupCodesSavedAt: string | null; +} + +/** Summary behind the Security status strip and the profile pointer card. */ +export interface SecurityOverview { + email: string; + isValidated: boolean; + hasPassword: boolean; + passwordChangedAt: string | null; + accountCreatedAt: string; + twoFactor: TwoFactorStatus; + activeSessions: number; +} + +/** What the API returns to enrol an authenticator app. */ +export interface TotpSetup { + secret: string; + /** Base32 key to type into an app that cannot scan. */ + manualKey: string; + otpAuthUrl: string; + /** PNG data URL rendered by the backend. */ + qrCode: string; +} + +/** Something on the Security page that needs the user's attention. */ +export type SecurityAttention = + | "two_factor_off" + | "backup_codes_unsaved" + | "backup_codes_low"; + +interface AttentionRule { + id: SecurityAttention; + applies: (overview: SecurityOverview) => boolean; +} + +const isTwoFactorOn = (overview: SecurityOverview): boolean => + overview.twoFactor.methods.length > 0; + +/** + * Codes generated before the "saved" stamp existed carry no generation date; + * they are not flagged, since nothing tells whether they were kept. + */ +const ATTENTION_RULES: AttentionRule[] = [ + { id: "two_factor_off", applies: (overview) => !isTwoFactorOn(overview) }, + { + id: "backup_codes_unsaved", + applies: ({ twoFactor }) => + twoFactor.hasBackupCodes && + !!twoFactor.backupCodesGeneratedAt && + !twoFactor.backupCodesSavedAt, + }, + { + id: "backup_codes_low", + applies: (overview) => + isTwoFactorOn(overview) && + overview.twoFactor.backupCodesLeft <= LOW_BACKUP_CODES, + }, +]; + +/** + * @param overview Security summary of the signed-in user + * @returns The items needing attention, most important first + */ +export function securityAttention( + overview: SecurityOverview, +): SecurityAttention[] { + return ATTENTION_RULES.filter((rule) => rule.applies(overview)).map( + (rule) => rule.id, + ); +} + +/** + * Shared Security summary: the status strip, every Security block and the + * profile pointer card read the same state, and any change refreshes it for + * all of them. It also keeps the settings nav dot of the Security page in + * sync with what needs attention. + */ +export function useSecurityOverview() { + const overview = useDmsState( + "dms-security-overview", + () => null, + ); + const isUnavailable = useDmsState( + "dms-security-overview-unavailable", + () => false, + ); + const { $authFetch } = useAuthFetch(); + const { setTrail, clearTrail } = useSettingsNavTrails(); + const { t } = useI18n(); + + const attention = computed(() => + overview.value ? securityAttention(overview.value) : [], + ); + + function syncTrail(): void { + const [first] = attention.value; + if (!first) { + clearTrail(SECURITY_PAGE_ID); + return; + } + setTrail({ + fullId: SECURITY_PAGE_ID, + status: "warning", + label: t(`page.settings.security.attention.${first}`), + }); + } + + async function refresh(): Promise { + try { + overview.value = await $authFetch(SECURITY_ENDPOINT); + isUnavailable.value = false; + } catch { + isUnavailable.value = true; + } + syncTrail(); + } + + return { overview, attention, isUnavailable, refresh }; +} diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavIndicators.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavIndicators.ts new file mode 100644 index 000000000..8dd32ff0d --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavIndicators.ts @@ -0,0 +1,108 @@ +import { onMounted, watch, type Ref } from "vue"; +import { useNavBadges } from "#dms-ui/app/composables/navigation/useNavBadges"; +import { useSecurityOverview } from "./security/useSecurityOverview"; +import { INVITES_PAGE_ID } from "./useSettingsNavigation"; +import { useSettingsNavTrails } from "./useSettingsNavTrails"; + +const MEMBERS_PAGE_ID = "settings.user.members"; +const ROLES_PAGE_ID = "settings.user.roles"; +const SECURITY_PAGE_ID = "settings.user.security"; +const MEMBERS_COUNT_ENDPOINT = "/api/tables/members/count/batch"; +const ROLES_OVERVIEW_ENDPOINT = "/settings/user/roles/overview"; +const MEMBERS_COUNT_QUERY_ID = "all"; +// The source the Members table's Invitations tab counts from. +const INVITES_LIST_ENDPOINT = "/api/tables/admin-invites/list"; +const INVITES_COUNT_QUERY = { limit: 1, offset: 0 }; + +interface RolesOverviewSummary { + roles?: unknown[]; +} + +interface ListTotal { + total?: number; +} + +/** + * Loads the indicators of the settings navigation — member and role counts, + * the security attention dot — as soon as the navigation shows, so they + * don't wait for a visit to each page. Only pages the viewer can open (the + * ones listed in the nav) are asked, so no request ends in a 403; a failed + * request just leaves its entry without an indicator. + */ +export function useSettingsNavIndicators(visiblePageIds: Ref>) { + const { $authFetch } = useAuthFetch(); + const { setNavBadge } = useNavBadges(); + const { setTrail } = useSettingsNavTrails(); + const security = useSecurityOverview(); + const { t } = useI18n(); + const route = useDmsRoute(); + + async function loadMembersCount(): Promise { + const counts = await $authFetch>( + MEMBERS_COUNT_ENDPOINT, + { + method: "POST", + body: { queries: [{ id: MEMBERS_COUNT_QUERY_ID, query: {} }] }, + }, + ); + const count = counts?.[MEMBERS_COUNT_QUERY_ID]; + if (typeof count === "number") setNavBadge(MEMBERS_PAGE_ID, String(count)); + } + + async function loadRolesCount(): Promise { + const overview = await $authFetch( + ROLES_OVERVIEW_ENDPOINT, + ); + if (Array.isArray(overview?.roles)) { + setNavBadge(ROLES_PAGE_ID, String(overview.roles.length)); + } + } + + // A trail rather than a nav badge: the overview card shows its label too. + async function loadInvitesCount(): Promise { + const response = await $authFetch(INVITES_LIST_ENDPOINT, { + query: INVITES_COUNT_QUERY, + }); + const count = response?.total; + if (typeof count !== "number") return; + setTrail({ + fullId: INVITES_PAGE_ID, + badge: count > 0 ? String(count) : undefined, + label: t("page.settings.shell.pending_invitations", count), + }); + } + + const loaders: Record Promise> = { + [MEMBERS_PAGE_ID]: loadMembersCount, + [ROLES_PAGE_ID]: loadRolesCount, + [INVITES_PAGE_ID]: loadInvitesCount, + [SECURITY_PAGE_ID]: () => security.refresh(), + }; + const loaded = new Set(); + + function loadVisible(): void { + for (const [pageId, load] of Object.entries(loaders)) { + if (loaded.has(pageId) || !visiblePageIds.value.has(pageId)) continue; + loaded.add(pageId); + load().catch(() => { + /* the entry simply shows no indicator */ + }); + } + } + + onMounted(() => { + loadVisible(); + watch(visiblePageIds, loadVisible); + // Invitations are sent, resent and revoked from pages that publish no + // count of them: read it again on each move between settings pages. + watch( + () => route.path, + () => { + if (!visiblePageIds.value.has(INVITES_PAGE_ID)) return; + loadInvitesCount().catch(() => { + /* the entry keeps its last indicator */ + }); + }, + ); + }); +} diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavTrails.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavTrails.ts new file mode 100644 index 000000000..da5c71269 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavTrails.ts @@ -0,0 +1,52 @@ +/** Severity of the dot a settings nav item can carry. */ +export type SettingsNavTrailStatus = "warning" | "error"; + +/** + * What the settings navigation shows at the end of an item. The nav renders a + * single trail per item, in this order of precedence: `badge`, then `status`, + * then `tag`. + * + * Every field is serializable, so a trail can be set from an SSR-safe plugin + * as well as from a page or a component. + */ +export interface SettingsNavTrail { + /** Settings page the trail belongs to (`settings.user.notifications`…). */ + fullId: string; + /** Short count or ratio (`3`, `8/10`). */ + badge?: string; + /** A dot drawing attention to the page. */ + status?: SettingsNavTrailStatus; + /** Module tag for a page a module contributes (`SAAS`). */ + tag?: string; + /** Accessible label of the dot or badge (`Payment failed`). */ + label?: string; +} + +interface UseSettingsNavTrailsReturn { + trails: Readonly>>; + setTrail: (trail: SettingsNavTrail) => void; + clearTrail: (fullId: string) => void; +} + +/** + * Registry of the live indicators shown in the settings navigation — unread + * counts, seat ratios, attention dots, module tags. Setting a trail replaces + * the one the page had. + */ +export const useSettingsNavTrails = (): UseSettingsNavTrailsReturn => { + const trails = useDmsState>( + "dms-settings-nav-trails", + () => ({}), + ); + + function setTrail(trail: SettingsNavTrail): void { + trails.value = { ...trails.value, [trail.fullId]: trail }; + } + + function clearTrail(fullId: string): void { + const { [fullId]: _removed, ...rest } = trails.value; + trails.value = rest; + } + + return { trails, setTrail, clearTrail }; +}; diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavigation.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavigation.ts new file mode 100644 index 000000000..16a2787a5 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/settings/useSettingsNavigation.ts @@ -0,0 +1,236 @@ +import type { PageInfo, SiteLayoutTree } from "../../types/page"; + +export const SETTINGS_ROOT_ID = "settings"; +const SETTINGS_ID_PREFIX = `${SETTINGS_ROOT_ID}.`; +const SETTINGS_INDEX_ID = `${SETTINGS_ROOT_ID}.${SETTINGS_ROOT_ID}`; +const USER_CATEGORY_PREFIX = `${SETTINGS_ID_PREFIX}user.`; +const WORKSPACE_CATEGORY_PREFIX = `${SETTINGS_ID_PREFIX}workspace.`; +const DEFAULT_SETTINGS_ICON = "i-ph-gear-six"; + +export const SettingsNavGroupId = { + ACCOUNT: "account", + WORKSPACE: "workspace", +} as const; + +/** + * Personal pages, in nav order. Everything else under the user category is + * personal too and follows them. + */ +const ACCOUNT_PAGE_ORDER = [ + "settings.user.profile", + "settings.user.region", + "settings.user.security", + "settings.user.notifications", + "settings.user.appearance", + "settings.user.shortcuts", +]; + +/** + * Pages registered under the user category that administer the workspace. + * Their ids stay where they are (they are permission ids); only the nav moves + * them next to the workspace category. + */ +const WORKSPACE_PAGE_ORDER = ["settings.user.members", "settings.user.roles"]; + +/** Pending invitations: a page nested under Members, hidden from the menu. */ +export const INVITES_PAGE_ID = "settings.user.members.invites"; + +/** + * Settings pages registered `hidden` (out of the menu tree) that the nav still + * lists, each right after the page it belongs with and under the label given + * here. They come from the site layout's page registry, which carries every + * page with the viewer's access to it, so one the viewer cannot open stays out. + */ +const LINKED_SETTINGS_PAGES: Record = + { + [INVITES_PAGE_ID]: { + after: "settings.user.members", + label: "$page.settings.shell.member_invitations", + }, + }; + +/** How far after the page it belongs with a linked page ranks. */ +const LINKED_PAGE_OFFSET = 0.5; + +/** The page a linked page is ranked and grouped with; itself otherwise. */ +const anchorOf = (fullId: string): string => + LINKED_SETTINGS_PAGES[fullId]?.after ?? fullId; + +export interface SettingsNavPage { + fullId: string; + label: string; + description: string; + icon: string; + to: string; +} + +export interface SettingsNavGroup { + id: string; + /** i18n key (`$…`) or a category display name. */ + label: string; + pages: SettingsNavPage[]; +} + +/** What the nav reads of a page: a menu tree node or a registry entry. */ +type SettingsPageNode = Omit; + +interface CollectedPage { + node: SettingsPageNode; + parent: SiteLayoutTree; +} + +const isSettingsPage = (node: SiteLayoutTree): boolean => + !!node.layoutUrl && + node.fullId.startsWith(SETTINGS_ID_PREFIX) && + node.fullId !== SETTINGS_INDEX_ID && + node.hasAccess !== false; + +function collectSettingsPages( + node: SiteLayoutTree, + parent: SiteLayoutTree | null, + into: CollectedPage[], +): void { + if (parent && isSettingsPage(node)) into.push({ node, parent }); + for (const childId of node.childrenOrders ?? Object.keys(node.children)) { + const child = node.children[childId]; + if (child) collectSettingsPages(child, node, into); + } +} + +const toNavPage = (node: SettingsPageNode): SettingsNavPage => ({ + fullId: node.fullId, + label: LINKED_SETTINGS_PAGES[node.fullId]?.label ?? node.displayName, + description: node.description || "", + icon: node.icon || DEFAULT_SETTINGS_ICON, + to: node.fullSlug, +}); + +/** Nav group a settings page belongs to; category id for non-core pages. */ +function groupIdOf({ node, parent }: CollectedPage): string { + const fullId = anchorOf(node.fullId); + if (WORKSPACE_PAGE_ORDER.includes(fullId)) { + return SettingsNavGroupId.WORKSPACE; + } + if (fullId.startsWith(USER_CATEGORY_PREFIX)) { + return SettingsNavGroupId.ACCOUNT; + } + if (fullId.startsWith(WORKSPACE_CATEGORY_PREFIX)) { + return SettingsNavGroupId.WORKSPACE; + } + return parent.fullId; +} + +/** + * Position of a settings page in the nav's curated order, `-1` for a page + * the nav lists after them by its `order`. The roles editor orders its + * settings permissions with it. + */ +export function curatedSettingsPageRank(fullId: string): number { + return [...ACCOUNT_PAGE_ORDER, ...WORKSPACE_PAGE_ORDER].indexOf(fullId); +} + +/** + * Rank of a page inside its group: the curated order first, then `order`. A + * linked page comes right after the page it belongs with. + */ +function rankOf(node: SettingsPageNode): number { + const anchor = anchorOf(node.fullId); + const linkedOffset = anchor === node.fullId ? 0 : LINKED_PAGE_OFFSET; + const curated = curatedSettingsPageRank(anchor); + return ( + linkedOffset + + (curated === -1 + ? ACCOUNT_PAGE_ORDER.length + + WORKSPACE_PAGE_ORDER.length + + (node.order ?? 0) + : curated) + ); +} + +/** The linked pages of the registry the viewer can open. */ +function collectLinkedPages( + pages: Record | undefined, + settingsRoot: SiteLayoutTree, + into: CollectedPage[], +): void { + for (const page of Object.values(pages ?? {})) { + if (LINKED_SETTINGS_PAGES[page.fullId] && page.hasAccess !== false) { + into.push({ node: page, parent: settingsRoot }); + } + } +} + +const GROUP_LABELS: Record = { + [SettingsNavGroupId.ACCOUNT]: "$page.settings.shell.account", + [SettingsNavGroupId.WORKSPACE]: "$page.settings.shell.workspace", +}; + +const GROUP_ORDER: string[] = [ + SettingsNavGroupId.ACCOUNT, + SettingsNavGroupId.WORKSPACE, +]; + +function buildGroups(pages: CollectedPage[]): SettingsNavGroup[] { + const groups = new Map(); + for (const page of pages) { + const id = groupIdOf(page); + if (!groups.has(id)) { + const known = GROUP_ORDER.indexOf(id); + groups.set(id, { + id, + label: GROUP_LABELS[id] ?? page.parent.displayName, + pages: [], + order: + known === -1 ? GROUP_ORDER.length + (page.parent.order ?? 0) : known, + }); + } + groups.get(id)!.pages.push(toNavPage(page.node)); + } + return [...groups.values()] + .sort((a, b) => a.order - b.order) + .map(({ order: _order, ...group }) => group); +} + +/** + * The settings pages the current user can open, grouped the way the settings + * navigation shows them: the account pages, then the workspace pages, then one + * group per other settings category a project or module registers. + */ +export const useSettingsNavigation = () => { + const siteLayout = useSiteLayout(); + + const groups = computed(() => { + const root = siteLayout.siteLayoutTree.value?.children[SETTINGS_ROOT_ID]; + if (!root) return []; + const collected: CollectedPage[] = []; + collectSettingsPages(root, null, collected); + collectLinkedPages(siteLayout.siteLayout?.value?.pages, root, collected); + collected.sort((a, b) => rankOf(a.node) - rankOf(b.node)); + return buildGroups(collected); + }); + + return { groups }; +}; + +/** + * The nav path the current route stands under: the longest one it equals or + * lies below, so a page nested under another (pending invitations under + * Members) is the only one marked active there. + */ +export function findActiveSettingsPath( + path: string, + paths: readonly string[], +): string | undefined { + let active: string | undefined; + for (const candidate of paths) { + const matches = path === candidate || path.startsWith(`${candidate}/`); + if (matches && candidate.length > (active?.length ?? -1)) { + active = candidate; + } + } + return active; +} + +/** Whether a page or category id belongs to the settings area. */ +export const isSettingsFullId = (fullId: string | null | undefined): boolean => + fullId === SETTINGS_ROOT_ID || !!fullId?.startsWith(SETTINGS_ID_PREFIX); diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/composables/useFooterLinks.ts b/packages/dms/frontend-vue/layers/dms-layout/app/composables/useFooterLinks.ts index db3144a51..9fe9efe98 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/composables/useFooterLinks.ts +++ b/packages/dms/frontend-vue/layers/dms-layout/app/composables/useFooterLinks.ts @@ -5,7 +5,26 @@ export interface FooterLink { order: number; } -const links = ref([]); +/** + * The Antelope links every footer starts with. A layer replaces one by + * registering an entry under the same id. + */ +const DEFAULT_FOOTER_LINKS: FooterLink[] = [ + { + id: "dms:documentation", + label: "empty_layout.footer.documentation", + to: "https://dms.antelopejs.com/docs/", + order: 10, + }, + { + id: "dms:website", + label: "empty_layout.footer.website", + to: "https://dms.antelopejs.com/", + order: 20, + }, +]; + +const links = ref([...DEFAULT_FOOTER_LINKS]); function compareByOrder(a: FooterLink, b: FooterLink): number { return a.order - b.order; diff --git a/packages/dms/frontend-vue/layers/dms-layout/app/custom-layouts/DefaultLayout.vue b/packages/dms/frontend-vue/layers/dms-layout/app/custom-layouts/DefaultLayout.vue index f4935c918..a82d38cf7 100644 --- a/packages/dms/frontend-vue/layers/dms-layout/app/custom-layouts/DefaultLayout.vue +++ b/packages/dms/frontend-vue/layers/dms-layout/app/custom-layouts/DefaultLayout.vue @@ -4,6 +4,18 @@ import PageHeader from "../build/components/layout/PageHeader.vue"; import DashboardSidebar from "../build/components/layout/DashboardSidebar.vue"; import DashboardHeader from "../build/components/layout/DashboardHeader.vue"; import DashboardBanners from "../build/components/layout/DashboardBanners.vue"; +import RolePreviewBar from "../build/components/layout/RolePreviewBar.vue"; +import PageHeaderActionBar, { + type LayoutHeaderAction, +} from "../build/components/layout/PageHeaderActionBar.vue"; +import SettingsShell from "../build/components/pages/settings/shell/SettingsShell.vue"; +import { isSettingsFullId } from "../composables/settings/useSettingsNavigation"; +import { providePageHeaderActions } from "../composables/layout/usePageHeaderActions"; + +// Sidebar sizes are in px (the v2 240px sidebar). The storage key changed with +// the unit, so a width saved in % is not read back as px. +const DASHBOARD_STORAGE_KEY = "dms-dashboard"; +const DASHBOARD_SIZE_UNIT = "px"; interface Props { fullWidth?: boolean; @@ -12,6 +24,8 @@ interface Props { icon?: string; title?: string; description?: string; + /** Header buttons declared by the backend page (`headerActions`). */ + headerActions?: LayoutHeaderAction[]; } const props = withDefaults(defineProps(), { @@ -21,6 +35,7 @@ const props = withDefaults(defineProps(), { icon: "i-ph-file", title: undefined, description: undefined, + headerActions: () => [], }); providePageFillHeight(toRef(props, "fillHeight")); @@ -28,16 +43,37 @@ providePageFillHeight(toRef(props, "fillHeight")); const regionClass = computed(() => props.fillHeight ? PAGE_FILL_HEIGHT_CLASSES.region : undefined, ); + +// Every settings page — core, module or project — gets the settings shell: +// the page is identified by the site layout, not by its layout options, so +// no page has to opt in. +const siteLayout = useSiteLayout(); +const route = useDmsRoute(); +const isSettingsPage = computed(() => + isSettingsFullId( + siteLayout.findMatchingRouteOrCategory(route.path)?.metadata.fullId, + ), +); + +const pageHeaderActions = providePageHeaderActions(); +const hasHeaderActions = computed( + () => !!pageHeaderActions.value || props.headerActions.length > 0, +);