diff --git a/.changeset/clear-breadcrumb-hooks.md b/.changeset/clear-breadcrumb-hooks.md new file mode 100644 index 000000000..56bfa9767 --- /dev/null +++ b/.changeset/clear-breadcrumb-hooks.md @@ -0,0 +1,6 @@ +--- +"@tailor-platform/app-shell": patch +--- + +Fix the `usePageMeta` breadcrumb example to call the hook at the top level of a child component +instead of inside a `map` callback. diff --git a/.changeset/tidy-public-api-docs.md b/.changeset/tidy-public-api-docs.md new file mode 100644 index 000000000..8adb42314 --- /dev/null +++ b/.changeset/tidy-public-api-docs.md @@ -0,0 +1,8 @@ +--- +"@tailor-platform/app-shell": patch +--- + +Correct authentication, routing, guard, and tooltip examples to match the current public APIs. +Document the remaining context, command-palette, AI-tool, sidebar, and date helper exports, +and link them to their existing reference pages for documentation drift checks. +Undocumented public exports now fail `docs:check` instead of producing only a warning. diff --git a/docs-kit.config.json b/docs-kit.config.json index 65d9f0639..d921cab97 100644 --- a/docs-kit.config.json +++ b/docs-kit.config.json @@ -64,7 +64,7 @@ }, "policy": { "coverage": { - "enforce": false, + "enforce": true, "exclusions": [] }, "skills": { diff --git a/docs-manifest.json b/docs-manifest.json index 2c68be482..680ed1b3a 100644 --- a/docs-manifest.json +++ b/docs-manifest.json @@ -116,9 +116,9 @@ "symbols": ["AppShell", "AppShellProps"], "hashes": { "typeSurface": "51313066e142afc2", - "outline": "25fb9b8ab6949331", + "outline": "87b615fbadec9d1b", "snapshot": null, - "outputMd": "cd57abd4909118a4", + "outputMd": "50e2cd78a3629b64", "examples": null } }, @@ -165,18 +165,27 @@ }, "authentication": { "slug": "authentication", - "kind": "prose", + "kind": "code-backed", "outline": "docs-src/concepts/authentication.docs.outline.md", "output": "docs/concepts/authentication.md", "examples": null, - "sources": [], - "claims": [], - "symbols": [], + "sources": ["packages/core/src/contexts/auth-context.tsx"], + "claims": ["AuthClient"], + "symbols": [ + "AuthClient", + "AuthClientConfig", + "AuthProvider", + "AuthState", + "EnhancedAuthClient", + "createAuthClient", + "useAuth", + "useAuthSuspense" + ], "hashes": { - "typeSurface": null, - "outline": "cd9dc5d220e4310c", + "typeSurface": "a9c6468e0f121418", + "outline": "9f7f5e7fdd604383", "snapshot": null, - "outputMd": "a3f7aa913d59fdd7", + "outputMd": "d067f3112db6e053", "examples": null } }, @@ -220,14 +229,17 @@ "outline": "docs-src/components/badge.docs.outline.md", "output": "docs/components/badge.md", "examples": "docs-src/components/badge.docs.examples.tsx", - "sources": ["packages/core/src/components/badge/**"], + "sources": [ + "packages/core/src/components/badge/**", + "packages/core/src/components/badge-list/**" + ], "claims": [], - "symbols": ["Badge", "BadgeProps", "badgeVariants"], + "symbols": ["Badge", "BadgeOptions", "BadgeProps", "BadgeVariant", "badgeVariants"], "hashes": { - "typeSurface": "f4b8b24fb5f5bab1", - "outline": "0949dbd1404aa129", + "typeSurface": "404b610eb5fb6d8b", + "outline": "b01f3ddda789187a", "snapshot": null, - "outputMd": "7897980baf93a074", + "outputMd": "f274f45e7ad34758", "examples": "e1241d5ce9845e2e" } }, @@ -305,29 +317,48 @@ "outline": "docs-src/components/command-palette.docs.outline.md", "output": "docs/components/command-palette.md", "examples": null, - "sources": ["packages/core/src/components/command-palette/**"], + "sources": [ + "packages/core/src/components/command-palette/**", + "packages/core/src/contexts/command-palette-context.tsx" + ], "claims": [], - "symbols": ["CommandPalette"], + "symbols": [ + "CommandPalette", + "CommandPaletteAction", + "CommandPaletteSearchResult", + "OpenCommandPaletteOptions", + "SearchSource", + "useOpenCommandPalette", + "useRegisterCommandPaletteActions" + ], "hashes": { - "typeSurface": "818f6808b94f8041", - "outline": "92145a0043e61c29", + "typeSurface": "177de62baffe68dd", + "outline": "14350665e19ce9ab", "snapshot": null, - "outputMd": "7e5bc675a593791a", + "outputMd": "60ca478a7a266726", "examples": null } }, "create-ai-gateway-client": { "slug": "create-ai-gateway-client", - "kind": "prose", + "kind": "code-backed", "outline": "docs-src/hooks/create-ai-gateway-client.docs.outline.md", "output": "docs/api/create-ai-gateway-client.md", "examples": null, - "sources": [], + "sources": ["packages/core/src/ai/client.ts"], "claims": [], - "symbols": [], + "symbols": [ + "AIChatCompletionEvent", + "AIGatewayChatMessage", + "AIGatewayChatRequest", + "AIGatewayClient", + "AIGatewayFunctionTool", + "AIGatewayToolCall", + "createAIGatewayClient" + ], "hashes": { - "typeSurface": null, - "outline": "43a13487e8f3e6bd", + "typeSurface": "7ff9cea870fa0208", + "outline": "8d0e04f39d8ff4bd", "snapshot": null, "outputMd": "ed0db6372d25e2f9", "examples": null @@ -335,18 +366,18 @@ }, "create-typed-paths": { "slug": "create-typed-paths", - "kind": "prose", + "kind": "code-backed", "outline": "docs-src/hooks/create-typed-paths.docs.outline.md", "output": "docs/api/create-typed-paths.md", "examples": null, - "sources": [], + "sources": ["packages/core/src/fs-routes/typed-paths.ts"], "claims": [], - "symbols": [], + "symbols": ["createTypedPaths"], "hashes": { - "typeSurface": null, - "outline": "a0e902f7bd84c957", + "typeSurface": "bee373b07c9b0579", + "outline": "09e50ed1cfbc56d7", "snapshot": null, - "outputMd": "4c3a858d3eb02a2a", + "outputMd": "8296d75638c44123", "examples": null } }, @@ -489,21 +520,51 @@ "outline": "docs-src/components/date-picker.docs.outline.md", "output": "docs/components/date-picker.md", "examples": "docs-src/components/date-picker.docs.examples.tsx", - "sources": ["packages/core/src/components/date-field/**"], - "claims": [], + "sources": [ + "packages/core/src/components/date-field/**", + "packages/core/src/components/calendar/**" + ], + "claims": [ + "CalendarDate", + "CalendarDateTime", + "DateValue", + "Time", + "ZonedDateTime", + "getLocalTimeZone", + "parseAbsolute", + "parseDate", + "parseDateTime", + "parseZonedDateTime" + ], "symbols": [ + "Calendar", + "CalendarDate", + "CalendarDateTime", + "CalendarProps", "DateField", "DateFieldProps", "DatePicker", "DatePickerProps", + "DateRange", "DateRangePicker", - "DateRangePickerProps" + "DateRangePickerProps", + "DateValue", + "RangeCalendar", + "RangeCalendarProps", + "RangeCalendarSelectionEvent", + "Time", + "ZonedDateTime", + "getLocalTimeZone", + "parseAbsolute", + "parseDate", + "parseDateTime", + "parseZonedDateTime" ], "hashes": { - "typeSurface": "a0f5522359e8f81d", - "outline": "328fcaa8d2f2b6df", + "typeSurface": "fb052f5803e23452", + "outline": "dd660b0a849469c9", "snapshot": null, - "outputMd": "376e7d4ad14c2934", + "outputMd": "0625c602d510a9ae", "examples": "b657b67c9745a60e" } }, @@ -530,12 +591,15 @@ "outline": "docs-src/components/default-sidebar.docs.outline.md", "output": "docs/components/default-sidebar.md", "examples": null, - "sources": ["packages/core/src/components/sidebar/default-sidebar.tsx"], + "sources": [ + "packages/core/src/components/sidebar/default-sidebar.tsx", + "packages/core/src/components/sidebar/primitives.tsx" + ], "claims": [], - "symbols": ["DefaultSidebar", "DefaultSidebarProps"], + "symbols": ["DefaultSidebar", "DefaultSidebarProps", "SidebarMenuButton", "SidebarMenuItem"], "hashes": { - "typeSurface": "48705640a924a509", - "outline": "52ae5de7c9328224", + "typeSurface": "e102548bae68e70a", + "outline": "79630ad185541c93", "snapshot": null, "outputMd": "9b1672c71b6db3ff", "examples": null @@ -569,9 +633,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "08dc6db1e89f1130", + "outline": "cd855d9c649f804b", "snapshot": null, - "outputMd": "75361d7687b43878", + "outputMd": "47bb307116c6f41f", "examples": null } }, @@ -586,9 +650,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "7fb31862d2ddb478", + "outline": "be07e745531ed5f7", "snapshot": null, - "outputMd": "27e4d84b41cf40e0", + "outputMd": "83e9ee8ceb56d3c6", "examples": null } }, @@ -696,18 +760,18 @@ }, "file-based-routing": { "slug": "file-based-routing", - "kind": "prose", + "kind": "code-backed", "outline": "docs-src/concepts/file-based-routing.docs.outline.md", "output": "docs/concepts/file-based-routing.md", "examples": null, - "sources": [], + "sources": ["packages/core/src/fs-routes/types.ts"], "claims": [], - "symbols": [], + "symbols": ["AppShellPageProps", "PageComponent"], "hashes": { - "typeSurface": null, - "outline": "c3de8a342b4a7be3", + "typeSurface": "bbb6812392460d45", + "outline": "3f4606dc9871c582", "snapshot": null, - "outputMd": "e189f95dbe4b0286", + "outputMd": "17558cfa495ab026", "examples": null } }, @@ -734,12 +798,16 @@ "outline": "docs-src/components/form.docs.outline.md", "output": "docs/components/form.md", "examples": "docs-src/components/form.docs.examples.tsx", - "sources": ["packages/core/src/components/form/**"], + "sources": [ + "packages/core/src/components/form/**", + "packages/core/src/components/field/**", + "packages/core/src/components/fieldset/**" + ], "claims": [], - "symbols": ["Form", "FormProps"], + "symbols": ["Field", "Fieldset", "Form", "FormProps"], "hashes": { - "typeSurface": "7b374d45d53d4535", - "outline": "fc23844ab3a67563", + "typeSurface": "1f163cea5d23f327", + "outline": "7eb7d87a97e6ba42", "snapshot": "5d7a7904c5256f29", "outputMd": "c97c3d6e426d8b29", "examples": "c56460c1a93d532b" @@ -836,12 +904,20 @@ "outline": "docs-src/components/global-header-layout.docs.outline.md", "output": "docs/components/global-header-layout.md", "examples": null, - "sources": ["packages/core/src/components/sidebar/global-header-layout.tsx"], + "sources": [ + "packages/core/src/components/sidebar/global-header-layout.tsx", + "packages/core/src/components/sidebar/global-header.tsx" + ], "claims": [], - "symbols": ["GlobalHeaderLayout", "GlobalHeaderLayoutProps"], + "symbols": [ + "GlobalHeader", + "GlobalHeaderLayout", + "GlobalHeaderLayoutProps", + "GlobalHeaderProps" + ], "hashes": { - "typeSurface": "70edbc7c68dcc7aa", - "outline": "44d1374ea9192b2e", + "typeSurface": "1e8c3a931efa81dd", + "outline": "bea325cb238fa1cc", "snapshot": null, "outputMd": "fe86450720c4d586", "examples": null @@ -892,9 +968,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "3407c9f64b8818d0", + "outline": "3480e7ace35e3e33", "snapshot": null, - "outputMd": "dda25877f7e40b82", + "outputMd": "4bdb31f22224dfc3", "examples": null } }, @@ -909,9 +985,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "190b6fddf62a7214", + "outline": "594acc401fdb99fd", "snapshot": null, - "outputMd": "bc694f0965c1d049", + "outputMd": "246bd29aea5d4333", "examples": null } }, @@ -926,9 +1002,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "346484ce0f450c7a", + "outline": "aed573c217e2cbfa", "snapshot": null, - "outputMd": "3363ac1c6a7905f8", + "outputMd": "b35b6e0f0e685b4f", "examples": null } }, @@ -943,9 +1019,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "ff7a089596252e7a", + "outline": "b697d163ecb790f6", "snapshot": null, - "outputMd": "1b08b8aa0d013dc7", + "outputMd": "be1dfedfe13174e5", "examples": null } }, @@ -1091,14 +1167,14 @@ "outline": "docs-src/components/menu.docs.outline.md", "output": "docs/components/menu.md", "examples": "docs-src/components/menu.docs.examples.tsx", - "sources": ["packages/core/src/components/menu/**"], + "sources": ["packages/core/src/components/menu/**", "packages/core/src/lib/position.ts"], "claims": [], - "symbols": ["Menu"], + "symbols": ["Menu", "PositionProps"], "hashes": { - "typeSurface": "943616def28cafb0", - "outline": "3cb7ee774065168f", + "typeSurface": "70443316dbb76f50", + "outline": "e62f73e86bc2400c", "snapshot": "212e64b91be708c9", - "outputMd": "05e75c52c12c3c32", + "outputMd": "6ecd9a3297729b38", "examples": "8c07f9e1d03c5524" } }, @@ -1138,18 +1214,29 @@ }, "modules-and-resources": { "slug": "modules-and-resources", - "kind": "prose", + "kind": "code-backed", "outline": "docs-src/concepts/modules-and-resources.docs.outline.md", "output": "docs/concepts/modules-and-resources.md", "examples": null, - "sources": [], + "sources": ["packages/core/src/resource.tsx"], "claims": [], - "symbols": [], + "symbols": [ + "ErrorBoundaryComponent", + "Guard", + "GuardContext", + "GuardResult", + "ResourceComponentProps", + "defineModule", + "defineResource", + "hidden", + "pass", + "redirectTo" + ], "hashes": { - "typeSurface": null, - "outline": "5dc437fe5f4c9975", + "typeSurface": "7ec80a1d3849df6b", + "outline": "6f5d50b35c95b5de", "snapshot": null, - "outputMd": "bf15b5460f22d165", + "outputMd": "4bc8fd13b43174ed", "examples": null } }, @@ -1228,11 +1315,61 @@ "output": "docs/concepts/routing-navigation.md", "examples": null, "sources": [], - "claims": [], - "symbols": [], + "claims": [ + "Blocker", + "BlockerFunction", + "Link", + "LinkProps", + "Location", + "NavLink", + "NavLinkProps", + "Navigate", + "NavigateFunction", + "NavigateOptions", + "Navigation", + "Params", + "PathMatch", + "To", + "useBeforeUnload", + "useBlocker", + "useLocation", + "useMatch", + "useNavigate", + "useNavigation", + "useParams", + "useResolvedPath", + "useRouteError", + "useSearchParams" + ], + "symbols": [ + "Blocker", + "BlockerFunction", + "Link", + "LinkProps", + "Location", + "NavLink", + "NavLinkProps", + "Navigate", + "NavigateFunction", + "NavigateOptions", + "Navigation", + "Params", + "PathMatch", + "To", + "useBeforeUnload", + "useBlocker", + "useLocation", + "useMatch", + "useNavigate", + "useNavigation", + "useParams", + "useResolvedPath", + "useRouteError", + "useSearchParams" + ], "hashes": { "typeSurface": null, - "outline": "72c3109bd8031a7c", + "outline": "42a9fc44fd42fce8", "snapshot": null, "outputMd": "225fb6e2b1efa4f6", "examples": null @@ -1244,14 +1381,17 @@ "outline": "docs-src/components/select.docs.outline.md", "output": "docs/components/select.md", "examples": "docs-src/components/select.docs.examples.tsx", - "sources": ["packages/core/src/components/select/**"], + "sources": [ + "packages/core/src/components/select/**", + "packages/core/src/components/dropdown-items/**" + ], "claims": [], - "symbols": ["Select", "SelectAsyncFetcher"], + "symbols": ["ItemGroup", "MappedItem", "Select", "SelectAsyncFetcher"], "hashes": { - "typeSurface": "429710973dfa912b", - "outline": "c542e6fc7c775d4a", + "typeSurface": "f2ada72158311d37", + "outline": "813f81e2f7809a60", "snapshot": "c7aa045d22de4cc7", - "outputMd": "7e20d26620366d82", + "outputMd": "a3127c163ee0d41a", "examples": "260fb265390c4947" } }, @@ -1312,14 +1452,31 @@ "outline": "docs-src/components/sidebar-layout.docs.outline.md", "output": "docs/components/sidebar-layout.md", "examples": null, - "sources": ["packages/core/src/components/sidebar/sidebar-layout.tsx"], + "sources": [ + "packages/core/src/components/sidebar/sidebar-layout.tsx", + "packages/core/src/components/sidebar/use-app-shell-sidebar.ts", + "packages/core/src/components/sidebar/sidebar-separator.tsx", + "packages/core/src/components/sidebar/dynamic-breadcrumb.tsx", + "packages/core/src/components/sidebar/content-container.tsx", + "packages/core/src/contexts/scroll-container-context.tsx" + ], "claims": [], - "symbols": ["SidebarLayout", "SidebarLayoutProps"], + "symbols": [ + "AppShellSidebarState", + "ContentContainerProps", + "DynamicBreadcrumb", + "SidebarLayout", + "SidebarLayoutProps", + "SidebarSeparator", + "useAppShellScrollContainer", + "useAppShellSidebar", + "usePathSegments" + ], "hashes": { - "typeSurface": "bbc777033634cea5", - "outline": "751ddd6bd3fe3ba6", + "typeSurface": "d0447013eda12f0a", + "outline": "b78948aa7736502b", "snapshot": null, - "outputMd": "af971809e42dfdb8", + "outputMd": "872a4d374bdf1923", "examples": null } }, @@ -1538,10 +1695,10 @@ "symbols": ["Tooltip"], "hashes": { "typeSurface": "d652b740db9471c7", - "outline": "6c02c292edc460ca", + "outline": "95fae4539ee3b7a6", "snapshot": "19ed635d615f04af", - "outputMd": "c3faff5e48922922", - "examples": "aadf606163c14558" + "outputMd": "0bcfb46bb66dffdc", + "examples": "5dd806683aaefa43" } }, "tree": { @@ -1577,35 +1734,55 @@ }, "use-ai-chat": { "slug": "use-ai-chat", - "kind": "prose", + "kind": "code-backed", "outline": "docs-src/hooks/use-ai-chat.docs.outline.md", "output": "docs/api/use-ai-chat.md", "examples": null, - "sources": [], + "sources": ["packages/core/src/ai/use-ai-chat.ts", "packages/core/src/ai/tools.ts"], "claims": [], - "symbols": [], + "symbols": [ + "AIChatMessage", + "AIChatStatus", + "AIChatToolContext", + "AIChatToolSchema", + "AILocalTool", + "defineAIChatTool", + "useAIChat" + ], "hashes": { - "typeSurface": null, - "outline": "807ee6ee2b33d5de", + "typeSurface": "6bcd382ee9880eaf", + "outline": "d89465e8df7eea67", "snapshot": null, - "outputMd": "3bcaceab3290ca92", + "outputMd": "23355a0bf39b25da", "examples": null } }, "use-app-shell": { "slug": "use-app-shell", - "kind": "prose", + "kind": "code-backed", "outline": "docs-src/hooks/use-app-shell.docs.outline.md", "output": "docs/api/use-app-shell.md", "examples": "docs-src/hooks/use-app-shell.docs.examples.tsx", - "sources": [], + "sources": ["packages/core/src/contexts/appshell-context.tsx"], "claims": [], - "symbols": [], + "symbols": [ + "AppInfo", + "AppInfoEntry", + "AppShellRegister", + "ContextData", + "RouteParams", + "TimeZone", + "useAppShell", + "useAppShellConfig", + "useAppShellData", + "useResolvedLocale", + "useTimeZone" + ], "hashes": { - "typeSurface": null, - "outline": "9fc0b4f43e702ebc", + "typeSurface": "e265b1572a4af12d", + "outline": "4b06081fab812e6f", "snapshot": null, - "outputMd": "18f76736141a6cf5", + "outputMd": "3ca2ab1005dd456d", "examples": "f70172b3ffe4a317" } }, @@ -1620,9 +1797,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "e9d8c057d07d752d", + "outline": "0b0b446c9be6eec8", "snapshot": null, - "outputMd": "fda8a8d0359561dd", + "outputMd": "c843db66f81d5d33", "examples": "2de13d7a01e94807" } }, @@ -1637,9 +1814,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "8186a6955258ce57", + "outline": "f558db6c2ac0baf1", "snapshot": null, - "outputMd": "2ad40b17e578246d", + "outputMd": "4ef17ad66dd9522a", "examples": null } }, @@ -1654,24 +1831,24 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "5e5a5a4bd831cd43", + "outline": "8d7836f608a9b906", "snapshot": null, - "outputMd": "7573794b872af4c8", + "outputMd": "0137e56d7bd78957", "examples": null } }, "use-override-breadcrumb": { "slug": "use-override-breadcrumb", - "kind": "prose", + "kind": "code-backed", "outline": "docs-src/hooks/use-override-breadcrumb.docs.outline.md", "output": "docs/api/use-override-breadcrumb.md", "examples": null, - "sources": [], + "sources": ["packages/core/src/hooks/use-override-breadcrumb.ts"], "claims": [], - "symbols": [], + "symbols": ["useOverrideBreadcrumb"], "hashes": { - "typeSurface": null, - "outline": "829cc2f578187e08", + "typeSurface": "1d86f173d76d02b5", + "outline": "2e799ff24a520be1", "snapshot": null, "outputMd": "6ec55fc3dfd8c21d", "examples": null @@ -1679,18 +1856,18 @@ }, "use-page-meta": { "slug": "use-page-meta", - "kind": "prose", + "kind": "code-backed", "outline": "docs-src/hooks/use-page-meta.docs.outline.md", "output": "docs/api/use-page-meta.md", "examples": null, - "sources": [], + "sources": ["packages/core/src/hooks/use-page-meta.ts"], "claims": [], - "symbols": [], + "symbols": ["PageMeta", "usePageMeta"], "hashes": { - "typeSurface": null, - "outline": "534c9034e7016fc6", + "typeSurface": "ec87fba2d8ddf9a2", + "outline": "bde4b4db3694b04d", "snapshot": null, - "outputMd": "f988bdc0fb180f0c", + "outputMd": "63e59386d0996c45", "examples": null } }, @@ -1705,9 +1882,9 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "990b894284c803c2", + "outline": "cfec989087062cb0", "snapshot": null, - "outputMd": "7144ae3dc68aa65b", + "outputMd": "6122c68c72a17608", "examples": null } }, @@ -1739,24 +1916,24 @@ "symbols": [], "hashes": { "typeSurface": null, - "outline": "80000f6fbaa15a6a", + "outline": "dcecfff33ac6de0d", "snapshot": null, - "outputMd": "1a44180ec84ce4b9", + "outputMd": "8a0bcc61b2640093", "examples": null } }, "use-theme": { "slug": "use-theme", - "kind": "prose", + "kind": "code-backed", "outline": "docs-src/hooks/use-theme.docs.outline.md", "output": "docs/api/use-theme.md", "examples": "docs-src/hooks/use-theme.docs.examples.tsx", - "sources": [], + "sources": ["packages/core/src/contexts/theme-context.tsx"], "claims": [], - "symbols": [], + "symbols": ["ColorTheme", "ResolvedColorTheme", "useTheme"], "hashes": { - "typeSurface": null, - "outline": "a03f681bf17dc2bf", + "typeSurface": "29d07acafcb8cb71", + "outline": "fc0017d330ece057", "snapshot": null, "outputMd": "000e2603cef83d47", "examples": "c2942d679a2b5ee3" @@ -1781,16 +1958,16 @@ }, "use-toast": { "slug": "use-toast", - "kind": "prose", + "kind": "code-backed", "outline": "docs-src/hooks/use-toast.docs.outline.md", "output": "docs/api/use-toast.md", "examples": "docs-src/hooks/use-toast.docs.examples.tsx", - "sources": [], + "sources": ["packages/core/src/hooks/use-toast.ts"], "claims": [], - "symbols": [], + "symbols": ["useToast"], "hashes": { - "typeSurface": null, - "outline": "9100b0606aa15761", + "typeSurface": "c157a9b35c9e8885", + "outline": "80c4d89611285727", "snapshot": null, "outputMd": "3f763c8074704709", "examples": "0dce35625d5e56cf" @@ -1815,11 +1992,11 @@ } }, "skill": { - "packages/core/skills/app-shell-patterns/references/concepts/authentication.md": "a3f7aa913d59fdd7", + "packages/core/skills/app-shell-patterns/references/concepts/authentication.md": "d067f3112db6e053", "packages/core/skills/app-shell-patterns/references/concepts/custom-components.md": "efba56e470f4f164", - "packages/core/skills/app-shell-patterns/references/concepts/file-based-routing.md": "e189f95dbe4b0286", + "packages/core/skills/app-shell-patterns/references/concepts/file-based-routing.md": "17558cfa495ab026", "packages/core/skills/app-shell-patterns/references/concepts/graphql.md": "0acfb736bcf90eff", - "packages/core/skills/app-shell-patterns/references/concepts/modules-and-resources.md": "bf15b5460f22d165", + "packages/core/skills/app-shell-patterns/references/concepts/modules-and-resources.md": "4bc8fd13b43174ed", "packages/core/skills/app-shell-patterns/references/concepts/routing-navigation.md": "225fb6e2b1efa4f6", "packages/core/skills/app-shell-patterns/references/concepts/sidebar-navigation.md": "5a3c8bac248061f9", "packages/core/skills/app-shell-patterns/references/concepts/styling-theming.md": "ba49357df367615b", @@ -1828,20 +2005,20 @@ "packages/core/skills/app-shell-patterns/references/components/activity-card.md": "230039d9f96fd264", "packages/core/skills/app-shell-patterns/references/components/ai-chat.md": "008761ccc93ef0fe", "packages/core/skills/app-shell-patterns/references/components/alert.md": "9b237d9c19b54102", - "packages/core/skills/app-shell-patterns/references/components/app-shell.md": "cd57abd4909118a4", + "packages/core/skills/app-shell-patterns/references/components/app-shell.md": "50e2cd78a3629b64", "packages/core/skills/app-shell-patterns/references/components/appearance-switcher.md": "b55f1d538651d467", "packages/core/skills/app-shell-patterns/references/components/attachment.md": "8922f126009ee1df", "packages/core/skills/app-shell-patterns/references/components/autocomplete.md": "f3179004d35f8c88", "packages/core/skills/app-shell-patterns/references/components/avatar.md": "1a98b46e63c2cf7c", - "packages/core/skills/app-shell-patterns/references/components/badge.md": "7897980baf93a074", + "packages/core/skills/app-shell-patterns/references/components/badge.md": "f274f45e7ad34758", "packages/core/skills/app-shell-patterns/references/components/button.md": "be862b0bff15cc1a", "packages/core/skills/app-shell-patterns/references/components/card.md": "c1f88a287f197d79", "packages/core/skills/app-shell-patterns/references/components/checkbox.md": "ebe55c40fb5fb2e6", "packages/core/skills/app-shell-patterns/references/components/combobox.md": "c79cd0fe175187e3", - "packages/core/skills/app-shell-patterns/references/components/command-palette.md": "7e5bc675a593791a", + "packages/core/skills/app-shell-patterns/references/components/command-palette.md": "60ca478a7a266726", "packages/core/skills/app-shell-patterns/references/components/csv-importer.md": "10c04c78bb846c9a", "packages/core/skills/app-shell-patterns/references/components/data-table.md": "c32c7ccf13528bf1", - "packages/core/skills/app-shell-patterns/references/components/date-picker.md": "376e7d4ad14c2934", + "packages/core/skills/app-shell-patterns/references/components/date-picker.md": "0625c602d510a9ae", "packages/core/skills/app-shell-patterns/references/components/default-header.md": "375e55f4b12fa2be", "packages/core/skills/app-shell-patterns/references/components/default-sidebar.md": "9b1672c71b6db3ff", "packages/core/skills/app-shell-patterns/references/components/description-card.md": "8930a410d7d45f89", @@ -1854,13 +2031,13 @@ "packages/core/skills/app-shell-patterns/references/components/input.md": "876dca4c3b3bc9c5", "packages/core/skills/app-shell-patterns/references/components/item-list.md": "0190e797cd8ed318", "packages/core/skills/app-shell-patterns/references/components/layout.md": "3b8bf269c15e2fa5", - "packages/core/skills/app-shell-patterns/references/components/menu.md": "05e75c52c12c3c32", + "packages/core/skills/app-shell-patterns/references/components/menu.md": "6ecd9a3297729b38", "packages/core/skills/app-shell-patterns/references/components/metric-card.md": "4742120c07f00991", - "packages/core/skills/app-shell-patterns/references/components/select.md": "7e20d26620366d82", + "packages/core/skills/app-shell-patterns/references/components/select.md": "a3127c163ee0d41a", "packages/core/skills/app-shell-patterns/references/components/sheet.md": "0be1c6430a4b7ec1", "packages/core/skills/app-shell-patterns/references/components/sidebar-group.md": "370eccb532278bd1", "packages/core/skills/app-shell-patterns/references/components/sidebar-item.md": "9236c03e53aa79f2", - "packages/core/skills/app-shell-patterns/references/components/sidebar-layout.md": "af971809e42dfdb8", + "packages/core/skills/app-shell-patterns/references/components/sidebar-layout.md": "872a4d374bdf1923", "packages/core/skills/app-shell-patterns/references/components/sidebar-section.md": "281cfa2dcbff14be", "packages/core/skills/app-shell-patterns/references/components/spinner.md": "eec440408611a233", "packages/core/skills/app-shell-patterns/references/components/table.md": "c5933b640a78c3bf", @@ -1869,32 +2046,32 @@ "packages/core/skills/app-shell-patterns/references/components/textarea.md": "cf324904899ed318", "packages/core/skills/app-shell-patterns/references/components/timeline.md": "5a0c1ec509b4c6dc", "packages/core/skills/app-shell-patterns/references/components/toolbar.md": "f8a45109e97391f5", - "packages/core/skills/app-shell-patterns/references/components/tooltip.md": "c3faff5e48922922", + "packages/core/skills/app-shell-patterns/references/components/tooltip.md": "0bcfb46bb66dffdc", "packages/core/skills/app-shell-patterns/references/components/tree.md": "6010470f3c41538a", "packages/core/skills/app-shell-patterns/references/components/with-guard.md": "86bb46eae81feb56", "packages/core/skills/app-shell-patterns/references/api/aggregations.md": "96c85ba79f5c64cc", "packages/core/skills/app-shell-patterns/references/api/create-ai-gateway-client.md": "ed0db6372d25e2f9", - "packages/core/skills/app-shell-patterns/references/api/create-typed-paths.md": "4c3a858d3eb02a2a", + "packages/core/skills/app-shell-patterns/references/api/create-typed-paths.md": "8296d75638c44123", "packages/core/skills/app-shell-patterns/references/api/define-i18n-labels.md": "3035dea9ac31b7f5", - "packages/core/skills/app-shell-patterns/references/api/define-module.md": "75361d7687b43878", - "packages/core/skills/app-shell-patterns/references/api/define-resource.md": "27e4d84b41cf40e0", - "packages/core/skills/app-shell-patterns/references/api/guards/hidden.md": "dda25877f7e40b82", - "packages/core/skills/app-shell-patterns/references/api/guards/overview.md": "bc694f0965c1d049", - "packages/core/skills/app-shell-patterns/references/api/guards/pass.md": "3363ac1c6a7905f8", - "packages/core/skills/app-shell-patterns/references/api/guards/redirect-to.md": "1b08b8aa0d013dc7", + "packages/core/skills/app-shell-patterns/references/api/define-module.md": "47bb307116c6f41f", + "packages/core/skills/app-shell-patterns/references/api/define-resource.md": "83e9ee8ceb56d3c6", + "packages/core/skills/app-shell-patterns/references/api/guards/hidden.md": "4bdb31f22224dfc3", + "packages/core/skills/app-shell-patterns/references/api/guards/overview.md": "246bd29aea5d4333", + "packages/core/skills/app-shell-patterns/references/api/guards/pass.md": "b35b6e0f0e685b4f", + "packages/core/skills/app-shell-patterns/references/api/guards/redirect-to.md": "be1dfedfe13174e5", "packages/core/skills/app-shell-patterns/references/api/router/use-location.md": "ccf87add77994830", "packages/core/skills/app-shell-patterns/references/api/router/use-navigate.md": "d018cb13a7ddc38b", "packages/core/skills/app-shell-patterns/references/api/router/use-params.md": "78c15519a8339ebb", - "packages/core/skills/app-shell-patterns/references/api/use-ai-chat.md": "3bcaceab3290ca92", - "packages/core/skills/app-shell-patterns/references/api/use-app-shell.md": "18f76736141a6cf5", - "packages/core/skills/app-shell-patterns/references/api/use-app-shell-config.md": "fda8a8d0359561dd", - "packages/core/skills/app-shell-patterns/references/api/use-app-shell-data.md": "2ad40b17e578246d", - "packages/core/skills/app-shell-patterns/references/api/use-auth.md": "7573794b872af4c8", + "packages/core/skills/app-shell-patterns/references/api/use-ai-chat.md": "23355a0bf39b25da", + "packages/core/skills/app-shell-patterns/references/api/use-app-shell.md": "3ca2ab1005dd456d", + "packages/core/skills/app-shell-patterns/references/api/use-app-shell-config.md": "c843db66f81d5d33", + "packages/core/skills/app-shell-patterns/references/api/use-app-shell-data.md": "4ef17ad66dd9522a", + "packages/core/skills/app-shell-patterns/references/api/use-auth.md": "0137e56d7bd78957", "packages/core/skills/app-shell-patterns/references/api/use-override-breadcrumb.md": "6ec55fc3dfd8c21d", - "packages/core/skills/app-shell-patterns/references/api/use-page-meta.md": "f988bdc0fb180f0c", - "packages/core/skills/app-shell-patterns/references/api/use-register-command-palette-actions.md": "7144ae3dc68aa65b", + "packages/core/skills/app-shell-patterns/references/api/use-page-meta.md": "63e59386d0996c45", + "packages/core/skills/app-shell-patterns/references/api/use-register-command-palette-actions.md": "6122c68c72a17608", "packages/core/skills/app-shell-patterns/references/api/use-resolved-locale.md": "eb5e8371ba10d771", - "packages/core/skills/app-shell-patterns/references/api/use-route-error.md": "1a44180ec84ce4b9", + "packages/core/skills/app-shell-patterns/references/api/use-route-error.md": "8a0bcc61b2640093", "packages/core/skills/app-shell-patterns/references/api/use-theme.md": "000e2603cef83d47", "packages/core/skills/app-shell-patterns/references/api/use-time-zone.md": "717d6989930fb8c8", "packages/core/skills/app-shell-patterns/references/api/use-toast.md": "3f763c8074704709", @@ -1909,7 +2086,7 @@ "packages/core/skills/app-shell-patterns/references/patterns/interaction-toast.md": "f68bdab855730f48", "packages/core/skills/app-shell-patterns/references/pages/document-collection.md": "e79d9120d86db198", "packages/core/skills/app-shell-patterns/references/pages/document-detail.md": "e07c7fee2478a21d", - "packages/core/skills/app-shell-patterns/SKILL.md": "18efee79280174e7", + "packages/core/skills/app-shell-patterns/SKILL.md": "dfc2f40438ad075c", "packages/core/skills/app-shell-upgrade/references/migrations.md": "9bd2735c34fd35e3", "packages/core/skills/app-shell-upgrade/SKILL.md": "f9be942f3e596c00" } diff --git a/docs-src/components/app-shell.docs.outline.md b/docs-src/components/app-shell.docs.outline.md index f879726c0..4eebb3005 100644 --- a/docs-src/components/app-shell.docs.outline.md +++ b/docs-src/components/app-shell.docs.outline.md @@ -27,6 +27,7 @@ const modules = [ path: "dashboard", component: DashboardPage, meta: { title: "Dashboard" }, + resources: [], }), ]; @@ -231,7 +232,7 @@ Access the configured timezone in components using [`useTimeZone`](../api/use-ti ### errorBoundary - **Type:** `ErrorBoundaryComponent` (optional) -- **Description:** Global error boundary component applied to all routes +- **Description:** Global error boundary element applied to all routes. Pass JSX such as ``, not a component constructor. ```tsx import { Text, useRouteError } from "@tailor-platform/app-shell"; @@ -246,7 +247,7 @@ const GlobalErrorBoundary = () => { ); }; - +}> {/* ... */} ; ``` @@ -262,6 +263,8 @@ First, define your context data type using module augmentation: ```typescript // types.d.ts — `User` and `ApiClient` are your application's own types +import "@tailor-platform/app-shell"; + declare module "@tailor-platform/app-shell" { interface AppShellRegister { contextData: { @@ -471,6 +474,7 @@ const modules = [ path: "dashboard", component: DashboardPage, meta: { title: "Dashboard" }, + resources: [], }), defineModule({ path: "products", @@ -508,7 +512,7 @@ function App() { settingsResources={settingsResources} locale="en" defaultColorTheme="system" - errorBoundary={ErrorBoundary} + errorBoundary={} contextData={{ currentUser }} > diff --git a/docs-src/components/badge.docs.outline.md b/docs-src/components/badge.docs.outline.md index da358d257..cfe73d6e0 100644 --- a/docs-src/components/badge.docs.outline.md +++ b/docs-src/components/badge.docs.outline.md @@ -5,6 +5,7 @@ title: Badge description: Display status, labels, and tags with customizable variants sources: - packages/core/src/components/badge/** + - packages/core/src/components/badge-list/** --- # Badge diff --git a/docs-src/components/command-palette.docs.outline.md b/docs-src/components/command-palette.docs.outline.md index 0f303ebd6..666fedc96 100644 --- a/docs-src/components/command-palette.docs.outline.md +++ b/docs-src/components/command-palette.docs.outline.md @@ -5,6 +5,7 @@ title: CommandPalette description: Keyboard-driven quick navigation with fuzzy search for all routes in your application sources: - packages/core/src/components/command-palette/** + - packages/core/src/contexts/command-palette-context.tsx --- # CommandPalette @@ -54,6 +55,34 @@ The CommandPalette will automatically: | `Enter` | Navigate to selected route | | Type to search | Filter routes by fuzzy search | +## Opening programmatically + +Call `useOpenCommandPalette()` at the top level of a component inside `AppShell`. It returns a function that opens the built-in palette; call that function from an event handler. + +```tsx +import { Button, useOpenCommandPalette } from "@tailor-platform/app-shell"; + +function SearchActions() { + const openCommandPalette = useOpenCommandPalette(); + + return ( + <> + + + + + ); +} +``` + +The returned function accepts an optional `OpenCommandPaletteOptions` object: + +| Property | Type | Description | +| -------- | -------- | ------------------------------------------------------------------------------------------------------------ | +| `search` | `string` | Initial search text. Omit it to open with an empty search. A registered `PREFIX:` activates its search mode. | + +Each call initializes the search, even if the palette is already open. The `ORD:` example requires an `ORD` source in AppShell's `searchSources`; without a matching source, the text is treated as an ordinary page/action search. + ## Features ### Fuzzy Search @@ -119,6 +148,8 @@ function OrderDetailPage() { { key: "confirm", label: "Confirm order", onSelect: handleConfirm }, { key: "cancel", label: "Cancel order", icon: , onSelect: handleCancel }, ]); + + return
{/* page content */}
; } ``` @@ -225,24 +256,27 @@ function App() { ### Prefix Syntax -The prefix match is **case-sensitive**. When a user types `ORD:`, the string after the colon (including any space) is forwarded to `search` as the query: +The prefix match is **case-sensitive**. When an initial value activates a search mode (for example, pasted text or programmatic opening), leading whitespace after the colon is removed from the initial query: ``` -User types: ORD: +Initial input: ORD: → search("", { signal }) — empty query, show all or hint -User types: ORD:12345 +Initial input: ORD:12345 → search("12345", { signal }) -User types: ORD: alice - → search(" alice", { signal }) — leading space preserved +Initial input: ORD: alice + → search("alice", { signal }) — leading space removed ``` +Once the mode is active, subsequent edits to its query are passed to `search` as entered. + ## Extending the built-in palette The supported extension points are: - `searchSources` on `AppShell` for async, prefix-activated search modes +- `useOpenCommandPalette` for opening with an optional initial search - [`useRegisterCommandPaletteActions`](../api/use-register-command-palette-actions.md) for page-level actions - [`ActionPanel`](./action-panel.md), whose enabled rows are registered automatically @@ -374,7 +408,7 @@ The CommandPalette follows these design principles: ## Related Components - [AppShell](./app-shell.md) - Root component that provides CommandPalette -- [SidebarLayout](./sidebar-layout.md) - Layout that includes CommandPalette +- [SidebarLayout](./sidebar-layout.md) - Default layout with a search entry for CommandPalette ## Related Concepts @@ -411,5 +445,5 @@ The CommandPalette follows these design principles: **Solutions:** 1. Check if another app is capturing the shortcut -2. Verify you're using `SidebarLayout` (CommandPalette is included) +2. Verify the page is inside `AppShell`, which provides the built-in CommandPalette 3. Check browser console for JavaScript errors diff --git a/docs-src/components/date-picker.docs.outline.md b/docs-src/components/date-picker.docs.outline.md index 207fdb78a..6a41a370c 100644 --- a/docs-src/components/date-picker.docs.outline.md +++ b/docs-src/components/date-picker.docs.outline.md @@ -5,6 +5,19 @@ title: DatePicker description: Accessible date input components (@internationalized/date + Base UI) sources: - packages/core/src/components/date-field/** + - packages/core/src/components/calendar/** +claims: + - CalendarDate + - CalendarDateTime + - DateValue + - Time + - ZonedDateTime + - getLocalTimeZone + - parseAbsolute + - parseDate + - parseDateTime + - parseZonedDateTime +upstream: https://react-spectrum.adobe.com/internationalized/date/ --- # DatePicker @@ -32,6 +45,41 @@ import { The examples below also import `Button`, `Form`, and `Text` from `@tailor-platform/app-shell`, and `useId` and `useState` from `react`. +## Date values and parsing helpers + +AppShell re-exports these types and helpers from [`@internationalized/date`](https://react-spectrum.adobe.com/internationalized/date/) so applications can import them from `@tailor-platform/app-shell` without an additional dependency. + +| Export | Purpose | +| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| `CalendarDate` | Date-only value, without a time or timezone. | +| `CalendarDateTime` | Date and time without a timezone; it does not identify a unique instant. | +| `ZonedDateTime` | Date and time with a timezone and UTC offset. | +| `Time` | Time of day without a date or timezone. | +| `DateValue` | Union of `CalendarDate`, `CalendarDateTime`, and `ZonedDateTime`, accepted by the date controls. It does not include `Time`. | +| `parseDate(text)` | Parse an ISO date into a `CalendarDate`. | +| `parseDateTime(text)` | Parse an ISO date/time without a timezone into a `CalendarDateTime`. | +| `parseAbsolute(text, timeZone)` | Parse an ISO instant containing `Z` or an offset and represent it in the supplied IANA timezone as a `ZonedDateTime`. | +| `parseZonedDateTime(text)` | Parse a date/time with a bracketed IANA timezone into a `ZonedDateTime`, preserving the named zone. | +| `getLocalTimeZone()` | Read the environment's local IANA timezone. This does not read AppShell's `timeZone` setting. | + +The first five exports are **types only**, not constructor values. Use the parsing helpers to create date values: + +```ts +import { + parseDate, + parseDateTime, + parseAbsolute, + parseZonedDateTime, +} from "@tailor-platform/app-shell"; + +const date = parseDate("2026-04-09"); +const localDateTime = parseDateTime("2026-04-09T09:30"); +const instantInTokyo = parseAbsolute("2026-04-09T00:30:00Z", "Asia/Tokyo"); +const zonedDateTime = parseZonedDateTime("2026-04-09T09:30[Asia/Tokyo]"); +``` + +Parsing can throw for invalid input; validate or catch errors when the string is not trusted. For application-timezone behavior in React components, call [`useTimeZone()`](../api/use-time-zone.md) at the component's top level and pass its `value` to `parseAbsolute`. Use its `today()` and `now()` methods for the current date and instant, rather than assuming the user's local timezone matches the configured one. + ## API shape `DateField` and `DatePicker` are standalone composite controls. @@ -57,9 +105,10 @@ Inside `Field.Root`: Controlled: ```tsx -const [date, setDate] = useState(null); - -; +function ControlledDateField() { + const [date, setDate] = useState(null); + return ; +} ``` ## DatePicker diff --git a/docs-src/components/default-sidebar.docs.outline.md b/docs-src/components/default-sidebar.docs.outline.md index 299cda7f4..41ab96dca 100644 --- a/docs-src/components/default-sidebar.docs.outline.md +++ b/docs-src/components/default-sidebar.docs.outline.md @@ -5,6 +5,7 @@ title: DefaultSidebar description: Built-in sidebar component for auto-generated or composed navigation, with optional search suppression and icon-rail mode sources: - packages/core/src/components/sidebar/default-sidebar.tsx + - packages/core/src/components/sidebar/primitives.tsx --- # DefaultSidebar diff --git a/docs-src/components/form.docs.outline.md b/docs-src/components/form.docs.outline.md index 4d36b96f0..040c12789 100644 --- a/docs-src/components/form.docs.outline.md +++ b/docs-src/components/form.docs.outline.md @@ -5,6 +5,8 @@ title: Form, Field, and Fieldset description: Components for building validated forms with automatic accessibility wiring, validation state management, and optional React Hook Form integration sources: - packages/core/src/components/form/** + - packages/core/src/components/field/** + - packages/core/src/components/fieldset/** --- # Form, Field, and Fieldset diff --git a/docs-src/components/global-header-layout.docs.outline.md b/docs-src/components/global-header-layout.docs.outline.md index 65d89c3fb..658b921e8 100644 --- a/docs-src/components/global-header-layout.docs.outline.md +++ b/docs-src/components/global-header-layout.docs.outline.md @@ -5,6 +5,7 @@ title: GlobalHeaderLayout description: Opinionated layout with an app-wide header above the whole shell and a sidebar that collapses to a persistent icon rail sources: - packages/core/src/components/sidebar/global-header-layout.tsx + - packages/core/src/components/sidebar/global-header.tsx --- # GlobalHeaderLayout diff --git a/docs-src/components/menu.docs.outline.md b/docs-src/components/menu.docs.outline.md index d9eb3e307..cd758e6f9 100644 --- a/docs-src/components/menu.docs.outline.md +++ b/docs-src/components/menu.docs.outline.md @@ -5,6 +5,7 @@ title: Menu description: Dropdown menu with a compound component API, supporting checkbox/radio items, groups, separators, and nested sub-menus sources: - packages/core/src/components/menu/** + - packages/core/src/lib/position.ts --- # Menu @@ -58,11 +59,23 @@ The runnable examples also import `useState` from `react`, `Button` and `Text` f ### Menu.Content Props -| Prop | Type | Default | Description | -| ----------- | -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ----------------------------------- | -| `position` | `{ side?: "top" \| "right" \| "bottom" \| "left"; align?: "start" \| "center" \| "end"; sideOffset?: number }` | `{ side: "bottom", align: "start", sideOffset: 4 }` | Placement of the popup | -| `className` | `string` | - | Additional CSS classes | -| `children` | `React.ReactNode` | - | Menu items and other sub-components | +| Prop | Type | Default | Description | +| ----------- | ----------------- | --------------------------------------------------- | ----------------------------------- | +| `position` | `PositionProps` | `{ side: "bottom", align: "start", sideOffset: 4 }` | Placement of the popup | +| `className` | `string` | - | Additional CSS classes | +| `children` | `React.ReactNode` | - | Menu items and other sub-components | + +### PositionProps + +The public `PositionProps` type is shared by the `position` prop on `Menu.Content` and [`Tooltip.Content`](./tooltip.md#tooltipcontent-props). Import it from `@tailor-platform/app-shell` when reusing a placement configuration. + +| Property | Type | Description | +| ------------ | ---------------------------------------- | ------------------------------------ | +| `side` | `"top" \| "right" \| "bottom" \| "left"` | Preferred side of the trigger. | +| `align` | `"start" \| "center" \| "end"` | Alignment along the cross axis. | +| `sideOffset` | `number` | Distance in pixels from the trigger. | + +All properties are optional. Defaults belong to the component: Menu uses bottom/start/4px, while Tooltip uses top/center/5px. ### Menu.Item Props diff --git a/docs-src/components/select.docs.outline.md b/docs-src/components/select.docs.outline.md index 8c13b6abc..c9d622369 100644 --- a/docs-src/components/select.docs.outline.md +++ b/docs-src/components/select.docs.outline.md @@ -5,6 +5,7 @@ title: Select description: Single or multi-select dropdown with optional async data fetching sources: - packages/core/src/components/select/** + - packages/core/src/components/dropdown-items/** --- # Select @@ -17,7 +18,7 @@ The `Select` component provides a fully assembled single or multi-select dropdow import { Select } from "@tailor-platform/app-shell"; ``` -The examples below also import `useState` from `react`, and `Field`, `Text`, and the `SelectAsyncFetcher` type from `@tailor-platform/app-shell`. +The examples below also import `useState` from `react`, and `Button`, `Field`, `Text`, and the `SelectAsyncFetcher` type from `@tailor-platform/app-shell`. ## Basic Usage @@ -45,6 +46,8 @@ The examples below also import `useState` from `react`, and `Field`, `Text`, and ### MappedItem +`MappedItem` and `ItemGroup` are public types shared by `Select`, `Combobox`, and `Autocomplete`; import them from `@tailor-platform/app-shell`. + ```ts interface MappedItem { label: string; // Display text, used for filtering and a11y @@ -154,14 +157,19 @@ or a server action. ### Controlled Select ```tsx -const [selected, setSelected] = useState(null); - - + ); +} ``` ### Custom Render @@ -187,46 +195,58 @@ const [selected, setSelected] = useState(null); Combine `Select.useAsync` with `Select.Parts` for full control over layout and rendering: -`Select.useAsync` accepts the same options as `Select.Async` (including `onFetchError`) and returns: +`Select.useAsync` accepts `fetcher` and optional `onFetchError`, and returns: -| Property | Type | Description | -| --------- | ------------ | ------------------------------------------------------- | -| `items` | `T[]` | Currently loaded items | -| `loading` | `boolean` | Whether a fetch is in progress | -| `error` | `unknown` | The error thrown by the last fetch, if any | -| `retry` | `() => void` | Re-runs the last fetch (use to build a custom retry UI) | +| Property | Type | Description | +| -------------- | ------------------------- | ------------------------------------------------------- | +| `items` | `T[]` | Currently loaded items | +| `loading` | `boolean` | Whether a fetch is in progress | +| `error` | `unknown` | The error thrown by the last fetch, if any | +| `retry` | `() => void` | Re-runs the last fetch (use to build a custom retry UI) | +| `onOpenChange` | `(open: boolean) => void` | Pass to the Root to fetch on open and cancel on close. | ```tsx type Fruit = { id: number; name: string }; -const fruits = Select.useAsync({ - fetcher: async ({ signal }) => { - const res = await fetch("/api/fruits", { signal }); - return res.json() as Promise; - }, - onFetchError: (error) => reportError(error), -}); - - f.name}> - - - - - {fruits.error ? ( -
- Couldn't load. -
- ) : fruits.loading ? ( -
Loading...
- ) : ( - fruits.items.map((f) => ( - - {f.name} - - )) - )} -
-
; +function FruitSelect() { + const fruits = Select.useAsync({ + fetcher: async ({ signal }) => { + const res = await fetch("/api/fruits", { signal }); + if (!res.ok) throw new Error(`Could not load fruits: ${res.status}`); + return res.json() as Promise; + }, + onFetchError: (error) => reportError(error), + }); + + return ( + + onOpenChange={fruits.onOpenChange} + itemToStringLabel={(fruit) => fruit.name} + > + + + + + {fruits.error ? ( +
+ Couldn't load.{" "} + +
+ ) : fruits.loading ? ( +
Loading...
+ ) : ( + fruits.items.map((fruit) => ( + + {fruit.name} + + )) + )} +
+ + ); +} ``` ## Accessibility diff --git a/docs-src/components/sidebar-layout.docs.outline.md b/docs-src/components/sidebar-layout.docs.outline.md index 2f4976e8f..cfdcca74c 100644 --- a/docs-src/components/sidebar-layout.docs.outline.md +++ b/docs-src/components/sidebar-layout.docs.outline.md @@ -5,6 +5,11 @@ title: SidebarLayout description: Default AppShell layout with a built-in sidebar, content header, optional app-wide top bar, and an escape-hatch body slot sources: - packages/core/src/components/sidebar/sidebar-layout.tsx + - packages/core/src/components/sidebar/use-app-shell-sidebar.ts + - packages/core/src/components/sidebar/sidebar-separator.tsx + - packages/core/src/components/sidebar/dynamic-breadcrumb.tsx + - packages/core/src/components/sidebar/content-container.tsx + - packages/core/src/contexts/scroll-container-context.tsx --- # SidebarLayout @@ -218,6 +223,16 @@ Use `body` when the stock content column is too restrictive and you need your ow `SidebarLayout.ContentContainer` is the stock main column: inset padding, pinned header slot, scroll region, and `useAppShellScrollContainer()` support. `SidebarLayout.Trigger` exposes the built-in sidebar toggle so custom headers do not need DOM workarounds. +### ContentContainerProps + +The exported `ContentContainerProps` type describes `SidebarLayout.ContentContainer` and `GlobalHeaderLayout.ContentContainer`: + +| Prop | Type | Description | +| ----------- | ----------------- | -------------------------------------------------------------------------------- | +| `header` | `React.ReactNode` | Optional pinned content above the scroll region. Omit for a bare content column. | +| `className` | `string` | Optional additional classes for the outer `
` element. | +| `children` | `React.ReactNode` | Optional scrolling content, usually the layout's `Outlet`. | + ## Reading and controlling the sidebar Use `useAppShellSidebar()` to read and control the sidebar state instead of observing internal DOM attributes or clicking the trigger through the DOM. It also exposes the effective `sidebarBehaviour`, already normalized from either public prop, so custom sidebars do not need to handle the deprecated boolean themselves. @@ -261,6 +276,23 @@ import { DynamicBreadcrumb, SidebarLayout } from "@tailor-platform/app-shell"; ; ``` +### Reading path segments + +`usePathSegments()` returns `{ basePath, segments }` for the current route. `basePath` is the configured base path or `null`. Each segment has `segment` (the URL segment), `path` (the accumulated path without the base path or a leading slash), `title` (the resolved, localized breadcrumb title), and `clickable` (whether it links to a page). + +Call the hook at the top level of a component, then iterate over its result: + +```tsx +import { usePathSegments } from "@tailor-platform/app-shell"; + +function CurrentPathTitles() { + const { segments } = usePathSegments(); + return {segments.map(({ title }) => title).join(" / ")}; +} +``` + +These titles come from route metadata; they do not include overrides from `useOverrideBreadcrumb()`. Use `DynamicBreadcrumb` for the built-in rendering, which also applies those overrides. + ## Accessing the content scroll container The AppShell is viewport-bounded (`h-svh`), so the **document itself does not scroll** — the content area does. Code that previously relied on `window`/document scroll (reading `window.scrollY`, listening to `window`'s `scroll` event, `window.scrollTo(...)`, or an `IntersectionObserver` with the default viewport root) should target the content scroll container instead. diff --git a/docs-src/components/tooltip.docs.examples.tsx b/docs-src/components/tooltip.docs.examples.tsx index 09d818672..15b86a92e 100644 --- a/docs-src/components/tooltip.docs.examples.tsx +++ b/docs-src/components/tooltip.docs.examples.tsx @@ -63,7 +63,7 @@ export function Placement() { return ( }>Trigger - + Appears on the right diff --git a/docs-src/components/tooltip.docs.outline.md b/docs-src/components/tooltip.docs.outline.md index 735d50d04..1e4820ab4 100644 --- a/docs-src/components/tooltip.docs.outline.md +++ b/docs-src/components/tooltip.docs.outline.md @@ -56,14 +56,14 @@ Wrap a section of your UI (e.g. a toolbar) with `Tooltip.Provider` to share dela ### Tooltip.Content Props -| Prop | Type | Default | Description | -| ------------ | ---------------------------------------- | ---------- | -------------------------------------------------------- | -| `side` | `"top" \| "right" \| "bottom" \| "left"` | `"top"` | Preferred placement of the tooltip | -| `align` | `"start" \| "center" \| "end"` | `"center"` | Alignment along the placement axis | -| `sideOffset` | `number` | `5` | Distance in px from the trigger | -| `noArrow` | `boolean` | `false` | When `true`, suppresses the arrow indicator on the popup | -| `className` | `string` | - | Additional CSS classes | -| `children` | `React.ReactNode` | - | Tooltip text or content | +| Prop | Type | Default | Description | +| ----------- | ----------------- | ------------------------------------------------- | --------------------------------------------------------- | +| `position` | `PositionProps` | `{ side: "top", align: "center", sideOffset: 5 }` | Preferred placement of the tooltip. | +| `noArrow` | `boolean` | `false` | When `true`, suppresses the arrow indicator on the popup. | +| `className` | `string` | - | Additional CSS classes. | +| `children` | `React.ReactNode` | - | Tooltip text or content. | + +[`PositionProps`](./menu.md#positionprops) is the public placement type shared with `Menu.Content`. Use `position={{ side: "right", align: "start" }}` to configure placement. The old flat `side`, `align`, and `sideOffset` props remain supported but deprecated; they are ignored when `position` is supplied. ## Placement diff --git a/docs-src/concepts/authentication.docs.outline.md b/docs-src/concepts/authentication.docs.outline.md index c6593309a..c69302314 100644 --- a/docs-src/concepts/authentication.docs.outline.md +++ b/docs-src/concepts/authentication.docs.outline.md @@ -1,8 +1,12 @@ --- -kind: prose +kind: code-backed group: authentication title: Authentication description: Set up OAuth2/OIDC authentication with Tailor Platform's Auth service using the AuthProvider component +sources: + - packages/core/src/contexts/auth-context.tsx +claims: + - AuthClient --- # Authentication @@ -84,6 +88,8 @@ const UserProfile = () => { | `logout` | `() => Promise` | Clears tokens and ends the session | | `checkAuthStatus` | `() => Promise` | Re-checks auth status (always makes a network request) | +`AuthState` is the exported state shape containing `isAuthenticated`, `isReady`, and `error`. `checkAuthStatus()` returns that shape; `useAuth()` exposes those fields together with the authentication methods above. + ### Return to the current page `autoLogin` records the current path, query string, and hash before redirecting, then returns there after a successful callback. Manual `login()` calls do the same by default. Pass `returnTo` to choose another same-origin destination: @@ -132,7 +138,9 @@ function ProtectedContent() { ## Auth Client -Use `createAuthClient` to create an authentication client that you pass to `AuthProvider`. The client handles token management and provides an authenticated `fetch` method for use with GraphQL clients. +Use `createAuthClient` to create an `EnhancedAuthClient` that you pass to `AuthProvider`. Create it once at module scope: if the URL contains OAuth callback parameters, client creation starts callback handling immediately, before React rendering. The client handles token management and provides an authenticated `fetch` method for use with GraphQL clients. + +`AuthClient` is the base type re-exported from [`@tailor-platform/auth-public-client`](https://www.npmjs.com/package/@tailor-platform/auth-public-client) for advanced integrations. `EnhancedAuthClient` extends that contract with AppShell helpers such as `getAppUri()`; `AuthProvider` requires this enhanced client, not just an arbitrary base client. ```tsx import { createAuthClient } from "@tailor-platform/app-shell"; @@ -291,13 +299,29 @@ The line is drawn on the shape of the response, not on how transient the underly To react to teardown yourself — clearing app-level caches, for instance — subscribe to the client's events: ```tsx -useEffect(() => { - return authClient.addEventListener((event) => { - if (event.type === "logout") { - clearAppCaches(); - } - }); -}, [authClient]); +import { useEffect } from "react"; +import type { EnhancedAuthClient } from "@tailor-platform/app-shell"; + +function SessionCleanup({ + client, + clearAppCaches, +}: { + client: EnhancedAuthClient; + clearAppCaches: () => void; +}) { + useEffect(() => { + return client.addEventListener((event) => { + if (event.type === "logout") { + clearAppCaches(); + } + }); + }, [client, clearAppCaches]); + + return null; +} + +// Mount alongside your app, using the same client passed to AuthProvider. +; ``` ## Testing diff --git a/docs-src/concepts/file-based-routing.docs.outline.md b/docs-src/concepts/file-based-routing.docs.outline.md index aedafccd7..48fbe5f9a 100644 --- a/docs-src/concepts/file-based-routing.docs.outline.md +++ b/docs-src/concepts/file-based-routing.docs.outline.md @@ -1,8 +1,10 @@ --- -kind: prose +kind: code-backed group: file-based-routing title: File-Based Routing description: Define pages via directory structure using the Vite plugin instead of explicit module configuration +sources: + - packages/core/src/fs-routes/types.ts --- # File-Based Routing @@ -155,6 +157,21 @@ For a dynamic label, use `breadcrumbTitle: (segment) => labels.t("order", { id: Other callbacks receive the URL segment; AppShell resolves any returned `LocalizedString` with the current locale. The existing `() => labels.t("orders")` form remains supported. Wrap handwritten locale functions in an outer callback rather than passing them directly. +### PageComponent Type + +`PageComponent` is the exported React function-component type with an optional `appShellPageProps: AppShellPageProps` static field. Use it when you want to annotate the component itself rather than applying `satisfies AppShellPageProps` to the metadata object: + +```tsx +import type { PageComponent } from "@tailor-platform/app-shell"; + +const AboutPage: PageComponent = () =>
About
; +AboutPage.appShellPageProps = { + meta: { title: "About" }, +}; + +export default AboutPage; +``` + ## Path Conventions | Directory Name | Converts To | Description | @@ -254,6 +271,7 @@ const ordersResource = defineResource({ }); const purchasingModule = defineModule({ path: "purchasing", + meta: { title: "Purchasing" }, resources: [ordersResource], }); diff --git a/docs-src/concepts/modules-and-resources.docs.outline.md b/docs-src/concepts/modules-and-resources.docs.outline.md index a4f4d8e55..dbe6e2517 100644 --- a/docs-src/concepts/modules-and-resources.docs.outline.md +++ b/docs-src/concepts/modules-and-resources.docs.outline.md @@ -1,8 +1,10 @@ --- -kind: prose +kind: code-backed group: modules-and-resources title: Modules and Resources description: Learn how to structure your AppShell application using modules and resources for automatic routing, navigation, and breadcrumbs +sources: + - packages/core/src/resource.tsx --- # Modules and Resources @@ -15,6 +17,8 @@ Modules and Resources both share core interface. Of interest: - `component: (props: ResourceComponentProps) => ReactNode` - the component to render when the router navigates to that module/resource (optional — omitting it causes the path to return a 404 while child routes remain accessible) - `guards?: Guard[]` - optional array of guard functions to control access based on permissions or feature flags +Module options also require `resources` and `meta`; use `[]` for no child resources and `{}` for default metadata. Resource options make `subResources` and `meta` optional. + A trivial `modules` example: ```tsx @@ -23,6 +27,7 @@ import { defineModule, defineResource, pass, hidden } from "@tailor-platform/app const appShellPropModule = [ defineModule({ path: "purchasing", + meta: { title: "Purchasing" }, component: PurchasingLandingPage, resources: [ defineResource({ @@ -44,6 +49,7 @@ const appShellPropModule = [ }), defineModule({ path: "sales", + meta: { title: "Sales" }, component: SalesLandingPage, resources: [ defineResource({ @@ -57,6 +63,7 @@ const appShellPropModule = [ // Module without component - /dashboard returns 404, child routes remain accessible defineModule({ path: "dashboard", + meta: { title: "Dashboard" }, resources: [ defineResource({ path: "overview", @@ -71,14 +78,13 @@ const appShellPropModule = [ // Module with guards for access control defineModule({ path: "reports", + meta: { title: "Reports" }, component: ReportsPage, resources: [reportsListResource], guards: [ - async ({ context, signal }) => { - const ok = await fetch("/api/me/permissions?scope=reports", { - signal, - }).then((r) => r.ok); - return ok ? pass() : hidden(); + async () => { + const response = await fetch("/api/me/permissions?scope=reports"); + return response.ok ? pass() : hidden(); }, ], }), @@ -111,6 +117,25 @@ Guards on component-less modules and resources execute correctly. For example, a > Read more about [client-side navigation](./routing-navigation.md) in AppShell apps +## Page Props and Error Boundaries + +`ResourceComponentProps` is the public type for a module or resource page's props. AppShell passes the localized `title` and the child `resources` (a module's `resources` or a resource's `subResources`). Although the type also declares an optional `icon`, the definers do not inject it into page props; icons belong to navigation metadata. + +```tsx +import { Text, type ResourceComponentProps } from "@tailor-platform/app-shell"; + +function ProductsPage({ title, resources }: ResourceComponentProps) { + return ( +
+ {title} + {resources?.length ?? 0} child resources +
+ ); +} +``` + +`ErrorBoundaryComponent` is the public type accepted by `errorBoundary`: a `ReactNode`, such as ``, **not** the component function `ErrorBoundary`. Read errors inside that element with [`useRouteError`](../api/use-route-error.md). See [`defineModule`](../api/define-module.md) and [`defineResource`](../api/define-resource.md) for examples and option types derived from their public signatures. + ## Route Guards Both modules and resources support `guards` - an array of functions that control access based on permissions, feature flags, or any other criteria. Guards are executed in order and provide: @@ -119,7 +144,9 @@ Both modules and resources support `guards` - an array of functions that control - Reusability: Share common guards across routes - Semantic constraints: Clear `pass()`, `hidden()`, or `redirectTo()` results -See the [Guards documentation](../api/guards/overview.md) for full details. +The public `Guard` function receives a `GuardContext` containing only `{ context: ContextData }` and returns a `GuardResult`, synchronously or asynchronously. Use `pass()`, `hidden()`, or `redirectTo(path)` to construct that result. No abort signal is passed to guards. + +See the [Guards documentation](../api/guards/overview.md) for the complete types and helper references. These client-side guards control navigation and rendering; the server must still enforce authorization for protected data and operations. ### Guard Examples @@ -130,12 +157,13 @@ import { defineModule, pass, hidden } from "@tailor-platform/app-shell"; const reportsModule = defineModule({ path: "reports", + meta: { title: "Reports" }, component: ReportsPage, resources: [reportsListResource], guards: [ - async ({ context }) => { - const ok = await fetch("/api/me/permissions?scope=reports").then((r) => r.ok); - return ok ? pass() : hidden(); + async () => { + const response = await fetch("/api/me/permissions?scope=reports"); + return response.ok ? pass() : hidden(); }, ], }); @@ -148,6 +176,7 @@ import { pass, hidden } from "@tailor-platform/app-shell"; const betaFeaturesModule = defineModule({ path: "beta", + meta: { title: "Beta Features" }, component: BetaFeaturesPage, resources: [newFeatureResource], guards: [ @@ -166,8 +195,9 @@ import { pass, hidden } from "@tailor-platform/app-shell"; const billingModule = defineModule({ path: "billing", + meta: { title: "Billing" }, component: BillingPage, - resources: [billingResources], + resources: billingResources, guards: [ async ({ context }) => { const plan = await getCurrentTenantPlan(); diff --git a/docs-src/concepts/routing-navigation.docs.outline.md b/docs-src/concepts/routing-navigation.docs.outline.md index f7df4ed40..65ae2d9c4 100644 --- a/docs-src/concepts/routing-navigation.docs.outline.md +++ b/docs-src/concepts/routing-navigation.docs.outline.md @@ -3,6 +3,31 @@ kind: prose group: routing-navigation title: Routing and Navigation description: Learn how to navigate between pages using React Router hooks and components re-exported from AppShell +claims: + - Blocker + - BlockerFunction + - Link + - LinkProps + - Location + - NavLink + - NavLinkProps + - Navigate + - NavigateFunction + - NavigateOptions + - Navigation + - Params + - PathMatch + - To + - useBeforeUnload + - useBlocker + - useLocation + - useMatch + - useNavigate + - useNavigation + - useParams + - useResolvedPath + - useRouteError + - useSearchParams --- # Routing and Navigation diff --git a/docs-src/hooks/create-ai-gateway-client.docs.outline.md b/docs-src/hooks/create-ai-gateway-client.docs.outline.md index 64463135d..2de4459bf 100644 --- a/docs-src/hooks/create-ai-gateway-client.docs.outline.md +++ b/docs-src/hooks/create-ai-gateway-client.docs.outline.md @@ -1,8 +1,10 @@ --- -kind: prose +kind: code-backed group: create-ai-gateway-client title: createAIGatewayClient description: Create a low-level AI Gateway client that reuses AppShell authentication +sources: + - packages/core/src/ai/client.ts --- # createAIGatewayClient diff --git a/docs-src/hooks/create-typed-paths.docs.outline.md b/docs-src/hooks/create-typed-paths.docs.outline.md index b71f120ad..c705895c9 100644 --- a/docs-src/hooks/create-typed-paths.docs.outline.md +++ b/docs-src/hooks/create-typed-paths.docs.outline.md @@ -1,31 +1,39 @@ --- -kind: prose +kind: code-backed group: create-typed-paths title: createTypedPaths -description: Generate type-safe route paths from file-based routing +description: Create type-safe route path helpers from a route-to-parameters type map +sources: + - packages/core/src/fs-routes/typed-paths.ts --- # createTypedPaths -Generates type-safe route path helpers from file-based routing structure. Only available when using the Vite plugin. +Creates a type-safe path builder from a route-to-parameters type map. The Vite plugin can generate this map and a ready-to-use `paths` helper, but the factory can also be used with a manually declared map. ## Signature ```typescript -function createTypedPaths>(pages: T): TypedPaths; +const paths = createTypedPaths(); ``` -## Parameters +The factory takes **no runtime arguments**. It does not accept a pages object or register routes. -### `pages` +## Type Parameter -- **Type:** `Record` -- **Required:** Yes -- **Description:** Pages object from virtual module (auto-generated by Vite plugin) +### `Routes` + +- **Constraint:** `Record>` +- **Description:** A map whose keys are route templates and whose values name each route's string parameters. Use `{}` for a static route. ## Return Value -Type-safe path builder functions for each route. +An object with a `for(template, params)` method: + +- Static routes need only the template. +- Dynamic routes require an object with the declared parameter names. +- The result is a URL path string; dynamic parameter values are URL-encoded. +- A query suffix on the template is preserved, such as `"/products/:id?tab=details"`. ## Usage @@ -33,85 +41,89 @@ Type-safe path builder functions for each route. ```typescript import { createTypedPaths } from "@tailor-platform/app-shell"; -import pages from "virtual:app-shell-pages"; -const paths = createTypedPaths(pages); +type Routes = { + "/products": {}; + "/products/:id": { id: string }; +}; -// Type-safe navigation -navigate(paths.products.detail({ id: "123" })); -// Result: "/products/123" +const paths = createTypedPaths(); + +paths.for("/products"); // "/products" +paths.for("/products/:id", { id: "123" }); // "/products/123" +paths.for("/products/:id?tab=details", { id: "123" }); // "/products/123?tab=details" ``` +The following examples reuse `paths` from above. Its type map must match the routes configured in your application. + ### With useNavigate -```typescript -import { useNavigate } from "@tailor-platform/app-shell"; +```tsx +import { Button, useNavigate } from "@tailor-platform/app-shell"; -function ProductCard({ product }: { product: Product }) { +function ProductCard({ id }: { id: string }) { const navigate = useNavigate(); - const paths = createTypedPaths(pages); - - const handleClick = () => { - navigate(paths.products.detail({ id: product.id })); - }; - return ; + return ; } ``` ### With Link Component -```typescript +```tsx import { Link } from "@tailor-platform/app-shell"; function ProductLink({ id }: { id: string }) { - const paths = createTypedPaths(pages); - - return ( - - View Product - - ); + return View Product; } ``` ### Nested Routes ```typescript -// File structure: -// pages/ -// orders/ -// page.tsx -// [id]/ -// page.tsx -// edit/ -// page.tsx - -paths.orders.index(); // "/orders" -paths.orders.detail({ id: "1" }); // "/orders/1" -paths.orders.edit({ id: "1" }); // "/orders/1/edit" +const orderPaths = createTypedPaths<{ + "/orders": {}; + "/orders/:id": { id: string }; + "/orders/:id/edit": { id: string }; +}>(); + +orderPaths.for("/orders"); // "/orders" +orderPaths.for("/orders/:id", { id: "1" }); // "/orders/1" +orderPaths.for("/orders/:id/edit", { id: "1" }); // "/orders/1/edit" ``` ## TypeScript Benefits ```typescript -// ✅ Type-safe parameters -paths.products.detail({ id: "123" }); // Valid +paths.for("/products/:id", { id: "123" }); // Valid -// ❌ Type error - missing required param -paths.products.detail(); // Error: Argument required +// @ts-expect-error Missing required parameters +paths.for("/products/:id"); -// ❌ Type error - wrong param name -paths.products.detail({ productId: "123" }); // Error: Unknown key +// @ts-expect-error Wrong parameter name +paths.for("/products/:id", { productId: "123" }); + +// @ts-expect-error Unknown route +paths.for("/missing"); ``` -## File-Based Routing Only +## Generated File-Based Routes + +With the Vite plugin's `generateTypedRoutes` option enabled, prefer importing `paths` from your generated routes file instead of maintaining the type map yourself. The generated file calls `createTypedPaths()` for you; application code still uses `paths.for(template, params)`. + +```tsx +import { Link } from "@tailor-platform/app-shell"; +import { paths } from "./routes.generated"; -This function is only available when using the Vite plugin with file-based routing. +function ProductLink({ id }: { id: string }) { + return View Product; +} +``` -See [File-Based Routing](../concepts/file-based-routing.md) for setup. +This assumes your generated map contains `/products/:id`. The import path depends on the configured output location. See [File-Based Routing](../concepts/file-based-routing.md) for setup. ## Related - [File-Based Routing](../concepts/file-based-routing.md) - Setup guide +- [Routing and Navigation](../concepts/routing-navigation.md) - Generated routes and navigation - [useNavigate](./router/use-navigate.md) - Programmatic navigation diff --git a/docs-src/hooks/define-module.docs.outline.md b/docs-src/hooks/define-module.docs.outline.md index 9e1fd78db..f285db3d0 100644 --- a/docs-src/hooks/define-module.docs.outline.md +++ b/docs-src/hooks/define-module.docs.outline.md @@ -12,9 +12,14 @@ Creates a top-level module that appears in the main navigation. Modules can cont ## Signature ```typescript -function defineModule(props: DefineModuleProps): Module; +import { defineModule } from "@tailor-platform/app-shell"; + +type ModuleOptions = Parameters[0]; +type AppModule = ReturnType; ``` +The option and return types can be derived from the public function; `DefineModuleProps` and `Module` are not package-root exports. + ## Parameters ### `path` @@ -26,6 +31,8 @@ function defineModule(props: DefineModuleProps): Module; ```typescript defineModule({ path: "products", // URL: /products + meta: {}, + resources: [], }); ``` @@ -33,29 +40,31 @@ defineModule({ - **Type:** `(props: ResourceComponentProps) => React.ReactNode` - **Required:** No -- **Description:** Landing page component for the module. If omitted, the module redirects to its first resource, and its breadcrumb segment is rendered as plain text (not a link). +- **Description:** Landing page component for the module. If omitted, the exact module path returns 404 while its child resource routes remain accessible, and its breadcrumb segment is plain text (not a link). Guards still run: use `redirectTo()` explicitly for a redirect; if all guards pass, the component-less path remains a 404. **ResourceComponentProps:** ```typescript -{ - title: string; // Resolved title - icon?: React.ReactNode; // Module icon - resources?: Resource[]; // Child resources -} +type ResourceComponentProps = { + title: string; // Resolved title + icon?: React.ReactNode; + resources?: Array>; // Child resources +}; ``` +Import `ResourceComponentProps` from AppShell when typing a page. AppShell passes `title` and `resources`; the optional `icon` field is not injected into page props. + ### `resources` -- **Type:** `Resource[]` +- **Type:** `Array>` - **Required:** Yes - **Description:** Array of resources within this module. Define using `defineResource()`. ### `meta` - **Type:** `object` -- **Required:** No -- **Description:** Metadata configuration for the module +- **Required:** Yes +- **Description:** Metadata configuration for the module. Pass `{}` to use the title derived from `path`. **meta.title** @@ -77,20 +86,20 @@ defineModule({ - **Type:** `Guard[]` - **Required:** No -- **Description:** Access control guards executed in order. If any guard returns non-pass, access is denied. +- **Description:** Access control guards executed in order. The first non-pass result stops execution: `hidden()` denies access and `redirectTo()` redirects. See [Guards Overview](./guards/overview.md) for details. ### `errorBoundary` -- **Type:** `React.ReactNode` +- **Type:** `ErrorBoundaryComponent` (`React.ReactNode`) - **Required:** No - **Description:** Error boundary component for this module and its child resources. Use `useRouteError` hook to access error details. ## Return Type ```typescript -Module; +type AppModule = ReturnType; ``` A module object that can be passed to the `modules` prop of `AppShell`. @@ -104,6 +113,7 @@ import { defineModule, Text } from "@tailor-platform/app-shell"; const dashboardModule = defineModule({ path: "dashboard", + meta: { title: "Dashboard" }, component: () => Dashboard, resources: [], }); @@ -130,6 +140,7 @@ const dashboardModule = defineModule({ ```typescript const productsModule = defineModule({ path: "products", + meta: { title: "Products" }, component: ProductsListPage, resources: [ defineResource({ @@ -144,12 +155,13 @@ const productsModule = defineModule({ }); ``` -### Module without Component (Auto-redirect) +### Module without Component (Grouping Only) ```typescript const dashboardModule = defineModule({ path: "dashboard", - // No component - automatically redirects to first resource + meta: { title: "Dashboard" }, + // /dashboard returns 404; /dashboard/overview and /dashboard/analytics work resources: [ defineResource({ path: "overview", @@ -170,8 +182,9 @@ import { pass, hidden } from "@tailor-platform/app-shell"; const adminModule = defineModule({ path: "admin", + meta: { title: "Admin" }, component: AdminPage, - resources: [adminResources], + resources: adminResources, guards: [ ({ context }) => { return context.currentUser?.role === "admin" ? pass() : hidden(); @@ -197,6 +210,7 @@ const ErrorBoundary = () => { const productsModule = defineModule({ path: "products", + meta: { title: "Products" }, component: ProductsPage, resources: [], errorBoundary: , @@ -226,15 +240,19 @@ const dashboardModule = defineModule({ ## TypeScript ```typescript -import { type DefineModuleProps, type Module } from "@tailor-platform/app-shell"; +import { defineModule } from "@tailor-platform/app-shell"; + +type ModuleOptions = Parameters[0]; +type AppModule = ReturnType; -const props: DefineModuleProps = { +const props: ModuleOptions = { path: "products", + meta: { title: "Products" }, component: ProductsPage, resources: [], }; -const module: Module = defineModule(props); +const productsModule: AppModule = defineModule(props); ``` ## Related diff --git a/docs-src/hooks/define-resource.docs.outline.md b/docs-src/hooks/define-resource.docs.outline.md index 2888d2f6d..95afb5f7d 100644 --- a/docs-src/hooks/define-resource.docs.outline.md +++ b/docs-src/hooks/define-resource.docs.outline.md @@ -12,9 +12,14 @@ Creates a nested resource (page) within a module. Resources represent individual ## Signature ```typescript -function defineResource(props: DefineResourceProps): Resource; +import { defineResource } from "@tailor-platform/app-shell"; + +type ResourceOptions = Parameters[0]; +type AppResource = ReturnType; ``` +The option and return types can be derived from the public function; `DefineResourceProps` and `Resource` are not package-root exports. + ## Parameters ### `path` @@ -24,28 +29,28 @@ function defineResource(props: DefineResourceProps): Resource; - **Description:** URL path segment for the resource. Supports dynamic parameters with `:param` syntax. ```typescript -defineResource({ - path: ":id", // Dynamic: /products/:id - path: "categories", // Static: /products/categories -}); +defineResource({ path: ":id" }); // Dynamic: /products/:id +defineResource({ path: "categories" }); // Static: /products/categories ``` ### `component` - **Type:** `(props: ResourceComponentProps) => React.ReactNode` -- **Required:** Yes -- **Description:** Page component to render +- **Required:** No +- **Description:** Page component to render. If omitted, the exact resource path returns 404 while its `subResources` remain accessible. Guards still run: `redirectTo()` can redirect; if all guards pass, the component-less path remains a 404. **ResourceComponentProps:** ```typescript -{ - title: string; // Resolved title - icon?: React.ReactNode; // Inherited from module - resources?: Resource[]; // Child resources -} +type ResourceComponentProps = { + title: string; // Resolved title + icon?: React.ReactNode; + resources?: Array>; // Sub-resources +}; ``` +Import `ResourceComponentProps` from AppShell when typing a page. AppShell passes `title` and `resources`; the optional `icon` field is not injected into page props. + ### `meta` - **Type:** `object` @@ -61,7 +66,7 @@ defineResource({ **meta.icon** - **Type:** `React.ReactNode` -- **Description:** Icon override (inherits from module by default) +- **Description:** Icon associated with this resource's navigation metadata. It is not inherited from the module or injected into page props. **meta.breadcrumbTitle** @@ -70,7 +75,7 @@ defineResource({ ### `subResources` -- **Type:** `Resource[]` +- **Type:** `Array>` - **Required:** No - **Description:** Nested resources within this resource @@ -84,14 +89,14 @@ See [Guards Overview](./guards/overview.md) for details. ### `errorBoundary` -- **Type:** `React.ReactNode` +- **Type:** `ErrorBoundaryComponent` (`React.ReactNode`) - **Required:** No - **Description:** Error boundary component for this resource ## Return Type ```typescript -Resource; +type AppResource = ReturnType; ``` A resource object used in the `resources` array of `defineModule`. @@ -123,18 +128,20 @@ const categoriesResource = defineResource({ ### Dynamic Route with useParams -```typescript -import { useParams } from "@tailor-platform/app-shell"; +```tsx +import { defineResource, useParams } from "@tailor-platform/app-shell"; + +function ProductDetailPage() { + const { id } = useParams(); + return
Product {id}
; +} const productDetailResource = defineResource({ path: ":id", meta: { title: "Product Details", }, - component: () => { - const { id } = useParams(); - return
Product {id}
; - }, + component: ProductDetailPage, }); ``` @@ -217,6 +224,7 @@ const orderResource = defineResource({ ```typescript const productsModule = defineModule({ path: "products", + meta: { title: "Products" }, component: ProductsPage, resources: [ defineResource({ @@ -252,6 +260,7 @@ Resources appear in: ```typescript defineModule({ path: "products", + meta: { title: "Products" }, component: ProductsPage, resources: [ defineResource({ @@ -288,15 +297,18 @@ Products > Product Details > Edit ## TypeScript ```typescript -import { type DefineResourceProps, type Resource } from "@tailor-platform/app-shell"; +import { defineResource } from "@tailor-platform/app-shell"; + +type ResourceOptions = Parameters[0]; +type AppResource = ReturnType; -const props: DefineResourceProps = { +const props: ResourceOptions = { path: ":id", component: DetailPage, guards: [], }; -const resource: Resource = defineResource(props); +const resource: AppResource = defineResource(props); ``` ## Related diff --git a/docs-src/hooks/guards/hidden.docs.outline.md b/docs-src/hooks/guards/hidden.docs.outline.md index 583314c34..780bf8b73 100644 --- a/docs-src/hooks/guards/hidden.docs.outline.md +++ b/docs-src/hooks/guards/hidden.docs.outline.md @@ -121,15 +121,17 @@ const conditionalHide: Guard = ({ context }) => { ### Async Permission Check ```typescript -const asyncHide: Guard = async ({ context }) => { - const allowed = await fetch("/api/check-access"); - if (!allowed) { +const asyncHide: Guard = async () => { + const response = await fetch("/api/check-access"); + if (!response.ok) { return hidden(); } return pass(); }; ``` +This endpoint must return a successful HTTP status only when access is allowed (for example, 204 for allowed and 403 for denied). A `Response` object is always truthy, including for 403 or 500 responses, so test `response.ok`, not the response itself. A rejected request propagates to the route error boundary rather than granting access. + ## vs redirectTo() | Aspect | hidden() | redirectTo() | diff --git a/docs-src/hooks/guards/overview.docs.outline.md b/docs-src/hooks/guards/overview.docs.outline.md index f2b8c3d26..0ab141b55 100644 --- a/docs-src/hooks/guards/overview.docs.outline.md +++ b/docs-src/hooks/guards/overview.docs.outline.md @@ -17,7 +17,7 @@ Guards are executed sequentially and can return one of three results: - **`hidden()`** - Deny access, return 404 - **`redirectTo(path)`** - Redirect to another page -If any guard returns `hidden()` or `redirectTo()`, execution stops immediately. +If any guard returns `hidden()` or `redirectTo()`, execution stops immediately. These client-side guards control navigation and rendering; protected APIs must enforce authorization on the server as well. ## Guard Function Signature @@ -38,7 +38,7 @@ type GuardResult = { type: "pass" } | { type: "hidden" } | { type: "redirect"; t Allows access and continues to the next guard. ```typescript -import { pass } from "@tailor-platform/app-shell"; +import { pass, type Guard } from "@tailor-platform/app-shell"; const allowAll: Guard = () => pass(); ``` @@ -50,7 +50,7 @@ const allowAll: Guard = () => pass(); Denies access and shows 404 Not Found. ```typescript -import { hidden } from "@tailor-platform/app-shell"; +import { hidden, type Guard } from "@tailor-platform/app-shell"; const denyAll: Guard = () => hidden(); ``` @@ -62,7 +62,7 @@ const denyAll: Guard = () => hidden(); Redirects to another page. ```typescript -import { redirectTo } from "@tailor-platform/app-shell"; +import { redirectTo, type Guard } from "@tailor-platform/app-shell"; const redirectToLogin: Guard = () => redirectTo("/login"); ``` @@ -80,7 +80,9 @@ import { defineModule, pass, hidden } from "@tailor-platform/app-shell"; const adminModule = defineModule({ path: "admin", + meta: { title: "Admin" }, component: AdminPage, + resources: [], guards: [ ({ context }) => { return context.currentUser?.role === "admin" ? pass() : hidden(); @@ -109,7 +111,9 @@ const isAdmin = ({ context }) => Guards receive context data from AppShell: ```typescript -// Define your context type +// Define your context type in a module augmentation +import "@tailor-platform/app-shell"; + declare module "@tailor-platform/app-shell" { interface AppShellRegister { contextData: { @@ -198,10 +202,12 @@ const requireFeature = ### Async Permission Check ```typescript -const checkApiPermission: Guard = async ({ context }) => { +const checkApiPermission: Guard = async () => { const response = await fetch("/api/permissions/admin"); + if (!response.ok) return hidden(); + const { allowed } = await response.json(); - return allowed ? pass() : hidden(); + return allowed === true ? pass() : hidden(); }; ``` @@ -213,6 +219,9 @@ const guards = [requireAuth, requireAdmin, requireFeature("beta")]; // All must pass() for access to be granted defineModule({ path: "admin", + meta: { title: "Admin" }, + component: AdminPage, + resources: [], guards: guards, }); ``` @@ -242,6 +251,9 @@ import { requireAuth, requireRole } from "./guards"; defineModule({ path: "admin", + meta: { title: "Admin" }, + component: AdminPage, + resources: [], guards: [requireAuth, requireRole("admin")], }); ``` @@ -326,13 +338,15 @@ const isAdmin: Guard = ({ context }) => { ### Async Guards (Slower) ```typescript -const checkPermission: Guard = async ({ context }) => { - const allowed = await fetch("/api/check"); - return allowed ? pass() : hidden(); +const checkPermission: Guard = async () => { + const response = await fetch("/api/check"); + return response.ok ? pass() : hidden(); }; // ~50-200ms - Network request ``` +This endpoint uses HTTP status as the permission result: success means allowed, while 403 or any other non-success status means denied. If an endpoint returns a permission flag in JSON instead, validate that flag as in [Async Permission Check](#async-permission-check). A rejected request propagates to the route error boundary rather than granting access. + **Tip:** Prefer sync guards when possible. Cache API results in context data. ## Comparison: Route vs Component Guards diff --git a/docs-src/hooks/guards/pass.docs.outline.md b/docs-src/hooks/guards/pass.docs.outline.md index c5fcd62e7..49923fdb9 100644 --- a/docs-src/hooks/guards/pass.docs.outline.md +++ b/docs-src/hooks/guards/pass.docs.outline.md @@ -120,7 +120,7 @@ guards: [ ]; ``` -If all guards return `pass()`, access is granted. +If all guards return `pass()`, guard evaluation permits access. This does not create a landing page or redirect: a module/resource without a `component` still returns 404 at its exact path while its child routes remain accessible. ## Related diff --git a/docs-src/hooks/guards/redirect-to.docs.outline.md b/docs-src/hooks/guards/redirect-to.docs.outline.md index 99124116a..64ede5d04 100644 --- a/docs-src/hooks/guards/redirect-to.docs.outline.md +++ b/docs-src/hooks/guards/redirect-to.docs.outline.md @@ -223,7 +223,9 @@ const guards = [ ```typescript const dashboardModule = defineModule({ path: "dashboard", + meta: { title: "Dashboard" }, component: DashboardPage, + resources: [], guards: [ ({ context }) => { if (!context.currentUser) { diff --git a/docs-src/hooks/use-ai-chat.docs.outline.md b/docs-src/hooks/use-ai-chat.docs.outline.md index 25f4d8913..96d48cbb3 100644 --- a/docs-src/hooks/use-ai-chat.docs.outline.md +++ b/docs-src/hooks/use-ai-chat.docs.outline.md @@ -1,8 +1,11 @@ --- -kind: prose +kind: code-backed group: use-ai-chat title: useAIChat description: AI Gateway chat hook with optional local tools +sources: + - packages/core/src/ai/use-ai-chat.ts + - packages/core/src/ai/tools.ts --- # useAIChat @@ -70,10 +73,26 @@ Calls become available before local tool execution. They record requested tool n Register local tools under a single object using `defineAIChatTool(...)`. Their schemas must implement both [Standard Schema](https://standardschema.dev/) validation and Standard JSON Schema generation (for example, Zod 4). Provider-native tools are not supported. +## Local tool API + +`defineAIChatTool({ schema, execute, description? })` returns an `AILocalTool` with `kind: "local"`. The helper infers the first `execute` argument from the schema's **validated output**, including schema transformations. It does not execute or validate inputs when the tool is defined: `useAIChat` validates the model's arguments before calling `execute`. + +`AIChatToolSchema` is the schema contract: it combines Standard Schema validation with Standard JSON Schema generation. Zod 4 implements both. AppShell sends the schema's input JSON Schema to the AI Gateway; the executor receives the validated output. + +The second `execute` argument is an `AIChatToolContext`: + +| Property | Type | Description | +| ---------- | ----------------- | ----------------------------------------------------------------------------------------------------------- | +| `signal` | `AbortSignal` | Cancellation signal for the active chat request. Forward it to `fetch` or other operations that support it. | +| `messages` | `AIChatMessage[]` | User/assistant text available to the current turn, excluding internal tool-call and tool-result messages. | + +Calling `stop()` or unmounting aborts the signal. Custom tool work must cooperate with cancellation; aborting does not undo side effects that have already happened. The example below forwards the signal to its request and checks the response status before returning a tool result. + ## Usage ```tsx import { + Button, createAuthClient, createAIGatewayClient, defineAIChatTool, @@ -96,8 +115,12 @@ const lookupCustomer = defineAIChatTool({ schema: z.object({ customerId: z.string(), }), - async execute({ customerId }) { - return { customerId, name: "Acme Corp" }; + async execute({ customerId }, { signal }) { + const response = await fetch(`/api/customers/${encodeURIComponent(customerId)}`, { signal }); + if (!response.ok) { + throw new Error(`Customer lookup failed: ${response.status}`); + } + return response.json(); }, }); @@ -121,15 +144,15 @@ export function ChatScreen() {
Tool call: {call.name}
))} - - + + {error ?
{error.message}
: null} ); diff --git a/docs-src/hooks/use-app-shell-config.docs.outline.md b/docs-src/hooks/use-app-shell-config.docs.outline.md index 936485ac8..509c00986 100644 --- a/docs-src/hooks/use-app-shell-config.docs.outline.md +++ b/docs-src/hooks/use-app-shell-config.docs.outline.md @@ -86,14 +86,16 @@ function SettingsMenu() { Use `useAppShellConfig` when you only need configuration data: -```typescript -// ✅ Good - subscribes to configuration only -const { configurations } = useAppShellConfig(); - -// ❌ Overkill - useAppShell also subscribes to contextData changes -const { configurations } = useAppShell(); +```tsx +function ModuleCount() { + // Subscribes to configuration only. + const { configurations } = useAppShellConfig(); + return {configurations.modules.length} modules; +} ``` +Using `useAppShell()` here would also subscribe to context-data changes that this component does not use. + ## Comparison with Other Hooks | Hook | Returns | Use When | diff --git a/docs-src/hooks/use-app-shell-data.docs.outline.md b/docs-src/hooks/use-app-shell-data.docs.outline.md index 1c234c3c4..8570d4631 100644 --- a/docs-src/hooks/use-app-shell-data.docs.outline.md +++ b/docs-src/hooks/use-app-shell-data.docs.outline.md @@ -96,6 +96,8 @@ Define your context type with module augmentation: ```typescript // types.d.ts +import "@tailor-platform/app-shell"; + type User = { name: string; email: string; role: string }; declare module "@tailor-platform/app-shell" { @@ -113,27 +115,31 @@ declare module "@tailor-platform/app-shell" { } ``` -Now `useAppShellData()` returns fully typed data: +Now `useAppShellData()` returns fully typed data inside your components: -```typescript -const { contextData } = useAppShellData(); -contextData.currentUser; // Type: User | null -contextData.permissions; // Type: string[] -contextData.featureFlags; // Type: { newEditor: boolean, betaDashboard: boolean } +```tsx +function UserSummary() { + const { contextData } = useAppShellData(); + // currentUser is User | null; permissions is string[]. + // featureFlags has newEditor and betaDashboard boolean properties. + return {contextData.currentUser?.name}; +} ``` ## When to Use Use `useAppShellData` when you only need context data: -```typescript -// ✅ Good - subscribes to context data only -const { contextData } = useAppShellData(); - -// ❌ Overkill - useAppShell also subscribes to configuration changes -const { contextData } = useAppShell(); +```tsx +function PermissionCount() { + // Subscribes to context data only. + const { contextData } = useAppShellData(); + return {contextData.permissions.length} permissions; +} ``` +Using `useAppShell()` here would also subscribe to configuration changes that this component does not use. + ## Comparison with Other Hooks | Hook | Returns | Use When | diff --git a/docs-src/hooks/use-app-shell.docs.outline.md b/docs-src/hooks/use-app-shell.docs.outline.md index 125739181..6e33d62cd 100644 --- a/docs-src/hooks/use-app-shell.docs.outline.md +++ b/docs-src/hooks/use-app-shell.docs.outline.md @@ -1,8 +1,10 @@ --- -kind: prose +kind: code-backed group: use-app-shell title: useAppShell description: Hook to access AppShell context data and configuration +sources: + - packages/core/src/contexts/appshell-context.tsx --- # useAppShell @@ -32,6 +34,18 @@ const useAppShell: () => { The hook merges the results of [`useAppShellConfig`](./use-app-shell-config.md) and [`useAppShellData`](./use-app-shell-data.md). Prefer one of those when you only need configuration or only need context data, so the component does not re-render for changes it does not use. +## Context API family + +| API | Reference | +| --------------------------------- | ----------------------------------------------------------------------------- | +| `useAppShellConfig` | [Configuration-only subscription](./use-app-shell-config.md) | +| `useAppShellData` | [Context-data-only subscription](./use-app-shell-data.md) | +| `useResolvedLocale` | [Full locale and language code](./use-resolved-locale.md) | +| `useTimeZone`, `TimeZone` | [Configured timezone and bound date/time helpers](./use-time-zone.md) | +| `AppInfo`, `AppInfoEntry` | [Metadata for the built-in app-info page](../components/app-shell.md#appinfo) | +| `AppShellRegister`, `ContextData` | [Context-data registration](#context-data) | +| `RouteParams` | [Registered route-parameter map](#route-parameter-types) | + ## Return Value ### `contextData` @@ -74,6 +88,8 @@ Define your context type with module augmentation: ```typescript // types.d.ts +import "@tailor-platform/app-shell"; + type User = { name: string; email: string; role: string }; declare module "@tailor-platform/app-shell" { @@ -85,7 +101,13 @@ declare module "@tailor-platform/app-shell" { }; } } +``` + +`AppShellRegister.contextData` sets the exported `ContextData` type. Without registration, `ContextData` falls back to `Record`. The side-effect import makes this declaration a module augmentation rather than a replacement module declaration. +Pass matching data to `AppShell`: + +```tsx // App.tsx +> + + +``` +Read the registered data inside a component: + +```tsx // MyComponent.tsx -const { contextData } = useAppShell(); -contextData.currentUser // Fully typed! -contextData.permissions // Fully typed! +import { useAppShell } from "@tailor-platform/app-shell"; + +function MyComponent() { + const { contextData } = useAppShell(); + + // currentUser is User | null; permissions is string[]. + return ( +
+ {contextData.currentUser?.name} ({contextData.permissions.length} permissions) +
+ ); +} ``` +## Route parameter types + +The exported `RouteParams` type reads `AppShellRegister.routeParams`. With no registration it falls back to `Record>`; register a route map to retain literal paths and parameter names: + +```typescript +// types.d.ts +import "@tailor-platform/app-shell"; + +declare module "@tailor-platform/app-shell" { + interface AppShellRegister { + routeParams: { + "/": {}; + "/orders/:id": { id: string }; + }; + } +} +``` + +```typescript +import type { RouteParams } from "@tailor-platform/app-shell"; + +type OrderParams = RouteParams["/orders/:id"]; // { id: string } +``` + +The Vite plugin registers its generated map for you when [typed-route generation](../concepts/file-based-routing.md#typed-routes) is enabled; do not also register a conflicting manual map. See [`createTypedPaths`](./create-typed-paths.md) for using a route map to build paths. + ## Examples ### Display User Info diff --git a/docs-src/hooks/use-auth.docs.outline.md b/docs-src/hooks/use-auth.docs.outline.md index 045f6ea93..f72385214 100644 --- a/docs-src/hooks/use-auth.docs.outline.md +++ b/docs-src/hooks/use-auth.docs.outline.md @@ -16,7 +16,7 @@ const useAuth: () => { error: string | null; isAuthenticated: boolean; isReady: boolean; - login: () => Promise; + login: (options?: { returnTo?: string }) => Promise; logout: () => Promise; checkAuthStatus: () => Promise; }; @@ -41,8 +41,8 @@ const useAuth: () => { ### `login()` -- **Type:** `() => Promise` -- **Description:** Initiates the login process. Redirects to Tailor Platform authentication page. +- **Type:** `(options?: { returnTo?: string }) => Promise` +- **Description:** Initiates the login process. Returns to the current path, query string, and hash after authentication by default. Pass `login({ returnTo: "/orders" })` to choose another same-origin destination. See [return to the current page](../concepts/authentication.md#return-to-the-current-page). ### `logout()` @@ -120,17 +120,25 @@ function AuthStatus() { ## With AuthProvider -```typescript -import { AuthProvider, AppShell, useAuth } from "@tailor-platform/app-shell"; +Create the client once at module scope, outside React rendering, then pass it to the provider: + +```tsx +import { + createAuthClient, + AuthProvider, + AppShell, + SidebarLayout, +} from "@tailor-platform/app-shell"; + +const authClient = createAuthClient({ + clientId: "your-client-id", + appUri: "https://your-app.erp.dev", + redirectUri: "http://localhost:3000/callback", +}); function App() { return ( - + diff --git a/docs-src/hooks/use-override-breadcrumb.docs.outline.md b/docs-src/hooks/use-override-breadcrumb.docs.outline.md index c84eacaf9..18579a126 100644 --- a/docs-src/hooks/use-override-breadcrumb.docs.outline.md +++ b/docs-src/hooks/use-override-breadcrumb.docs.outline.md @@ -1,8 +1,10 @@ --- -kind: prose +kind: code-backed group: use-override-breadcrumb title: useOverrideBreadcrumb description: Hook for dynamically overriding breadcrumb titles from within page components +sources: + - packages/core/src/hooks/use-override-breadcrumb.ts --- # useOverrideBreadcrumb diff --git a/docs-src/hooks/use-page-meta.docs.outline.md b/docs-src/hooks/use-page-meta.docs.outline.md index cceb49b4f..091435925 100644 --- a/docs-src/hooks/use-page-meta.docs.outline.md +++ b/docs-src/hooks/use-page-meta.docs.outline.md @@ -1,8 +1,10 @@ --- -kind: prose +kind: code-backed group: use-page-meta title: usePageMeta description: Hook to resolve page metadata from route path +sources: + - packages/core/src/hooks/use-page-meta.ts --- # usePageMeta @@ -70,14 +72,18 @@ function CustomLink({ to }: { to: string }) { ### Breadcrumb Builder -```typescript +```tsx +function BreadcrumbItem({ path }: { path: string }) { + const meta = usePageMeta(path); + return {meta?.title}; +} + function Breadcrumb({ paths }: { paths: string[] }) { return (
- {paths.map((path) => { - const meta = usePageMeta(path); - return {meta?.title}; - })} + {paths.map((path) => ( + + ))}
); } diff --git a/docs-src/hooks/use-register-command-palette-actions.docs.outline.md b/docs-src/hooks/use-register-command-palette-actions.docs.outline.md index 11466cd46..221b2e8e9 100644 --- a/docs-src/hooks/use-register-command-palette-actions.docs.outline.md +++ b/docs-src/hooks/use-register-command-palette-actions.docs.outline.md @@ -80,7 +80,7 @@ function OrderDetailPage() { ## Behavior - Actions are registered while the component is mounted and removed on unmount. -- Re-rendering with a new `actions` array replaces the previously registered set. +- Changes to action keys, labels, or the group update the registered set. The latest `onSelect` callbacks are used without requiring re-registration. - `icon` changes alone do not trigger re-registration. If you need to reflect a dynamic icon update, also change the action's `key` or `label`. - The hook requires `CommandPaletteProvider`, which is mounted automatically by `AppShell`. diff --git a/docs-src/hooks/use-route-error.docs.outline.md b/docs-src/hooks/use-route-error.docs.outline.md index 58e53c1b8..68ab4c17d 100644 --- a/docs-src/hooks/use-route-error.docs.outline.md +++ b/docs-src/hooks/use-route-error.docs.outline.md @@ -54,9 +54,10 @@ import { defineModule } from "@tailor-platform/app-shell"; const myModule = defineModule({ path: "dashboard", + meta: { title: "Dashboard" }, component: DashboardPage, errorBoundary: , - resources: [...] + resources: [], }); ``` @@ -65,6 +66,7 @@ const myModule = defineModule({ ```typescript const productsModule = defineModule({ path: "products", + meta: { title: "Products" }, component: ProductsPage, resources: [ defineResource({ @@ -79,17 +81,22 @@ const productsModule = defineModule({ ### Advanced Error Handling ```typescript -import { isRouteErrorResponse, Text, useRouteError } from "@tailor-platform/app-shell"; +import { Text, useRouteError } from "@tailor-platform/app-shell"; function ErrorBoundary() { const error = useRouteError(); - // Handle route error responses (404, 500, etc.) - if (isRouteErrorResponse(error)) { + // Narrow the unknown error before reading an HTTP status. + if ( + typeof error === "object" && + error !== null && + "status" in error && + typeof error.status === "number" + ) { return (
- {error.status} {error.statusText} - {error.data} + HTTP {error.status} + The requested page could not be loaded.
); } @@ -142,7 +149,12 @@ function ErrorBoundary() { function ErrorBoundary() { const error = useRouteError(); - if (isRouteErrorResponse(error)) { + if ( + typeof error === "object" && + error !== null && + "status" in error && + typeof error.status === "number" + ) { if (error.status === 404) { return ; } @@ -168,8 +180,9 @@ Error boundaries can be defined at different levels: // Module-level - catches errors in all resources defineModule({ path: "products", + meta: { title: "Products" }, errorBoundary: , - resources: [...] + resources: [], }) // Resource-level - catches errors in specific resource diff --git a/docs-src/hooks/use-theme.docs.outline.md b/docs-src/hooks/use-theme.docs.outline.md index 463cbec1d..8623ed87a 100644 --- a/docs-src/hooks/use-theme.docs.outline.md +++ b/docs-src/hooks/use-theme.docs.outline.md @@ -1,8 +1,10 @@ --- -kind: prose +kind: code-backed group: use-theme title: useTheme description: Hook for accessing and controlling theme (light/dark mode) +sources: + - packages/core/src/contexts/theme-context.tsx --- # useTheme diff --git a/docs-src/hooks/use-toast.docs.outline.md b/docs-src/hooks/use-toast.docs.outline.md index 9f198f37e..d32721c30 100644 --- a/docs-src/hooks/use-toast.docs.outline.md +++ b/docs-src/hooks/use-toast.docs.outline.md @@ -1,8 +1,10 @@ --- -kind: prose +kind: code-backed group: use-toast title: useToast description: Hook for displaying toast notifications +sources: + - packages/core/src/hooks/use-toast.ts --- # useToast diff --git a/docs/api/create-typed-paths.md b/docs/api/create-typed-paths.md index 09c7a4372..71c58e5c9 100644 --- a/docs/api/create-typed-paths.md +++ b/docs/api/create-typed-paths.md @@ -1,31 +1,37 @@ --- title: createTypedPaths -description: Generate type-safe route paths from file-based routing +description: Create type-safe route path helpers from a route-to-parameters type map --- # createTypedPaths -Generates type-safe route path helpers from file-based routing structure. Only available when using the Vite plugin. +Creates a type-safe path builder from a route-to-parameters type map. The Vite plugin can generate this map and a ready-to-use `paths` helper, but the factory can also be used with a manually declared map. ## Signature ```typescript -function createTypedPaths>(pages: T): TypedPaths; +const paths = createTypedPaths(); ``` -## Parameters +The factory takes **no runtime arguments**. It does not accept a pages object or register routes. -### `pages` +## Type Parameter -- **Type:** `Record` -- **Required:** Yes -- **Description:** Pages object from virtual module (auto-generated by Vite plugin) +### `Routes` + +- **Constraint:** `Record>` +- **Description:** A map whose keys are route templates and whose values name each route's string parameters. Use `{}` for a static route. ## Return Value -Type-safe path builder functions for each route. +An object with a `for(template, params)` method: + +- Static routes need only the template. +- Dynamic routes require an object with the declared parameter names. +- The result is a URL path string; dynamic parameter values are URL-encoded. +- A query suffix on the template is preserved, such as `"/products/:id?tab=details"`. ## Usage @@ -33,85 +39,89 @@ Type-safe path builder functions for each route. ```typescript import { createTypedPaths } from "@tailor-platform/app-shell"; -import pages from "virtual:app-shell-pages"; -const paths = createTypedPaths(pages); +type Routes = { + "/products": {}; + "/products/:id": { id: string }; +}; -// Type-safe navigation -navigate(paths.products.detail({ id: "123" })); -// Result: "/products/123" +const paths = createTypedPaths(); + +paths.for("/products"); // "/products" +paths.for("/products/:id", { id: "123" }); // "/products/123" +paths.for("/products/:id?tab=details", { id: "123" }); // "/products/123?tab=details" ``` +The following examples reuse `paths` from above. Its type map must match the routes configured in your application. + ### With useNavigate -```typescript -import { useNavigate } from "@tailor-platform/app-shell"; +```tsx +import { Button, useNavigate } from "@tailor-platform/app-shell"; -function ProductCard({ product }: { product: Product }) { +function ProductCard({ id }: { id: string }) { const navigate = useNavigate(); - const paths = createTypedPaths(pages); - - const handleClick = () => { - navigate(paths.products.detail({ id: product.id })); - }; - return ; + return ; } ``` ### With Link Component -```typescript +```tsx import { Link } from "@tailor-platform/app-shell"; function ProductLink({ id }: { id: string }) { - const paths = createTypedPaths(pages); - - return ( - - View Product - - ); + return View Product; } ``` ### Nested Routes ```typescript -// File structure: -// pages/ -// orders/ -// page.tsx -// [id]/ -// page.tsx -// edit/ -// page.tsx - -paths.orders.index(); // "/orders" -paths.orders.detail({ id: "1" }); // "/orders/1" -paths.orders.edit({ id: "1" }); // "/orders/1/edit" +const orderPaths = createTypedPaths<{ + "/orders": {}; + "/orders/:id": { id: string }; + "/orders/:id/edit": { id: string }; +}>(); + +orderPaths.for("/orders"); // "/orders" +orderPaths.for("/orders/:id", { id: "1" }); // "/orders/1" +orderPaths.for("/orders/:id/edit", { id: "1" }); // "/orders/1/edit" ``` ## TypeScript Benefits ```typescript -// ✅ Type-safe parameters -paths.products.detail({ id: "123" }); // Valid +paths.for("/products/:id", { id: "123" }); // Valid -// ❌ Type error - missing required param -paths.products.detail(); // Error: Argument required +// @ts-expect-error Missing required parameters +paths.for("/products/:id"); -// ❌ Type error - wrong param name -paths.products.detail({ productId: "123" }); // Error: Unknown key +// @ts-expect-error Wrong parameter name +paths.for("/products/:id", { productId: "123" }); + +// @ts-expect-error Unknown route +paths.for("/missing"); ``` -## File-Based Routing Only +## Generated File-Based Routes + +With the Vite plugin's `generateTypedRoutes` option enabled, prefer importing `paths` from your generated routes file instead of maintaining the type map yourself. The generated file calls `createTypedPaths()` for you; application code still uses `paths.for(template, params)`. + +```tsx +import { Link } from "@tailor-platform/app-shell"; +import { paths } from "./routes.generated"; -This function is only available when using the Vite plugin with file-based routing. +function ProductLink({ id }: { id: string }) { + return View Product; +} +``` -See [File-Based Routing](../concepts/file-based-routing.md) for setup. +This assumes your generated map contains `/products/:id`. The import path depends on the configured output location. See [File-Based Routing](../concepts/file-based-routing.md) for setup. ## Related - [File-Based Routing](../concepts/file-based-routing.md) - Setup guide +- [Routing and Navigation](../concepts/routing-navigation.md) - Generated routes and navigation - [useNavigate](./router/use-navigate.md) - Programmatic navigation diff --git a/docs/api/define-module.md b/docs/api/define-module.md index c92eec9d0..96505b8d4 100644 --- a/docs/api/define-module.md +++ b/docs/api/define-module.md @@ -12,9 +12,14 @@ Creates a top-level module that appears in the main navigation. Modules can cont ## Signature ```typescript -function defineModule(props: DefineModuleProps): Module; +import { defineModule } from "@tailor-platform/app-shell"; + +type ModuleOptions = Parameters[0]; +type AppModule = ReturnType; ``` +The option and return types can be derived from the public function; `DefineModuleProps` and `Module` are not package-root exports. + ## Parameters ### `path` @@ -26,6 +31,8 @@ function defineModule(props: DefineModuleProps): Module; ```typescript defineModule({ path: "products", // URL: /products + meta: {}, + resources: [], }); ``` @@ -33,29 +40,31 @@ defineModule({ - **Type:** `(props: ResourceComponentProps) => React.ReactNode` - **Required:** No -- **Description:** Landing page component for the module. If omitted, the module redirects to its first resource, and its breadcrumb segment is rendered as plain text (not a link). +- **Description:** Landing page component for the module. If omitted, the exact module path returns 404 while its child resource routes remain accessible, and its breadcrumb segment is plain text (not a link). Guards still run: use `redirectTo()` explicitly for a redirect; if all guards pass, the component-less path remains a 404. **ResourceComponentProps:** ```typescript -{ - title: string; // Resolved title - icon?: React.ReactNode; // Module icon - resources?: Resource[]; // Child resources -} +type ResourceComponentProps = { + title: string; // Resolved title + icon?: React.ReactNode; + resources?: Array>; // Child resources +}; ``` +Import `ResourceComponentProps` from AppShell when typing a page. AppShell passes `title` and `resources`; the optional `icon` field is not injected into page props. + ### `resources` -- **Type:** `Resource[]` +- **Type:** `Array>` - **Required:** Yes - **Description:** Array of resources within this module. Define using `defineResource()`. ### `meta` - **Type:** `object` -- **Required:** No -- **Description:** Metadata configuration for the module +- **Required:** Yes +- **Description:** Metadata configuration for the module. Pass `{}` to use the title derived from `path`. **meta.title** @@ -77,20 +86,20 @@ defineModule({ - **Type:** `Guard[]` - **Required:** No -- **Description:** Access control guards executed in order. If any guard returns non-pass, access is denied. +- **Description:** Access control guards executed in order. The first non-pass result stops execution: `hidden()` denies access and `redirectTo()` redirects. See [Guards Overview](./guards/overview.md) for details. ### `errorBoundary` -- **Type:** `React.ReactNode` +- **Type:** `ErrorBoundaryComponent` (`React.ReactNode`) - **Required:** No - **Description:** Error boundary component for this module and its child resources. Use `useRouteError` hook to access error details. ## Return Type ```typescript -Module; +type AppModule = ReturnType; ``` A module object that can be passed to the `modules` prop of `AppShell`. @@ -104,6 +113,7 @@ import { defineModule, Text } from "@tailor-platform/app-shell"; const dashboardModule = defineModule({ path: "dashboard", + meta: { title: "Dashboard" }, component: () => Dashboard, resources: [], }); @@ -130,6 +140,7 @@ const dashboardModule = defineModule({ ```typescript const productsModule = defineModule({ path: "products", + meta: { title: "Products" }, component: ProductsListPage, resources: [ defineResource({ @@ -144,12 +155,13 @@ const productsModule = defineModule({ }); ``` -### Module without Component (Auto-redirect) +### Module without Component (Grouping Only) ```typescript const dashboardModule = defineModule({ path: "dashboard", - // No component - automatically redirects to first resource + meta: { title: "Dashboard" }, + // /dashboard returns 404; /dashboard/overview and /dashboard/analytics work resources: [ defineResource({ path: "overview", @@ -170,8 +182,9 @@ import { pass, hidden } from "@tailor-platform/app-shell"; const adminModule = defineModule({ path: "admin", + meta: { title: "Admin" }, component: AdminPage, - resources: [adminResources], + resources: adminResources, guards: [ ({ context }) => { return context.currentUser?.role === "admin" ? pass() : hidden(); @@ -197,6 +210,7 @@ const ErrorBoundary = () => { const productsModule = defineModule({ path: "products", + meta: { title: "Products" }, component: ProductsPage, resources: [], errorBoundary: , @@ -226,15 +240,19 @@ const dashboardModule = defineModule({ ## TypeScript ```typescript -import { type DefineModuleProps, type Module } from "@tailor-platform/app-shell"; +import { defineModule } from "@tailor-platform/app-shell"; + +type ModuleOptions = Parameters[0]; +type AppModule = ReturnType; -const props: DefineModuleProps = { +const props: ModuleOptions = { path: "products", + meta: { title: "Products" }, component: ProductsPage, resources: [], }; -const module: Module = defineModule(props); +const productsModule: AppModule = defineModule(props); ``` ## Related diff --git a/docs/api/define-resource.md b/docs/api/define-resource.md index 889a04e5d..3f24f394d 100644 --- a/docs/api/define-resource.md +++ b/docs/api/define-resource.md @@ -12,9 +12,14 @@ Creates a nested resource (page) within a module. Resources represent individual ## Signature ```typescript -function defineResource(props: DefineResourceProps): Resource; +import { defineResource } from "@tailor-platform/app-shell"; + +type ResourceOptions = Parameters[0]; +type AppResource = ReturnType; ``` +The option and return types can be derived from the public function; `DefineResourceProps` and `Resource` are not package-root exports. + ## Parameters ### `path` @@ -24,28 +29,28 @@ function defineResource(props: DefineResourceProps): Resource; - **Description:** URL path segment for the resource. Supports dynamic parameters with `:param` syntax. ```typescript -defineResource({ - path: ":id", // Dynamic: /products/:id - path: "categories", // Static: /products/categories -}); +defineResource({ path: ":id" }); // Dynamic: /products/:id +defineResource({ path: "categories" }); // Static: /products/categories ``` ### `component` - **Type:** `(props: ResourceComponentProps) => React.ReactNode` -- **Required:** Yes -- **Description:** Page component to render +- **Required:** No +- **Description:** Page component to render. If omitted, the exact resource path returns 404 while its `subResources` remain accessible. Guards still run: `redirectTo()` can redirect; if all guards pass, the component-less path remains a 404. **ResourceComponentProps:** ```typescript -{ - title: string; // Resolved title - icon?: React.ReactNode; // Inherited from module - resources?: Resource[]; // Child resources -} +type ResourceComponentProps = { + title: string; // Resolved title + icon?: React.ReactNode; + resources?: Array>; // Sub-resources +}; ``` +Import `ResourceComponentProps` from AppShell when typing a page. AppShell passes `title` and `resources`; the optional `icon` field is not injected into page props. + ### `meta` - **Type:** `object` @@ -61,7 +66,7 @@ defineResource({ **meta.icon** - **Type:** `React.ReactNode` -- **Description:** Icon override (inherits from module by default) +- **Description:** Icon associated with this resource's navigation metadata. It is not inherited from the module or injected into page props. **meta.breadcrumbTitle** @@ -70,7 +75,7 @@ defineResource({ ### `subResources` -- **Type:** `Resource[]` +- **Type:** `Array>` - **Required:** No - **Description:** Nested resources within this resource @@ -84,14 +89,14 @@ See [Guards Overview](./guards/overview.md) for details. ### `errorBoundary` -- **Type:** `React.ReactNode` +- **Type:** `ErrorBoundaryComponent` (`React.ReactNode`) - **Required:** No - **Description:** Error boundary component for this resource ## Return Type ```typescript -Resource; +type AppResource = ReturnType; ``` A resource object used in the `resources` array of `defineModule`. @@ -123,18 +128,20 @@ const categoriesResource = defineResource({ ### Dynamic Route with useParams -```typescript -import { useParams } from "@tailor-platform/app-shell"; +```tsx +import { defineResource, useParams } from "@tailor-platform/app-shell"; + +function ProductDetailPage() { + const { id } = useParams(); + return
Product {id}
; +} const productDetailResource = defineResource({ path: ":id", meta: { title: "Product Details", }, - component: () => { - const { id } = useParams(); - return
Product {id}
; - }, + component: ProductDetailPage, }); ``` @@ -217,6 +224,7 @@ const orderResource = defineResource({ ```typescript const productsModule = defineModule({ path: "products", + meta: { title: "Products" }, component: ProductsPage, resources: [ defineResource({ @@ -252,6 +260,7 @@ Resources appear in: ```typescript defineModule({ path: "products", + meta: { title: "Products" }, component: ProductsPage, resources: [ defineResource({ @@ -288,15 +297,18 @@ Products > Product Details > Edit ## TypeScript ```typescript -import { type DefineResourceProps, type Resource } from "@tailor-platform/app-shell"; +import { defineResource } from "@tailor-platform/app-shell"; + +type ResourceOptions = Parameters[0]; +type AppResource = ReturnType; -const props: DefineResourceProps = { +const props: ResourceOptions = { path: ":id", component: DetailPage, guards: [], }; -const resource: Resource = defineResource(props); +const resource: AppResource = defineResource(props); ``` ## Related diff --git a/docs/api/guards/hidden.md b/docs/api/guards/hidden.md index bfe9e64cd..065f7c3ec 100644 --- a/docs/api/guards/hidden.md +++ b/docs/api/guards/hidden.md @@ -121,15 +121,17 @@ const conditionalHide: Guard = ({ context }) => { ### Async Permission Check ```typescript -const asyncHide: Guard = async ({ context }) => { - const allowed = await fetch("/api/check-access"); - if (!allowed) { +const asyncHide: Guard = async () => { + const response = await fetch("/api/check-access"); + if (!response.ok) { return hidden(); } return pass(); }; ``` +This endpoint must return a successful HTTP status only when access is allowed (for example, 204 for allowed and 403 for denied). A `Response` object is always truthy, including for 403 or 500 responses, so test `response.ok`, not the response itself. A rejected request propagates to the route error boundary rather than granting access. + ## vs redirectTo() | Aspect | hidden() | redirectTo() | diff --git a/docs/api/guards/overview.md b/docs/api/guards/overview.md index e142625af..21cf879a3 100644 --- a/docs/api/guards/overview.md +++ b/docs/api/guards/overview.md @@ -17,7 +17,7 @@ Guards are executed sequentially and can return one of three results: - **`hidden()`** - Deny access, return 404 - **`redirectTo(path)`** - Redirect to another page -If any guard returns `hidden()` or `redirectTo()`, execution stops immediately. +If any guard returns `hidden()` or `redirectTo()`, execution stops immediately. These client-side guards control navigation and rendering; protected APIs must enforce authorization on the server as well. ## Guard Function Signature @@ -38,7 +38,7 @@ type GuardResult = { type: "pass" } | { type: "hidden" } | { type: "redirect"; t Allows access and continues to the next guard. ```typescript -import { pass } from "@tailor-platform/app-shell"; +import { pass, type Guard } from "@tailor-platform/app-shell"; const allowAll: Guard = () => pass(); ``` @@ -50,7 +50,7 @@ const allowAll: Guard = () => pass(); Denies access and shows 404 Not Found. ```typescript -import { hidden } from "@tailor-platform/app-shell"; +import { hidden, type Guard } from "@tailor-platform/app-shell"; const denyAll: Guard = () => hidden(); ``` @@ -62,7 +62,7 @@ const denyAll: Guard = () => hidden(); Redirects to another page. ```typescript -import { redirectTo } from "@tailor-platform/app-shell"; +import { redirectTo, type Guard } from "@tailor-platform/app-shell"; const redirectToLogin: Guard = () => redirectTo("/login"); ``` @@ -80,7 +80,9 @@ import { defineModule, pass, hidden } from "@tailor-platform/app-shell"; const adminModule = defineModule({ path: "admin", + meta: { title: "Admin" }, component: AdminPage, + resources: [], guards: [ ({ context }) => { return context.currentUser?.role === "admin" ? pass() : hidden(); @@ -109,7 +111,9 @@ const isAdmin = ({ context }) => Guards receive context data from AppShell: ```typescript -// Define your context type +// Define your context type in a module augmentation +import "@tailor-platform/app-shell"; + declare module "@tailor-platform/app-shell" { interface AppShellRegister { contextData: { @@ -198,10 +202,12 @@ const requireFeature = ### Async Permission Check ```typescript -const checkApiPermission: Guard = async ({ context }) => { +const checkApiPermission: Guard = async () => { const response = await fetch("/api/permissions/admin"); + if (!response.ok) return hidden(); + const { allowed } = await response.json(); - return allowed ? pass() : hidden(); + return allowed === true ? pass() : hidden(); }; ``` @@ -213,6 +219,9 @@ const guards = [requireAuth, requireAdmin, requireFeature("beta")]; // All must pass() for access to be granted defineModule({ path: "admin", + meta: { title: "Admin" }, + component: AdminPage, + resources: [], guards: guards, }); ``` @@ -242,6 +251,9 @@ import { requireAuth, requireRole } from "./guards"; defineModule({ path: "admin", + meta: { title: "Admin" }, + component: AdminPage, + resources: [], guards: [requireAuth, requireRole("admin")], }); ``` @@ -326,13 +338,15 @@ const isAdmin: Guard = ({ context }) => { ### Async Guards (Slower) ```typescript -const checkPermission: Guard = async ({ context }) => { - const allowed = await fetch("/api/check"); - return allowed ? pass() : hidden(); +const checkPermission: Guard = async () => { + const response = await fetch("/api/check"); + return response.ok ? pass() : hidden(); }; // ~50-200ms - Network request ``` +This endpoint uses HTTP status as the permission result: success means allowed, while 403 or any other non-success status means denied. If an endpoint returns a permission flag in JSON instead, validate that flag as in [Async Permission Check](#async-permission-check). A rejected request propagates to the route error boundary rather than granting access. + **Tip:** Prefer sync guards when possible. Cache API results in context data. ## Comparison: Route vs Component Guards diff --git a/docs/api/guards/pass.md b/docs/api/guards/pass.md index a143cc544..dea6e1e41 100644 --- a/docs/api/guards/pass.md +++ b/docs/api/guards/pass.md @@ -120,7 +120,7 @@ guards: [ ]; ``` -If all guards return `pass()`, access is granted. +If all guards return `pass()`, guard evaluation permits access. This does not create a landing page or redirect: a module/resource without a `component` still returns 404 at its exact path while its child routes remain accessible. ## Related diff --git a/docs/api/guards/redirect-to.md b/docs/api/guards/redirect-to.md index 4747877f3..3865b79ac 100644 --- a/docs/api/guards/redirect-to.md +++ b/docs/api/guards/redirect-to.md @@ -223,7 +223,9 @@ const guards = [ ```typescript const dashboardModule = defineModule({ path: "dashboard", + meta: { title: "Dashboard" }, component: DashboardPage, + resources: [], guards: [ ({ context }) => { if (!context.currentUser) { diff --git a/docs/api/use-ai-chat.md b/docs/api/use-ai-chat.md index 9b1b3fbd8..d8c2b498b 100644 --- a/docs/api/use-ai-chat.md +++ b/docs/api/use-ai-chat.md @@ -70,10 +70,26 @@ Calls become available before local tool execution. They record requested tool n Register local tools under a single object using `defineAIChatTool(...)`. Their schemas must implement both [Standard Schema](https://standardschema.dev/) validation and Standard JSON Schema generation (for example, Zod 4). Provider-native tools are not supported. +## Local tool API + +`defineAIChatTool({ schema, execute, description? })` returns an `AILocalTool` with `kind: "local"`. The helper infers the first `execute` argument from the schema's **validated output**, including schema transformations. It does not execute or validate inputs when the tool is defined: `useAIChat` validates the model's arguments before calling `execute`. + +`AIChatToolSchema` is the schema contract: it combines Standard Schema validation with Standard JSON Schema generation. Zod 4 implements both. AppShell sends the schema's input JSON Schema to the AI Gateway; the executor receives the validated output. + +The second `execute` argument is an `AIChatToolContext`: + +| Property | Type | Description | +| ---------- | ----------------- | ----------------------------------------------------------------------------------------------------------- | +| `signal` | `AbortSignal` | Cancellation signal for the active chat request. Forward it to `fetch` or other operations that support it. | +| `messages` | `AIChatMessage[]` | User/assistant text available to the current turn, excluding internal tool-call and tool-result messages. | + +Calling `stop()` or unmounting aborts the signal. Custom tool work must cooperate with cancellation; aborting does not undo side effects that have already happened. The example below forwards the signal to its request and checks the response status before returning a tool result. + ## Usage ```tsx import { + Button, createAuthClient, createAIGatewayClient, defineAIChatTool, @@ -96,8 +112,12 @@ const lookupCustomer = defineAIChatTool({ schema: z.object({ customerId: z.string(), }), - async execute({ customerId }) { - return { customerId, name: "Acme Corp" }; + async execute({ customerId }, { signal }) { + const response = await fetch(`/api/customers/${encodeURIComponent(customerId)}`, { signal }); + if (!response.ok) { + throw new Error(`Customer lookup failed: ${response.status}`); + } + return response.json(); }, }); @@ -121,15 +141,15 @@ export function ChatScreen() {
Tool call: {call.name}
))} - - + + {error ?
{error.message}
: null} ); diff --git a/docs/api/use-app-shell-config.md b/docs/api/use-app-shell-config.md index e0de25c3d..0131a4906 100644 --- a/docs/api/use-app-shell-config.md +++ b/docs/api/use-app-shell-config.md @@ -111,14 +111,16 @@ function SettingsMenu() { Use `useAppShellConfig` when you only need configuration data: -```typescript -// ✅ Good - subscribes to configuration only -const { configurations } = useAppShellConfig(); - -// ❌ Overkill - useAppShell also subscribes to contextData changes -const { configurations } = useAppShell(); +```tsx +function ModuleCount() { + // Subscribes to configuration only. + const { configurations } = useAppShellConfig(); + return {configurations.modules.length} modules; +} ``` +Using `useAppShell()` here would also subscribe to context-data changes that this component does not use. + ## Comparison with Other Hooks | Hook | Returns | Use When | diff --git a/docs/api/use-app-shell-data.md b/docs/api/use-app-shell-data.md index d617aa9e5..24fc5a650 100644 --- a/docs/api/use-app-shell-data.md +++ b/docs/api/use-app-shell-data.md @@ -96,6 +96,8 @@ Define your context type with module augmentation: ```typescript // types.d.ts +import "@tailor-platform/app-shell"; + type User = { name: string; email: string; role: string }; declare module "@tailor-platform/app-shell" { @@ -113,27 +115,31 @@ declare module "@tailor-platform/app-shell" { } ``` -Now `useAppShellData()` returns fully typed data: +Now `useAppShellData()` returns fully typed data inside your components: -```typescript -const { contextData } = useAppShellData(); -contextData.currentUser; // Type: User | null -contextData.permissions; // Type: string[] -contextData.featureFlags; // Type: { newEditor: boolean, betaDashboard: boolean } +```tsx +function UserSummary() { + const { contextData } = useAppShellData(); + // currentUser is User | null; permissions is string[]. + // featureFlags has newEditor and betaDashboard boolean properties. + return {contextData.currentUser?.name}; +} ``` ## When to Use Use `useAppShellData` when you only need context data: -```typescript -// ✅ Good - subscribes to context data only -const { contextData } = useAppShellData(); - -// ❌ Overkill - useAppShell also subscribes to configuration changes -const { contextData } = useAppShell(); +```tsx +function PermissionCount() { + // Subscribes to context data only. + const { contextData } = useAppShellData(); + return {contextData.permissions.length} permissions; +} ``` +Using `useAppShell()` here would also subscribe to configuration changes that this component does not use. + ## Comparison with Other Hooks | Hook | Returns | Use When | diff --git a/docs/api/use-app-shell.md b/docs/api/use-app-shell.md index 7e964cea2..797b3512c 100644 --- a/docs/api/use-app-shell.md +++ b/docs/api/use-app-shell.md @@ -32,6 +32,18 @@ const useAppShell: () => { The hook merges the results of [`useAppShellConfig`](./use-app-shell-config.md) and [`useAppShellData`](./use-app-shell-data.md). Prefer one of those when you only need configuration or only need context data, so the component does not re-render for changes it does not use. +## Context API family + +| API | Reference | +| --------------------------------- | ----------------------------------------------------------------------------- | +| `useAppShellConfig` | [Configuration-only subscription](./use-app-shell-config.md) | +| `useAppShellData` | [Context-data-only subscription](./use-app-shell-data.md) | +| `useResolvedLocale` | [Full locale and language code](./use-resolved-locale.md) | +| `useTimeZone`, `TimeZone` | [Configured timezone and bound date/time helpers](./use-time-zone.md) | +| `AppInfo`, `AppInfoEntry` | [Metadata for the built-in app-info page](../components/app-shell.md#appinfo) | +| `AppShellRegister`, `ContextData` | [Context-data registration](#context-data) | +| `RouteParams` | [Registered route-parameter map](#route-parameter-types) | + ## Return Value ### `contextData` @@ -81,6 +93,8 @@ Define your context type with module augmentation: ```typescript // types.d.ts +import "@tailor-platform/app-shell"; + type User = { name: string; email: string; role: string }; declare module "@tailor-platform/app-shell" { @@ -92,7 +106,13 @@ declare module "@tailor-platform/app-shell" { }; } } +``` + +`AppShellRegister.contextData` sets the exported `ContextData` type. Without registration, `ContextData` falls back to `Record`. The side-effect import makes this declaration a module augmentation rather than a replacement module declaration. + +Pass matching data to `AppShell`: +```tsx // App.tsx +> + + +``` +Read the registered data inside a component: + +```tsx // MyComponent.tsx -const { contextData } = useAppShell(); -contextData.currentUser // Fully typed! -contextData.permissions // Fully typed! +import { useAppShell } from "@tailor-platform/app-shell"; + +function MyComponent() { + const { contextData } = useAppShell(); + + // currentUser is User | null; permissions is string[]. + return ( +
+ {contextData.currentUser?.name} ({contextData.permissions.length} permissions) +
+ ); +} +``` + +## Route parameter types + +The exported `RouteParams` type reads `AppShellRegister.routeParams`. With no registration it falls back to `Record>`; register a route map to retain literal paths and parameter names: + +```typescript +// types.d.ts +import "@tailor-platform/app-shell"; + +declare module "@tailor-platform/app-shell" { + interface AppShellRegister { + routeParams: { + "/": {}; + "/orders/:id": { id: string }; + }; + } +} ``` +```typescript +import type { RouteParams } from "@tailor-platform/app-shell"; + +type OrderParams = RouteParams["/orders/:id"]; // { id: string } +``` + +The Vite plugin registers its generated map for you when [typed-route generation](../concepts/file-based-routing.md#typed-routes) is enabled; do not also register a conflicting manual map. See [`createTypedPaths`](./create-typed-paths.md) for using a route map to build paths. + ## Examples ### Display User Info diff --git a/docs/api/use-auth.md b/docs/api/use-auth.md index 3f7a1ef3f..b8023e72d 100644 --- a/docs/api/use-auth.md +++ b/docs/api/use-auth.md @@ -16,7 +16,7 @@ const useAuth: () => { error: string | null; isAuthenticated: boolean; isReady: boolean; - login: () => Promise; + login: (options?: { returnTo?: string }) => Promise; logout: () => Promise; checkAuthStatus: () => Promise; }; @@ -41,8 +41,8 @@ const useAuth: () => { ### `login()` -- **Type:** `() => Promise` -- **Description:** Initiates the login process. Redirects to Tailor Platform authentication page. +- **Type:** `(options?: { returnTo?: string }) => Promise` +- **Description:** Initiates the login process. Returns to the current path, query string, and hash after authentication by default. Pass `login({ returnTo: "/orders" })` to choose another same-origin destination. See [return to the current page](../concepts/authentication.md#return-to-the-current-page). ### `logout()` @@ -120,17 +120,25 @@ function AuthStatus() { ## With AuthProvider -```typescript -import { AuthProvider, AppShell, useAuth } from "@tailor-platform/app-shell"; +Create the client once at module scope, outside React rendering, then pass it to the provider: + +```tsx +import { + createAuthClient, + AuthProvider, + AppShell, + SidebarLayout, +} from "@tailor-platform/app-shell"; + +const authClient = createAuthClient({ + clientId: "your-client-id", + appUri: "https://your-app.erp.dev", + redirectUri: "http://localhost:3000/callback", +}); function App() { return ( - + diff --git a/docs/api/use-page-meta.md b/docs/api/use-page-meta.md index c2d78bb5d..d397cc08c 100644 --- a/docs/api/use-page-meta.md +++ b/docs/api/use-page-meta.md @@ -70,14 +70,18 @@ function CustomLink({ to }: { to: string }) { ### Breadcrumb Builder -```typescript +```tsx +function BreadcrumbItem({ path }: { path: string }) { + const meta = usePageMeta(path); + return {meta?.title}; +} + function Breadcrumb({ paths }: { paths: string[] }) { return (
- {paths.map((path) => { - const meta = usePageMeta(path); - return {meta?.title}; - })} + {paths.map((path) => ( + + ))}
); } diff --git a/docs/api/use-register-command-palette-actions.md b/docs/api/use-register-command-palette-actions.md index 5be3cc29a..6d37dddc5 100644 --- a/docs/api/use-register-command-palette-actions.md +++ b/docs/api/use-register-command-palette-actions.md @@ -80,7 +80,7 @@ function OrderDetailPage() { ## Behavior - Actions are registered while the component is mounted and removed on unmount. -- Re-rendering with a new `actions` array replaces the previously registered set. +- Changes to action keys, labels, or the group update the registered set. The latest `onSelect` callbacks are used without requiring re-registration. - `icon` changes alone do not trigger re-registration. If you need to reflect a dynamic icon update, also change the action's `key` or `label`. - The hook requires `CommandPaletteProvider`, which is mounted automatically by `AppShell`. diff --git a/docs/api/use-route-error.md b/docs/api/use-route-error.md index d27c7c4c3..5ad2c6d00 100644 --- a/docs/api/use-route-error.md +++ b/docs/api/use-route-error.md @@ -54,9 +54,10 @@ import { defineModule } from "@tailor-platform/app-shell"; const myModule = defineModule({ path: "dashboard", + meta: { title: "Dashboard" }, component: DashboardPage, errorBoundary: , - resources: [...] + resources: [], }); ``` @@ -65,6 +66,7 @@ const myModule = defineModule({ ```typescript const productsModule = defineModule({ path: "products", + meta: { title: "Products" }, component: ProductsPage, resources: [ defineResource({ @@ -79,17 +81,22 @@ const productsModule = defineModule({ ### Advanced Error Handling ```typescript -import { isRouteErrorResponse, Text, useRouteError } from "@tailor-platform/app-shell"; +import { Text, useRouteError } from "@tailor-platform/app-shell"; function ErrorBoundary() { const error = useRouteError(); - // Handle route error responses (404, 500, etc.) - if (isRouteErrorResponse(error)) { + // Narrow the unknown error before reading an HTTP status. + if ( + typeof error === "object" && + error !== null && + "status" in error && + typeof error.status === "number" + ) { return (
- {error.status} {error.statusText} - {error.data} + HTTP {error.status} + The requested page could not be loaded.
); } @@ -142,7 +149,12 @@ function ErrorBoundary() { function ErrorBoundary() { const error = useRouteError(); - if (isRouteErrorResponse(error)) { + if ( + typeof error === "object" && + error !== null && + "status" in error && + typeof error.status === "number" + ) { if (error.status === 404) { return ; } @@ -168,8 +180,9 @@ Error boundaries can be defined at different levels: // Module-level - catches errors in all resources defineModule({ path: "products", + meta: { title: "Products" }, errorBoundary: , - resources: [...] + resources: [], }) // Resource-level - catches errors in specific resource diff --git a/docs/components/app-shell.md b/docs/components/app-shell.md index cef77a032..a60f6f778 100644 --- a/docs/components/app-shell.md +++ b/docs/components/app-shell.md @@ -25,6 +25,7 @@ const modules = [ path: "dashboard", component: DashboardPage, meta: { title: "Dashboard" }, + resources: [], }), ]; @@ -229,7 +230,7 @@ Access the configured timezone in components using [`useTimeZone`](../api/use-ti ### errorBoundary - **Type:** `ErrorBoundaryComponent` (optional) -- **Description:** Global error boundary component applied to all routes +- **Description:** Global error boundary element applied to all routes. Pass JSX such as ``, not a component constructor. ```tsx import { Text, useRouteError } from "@tailor-platform/app-shell"; @@ -244,7 +245,7 @@ const GlobalErrorBoundary = () => { ); }; - +}> {/* ... */} ; ``` @@ -260,6 +261,8 @@ First, define your context data type using module augmentation: ```typescript // types.d.ts — `User` and `ApiClient` are your application's own types +import "@tailor-platform/app-shell"; + declare module "@tailor-platform/app-shell" { interface AppShellRegister { contextData: { @@ -469,6 +472,7 @@ const modules = [ path: "dashboard", component: DashboardPage, meta: { title: "Dashboard" }, + resources: [], }), defineModule({ path: "products", @@ -506,7 +510,7 @@ function App() { settingsResources={settingsResources} locale="en" defaultColorTheme="system" - errorBoundary={ErrorBoundary} + errorBoundary={} contextData={{ currentUser }} > diff --git a/docs/components/badge.md b/docs/components/badge.md index 1cc28661a..ae17f050f 100644 --- a/docs/components/badge.md +++ b/docs/components/badge.md @@ -101,7 +101,9 @@ _Generated from the type surface — first-party props only._ ## Exports - `Badge` — function +- `BadgeOptions` — interface - `BadgeProps` — interface +- `BadgeVariant` — type - `badgeVariants` — const ### Badge Variants diff --git a/docs/components/command-palette.md b/docs/components/command-palette.md index b9ec548c5..a08e7dd8b 100644 --- a/docs/components/command-palette.md +++ b/docs/components/command-palette.md @@ -52,6 +52,34 @@ The CommandPalette will automatically: | `Enter` | Navigate to selected route | | Type to search | Filter routes by fuzzy search | +## Opening programmatically + +Call `useOpenCommandPalette()` at the top level of a component inside `AppShell`. It returns a function that opens the built-in palette; call that function from an event handler. + +```tsx +import { Button, useOpenCommandPalette } from "@tailor-platform/app-shell"; + +function SearchActions() { + const openCommandPalette = useOpenCommandPalette(); + + return ( + <> + + + + + ); +} +``` + +The returned function accepts an optional `OpenCommandPaletteOptions` object: + +| Property | Type | Description | +| -------- | -------- | ------------------------------------------------------------------------------------------------------------ | +| `search` | `string` | Initial search text. Omit it to open with an empty search. A registered `PREFIX:` activates its search mode. | + +Each call initializes the search, even if the palette is already open. The `ORD:` example requires an `ORD` source in AppShell's `searchSources`; without a matching source, the text is treated as an ordinary page/action search. + ## Features ### Fuzzy Search @@ -117,6 +145,8 @@ function OrderDetailPage() { { key: "confirm", label: "Confirm order", onSelect: handleConfirm }, { key: "cancel", label: "Cancel order", icon: , onSelect: handleCancel }, ]); + + return
{/* page content */}
; } ``` @@ -223,24 +253,27 @@ function App() { ### Prefix Syntax -The prefix match is **case-sensitive**. When a user types `ORD:`, the string after the colon (including any space) is forwarded to `search` as the query: +The prefix match is **case-sensitive**. When an initial value activates a search mode (for example, pasted text or programmatic opening), leading whitespace after the colon is removed from the initial query: ``` -User types: ORD: +Initial input: ORD: → search("", { signal }) — empty query, show all or hint -User types: ORD:12345 +Initial input: ORD:12345 → search("12345", { signal }) -User types: ORD: alice - → search(" alice", { signal }) — leading space preserved +Initial input: ORD: alice + → search("alice", { signal }) — leading space removed ``` +Once the mode is active, subsequent edits to its query are passed to `search` as entered. + ## Extending the built-in palette The supported extension points are: - `searchSources` on `AppShell` for async, prefix-activated search modes +- `useOpenCommandPalette` for opening with an optional initial search - [`useRegisterCommandPaletteActions`](../api/use-register-command-palette-actions.md) for page-level actions - [`ActionPanel`](./action-panel.md), whose enabled rows are registered automatically @@ -372,7 +405,7 @@ The CommandPalette follows these design principles: ## Related Components - [AppShell](./app-shell.md) - Root component that provides CommandPalette -- [SidebarLayout](./sidebar-layout.md) - Layout that includes CommandPalette +- [SidebarLayout](./sidebar-layout.md) - Default layout with a search entry for CommandPalette ## Related Concepts @@ -409,5 +442,5 @@ The CommandPalette follows these design principles: **Solutions:** 1. Check if another app is capturing the shortcut -2. Verify you're using `SidebarLayout` (CommandPalette is included) +2. Verify the page is inside `AppShell`, which provides the built-in CommandPalette 3. Check browser console for JavaScript errors diff --git a/docs/components/date-picker.md b/docs/components/date-picker.md index 1329c79a8..6bb604feb 100644 --- a/docs/components/date-picker.md +++ b/docs/components/date-picker.md @@ -30,6 +30,41 @@ import { The examples below also import `Button`, `Form`, and `Text` from `@tailor-platform/app-shell`, and `useId` and `useState` from `react`. +## Date values and parsing helpers + +AppShell re-exports these types and helpers from [`@internationalized/date`](https://react-spectrum.adobe.com/internationalized/date/) so applications can import them from `@tailor-platform/app-shell` without an additional dependency. + +| Export | Purpose | +| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| `CalendarDate` | Date-only value, without a time or timezone. | +| `CalendarDateTime` | Date and time without a timezone; it does not identify a unique instant. | +| `ZonedDateTime` | Date and time with a timezone and UTC offset. | +| `Time` | Time of day without a date or timezone. | +| `DateValue` | Union of `CalendarDate`, `CalendarDateTime`, and `ZonedDateTime`, accepted by the date controls. It does not include `Time`. | +| `parseDate(text)` | Parse an ISO date into a `CalendarDate`. | +| `parseDateTime(text)` | Parse an ISO date/time without a timezone into a `CalendarDateTime`. | +| `parseAbsolute(text, timeZone)` | Parse an ISO instant containing `Z` or an offset and represent it in the supplied IANA timezone as a `ZonedDateTime`. | +| `parseZonedDateTime(text)` | Parse a date/time with a bracketed IANA timezone into a `ZonedDateTime`, preserving the named zone. | +| `getLocalTimeZone()` | Read the environment's local IANA timezone. This does not read AppShell's `timeZone` setting. | + +The first five exports are **types only**, not constructor values. Use the parsing helpers to create date values: + +```ts +import { + parseDate, + parseDateTime, + parseAbsolute, + parseZonedDateTime, +} from "@tailor-platform/app-shell"; + +const date = parseDate("2026-04-09"); +const localDateTime = parseDateTime("2026-04-09T09:30"); +const instantInTokyo = parseAbsolute("2026-04-09T00:30:00Z", "Asia/Tokyo"); +const zonedDateTime = parseZonedDateTime("2026-04-09T09:30[Asia/Tokyo]"); +``` + +Parsing can throw for invalid input; validate or catch errors when the string is not trusted. For application-timezone behavior in React components, call [`useTimeZone()`](../api/use-time-zone.md) at the component's top level and pass its `value` to `parseAbsolute`. Use its `today()` and `now()` methods for the current date and instant, rather than assuming the user's local timezone matches the configured one. + ## API shape `DateField` and `DatePicker` are standalone composite controls. @@ -88,9 +123,10 @@ function DateFieldWithField() { Controlled: ```tsx -const [date, setDate] = useState(null); - -; +function ControlledDateField() { + const [date, setDate] = useState(null); + return ; +} ``` ## DatePicker diff --git a/docs/components/menu.md b/docs/components/menu.md index f6db856f4..1ebc20d7f 100644 --- a/docs/components/menu.md +++ b/docs/components/menu.md @@ -72,11 +72,23 @@ function BasicUsage() { ### Menu.Content Props -| Prop | Type | Default | Description | -| ----------- | -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ----------------------------------- | -| `position` | `{ side?: "top" \| "right" \| "bottom" \| "left"; align?: "start" \| "center" \| "end"; sideOffset?: number }` | `{ side: "bottom", align: "start", sideOffset: 4 }` | Placement of the popup | -| `className` | `string` | - | Additional CSS classes | -| `children` | `React.ReactNode` | - | Menu items and other sub-components | +| Prop | Type | Default | Description | +| ----------- | ----------------- | --------------------------------------------------- | ----------------------------------- | +| `position` | `PositionProps` | `{ side: "bottom", align: "start", sideOffset: 4 }` | Placement of the popup | +| `className` | `string` | - | Additional CSS classes | +| `children` | `React.ReactNode` | - | Menu items and other sub-components | + +### PositionProps + +The public `PositionProps` type is shared by the `position` prop on `Menu.Content` and [`Tooltip.Content`](./tooltip.md#tooltipcontent-props). Import it from `@tailor-platform/app-shell` when reusing a placement configuration. + +| Property | Type | Description | +| ------------ | ---------------------------------------- | ------------------------------------ | +| `side` | `"top" \| "right" \| "bottom" \| "left"` | Preferred side of the trigger. | +| `align` | `"start" \| "center" \| "end"` | Alignment along the cross axis. | +| `sideOffset` | `number` | Distance in pixels from the trigger. | + +All properties are optional. Defaults belong to the component: Menu uses bottom/start/4px, while Tooltip uses top/center/5px. ### Menu.Item Props diff --git a/docs/components/select.md b/docs/components/select.md index e6e88bb46..84e479177 100644 --- a/docs/components/select.md +++ b/docs/components/select.md @@ -15,7 +15,7 @@ The `Select` component provides a fully assembled single or multi-select dropdow import { Select } from "@tailor-platform/app-shell"; ``` -The examples below also import `useState` from `react`, and `Field`, `Text`, and the `SelectAsyncFetcher` type from `@tailor-platform/app-shell`. +The examples below also import `useState` from `react`, and `Button`, `Field`, `Text`, and the `SelectAsyncFetcher` type from `@tailor-platform/app-shell`. ## Basic Usage @@ -55,6 +55,8 @@ function BasicUsage() { ### MappedItem +`MappedItem` and `ItemGroup` are public types shared by `Select`, `Combobox`, and `Autocomplete`; import them from `@tailor-platform/app-shell`. + ```ts interface MappedItem { label: string; // Display text, used for filtering and a11y @@ -252,14 +254,19 @@ or a server action. ### Controlled Select ```tsx -const [selected, setSelected] = useState(null); +function ControlledSelect() { + const [selected, setSelected] = useState(null); - + ); +} ``` ### Custom Render @@ -285,46 +292,58 @@ const [selected, setSelected] = useState(null); Combine `Select.useAsync` with `Select.Parts` for full control over layout and rendering: -`Select.useAsync` accepts the same options as `Select.Async` (including `onFetchError`) and returns: +`Select.useAsync` accepts `fetcher` and optional `onFetchError`, and returns: -| Property | Type | Description | -| --------- | ------------ | ------------------------------------------------------- | -| `items` | `T[]` | Currently loaded items | -| `loading` | `boolean` | Whether a fetch is in progress | -| `error` | `unknown` | The error thrown by the last fetch, if any | -| `retry` | `() => void` | Re-runs the last fetch (use to build a custom retry UI) | +| Property | Type | Description | +| -------------- | ------------------------- | ------------------------------------------------------- | +| `items` | `T[]` | Currently loaded items | +| `loading` | `boolean` | Whether a fetch is in progress | +| `error` | `unknown` | The error thrown by the last fetch, if any | +| `retry` | `() => void` | Re-runs the last fetch (use to build a custom retry UI) | +| `onOpenChange` | `(open: boolean) => void` | Pass to the Root to fetch on open and cancel on close. | ```tsx type Fruit = { id: number; name: string }; -const fruits = Select.useAsync({ - fetcher: async ({ signal }) => { - const res = await fetch("/api/fruits", { signal }); - return res.json() as Promise; - }, - onFetchError: (error) => reportError(error), -}); - - f.name}> - - - - - {fruits.error ? ( -
- Couldn't load. -
- ) : fruits.loading ? ( -
Loading...
- ) : ( - fruits.items.map((f) => ( - - {f.name} - - )) - )} -
-
; +function FruitSelect() { + const fruits = Select.useAsync({ + fetcher: async ({ signal }) => { + const res = await fetch("/api/fruits", { signal }); + if (!res.ok) throw new Error(`Could not load fruits: ${res.status}`); + return res.json() as Promise; + }, + onFetchError: (error) => reportError(error), + }); + + return ( + + onOpenChange={fruits.onOpenChange} + itemToStringLabel={(fruit) => fruit.name} + > + + + + + {fruits.error ? ( +
+ Couldn't load.{" "} + +
+ ) : fruits.loading ? ( +
Loading...
+ ) : ( + fruits.items.map((fruit) => ( + + {fruit.name} + + )) + )} +
+ + ); +} ``` ## Accessibility diff --git a/docs/components/sidebar-layout.md b/docs/components/sidebar-layout.md index 9997cb208..c6ed8ec55 100644 --- a/docs/components/sidebar-layout.md +++ b/docs/components/sidebar-layout.md @@ -216,6 +216,16 @@ Use `body` when the stock content column is too restrictive and you need your ow `SidebarLayout.ContentContainer` is the stock main column: inset padding, pinned header slot, scroll region, and `useAppShellScrollContainer()` support. `SidebarLayout.Trigger` exposes the built-in sidebar toggle so custom headers do not need DOM workarounds. +### ContentContainerProps + +The exported `ContentContainerProps` type describes `SidebarLayout.ContentContainer` and `GlobalHeaderLayout.ContentContainer`: + +| Prop | Type | Description | +| ----------- | ----------------- | -------------------------------------------------------------------------------- | +| `header` | `React.ReactNode` | Optional pinned content above the scroll region. Omit for a bare content column. | +| `className` | `string` | Optional additional classes for the outer `
` element. | +| `children` | `React.ReactNode` | Optional scrolling content, usually the layout's `Outlet`. | + ## Reading and controlling the sidebar Use `useAppShellSidebar()` to read and control the sidebar state instead of observing internal DOM attributes or clicking the trigger through the DOM. It also exposes the effective `sidebarBehaviour`, already normalized from either public prop, so custom sidebars do not need to handle the deprecated boolean themselves. @@ -259,6 +269,23 @@ import { DynamicBreadcrumb, SidebarLayout } from "@tailor-platform/app-shell"; ; ``` +### Reading path segments + +`usePathSegments()` returns `{ basePath, segments }` for the current route. `basePath` is the configured base path or `null`. Each segment has `segment` (the URL segment), `path` (the accumulated path without the base path or a leading slash), `title` (the resolved, localized breadcrumb title), and `clickable` (whether it links to a page). + +Call the hook at the top level of a component, then iterate over its result: + +```tsx +import { usePathSegments } from "@tailor-platform/app-shell"; + +function CurrentPathTitles() { + const { segments } = usePathSegments(); + return {segments.map(({ title }) => title).join(" / ")}; +} +``` + +These titles come from route metadata; they do not include overrides from `useOverrideBreadcrumb()`. Use `DynamicBreadcrumb` for the built-in rendering, which also applies those overrides. + ## Accessing the content scroll container The AppShell is viewport-bounded (`h-svh`), so the **document itself does not scroll** — the content area does. Code that previously relied on `window`/document scroll (reading `window.scrollY`, listening to `window`'s `scroll` event, `window.scrollTo(...)`, or an `IntersectionObserver` with the default viewport root) should target the content scroll container instead. diff --git a/docs/components/tooltip.md b/docs/components/tooltip.md index f4eef79f5..e0584d1c9 100644 --- a/docs/components/tooltip.md +++ b/docs/components/tooltip.md @@ -65,14 +65,14 @@ Wrap a section of your UI (e.g. a toolbar) with `Tooltip.Provider` to share dela ### Tooltip.Content Props -| Prop | Type | Default | Description | -| ------------ | ---------------------------------------- | ---------- | -------------------------------------------------------- | -| `side` | `"top" \| "right" \| "bottom" \| "left"` | `"top"` | Preferred placement of the tooltip | -| `align` | `"start" \| "center" \| "end"` | `"center"` | Alignment along the placement axis | -| `sideOffset` | `number` | `5` | Distance in px from the trigger | -| `noArrow` | `boolean` | `false` | When `true`, suppresses the arrow indicator on the popup | -| `className` | `string` | - | Additional CSS classes | -| `children` | `React.ReactNode` | - | Tooltip text or content | +| Prop | Type | Default | Description | +| ----------- | ----------------- | ------------------------------------------------- | --------------------------------------------------------- | +| `position` | `PositionProps` | `{ side: "top", align: "center", sideOffset: 5 }` | Preferred placement of the tooltip. | +| `noArrow` | `boolean` | `false` | When `true`, suppresses the arrow indicator on the popup. | +| `className` | `string` | - | Additional CSS classes. | +| `children` | `React.ReactNode` | - | Tooltip text or content. | + +[`PositionProps`](./menu.md#positionprops) is the public placement type shared with `Menu.Content`. Use `position={{ side: "right", align: "start" }}` to configure placement. The old flat `side`, `align`, and `sideOffset` props remain supported but deprecated; they are ignored when `position` is supplied. ## Placement @@ -83,7 +83,7 @@ function Placement() { return ( }>Trigger - + Appears on the right diff --git a/docs/concepts/authentication.md b/docs/concepts/authentication.md index c9e9d12c8..1bd290066 100644 --- a/docs/concepts/authentication.md +++ b/docs/concepts/authentication.md @@ -84,6 +84,8 @@ const UserProfile = () => { | `logout` | `() => Promise` | Clears tokens and ends the session | | `checkAuthStatus` | `() => Promise` | Re-checks auth status (always makes a network request) | +`AuthState` is the exported state shape containing `isAuthenticated`, `isReady`, and `error`. `checkAuthStatus()` returns that shape; `useAuth()` exposes those fields together with the authentication methods above. + ### Return to the current page `autoLogin` records the current path, query string, and hash before redirecting, then returns there after a successful callback. Manual `login()` calls do the same by default. Pass `returnTo` to choose another same-origin destination: @@ -132,7 +134,9 @@ function ProtectedContent() { ## Auth Client -Use `createAuthClient` to create an authentication client that you pass to `AuthProvider`. The client handles token management and provides an authenticated `fetch` method for use with GraphQL clients. +Use `createAuthClient` to create an `EnhancedAuthClient` that you pass to `AuthProvider`. Create it once at module scope: if the URL contains OAuth callback parameters, client creation starts callback handling immediately, before React rendering. The client handles token management and provides an authenticated `fetch` method for use with GraphQL clients. + +`AuthClient` is the base type re-exported from [`@tailor-platform/auth-public-client`](https://www.npmjs.com/package/@tailor-platform/auth-public-client) for advanced integrations. `EnhancedAuthClient` extends that contract with AppShell helpers such as `getAppUri()`; `AuthProvider` requires this enhanced client, not just an arbitrary base client. ```tsx import { createAuthClient } from "@tailor-platform/app-shell"; @@ -291,13 +295,29 @@ The line is drawn on the shape of the response, not on how transient the underly To react to teardown yourself — clearing app-level caches, for instance — subscribe to the client's events: ```tsx -useEffect(() => { - return authClient.addEventListener((event) => { - if (event.type === "logout") { - clearAppCaches(); - } - }); -}, [authClient]); +import { useEffect } from "react"; +import type { EnhancedAuthClient } from "@tailor-platform/app-shell"; + +function SessionCleanup({ + client, + clearAppCaches, +}: { + client: EnhancedAuthClient; + clearAppCaches: () => void; +}) { + useEffect(() => { + return client.addEventListener((event) => { + if (event.type === "logout") { + clearAppCaches(); + } + }); + }, [client, clearAppCaches]); + + return null; +} + +// Mount alongside your app, using the same client passed to AuthProvider. +; ``` ## Testing diff --git a/docs/concepts/file-based-routing.md b/docs/concepts/file-based-routing.md index c3f303290..2db9f598d 100644 --- a/docs/concepts/file-based-routing.md +++ b/docs/concepts/file-based-routing.md @@ -155,6 +155,21 @@ For a dynamic label, use `breadcrumbTitle: (segment) => labels.t("order", { id: Other callbacks receive the URL segment; AppShell resolves any returned `LocalizedString` with the current locale. The existing `() => labels.t("orders")` form remains supported. Wrap handwritten locale functions in an outer callback rather than passing them directly. +### PageComponent Type + +`PageComponent` is the exported React function-component type with an optional `appShellPageProps: AppShellPageProps` static field. Use it when you want to annotate the component itself rather than applying `satisfies AppShellPageProps` to the metadata object: + +```tsx +import type { PageComponent } from "@tailor-platform/app-shell"; + +const AboutPage: PageComponent = () =>
About
; +AboutPage.appShellPageProps = { + meta: { title: "About" }, +}; + +export default AboutPage; +``` + ## Path Conventions | Directory Name | Converts To | Description | @@ -254,6 +269,7 @@ const ordersResource = defineResource({ }); const purchasingModule = defineModule({ path: "purchasing", + meta: { title: "Purchasing" }, resources: [ordersResource], }); diff --git a/docs/concepts/modules-and-resources.md b/docs/concepts/modules-and-resources.md index b4a1ed3d9..e83d9a972 100644 --- a/docs/concepts/modules-and-resources.md +++ b/docs/concepts/modules-and-resources.md @@ -15,6 +15,8 @@ Modules and Resources both share core interface. Of interest: - `component: (props: ResourceComponentProps) => ReactNode` - the component to render when the router navigates to that module/resource (optional — omitting it causes the path to return a 404 while child routes remain accessible) - `guards?: Guard[]` - optional array of guard functions to control access based on permissions or feature flags +Module options also require `resources` and `meta`; use `[]` for no child resources and `{}` for default metadata. Resource options make `subResources` and `meta` optional. + A trivial `modules` example: ```tsx @@ -23,6 +25,7 @@ import { defineModule, defineResource, pass, hidden } from "@tailor-platform/app const appShellPropModule = [ defineModule({ path: "purchasing", + meta: { title: "Purchasing" }, component: PurchasingLandingPage, resources: [ defineResource({ @@ -44,6 +47,7 @@ const appShellPropModule = [ }), defineModule({ path: "sales", + meta: { title: "Sales" }, component: SalesLandingPage, resources: [ defineResource({ @@ -57,6 +61,7 @@ const appShellPropModule = [ // Module without component - /dashboard returns 404, child routes remain accessible defineModule({ path: "dashboard", + meta: { title: "Dashboard" }, resources: [ defineResource({ path: "overview", @@ -71,14 +76,13 @@ const appShellPropModule = [ // Module with guards for access control defineModule({ path: "reports", + meta: { title: "Reports" }, component: ReportsPage, resources: [reportsListResource], guards: [ - async ({ context, signal }) => { - const ok = await fetch("/api/me/permissions?scope=reports", { - signal, - }).then((r) => r.ok); - return ok ? pass() : hidden(); + async () => { + const response = await fetch("/api/me/permissions?scope=reports"); + return response.ok ? pass() : hidden(); }, ], }), @@ -111,6 +115,25 @@ Guards on component-less modules and resources execute correctly. For example, a > Read more about [client-side navigation](./routing-navigation.md) in AppShell apps +## Page Props and Error Boundaries + +`ResourceComponentProps` is the public type for a module or resource page's props. AppShell passes the localized `title` and the child `resources` (a module's `resources` or a resource's `subResources`). Although the type also declares an optional `icon`, the definers do not inject it into page props; icons belong to navigation metadata. + +```tsx +import { Text, type ResourceComponentProps } from "@tailor-platform/app-shell"; + +function ProductsPage({ title, resources }: ResourceComponentProps) { + return ( +
+ {title} + {resources?.length ?? 0} child resources +
+ ); +} +``` + +`ErrorBoundaryComponent` is the public type accepted by `errorBoundary`: a `ReactNode`, such as ``, **not** the component function `ErrorBoundary`. Read errors inside that element with [`useRouteError`](../api/use-route-error.md). See [`defineModule`](../api/define-module.md) and [`defineResource`](../api/define-resource.md) for examples and option types derived from their public signatures. + ## Route Guards Both modules and resources support `guards` - an array of functions that control access based on permissions, feature flags, or any other criteria. Guards are executed in order and provide: @@ -119,7 +142,9 @@ Both modules and resources support `guards` - an array of functions that control - Reusability: Share common guards across routes - Semantic constraints: Clear `pass()`, `hidden()`, or `redirectTo()` results -See the [Guards documentation](../api/guards/overview.md) for full details. +The public `Guard` function receives a `GuardContext` containing only `{ context: ContextData }` and returns a `GuardResult`, synchronously or asynchronously. Use `pass()`, `hidden()`, or `redirectTo(path)` to construct that result. No abort signal is passed to guards. + +See the [Guards documentation](../api/guards/overview.md) for the complete types and helper references. These client-side guards control navigation and rendering; the server must still enforce authorization for protected data and operations. ### Guard Examples @@ -130,12 +155,13 @@ import { defineModule, pass, hidden } from "@tailor-platform/app-shell"; const reportsModule = defineModule({ path: "reports", + meta: { title: "Reports" }, component: ReportsPage, resources: [reportsListResource], guards: [ - async ({ context }) => { - const ok = await fetch("/api/me/permissions?scope=reports").then((r) => r.ok); - return ok ? pass() : hidden(); + async () => { + const response = await fetch("/api/me/permissions?scope=reports"); + return response.ok ? pass() : hidden(); }, ], }); @@ -148,6 +174,7 @@ import { pass, hidden } from "@tailor-platform/app-shell"; const betaFeaturesModule = defineModule({ path: "beta", + meta: { title: "Beta Features" }, component: BetaFeaturesPage, resources: [newFeatureResource], guards: [ @@ -166,8 +193,9 @@ import { pass, hidden } from "@tailor-platform/app-shell"; const billingModule = defineModule({ path: "billing", + meta: { title: "Billing" }, component: BillingPage, - resources: [billingResources], + resources: billingResources, guards: [ async ({ context }) => { const plan = await getCurrentTenantPlan();