Skip to content

Added Post Analytics skeleton in React - #22978

Merged
peterzimon merged 7 commits into
mainfrom
ta-post-analytics-skeleton
Apr 22, 2025
Merged

peterzimon merged 7 commits into
mainfrom
ta-post-analytics-skeleton

Conversation

@peterzimon

@peterzimon peterzimon commented Apr 22, 2025 •

Copy link
Copy Markdown
Contributor

ref https://linear.app/ghost/issue/PROD-234/build-post-analytics-skeleton

  • With the new analytics we're rebuilding the post analytics page to accommodate a much better breakdown of post related stats that Ghost customers would need. With this PR we added a first version of a new React app focusing on Web analytics in the context of a single post.

@coderabbitai

coderabbitai Bot commented Apr 22, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This change set introduces significant restructuring and refactoring across the posts analytics feature and its integration with routing, UI layout, and navigation. The posts app replaces its previous routing configuration with a new routes.tsx file that defines a /posts route prefix and updated nested routes, including redirects and error handling. Multiple new React components are added, such as MainLayout, PostAnalytics, PostAnalyticsContent, PostAnalyticsView, Sidebar, and PostAnalyticsLayout, while many older analytics and newsletter-related components and mock-data-driven presentational components have been removed.

The navigation system is enhanced by moving the Navigate export to a custom internal provider that supports cross-application navigation. The posts app restructures its component hierarchy by removing the SidebarProvider and adjusting the RouterProvider placement. The ErrorPage and breadcrumb UI components receive style and interface updates, and a new ViewHeader component is introduced and adopted in the stats app, replacing previous header components. TypeScript and Vite configurations are updated to add path aliases and type definitions for improved module resolution.

In the Ghost Admin app, the "Post analytics" navigation menu item is removed, a new "Web stats" button is conditionally added to the analytics header, and new route and controller classes are introduced for posts analytics with corresponding template rendering changes. Minor CSS updates adjust font sizes and spacing in breadcrumb and analytics meta elements.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/posts/src/views/PostAnalytics/PostAnalytics.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react-hooks".

(The package "eslint-plugin-react-hooks" was not found when loaded as a Node module from the directory "/apps/posts".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react-hooks@latest --save-dev

The plugin "eslint-plugin-react-hooks" was referenced from the config file in "apps/posts/.eslintrc.cjs".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

apps/posts/src/App.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react-hooks".

(The package "eslint-plugin-react-hooks" was not found when loaded as a Node module from the directory "/apps/posts".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react-hooks@latest --save-dev

The plugin "eslint-plugin-react-hooks" was referenced from the config file in "apps/posts/.eslintrc.cjs".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

apps/admin-x-framework/src/index.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react-hooks".

(The package "eslint-plugin-react-hooks" was not found when loaded as a Node module from the directory "/apps/admin-x-framework".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react-hooks@latest --save-dev

The plugin "eslint-plugin-react-hooks" was referenced from the config file in "apps/admin-x-framework/.eslintrc.cjs".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

  • 25 others
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@peterzimon
peterzimon enabled auto-merge (squash) April 22, 2025 10:40

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🔭 Outside diff range comments (1)
apps/shade/src/components/ui/breadcrumb.tsx (1)

105-105: ⚠️ Potential issue

Fix typo in displayName of BreadcrumbEllipsis
The displayName is misspelled as BreadcrumbElipssis, which can confuse devtools and error messages.

Proposed fix:

- BreadcrumbEllipsis.displayName = 'BreadcrumbElipssis';
+ BreadcrumbEllipsis.displayName = 'BreadcrumbEllipsis';
🧹 Nitpick comments (16)
apps/shade/src/index.ts (1)

26-26: Remove redundant type rename

The type export includes an unnecessary self-rename that can be simplified.

-export type {DropdownMenuCheckboxItemProps as DropdownMenuCheckboxItemProps} from '@radix-ui/react-dropdown-menu';
+export type {DropdownMenuCheckboxItemProps} from '@radix-ui/react-dropdown-menu';
🧰 Tools
🪛 Biome (1.9.4)

[error] 26-26: Useless rename.

Safe fix: Remove the renaming.

(lint/complexity/noUselessRename)

apps/admin-x-framework/src/index.ts (1)

8-10: Changed Navigate export to use local implementation with cross-app navigation support.

The export of Navigate has been switched from React Router's version to a custom implementation in RouterProvider. This change centralizes navigation logic and enables cross-application navigation support through the custom implementation.

However, I recommend adding a brief comment in the code to highlight the purpose of this change for future maintainers:

// Routing
export type {RouteObject} from 'react-router';
export type {RouterProviderProps} from './providers/RouterProvider';
-export {RouterProvider, useNavigate, useBaseRoute, useRouteHasParams, resetScrollPosition, ScrollRestoration, Navigate} from './providers/RouterProvider';
+// Using custom Navigate implementation to support cross-app navigation
+export {RouterProvider, useNavigate, useBaseRoute, useRouteHasParams, resetScrollPosition, ScrollRestoration, Navigate} from './providers/RouterProvider';
export {useNavigationStack} from './providers/NavigationStackProvider';
-export {Link, NavLink, Outlet, useLocation, useParams, useSearchParams, redirect, matchRoutes} from 'react-router';
+export {Link, NavLink, Outlet, useLocation, useParams, useSearchParams, redirect, matchRoutes} from 'react-router';
apps/posts/src/views/PostAnalytics/layout/PostAnalyticsLayout.tsx (1)

4-8: Forward HTML props to MainLayout for flexibility
The component type includes HTMLAttributes<HTMLDivElement>, but only children is being destructured. To allow consumers to pass className, id, or other props, spread the rest onto MainLayout.

Apply this diff:

- const PostAnalyticsLayout: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({children}) => {
+ const PostAnalyticsLayout: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({children, ...props}) => {
     return (
-        <MainLayout>
+        <MainLayout {...props}>
             <div className='grid w-full grow'>
                 <div className='flex h-full flex-col px-8'>
                     {children}
apps/posts/src/views/PostAnalytics/components/EmptyStatView.tsx (1)

6-11: Enhance accessibility and dark‑mode support

  • Add role="status" and aria-live="polite" to announce the empty state to screen readers.
  • Include aria-hidden="true" on the decorative icon.
  • Adjust text color for dark mode (e.g., dark:text-gray-300).
- <div className='flex h-full flex-col items-center justify-center gap-4 text-gray-700'>
+ <div 
+     role="status" 
+     aria-live="polite" 
+     className='flex h-full flex-col items-center justify-center gap-4 text-gray-700 dark:text-gray-300'
+ >
     <div className='-mt-10 flex size-18 items-center justify-center rounded-full bg-gray-100 dark:bg-gray-950'>
-        <LucideIcon.ChartScatter size={24} strokeWidth={1.5} />
+        <LucideIcon.ChartScatter size={24} strokeWidth={1.5} aria-hidden="true" />
     </div>
     No stats available for this filter.
 </div>
apps/stats/src/views/Stats/Sources.tsx (1)

6-6: Import list contains components that aren't used in this file

The import statement includes several components from @tryghost/shade that don't appear to be used in the modified code, such as ChartConfig, ChartContainer, ChartTooltip, and ChartTooltipContent. These are likely used elsewhere in the file, but consider removing unused imports to improve code clarity and potentially reduce bundle size.

apps/posts/src/views/PostAnalytics/components/Sidebar.tsx (2)

12-12: Magic number in sticky positioning

The 134px magic number in the top-[134px] class value isn't self-explanatory and may not adapt well to UI changes.

Consider replacing this with a named CSS variable or a more descriptive class name that can be maintained centrally, making it clearer what this offset represents.


5-5: Use TypeScript interface for component props

Even though the component doesn't currently accept props, it's a good practice to define a props interface for future extensibility.

-const Sidebar:React.FC = () => {
+interface SidebarProps {}
+
+const Sidebar: React.FC<SidebarProps> = () => {
apps/posts/src/views/PostAnalytics/components/PostAnalyticsContent.tsx (1)

1-4: Commented-out import that should be removed or implemented

There's a commented-out import for Sidebar which has a corresponding commented-out component usage on line 11. Either this component should be fully implemented and the comments removed, or the commented code should be deleted entirely.

import React from 'react';
-// import Sidebar from './Sidebar';
import {cn} from '@tryghost/shade';
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (2)

6-6: Empty interface should be refactored to a type alias

An empty interface is equivalent to {}. The static analysis tool correctly identifies this as a potential issue.

-interface postAnalyticsProps {};
+type PostAnalyticsProps = Record<string, never>;

Additionally, the interface name should follow PascalCase convention (PostAnalyticsProps instead of postAnalyticsProps).

🧰 Tools
🪛 Biome (1.9.4)

[error] 5-6: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)


19-28: Duplicated cross-app navigation logic

Both breadcrumb links use {crossApp: true} to navigate between apps. This is a good pattern, but the crossApp flag is used in two places with similar routing logic, suggesting this could be abstracted.

Consider creating a helper function to handle cross-app navigation consistently across components:

const navigateCrossApp = (path: string) => navigate(path, {crossApp: true});

// Then use it like:
<BreadcrumbLink className='cursor-pointer' onClick={() => navigateCrossApp('/posts/')}>
apps/posts/src/views/PostAnalytics/components/PostAnalyticsView.tsx (2)

13-19: Consider enhancing the default loading state

The default loading state is a simple text string which may not be consistent with the application's design system or support internationalization.

- loadingComponent = <>Loading...</>,
+ loadingComponent = <LoadingIndicator /> // or another component from your design system

1-34: Add JSDoc comments to improve component documentation

The component would benefit from JSDoc comments to explain its purpose, usage, and props.

+/**
+ * A generic component for handling loading states, empty states, and content rendering
+ * based on data availability.
+ * 
+ * @template T - The type of items in the data array
+ */
interface PostAnalyticsViewProps<T> {
    isLoading?: boolean;
    data?: T[] | null;
    children?: React.ReactNode;
    loadingComponent?: React.ReactNode;
    emptyComponent?: React.ReactNode;
}

+/**
+ * Renders content based on loading and data states:
+ * - Shows loading component when isLoading is true
+ * - Shows empty state when data is null or empty
+ * - Shows children when data is available
+ * 
+ * @template T - The type of items in the data array
+ */
const PostAnalyticsView = <T,>({
apps/posts/src/routes.tsx (2)

5-5: Utilize APP_ROUTE_PREFIX in navigation paths

You've defined an APP_ROUTE_PREFIX constant but it's not used in the route path definitions. Consider using this constant to keep paths consistent.

- element: <Navigate crossApp={true} to='/posts/analytics/:postId' />
+ element: <Navigate crossApp={true} to={`${APP_ROUTE_PREFIX}/analytics/${postId}`} />

24-26: DRY: Extract the ErrorPage component with callback to a constant

Both root and catch-all routes use identical error components with identical TODO comments. Extract this to a constant to avoid duplication.

+ const errorComponent = <ErrorPage onBackToDashboard={() => {}} />; // @TODO: add back to dashboard click handle

  export const routes: RouteObject[] = [
      {
          // Root route configuration
          path: '',
-         errorElement: <ErrorPage onBackToDashboard={() => {}} />, // @TODO: add back to dashboard click handle
+         errorElement: errorComponent,
          children: [
              // ...
              {
                  path: '*',
-                 element: <ErrorPage onBackToDashboard={() => {}} /> // @TODO: add back to dashboard click handle
+                 element: errorComponent
              }
          ]
      }
  ];
ghost/admin/app/router.js (1)

61-63: Remove commented-out code

There's commented-out code for a route that's no longer needed. Rather than leaving it in the codebase, it should be removed to avoid confusion.

- // this.route('posts-x', {path: '/posts/analytics/:post_id/web'}, function () {
- //     this.route('posts-x', {path: '/*sub'});
- // });
apps/admin-x-framework/src/providers/RouterProvider.tsx (1)

177-184: Add JSDoc comments for the Navigate component

The Navigate component would benefit from JSDoc comments explaining its purpose, usage, and especially when to use the crossApp property.

+/**
+ * A navigation component that extends React Router's Navigate to support cross-app navigation.
+ * 
+ * @param to - The target route to navigate to
+ * @param replace - Whether to replace the current history entry
+ * @param state - State to persist to the location
+ * @param crossApp - Set to true when navigating to a route in a different Ghost app (uses externalNavigate)
+ */
interface CustomNavigateProps {
    to: string;
    replace?: boolean;
    state?: unknown;
    crossApp?: boolean;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d6bcaa4 and 9fc8b0d3db7bd74e0e2510f781b1aedf68b3639a.

📒 Files selected for processing (45)
  • apps/admin-x-framework/src/index.ts (1 hunks)
  • apps/admin-x-framework/src/providers/RouterProvider.tsx (2 hunks)
  • apps/posts/src/App.tsx (2 hunks)
  • apps/posts/src/components/Header.tsx (0 hunks)
  • apps/posts/src/components/layout/MainLayout.tsx (1 hunks)
  • apps/posts/src/routes.ts (0 hunks)
  • apps/posts/src/routes.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/EmptyStatView.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/PostAnalyticsContent.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/PostAnalyticsView.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/Sidebar.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/layout/PostAnalyticsLayout.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/modals/ShareModal.tsx (1 hunks)
  • apps/posts/src/views/post-analytics/PostAnalytics.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/Newsletter.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/Overview.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/StatsTabs.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/newsletter/OpenedList.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/newsletter/SentList.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/overview/ClickPerformance.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/overview/Conversions.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/overview/Feedback.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/overview/Metric.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/overview/NewsletterPerformance.tsx (0 hunks)
  • apps/posts/src/views/posts/Posts.tsx (0 hunks)
  • apps/posts/tsconfig.json (2 hunks)
  • apps/posts/vite.config.mjs (1 hunks)
  • apps/shade/src/components/layout/error-page.tsx (1 hunks)
  • apps/shade/src/components/layout/heading.tsx (1 hunks)
  • apps/shade/src/components/layout/view-header.tsx (1 hunks)
  • apps/shade/src/components/ui/breadcrumb.tsx (4 hunks)
  • apps/shade/src/index.ts (1 hunks)
  • apps/shade/tailwind.config.cjs (2 hunks)
  • apps/stats/src/components/layout/Header.tsx (0 hunks)
  • apps/stats/src/views/Stats/Locations.tsx (2 hunks)
  • apps/stats/src/views/Stats/Sources.tsx (2 hunks)
  • apps/stats/src/views/Stats/Web.tsx (2 hunks)
  • ghost/admin/app/components/gh-nav-menu/main.hbs (1 hunks)
  • ghost/admin/app/components/posts/analytics.hbs (1 hunks)
  • ghost/admin/app/controllers/posts/analytics/posts-x.js (1 hunks)
  • ghost/admin/app/router.js (2 hunks)
  • ghost/admin/app/routes/posts/analytics/posts-x.js (1 hunks)
  • ghost/admin/app/styles/layouts/content.css (1 hunks)
  • ghost/admin/app/styles/layouts/main.css (2 hunks)
💤 Files with no reviewable changes (15)
  • apps/posts/src/views/post-analytics/components/Overview.tsx
  • apps/posts/src/views/post-analytics/components/overview/Metric.tsx
  • apps/posts/src/components/Header.tsx
  • apps/posts/src/views/posts/Posts.tsx
  • apps/posts/src/views/post-analytics/components/newsletter/SentList.tsx
  • apps/posts/src/views/post-analytics/components/overview/Conversions.tsx
  • apps/posts/src/views/post-analytics/PostAnalytics.tsx
  • apps/posts/src/views/post-analytics/components/overview/Feedback.tsx
  • apps/posts/src/views/post-analytics/components/StatsTabs.tsx
  • apps/stats/src/components/layout/Header.tsx
  • apps/posts/src/views/post-analytics/components/Newsletter.tsx
  • apps/posts/src/routes.ts
  • apps/posts/src/views/post-analytics/components/newsletter/OpenedList.tsx
  • apps/posts/src/views/post-analytics/components/overview/NewsletterPerformance.tsx
  • apps/posts/src/views/post-analytics/components/overview/ClickPerformance.tsx
🧰 Additional context used
🧬 Code Graph Analysis (7)
apps/posts/src/views/PostAnalytics/modals/ShareModal.tsx (1)
apps/shade/src/components/ui/dialog.tsx (4)
  • DialogContent (112-112)
  • DialogHeader (113-113)
  • DialogTitle (115-115)
  • DialogDescription (116-116)
apps/stats/src/views/Stats/Locations.tsx (2)
apps/shade/src/components/layout/view-header.tsx (2)
  • ViewHeader (32-32)
  • ViewHeaderActions (32-32)
apps/shade/src/components/layout/heading.tsx (1)
  • H1 (56-56)
apps/stats/src/views/Stats/Web.tsx (2)
apps/shade/src/components/layout/view-header.tsx (2)
  • ViewHeader (32-32)
  • ViewHeaderActions (32-32)
apps/shade/src/components/layout/heading.tsx (1)
  • H1 (56-56)
apps/stats/src/views/Stats/Sources.tsx (2)
apps/shade/src/components/layout/view-header.tsx (2)
  • ViewHeader (32-32)
  • ViewHeaderActions (32-32)
apps/shade/src/components/layout/heading.tsx (1)
  • H1 (56-56)
apps/posts/src/App.tsx (3)
apps/admin-x-framework/src/index.ts (2)
  • RouterProvider (8-8)
  • Outlet (10-10)
apps/admin-x-framework/src/providers/RouterProvider.tsx (1)
  • RouterProvider (101-134)
apps/posts/src/routes.tsx (2)
  • APP_ROUTE_PREFIX (5-5)
  • routes (7-29)
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (4)
apps/admin-x-framework/src/index.ts (2)
  • useParams (10-10)
  • useNavigate (8-8)
apps/shade/src/components/layout/view-header.tsx (1)
  • ViewHeader (32-32)
apps/shade/src/components/ui/breadcrumb.tsx (6)
  • Breadcrumb (108-108)
  • BreadcrumbList (109-109)
  • BreadcrumbItem (110-110)
  • BreadcrumbLink (111-111)
  • BreadcrumbSeparator (113-113)
  • BreadcrumbPage (112-112)
apps/shade/src/components/layout/heading.tsx (1)
  • H1 (56-56)
apps/admin-x-framework/src/providers/RouterProvider.tsx (1)
apps/admin-x-framework/src/index.ts (2)
  • Navigate (8-8)
  • useFramework (3-3)
🪛 Biome (1.9.4)
apps/shade/src/index.ts

[error] 26-26: Useless rename.

Safe fix: Remove the renaming.

(lint/complexity/noUselessRename)

apps/posts/src/views/PostAnalytics/PostAnalytics.tsx

[error] 5-6: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Unit tests (Node 22.13.1)
  • GitHub Check: Unit tests (Node 20.11.1)
  • GitHub Check: Unit tests (Node 18.12.1)
  • GitHub Check: Lint
  • GitHub Check: Admin tests - Chrome
🔇 Additional comments (37)
apps/shade/tailwind.config.cjs (2)

144-144: Typography refinement for letter spacing

The letter spacing for "tighter" has been adjusted from '-0.025em' to '-0.02em', making it slightly less tight. This subtle adjustment aligns with the overall typography improvements in the new post analytics UI.


345-345: Typography refinement for heading size

The font size for "3xl" was increased from '2.7rem' to '2.8rem', providing slightly larger headings. This change supports the visual hierarchy in the new post analytics interface and ensures consistent typography across components.

apps/shade/src/index.ts (1)

32-32: Export view-header components for reuse

Good addition of the view-header exports. This makes the new ViewHeader and ViewHeaderActions components available for use in the post analytics feature and other areas of the application.

apps/shade/src/components/layout/view-header.tsx (2)

1-14: Well-structured ViewHeaderActions component

The ViewHeaderActions component is well-designed with proper TypeScript interface extension and a clean implementation. The flex container with gap spacing provides a good foundation for action buttons.


15-32: Well-implemented ViewHeader with proper children handling

The ViewHeader component is well-structured with:

  • Proper TypeScript interface for props
  • Smart children decomposition using React.Children.toArray
  • Clean sticky header implementation with backdrop blur
  • Good use of the cn utility for className composition

The positioning with z-index and styling with pseudo-elements for the border is a clean approach.

ghost/admin/app/styles/layouts/content.css (1)

854-854: Consistent typography size adjustment

The font size reduction from '1.35rem' to '1.3rem' for post analytics meta text maintains consistency with other typography changes in this PR, resulting in a more cohesive visual design throughout the post analytics UI.

apps/posts/src/views/PostAnalytics/modals/ShareModal.tsx (2)

5-5: Removed width constraint to allow responsive sizing.

The removal of the max-w-2xl class from the DialogContent allows the modal to be more flexible with its width rather than constraining it to a maximum width of 2xl (typically 42rem or 672px).


8-9: Simplified dialog description text.

The description text has been shortened from the previous placeholder text to a more concise and appropriate description that better represents the dialog's purpose.

ghost/admin/app/styles/layouts/main.css (2)

1228-1228: Fine-tuned breadcrumb font size for better visual hierarchy.

The breadcrumb text size was slightly reduced from 1.35rem to 1.3rem, which helps maintain proper visual hierarchy in the navigation system while keeping text legible.


1249-1249: Increased horizontal spacing for breadcrumb separators.

The horizontal margin on breadcrumb SVG icons (likely used as separators) was increased from 6px to 10px, providing better visual separation between breadcrumb segments.

ghost/admin/app/components/gh-nav-menu/main.hbs (1)

173-177: Commented out old Post analytics navigation item.

The previous "Post analytics" navigation link has been commented out as part of the migration to the new React-based post analytics implementation referenced in the PR. This prevents users from accessing the old analytics page while the new one is being implemented.

This change aligns with the PR objective of rebuilding the post analytics feature. However, ensure that users have a clear way to access the new analytics functionality when it's ready.

ghost/admin/app/routes/posts/analytics/posts-x.js (1)

1-11: Added new route for Posts analytics feature.

This new route class properly extends the existing AnalyticsRoute and configures rendering for the posts-x template, setting up the foundation for the new React-based analytics feature.

This implementation follows Ghost's established patterns for route configuration where:

  1. The correct parent class is extended
  2. The template rendering is configured appropriately
  3. The controller is explicitly specified
  4. The outlet destination is set to "application"

This route will handle the new posts analytics feature described in the PR objectives.

ghost/admin/app/controllers/posts/analytics/posts-x.js (1)

1-4: New controller extends AnalyticsController without custom implementation.

This controller serves as a placeholder to support the new posts-x route for web analytics. Since it extends AnalyticsController without adding new functionality, it inherits all the base analytics behavior.

apps/stats/src/views/Stats/Locations.tsx (2)

9-9: Updated imports to use shared components from @tryghost/shade.

The implementation now imports UI components from the shared package rather than local components, which aligns with broader component standardization efforts.


162-168: Refactored header structure to use shared ViewHeader components.

The implementation correctly replaces local header components with the standardized ViewHeader, H1, and ViewHeaderActions components from the shared @tryghost/shade package. This helps maintain UI consistency across the application.

ghost/admin/app/components/posts/analytics.hbs (1)

38-42: Added conditional "Web stats" button for admin users with stats feature enabled.

This addition provides a clear entry point to the new post web analytics feature, appropriately conditioned on proper permissions and feature flag. The button correctly links to the new posts.analytics.posts-x route and passes the current post's ID as a parameter.

apps/shade/src/components/layout/heading.tsx (1)

12-12: H1 styling update aligns with Tailwind config
The updated class names for H1 (leading-[1.1em] tracking-tighter) correctly reflect the new Tailwind settings for line‑height and letter‑spacing. No behavioral or API changes introduced here.

apps/posts/src/components/layout/MainLayout.tsx (1)

5-9: Layout container correctly forwards props and uses full viewport
The MainLayout component cleanly composes two wrappers for full‑height scrollable content and forwards ...props to the inner container. This matches the intended design.

apps/stats/src/views/Stats/Sources.tsx (1)

95-101: Standardized header component usage looks good

The replacement of custom header elements with standard ViewHeader components from the @tryghost/shade package improves consistency across the application. This change aligns with similar updates in other view files like Web.tsx.

apps/posts/tsconfig.json (3)

7-7: Good addition of development and testing types

Adding "vite/client" and "jest" types enables proper TypeScript support for development and testing environments, which will help catch type errors earlier.


21-21: Enhanced type safety with switch case checking

The noFallthroughCasesInSwitch option helps prevent bugs by requiring explicit break statements or return statements in switch cases, which is a good practice for type safety.


23-32: Well-structured path aliases

The path aliases are well-organized and follow a consistent pattern. This will make imports cleaner and more maintainable throughout the codebase. These aliases correctly align with the ones defined in vite.config.mjs.

apps/stats/src/views/Stats/Web.tsx (2)

7-7: Consistent use of shared components

The import of ViewHeader, ViewHeaderActions, and H1 from @tryghost/shade aligns with the standardization efforts across the application.


37-43: Improved header structure with semantic HTML

The replacement of custom header elements with the standardized ViewHeader components and wrapping the title in an H1 component improves the semantic structure of the page, which is good for accessibility and consistency.

apps/posts/vite.config.mjs (1)

9-26: Well-aligned configuration with tsconfig.json

The path aliases defined in the Vite configuration perfectly match those in tsconfig.json, ensuring consistency between TypeScript's type checking and Vite's module resolution. The test patterns are also well-defined for comprehensive test coverage.

apps/posts/src/App.tsx (2)

1-3: Good implementation of path aliasing

The import paths have been changed from relative to absolute using the @src alias, which improves maintainability and readability.


13-17: Improved routing structure with cleaner component hierarchy

The routing structure has been refactored to use the Outlet pattern from React Router, which is a cleaner way to handle nested routes. This makes the component hierarchy more maintainable.

apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (2)

37-40: Placeholder text for post title and published date

The component is using static placeholder text for the post title and published date instead of fetching the actual data from an API or using props.

This appears to be part of the skeleton implementation mentioned in the PR description, but it would be helpful to add a TODO comment to indicate that these placeholders will be replaced with actual data in the future.

-                    <H1 className='mt-0.5 min-h-[35px] indent-0'>Post title</H1>
-                    <div className='-mt-0.5 flex h-9 items-center text-sm text-gray-700'>
-                        Published date
+                    <H1 className='mt-0.5 min-h-[35px] indent-0'>Post title</H1> {/* TODO: Replace with actual post title */}
+                    <div className='-mt-0.5 flex h-9 items-center text-sm text-gray-700'>
+                        Published date {/* TODO: Replace with actual published date */}

43-45: Mock data being passed to PostAnalyticsView

The PostAnalyticsView component is being passed static mock data (data={[1]}) and a hardcoded loading state (isLoading={false}).

Since this is a skeleton implementation, it would be helpful to add a TODO comment to indicate that this will be replaced with actual data fetching logic.

-            <PostAnalyticsView data={[1]} isLoading={false}>
+            <PostAnalyticsView data={[1]} isLoading={false}> {/* TODO: Replace with actual data fetching */}
                Hello post analytics ({postId})
            </PostAnalyticsView>
apps/posts/src/views/PostAnalytics/components/PostAnalyticsView.tsx (2)

1-12: Good use of TypeScript generics for reusable data handling

The component is well-structured with a clear interface using TypeScript generics, making it reusable across different data types.


20-31: Conditional rendering logic is clean and concise

The component's rendering logic follows a clear priority: loading state → empty state → content. This pattern is easy to understand and maintains a consistent user experience.

ghost/admin/app/router.js (2)

38-40: Using nested routes for analytics with web sub-route

The route structure for post analytics has been improved with proper nesting, making the URL structure more intuitive and maintainable.


38-40:

Details

❌ Incorrect review comment

Consider route parameter naming consistency

The Ember route uses snake_case (post_id) while React routes typically use camelCase (postId). This inconsistency might cause confusion.


🏁 Script executed:

#!/bin/bash
# Check for parameter naming patterns in routes
echo "Checking for parameter naming patterns in routes..."
echo "Ember routes (expecting snake_case):"
rg -t js "path:.+:(\w+_\w+)" --only-matching --no-filename | sort | uniq

echo -e "\nReact routes (expecting camelCase):"
rg -t tsx "path:.+:(\w+[A-Z]\w+)" --only-matching --no-filename | sort | uniq

Length of output: 570


🏁 Script executed:

#!/bin/bash
# Check for presence of React-related file types in the repository
echo "Searching for TSX files:"
rg --files --glob '*.tsx' || echo "No tsx files found"

echo "Searching for JSX files:"
rg --files --glob '*.jsx' || echo "No jsx files found"

echo "Searching for TS files (excluding tsx):"
rg --files --glob '*.ts' | grep -v '\.tsx' || echo "No ts files found"

Length of output: 48385


Ignore React naming conventions in Ember routes

This router file is part of Ghost’s Ember‐based admin app, which by convention uses snake_case for dynamic segments (e.g. :post_id). The React‐based admin‑x apps live under separate directories and manage their own routing (with their own conventions). There’s no shared router configuration, so no change is needed here.

Likely an incorrect or invalid review comment.

apps/admin-x-framework/src/providers/RouterProvider.tsx (1)

177-193: Well-implemented cross-app navigation component

The custom Navigate component effectively extends React Router's functionality to support cross-app navigation, providing a clean declarative approach.

apps/shade/src/components/layout/error-page.tsx (3)

5-7: Good enhancement with the optional dashboard callback.

The addition of the optional onBackToDashboard callback provides a clear way for parent components to handle navigation when users need to recover from errors. Making it optional maintains backward compatibility.


10-10: LGTM: Proper prop destructuring.

The component properly destructures the new optional callback along with existing props.


14-14: Style system change noted.

The component has moved from utility-based classes to a more structured class naming approach with admin-x-container-error. This appears to be part of a broader styling system update.

Comment on lines 19 to 21

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

URL path mismatch in navigation links

The "Overview" link navigates to /posts/analytics/${postId} with crossApp: true flag, but the "Web" link navigates to /analytics/${postId}/web without the /posts prefix and without the crossApp flag. This inconsistency could lead to navigation issues.

Based on the routing configuration in routes.tsx, both links should be consistent in their structure. Apply this diff:

-                <RightSidebarMenuLink active={location.pathname === `/analytics/${postId}/web`} onClick={() => {
-                    navigate(`/analytics/${postId}/web`);
+                <RightSidebarMenuLink active={location.pathname === `/posts/analytics/${postId}/web`} onClick={() => {
+                    navigate(`/posts/analytics/${postId}/web`, {crossApp: true});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<RightSidebarMenuLink active={location.pathname === `/analytics/${postId}/web`} onClick={() => {
navigate(`/analytics/${postId}/web`);
}}>
<RightSidebarMenuLink active={location.pathname === `/posts/analytics/${postId}/web`} onClick={() => {
navigate(`/posts/analytics/${postId}/web`, {crossApp: true});
}}>

Comment on lines 7 to 12

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Grid layout inconsistency with commented code

The component sets up a two-column grid layout (grid-cols-[auto_288px]), but the second column's content (<Sidebar />) is commented out. This creates a layout inconsistency where space is reserved but not used.

Either uncomment and implement the Sidebar component, or modify the grid to use a single column when the Sidebar is not present:

-        <section className={cn('gap-8 pb-8 grid w-full grow grid-cols-[auto_288px]', className)} {...props}>
+        <section className={cn('gap-8 pb-8 grid w-full grow grid-cols-[auto]', className)} {...props}>
            <div className='flex size-full flex-col gap-8'>
                {children}
            </div>
-            {/* <Sidebar /> */}
        </section>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<section className={cn('gap-8 pb-8 grid w-full grow grid-cols-[auto_288px]', className)} {...props}>
<div className='flex size-full flex-col gap-8'>
{children}
</div>
{/* <Sidebar /> */}
</section>
<section
className={cn(
- 'gap-8 pb-8 grid w-full grow grid-cols-[auto_288px]',
+ 'gap-8 pb-8 grid w-full grow grid-cols-[auto]',
className
)}
{...props}
>
<div className="flex size-full flex-col gap-8">
{children}
</div>
</section>

Comment thread apps/posts/src/routes.tsx Outdated
Comment on lines 14 to 17

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix potential route parameter issue in navigation path

The Navigate component uses a hardcoded path that includes the literal :postId parameter, which might not work as expected. Parameters should be replaced with actual values.

- element: <Navigate crossApp={true} to='/posts/analytics/:postId' />
+ element: <Navigate crossApp={true} to={`/posts/analytics/${postId}`} />

You'll need to extract the postId from useParams() first:

// At the component level
import { useParams } from '@tryghost/admin-x-framework';

const AnalyticsRedirect = () => {
    const { postId } = useParams();
    return <Navigate crossApp={true} to={`/posts/analytics/${postId}`} />;
};

// Then in your route definition
element: <AnalyticsRedirect />

Comment thread apps/posts/src/routes.tsx Outdated
Comment on lines 9 to 11

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Implement the dashboard click handler

The TODO comment indicates that the dashboard click handler needs to be implemented, which is currently an empty function.


🏁 Script executed:

#!/bin/bash
# Search for existing back to dashboard handlers in other files
rg "onBackToDashboard" --type ts --type tsx -B2 -A2

Length of output: 79


🏁 Script executed:

#!/bin/bash
# Search for existing back to dashboard handlers in both .ts and .tsx files
rg "onBackToDashboard" --glob "*.{ts,tsx}" -B2 -A2

Length of output: 2095


Implement the “Back to Dashboard” click handler

The ErrorPage component in apps/shade expects an onBackToDashboard callback, but in apps/posts/src/routes.tsx both errorElement and the fallback element are still passing an empty function. Let’s wire up React Router’s useNavigate to send users back to the root (dashboard).

• In apps/posts/src/routes.tsx, define a wrapper component that uses useNavigate and renders ErrorPage with a proper handler.
• Replace the two instances of <ErrorPage onBackToDashboard={() => {}} /> with your new wrapper.
• Remove the // @TODO comments once implemented.

Proposed diff:

--- a/apps/posts/src/routes.tsx
+++ b/apps/posts/src/routes.tsx
@@ -1,3 +1,9 @@
 import React from 'react';
-import { createBrowserRouter, RouterProvider, RouteObject } from 'react-router-dom';
+import {
+  createBrowserRouter,
+  RouterProvider,
+  RouteObject,
+  useNavigate,
+} from 'react-router-dom';
 import ErrorPage from 'apps/shade/src/components/layout/error-page';

+// Wrapper to provide navigation back to dashboard
+const BackToDashboardErrorPage: React.FC = () => {
+  const navigate = useNavigate();
+  return <ErrorPage onBackToDashboard={() => navigate('/')} />;
+};

 const router: RouteObject[] = [
   {
@@ -8,7 +14,7 @@ const router: RouteObject[] = [
     path: '',
-    errorElement: <ErrorPage onBackToDashboard={() => {}} />, // @TODO: add back to dashboard click handle
+    errorElement: <BackToDashboardErrorPage />,
     children: [
       {
         path: '*',
@@ -16,7 +22,7 @@ const router: RouteObject[] = [
       {
-        element: <ErrorPage onBackToDashboard={() => {}} />, // @TODO: add back to dashboard click handle
+        element: <BackToDashboardErrorPage />,
       },
     ],
   },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Root route configuration
path: '',
errorElement: <ErrorPage onBackToDashboard={() => {}} />, // @TODO: add back to dashboard click handle
import React from 'react';
import {
createBrowserRouter,
RouterProvider,
RouteObject,
useNavigate,
} from 'react-router-dom';
import ErrorPage from 'apps/shade/src/components/layout/error-page';
// Wrapper to provide navigation back to dashboard
const BackToDashboardErrorPage: React.FC = () => {
const navigate = useNavigate();
return <ErrorPage onBackToDashboard={() => navigate('/')} />;
};
const router: RouteObject[] = [
{
// Root route configuration
path: '',
errorElement: <BackToDashboardErrorPage />,
children: [
{
path: '*',
element: <BackToDashboardErrorPage />,
},
],
},
];
export default router;

Comment on lines 187 to 190

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify cross-app navigation with comprehensive tests

The cross-app navigation logic is a critical functionality that should be thoroughly tested to ensure it works correctly across different parts of the application.


🌐 Web query:

What are best practices for testing cross-app navigation in React applications?

💡 Result:

Best Practices for Testing Cross-App Navigation in React Applications

Testing cross-app navigation in React requires a comprehensive, multi-layered approach that addresses both user experience and technical robustness across platforms and app boundaries. Here are the best practices, supported by the latest insights and tooling recommendations.


1. Structure Testing by Type: Unit, Integration, and E2E

  • Unit tests: Test navigation components and utility functions in isolation using Jest or similar tools.
  • Integration tests: Render navigation flows within a navigation context (such as NavigationContainer), and simulate user interactions with libraries like React Testing Library or React Navigation Testing Library[6].
  • End-to-end (E2E) tests: Validate full user journeys and screen transitions using tools like Detox, Cypress, or Selenium. This is especially important for cross-app scenarios where navigation might depend on context, authentication, or inter-app communication[1][6].

2. Simulate Real User Interactions

  • Use libraries such as React Testing Library to render components inside a real navigation context. Instead of mocking navigation, test how users interact with the app by simulating gestures, clicks, and swipes[4][6].
  • For cross-app transitions—such as navigating to a different part of a microfrontend architecture, or jumping between web and native apps—write E2E tests that simulate these workflows at the UI layer.

3. Use Realistic Contexts for Navigation Components

  • Always wrap components under test with the correct navigation provider, such as NavigationContainer (React Navigation) or routing context (React Router). This ensures transitions and stack management behave as in production[4][6].
  • When testing navigation flows, assert for visibility or existence of the expected destination screen or component after navigation triggers, using matchers like toBeVisible[4].

4. Validate Deep Linking and External Navigation

  • To ensure robust handling of incoming URLs or cross-app links, mock and test deep link events to verify the app navigates to the correct screen or initiates the correct cross-app action[3][6].
  • For web-to-app or app-to-web flows, use E2E tools (like WebdriverIO with Puppeteer for the web and Appium for mobile) to script navigation from one app to another and confirm states post-navigation[1].

5. Make Tests Behavior-Focused and Isolated

  • Test the outcome of navigation rather than the internal implementation—for example, check that the correct page or UI is visible after a navigation event, not just that a navigation function was called[4][7].
  • Keep tests decoupled: Each test should set up its own navigation context and assert only its intended flow, to avoid flakiness and improve maintainability[7].

6. Ensure Coverage and Monitor Navigation Edge Cases

  • Use coverage tools (like Jest coverage reports) to ensure all navigation paths—especially permission/protected routes and error boundaries—are exercised by tests[7].
  • Test edge cases such as blocked navigation, failed deep links, session timeouts, and navigation based on conditional logic[10].

7. Cross-Browser and Cross-Platform Testing

  • Leverage tools like BrowserStack, Sauce Labs, or Cypress for automated cross-browser and cross-device testing to catch navigation issues specific to certain environments[5][7].
  • For React Native or hybrid apps, combine device simulators/emulators with Appium or Detox for mobile, and Puppeteer or Selenium for the web, ensuring consistent navigation across platforms[1][6].

8. Integrate Navigation Tests into CI/CD

  • Automate navigation test suites as part of your CI/CD pipeline for continuous feedback on regressions or cross-app integration breaks[9].

Recommended Toolchain

Test Type Recommended Tools
Unit Jest
Integration React Testing Library, React Navigation Testing Library
E2E Cypress, Detox (mobile), Selenium, WebdriverIO, Appium, Puppeteer
Cross-Browser BrowserStack, Sauce Labs

Key Takeaways

  • Use real navigation providers and simulate actual user flows for realistic and reliable tests[4][6].
  • Assert on visible outcomes, not internal actions, to make tests user-centric and robust[4].
  • Cover deep links, conditional navigation, and environment-specific navigation quirks.
  • Combine multiple levels of testing (unit, integration, E2E) for best coverage and confidence[6].

By following these practices, you ensure smooth, reliable navigation both within and across React applications, across devices and browsers, delivering consistent user experiences[1][5][6].

Citations:


Add comprehensive tests for cross‑app navigation

Cross‑app navigation in RouterProvider (lines 187–190) is a critical path and should be covered by a full spectrum of tests:

• Unit tests (Jest)
– Verify that when crossApp is true, externalNavigate({route: to, isExternal: true}) is called and the component returns null.

• Integration tests (React Testing Library or React Navigation Testing Library)
– Render the provider or consuming component inside its navigation context and simulate a cross‑app trigger.
– Assert that the correct UI state (or null) is rendered and externalNavigate is invoked.

• End‑to‑end tests (Cypress, Detox/Appium, or similar)
– Script user flows that jump between apps or deep links.
– Confirm that deep links land on the intended screen and that external navigation flags are respected.

• Edge‑case coverage
– Blocked or failed deep links, session timeouts, conditional navigation logic.

• CI/CD integration
– Run all navigation tests automatically to catch regressions across app boundaries.

File(s) to update:

  • apps/admin-x-framework/src/providers/RouterProvider.tsx (branch tests for lines 187–190)
  • Create corresponding test files (e.g. RouterProvider.test.tsx, RouterProvider.integration.tsx, E2E spec)

Comment on lines 17 to 21

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improved user experience with more helpful error content.

The error page now provides much better context with a clear heading, descriptive text, and navigation option. However, there are two issues to address:

  1. Using an <a> tag without an href attribute creates accessibility issues
  2. No fallback behavior is provided when onBackToDashboard is undefined

Consider implementing these improvements:

<div className="admin-x-error max-w-xl">
    <h1>Loading interrupted</h1>
    <p>They say life is a series of trials and tribulations. This moment right here? It&apos;s a tribulation. Our app was supposed to load, and yet here we are. Loadless. Click back to the dashboard to try again.</p>
-   <a className='cursor-pointer text-green' onClick={onBackToDashboard}>&larr; Back to the dashboard</a>
+   {onBackToDashboard ? (
+     <button type="button" className='text-green' onClick={onBackToDashboard}>&larr; Back to the dashboard</button>
+   ) : (
+     <a href="/" className='text-green'>&larr; Back to the dashboard</a>
+   )}
</div>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<div className="admin-x-error max-w-xl">
<h1>Loading interrupted</h1>
<p>They say life is a series of trials and tribulations. This moment right here? It&apos;s a tribulation. Our app was supposed to load, and yet here we are. Loadless. Click back to the dashboard to try again.</p>
<a className='cursor-pointer text-green' onClick={onBackToDashboard}>&larr; Back to the dashboard</a>
</div>
<div className="admin-x-error max-w-xl">
<h1>Loading interrupted</h1>
<p>They say life is a series of trials and tribulations. This moment right here? It&apos;s a tribulation. Our app was supposed to load, and yet here we are. Loadless. Click back to the dashboard to try again.</p>
{onBackToDashboard ? (
<button type="button" className='text-green' onClick={onBackToDashboard}>&larr; Back to the dashboard</button>
) : (
<a href="/" className='text-green'>&larr; Back to the dashboard</a>
)}
</div>

@peterzimon
peterzimon disabled auto-merge April 22, 2025 11:02
@peterzimon
peterzimon force-pushed the ta-post-analytics-skeleton branch from afe03b2 to 00abe0d Compare April 22, 2025 11:06
@peterzimon
peterzimon enabled auto-merge (squash) April 22, 2025 11:07
@peterzimon
peterzimon disabled auto-merge April 22, 2025 11:07
@peterzimon
peterzimon enabled auto-merge (squash) April 22, 2025 11:07
ref https://linear.app/ghost/issue/PROD-234/build-post-analytics-skeleton

- With the new analytics we're rebuilding the post analytics page to accommodate a much better breakdown of post related stats that Ghost customers would need. With this PR we added a first version of a new React app focusing on Web analytics in the context of a particular post.
@peterzimon
peterzimon force-pushed the ta-post-analytics-skeleton branch from 00abe0d to 63d50fc Compare April 22, 2025 11:23

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (3)
apps/shade/src/index.ts (1)

26-26: Remove useless type renaming.

The current export renames DropdownMenuCheckboxItemProps to itself, which is redundant.

-export type {DropdownMenuCheckboxItemProps as DropdownMenuCheckboxItemProps} from '@radix-ui/react-dropdown-menu';
+export type {DropdownMenuCheckboxItemProps} from '@radix-ui/react-dropdown-menu';
🧰 Tools
🪛 Biome (1.9.4)

[error] 26-26: Useless rename.

Safe fix: Remove the renaming.

(lint/complexity/noUselessRename)

apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (2)

6-6: Replace empty interface with type alias or remove it.

The empty interface postAnalyticsProps doesn't provide any value and could be simplified.

-interface postAnalyticsProps {};
+type PostAnalyticsProps = {};

Or you could simply remove it and directly type the component:

-interface postAnalyticsProps {};
-
-const PostAnalytics: React.FC<postAnalyticsProps> = () => {
+const PostAnalytics: React.FC = () => {
🧰 Tools
🪛 Biome (1.9.4)

[error] 5-6: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)


6-6: Apply PascalCase naming convention for interface.

Following React best practices, interface names should use PascalCase rather than camelCase.

-interface postAnalyticsProps {};
+interface PostAnalyticsProps {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 5-6: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 465ffc578c58db2c19b824e46d8a01553b1243ac and 63d50fc.

📒 Files selected for processing (46)
  • apps/admin-x-framework/src/index.ts (1 hunks)
  • apps/admin-x-framework/src/providers/RouterProvider.tsx (2 hunks)
  • apps/posts/src/App.tsx (2 hunks)
  • apps/posts/src/components/Header.tsx (0 hunks)
  • apps/posts/src/components/layout/MainLayout.tsx (1 hunks)
  • apps/posts/src/routes.ts (0 hunks)
  • apps/posts/src/routes.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/EmptyStatView.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/PostAnalyticsContent.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/PostAnalyticsView.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/Sidebar.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/layout/PostAnalyticsLayout.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/modals/ShareModal.tsx (1 hunks)
  • apps/posts/src/views/post-analytics/PostAnalytics.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/Newsletter.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/Overview.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/StatsTabs.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/newsletter/OpenedList.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/newsletter/SentList.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/overview/ClickPerformance.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/overview/Conversions.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/overview/Feedback.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/overview/Metric.tsx (0 hunks)
  • apps/posts/src/views/post-analytics/components/overview/NewsletterPerformance.tsx (0 hunks)
  • apps/posts/src/views/posts/Posts.tsx (0 hunks)
  • apps/posts/tsconfig.json (2 hunks)
  • apps/posts/vite.config.mjs (1 hunks)
  • apps/shade/src/components/layout/error-page.tsx (1 hunks)
  • apps/shade/src/components/layout/heading.tsx (1 hunks)
  • apps/shade/src/components/layout/view-header.tsx (1 hunks)
  • apps/shade/src/components/ui/breadcrumb.tsx (4 hunks)
  • apps/shade/src/index.ts (1 hunks)
  • apps/shade/tailwind.config.cjs (2 hunks)
  • apps/stats/src/components/layout/Header.tsx (0 hunks)
  • apps/stats/src/views/Stats/Locations.tsx (2 hunks)
  • apps/stats/src/views/Stats/Sources.tsx (2 hunks)
  • apps/stats/src/views/Stats/Web.tsx (2 hunks)
  • ghost/admin/app/components/gh-nav-menu/main.hbs (0 hunks)
  • ghost/admin/app/components/posts/analytics.hbs (1 hunks)
  • ghost/admin/app/controllers/posts/analytics/posts-x.js (1 hunks)
  • ghost/admin/app/router.js (1 hunks)
  • ghost/admin/app/routes/lexical-editor.js (1 hunks)
  • ghost/admin/app/routes/posts/analytics/posts-x.js (1 hunks)
  • ghost/admin/app/styles/layouts/content.css (1 hunks)
  • ghost/admin/app/styles/layouts/main.css (2 hunks)
💤 Files with no reviewable changes (16)
  • ghost/admin/app/components/gh-nav-menu/main.hbs
  • apps/posts/src/views/post-analytics/components/overview/Metric.tsx
  • apps/posts/src/views/post-analytics/PostAnalytics.tsx
  • apps/stats/src/components/layout/Header.tsx
  • apps/posts/src/views/post-analytics/components/newsletter/OpenedList.tsx
  • apps/posts/src/components/Header.tsx
  • apps/posts/src/views/post-analytics/components/overview/ClickPerformance.tsx
  • apps/posts/src/views/post-analytics/components/overview/Feedback.tsx
  • apps/posts/src/views/post-analytics/components/newsletter/SentList.tsx
  • apps/posts/src/views/post-analytics/components/overview/NewsletterPerformance.tsx
  • apps/posts/src/views/post-analytics/components/Overview.tsx
  • apps/posts/src/views/post-analytics/components/overview/Conversions.tsx
  • apps/posts/src/views/post-analytics/components/StatsTabs.tsx
  • apps/posts/src/routes.ts
  • apps/posts/src/views/posts/Posts.tsx
  • apps/posts/src/views/post-analytics/components/Newsletter.tsx
✅ Files skipped from review due to trivial changes (3)
  • apps/stats/src/views/Stats/Locations.tsx
  • ghost/admin/app/styles/layouts/main.css
  • apps/posts/src/routes.tsx
🚧 Files skipped from review as they are similar to previous changes (25)
  • ghost/admin/app/styles/layouts/content.css
  • apps/admin-x-framework/src/index.ts
  • apps/posts/src/views/PostAnalytics/modals/ShareModal.tsx
  • apps/posts/src/components/layout/MainLayout.tsx
  • apps/posts/src/views/PostAnalytics/components/PostAnalyticsContent.tsx
  • apps/posts/tsconfig.json
  • ghost/admin/app/components/posts/analytics.hbs
  • apps/posts/src/views/PostAnalytics/components/Sidebar.tsx
  • ghost/admin/app/controllers/posts/analytics/posts-x.js
  • ghost/admin/app/routes/posts/analytics/posts-x.js
  • apps/posts/src/views/PostAnalytics/layout/PostAnalyticsLayout.tsx
  • apps/shade/src/components/layout/heading.tsx
  • apps/stats/src/views/Stats/Sources.tsx
  • ghost/admin/app/routes/lexical-editor.js
  • apps/posts/src/views/PostAnalytics/components/EmptyStatView.tsx
  • apps/stats/src/views/Stats/Web.tsx
  • ghost/admin/app/router.js
  • apps/shade/src/components/layout/error-page.tsx
  • apps/shade/src/components/ui/breadcrumb.tsx
  • apps/shade/tailwind.config.cjs
  • apps/admin-x-framework/src/providers/RouterProvider.tsx
  • apps/shade/src/components/layout/view-header.tsx
  • apps/posts/vite.config.mjs
  • apps/posts/src/views/PostAnalytics/components/PostAnalyticsView.tsx
  • apps/posts/src/App.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (5)
apps/admin-x-framework/src/index.ts (2)
  • useParams (10-10)
  • useNavigate (8-8)
apps/admin-x-framework/src/providers/RouterProvider.tsx (1)
  • useNavigate (145-165)
apps/shade/src/components/layout/view-header.tsx (1)
  • ViewHeader (32-32)
apps/shade/src/components/ui/breadcrumb.tsx (6)
  • Breadcrumb (108-108)
  • BreadcrumbList (109-109)
  • BreadcrumbItem (110-110)
  • BreadcrumbLink (111-111)
  • BreadcrumbSeparator (113-113)
  • BreadcrumbPage (112-112)
apps/shade/src/components/layout/heading.tsx (1)
  • H1 (56-56)
🪛 Biome (1.9.4)
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx

[error] 5-6: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)

apps/shade/src/index.ts

[error] 26-26: Useless rename.

Safe fix: Remove the renaming.

(lint/complexity/noUselessRename)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Setup
🔇 Additional comments (1)
apps/shade/src/index.ts (1)

32-32: LGTM - New view-header layout components export.

This addition of the view-header components properly exposes the new ViewHeader and ViewHeaderActions components for use across the application, consistent with the post analytics feature improvements.

Comment on lines +1 to +50
import PostAnalyticsLayout from './layout/PostAnalyticsLayout';
import PostAnalyticsView from './components/PostAnalyticsView';
import {Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator, H1, ViewHeader} from '@tryghost/shade';
import {useNavigate, useParams} from '@tryghost/admin-x-framework';

interface postAnalyticsProps {};

const PostAnalytics: React.FC<postAnalyticsProps> = () => {
const {postId} = useParams();
const navigate = useNavigate();

return (
<PostAnalyticsLayout>
<ViewHeader className='pb-4'>
<div className='flex w-full max-w-[700px] grow flex-col'>
<Breadcrumb>
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbLink className='cursor-pointer' onClick={() => navigate('/posts/', {crossApp: true})}>
Posts
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbLink className='cursor-pointer' onClick={() => navigate(`/posts/analytics/${postId}`, {crossApp: true})}>
Analytics
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbPage>
Web
</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>
<H1 className='mt-0.5 min-h-[35px] indent-0'>Post title</H1>
<div className='-mt-0.5 flex h-9 items-center text-sm text-gray-700'>
Published date
</div>
</div>
</ViewHeader>
<PostAnalyticsView data={[1]} isLoading={false}>
Hello post analytics ({postId})
</PostAnalyticsView>
</PostAnalyticsLayout>
);
};

export default PostAnalytics;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Add unit tests for the component.

Since this is a new component implementing important functionality, consider adding unit tests to verify its behavior.

Would you like me to help create unit tests for this component? I can generate test cases that verify:

  1. The component renders correctly with the provided props
  2. Navigation works as expected when clicking on breadcrumb links
  3. Error states are handled properly
  4. Loading states are displayed correctly

🏁 Script executed:

#!/bin/bash
# Check for existing test patterns in the codebase

echo "Searching for test patterns..."
fd -t f "\.test\.|\.spec\." apps/posts

Length of output: 111


Add unit tests for the new PostAnalytics component

We didn’t find any existing test files under apps/posts, so let’s cover this important new functionality with unit tests. At a minimum, please add tests to verify:

  • The component renders without errors and displays the title, date, and children correctly
  • Breadcrumb links invoke navigate with the correct paths and crossApp: true
  • The isLoading state renders a loading indicator when true
  • The component handles empty or error data states (if applicable)

Let me know if you’d like help generating these test cases (e.g. Jest + React Testing Library) for PostAnalytics!

🧰 Tools
🪛 Biome (1.9.4)

[error] 5-6: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)

Comment on lines +43 to +45
<PostAnalyticsView data={[1]} isLoading={false}>
Hello post analytics ({postId})
</PostAnalyticsView>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Replace static props with actual analytics data.

The PostAnalyticsView component is receiving static props (data={[1]} and isLoading={false}). This should be replaced with actual analytics data fetched from an API.

Consider implementing a data fetching hook for post analytics:

+    const {data: analyticsData, isLoading} = usePostAnalytics(postId);
+
     return (
         <PostAnalyticsLayout>
             {/* ... */}
-            <PostAnalyticsView data={[1]} isLoading={false}>
-                Hello post analytics ({postId})
+            <PostAnalyticsView data={analyticsData} isLoading={isLoading}>
+                {analyticsData ? (
+                    <AnalyticsContent data={analyticsData} />
+                ) : (
+                    <EmptyState>No analytics data available for this post.</EmptyState>
+                )}
             </PostAnalyticsView>

Committable suggestion skipped: line range outside the PR's diff.


🛠️ Refactor suggestion

Implement proper error handling.

The component doesn't handle potential errors when loading post analytics data. Consider adding error handling to provide feedback to users.

-    const {data: analyticsData, isLoading} = usePostAnalytics(postId);
+    const {data: analyticsData, isLoading, error} = usePostAnalytics(postId);

     return (
         <PostAnalyticsLayout>
             {/* ... */}
-            <PostAnalyticsView data={analyticsData} isLoading={isLoading}>
+            <PostAnalyticsView 
+                data={analyticsData} 
+                isLoading={isLoading}
+                error={error}
+            >
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<PostAnalyticsView data={[1]} isLoading={false}>
Hello post analytics ({postId})
</PostAnalyticsView>
// Before:
const { data: analyticsData, isLoading } = usePostAnalytics(postId);
return (
<PostAnalyticsLayout>
{/* ... */}
<PostAnalyticsView data={analyticsData} isLoading={isLoading}>
Hello post analytics ({postId})
</PostAnalyticsView>
</PostAnalyticsLayout>
);
// After applying the diff:
const { data: analyticsData, isLoading, error } = usePostAnalytics(postId);
return (
<PostAnalyticsLayout>
{/* ... */}
<PostAnalyticsView
data={analyticsData}
isLoading={isLoading}
error={error}
>
Hello post analytics ({postId})
</PostAnalyticsView>
</PostAnalyticsLayout>
);

Comment on lines +19 to +21
<BreadcrumbLink className='cursor-pointer' onClick={() => navigate('/posts/', {crossApp: true})}>
Posts
</BreadcrumbLink>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Consider when to use crossApp navigation.

All navigation uses the crossApp: true option. Ensure this is intentional and only used when navigation should truly cross application boundaries.

From the context, crossApp: true triggers external navigation via externalNavigate. If you're navigating within the same app, consider removing this option for better performance:

-<BreadcrumbLink className='cursor-pointer' onClick={() => navigate('/posts/', {crossApp: true})}>
+<BreadcrumbLink className='cursor-pointer' onClick={() => navigate('/posts/')}>

Also applies to: 25-27


🏁 Script executed:

#!/bin/bash
# Check how crossApp navigation is used elsewhere

echo "Searching for crossApp navigation patterns..."
rg "navigate.*crossApp.*true" --type=tsx --type=ts

Length of output: 181


🏁 Script executed:

#!/bin/bash
# Broaden search to locate any usage of `crossApp` across TS and TSX files
echo "Searching for `crossApp` occurrences in .ts/.tsx files..."
rg "crossApp" --glob "*.ts*" -n

Length of output: 1625


Limit crossApp: true to genuine cross-application routes

Currently every navigation in this file (and elsewhere in the Posts app) uses crossApp: true, which forces an external full‑app reload. For intra‑app routes—like going back to /posts/ or to /posts/analytics/${postId}—you can drop the crossApp flag and use the internal router for faster, seamless transitions.

Please update:

• apps/posts/src/views/PostAnalytics/PostAnalytics.tsx

  • Lines 19–21, 25–27: remove {crossApp: true}
- onClick={() => navigate('/posts/', {crossApp: true})}
+ onClick={() => navigate('/posts/')}

- onClick={() => navigate(`/posts/analytics/${postId}`, {crossApp: true})}
+ onClick={() => navigate(`/posts/analytics/${postId}`)}

• Audit other internal navigations in this app (e.g., Sidebar.tsx) and in apps/posts/src/routes.tsx for similar crossApp misuse.

Comment on lines +15 to +41
<div className='flex w-full max-w-[700px] grow flex-col'>
<Breadcrumb>
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbLink className='cursor-pointer' onClick={() => navigate('/posts/', {crossApp: true})}>
Posts
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbLink className='cursor-pointer' onClick={() => navigate(`/posts/analytics/${postId}`, {crossApp: true})}>
Analytics
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbPage>
Web
</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>
<H1 className='mt-0.5 min-h-[35px] indent-0'>Post title</H1>
<div className='-mt-0.5 flex h-9 items-center text-sm text-gray-700'>
Published date
</div>
</div>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Replace hardcoded placeholder content with actual post data.

The component currently uses hardcoded placeholder text for the post title and published date. These should be replaced with actual data from the post.

Consider fetching the post data using the postId parameter and displaying the actual title and published date, for example:

-                    <H1 className='mt-0.5 min-h-[35px] indent-0'>Post title</H1>
-                    <div className='-mt-0.5 flex h-9 items-center text-sm text-gray-700'>
-                        Published date
+                    <H1 className='mt-0.5 min-h-[35px] indent-0'>{post?.title || 'Untitled'}</H1>
+                    <div className='-mt-0.5 flex h-9 items-center text-sm text-gray-700'>
+                        {post?.published_at ? formatDate(post.published_at) : 'Draft'}

🏁 Script executed:

#!/bin/bash
# Check if there's existing post data fetching logic in the codebase

echo "Searching for post data fetching patterns..."
rg -A 10 "useQuery.*post.*id" --type=tsx --type=ts

Length of output: 179


🏁 Script executed:

#!/bin/bash
set -e

echo "== Inspecting PostAnalytics.tsx (first 200 lines) =="
find apps/posts/src/views -type f -name PostAnalytics.tsx -exec sed -n '1,200p' {} \;

echo
echo "== Searching for hook invocations in PostAnalytics.tsx =="
find apps/posts/src/views -type f -name PostAnalytics.tsx -exec rg -n "use[A-Za-z]" {} \;

echo
echo "== Searching for any data‑fetching hooks referencing 'post' in apps/posts =="
rg -n "use.*post" apps/posts/src

Length of output: 3084


Implement post data fetching and replace placeholders

The PostAnalytics component currently renders hardcoded “Post title” and “Published date” without fetching any post details. You should:

  • Add a data‐fetch (e.g. a custom usePostById(postId) hook or a useQuery call) to load the post’s metadata using the postId from useParams().
  • Replace the hardcoded <H1> and date <div> with the actual post.title and a formatted post.published_at, handling loading and empty states.

File: apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (around lines 15–41)

Suggested diff:

+// 1) Import your post‐fetching hook or query util
+import {usePostById} from '../../hooks/usePostById';
 import {useNavigate, useParams} from '@tryghost/admin-x-framework';
 
 const PostAnalytics: React.FC = () => {
   const {postId} = useParams();
+  const {data: post, isLoading: postLoading} = usePostById(postId as string);
   const navigate = useNavigate();
 
   return (
     <PostAnalyticsLayout>
       <ViewHeader className='pb-4'>
         <div className='flex w-full max-w-[700px] grow flex-col'>
           <Breadcrumb>…</Breadcrumb>
-          <H1 className='mt-0.5 min-h-[35px] indent-0'>Post title</H1>
-          <div className='-mt-0.5 flex h-9 items-center text-sm text-gray-700'>
-            Published date
+          <H1 className='mt-0.5 min-h-[35px] indent-0'>
+            {postLoading
+              ? 'Loading title…'
+              : post?.title || 'Untitled'}
+          </H1>
+          <div className='-mt-0.5 flex h-9 items-center text-sm text-gray-700'>
+            {postLoading
+              ? 'Loading date…'
+              : post?.published_at
+                ? formatDate(post.published_at)
+                : 'Draft'}
           </div>
         </div>
       </ViewHeader>
       <PostAnalyticsView data={[1]} isLoading={false}>
         Hello post analytics ({postId})
       </PostAnalyticsView>
     </PostAnalyticsLayout>
   );
 };
 
 export default PostAnalytics;

Committable suggestion skipped: line range outside the PR's diff.

@peterzimon
peterzimon merged commit ad52284 into main Apr 22, 2025
@peterzimon
peterzimon deleted the ta-post-analytics-skeleton branch April 22, 2025 11:30
cmraible added a commit that referenced this pull request Aug 20, 2026
no refs

## Evidence that the component is unused

`PostAnalyticsView` is not exported by the private Admin package, and
repository-wide searches for both its symbol and module path find no
importer. Admin-only Knip reported
`apps/admin/src/posts/analytics/components/post-analytics-view.tsx` as
an unused file before this removal and stopped reporting it afterward.
The Admin build uses explicit routes and entry points; no dynamic import
or glob references this path.

## History and intentionality

Documented facts:

-
ad52284
introduced the component as the loading/empty/content wrapper in the
first React post-analytics skeleton.
#22978 explains that the work
began a better breakdown of post statistics, initially focused on web
analytics for one post.
-
54d993b
replaced that static wrapper in the main page with real post and traffic
data. #22986 says this made the
previously static skeleton usable for beta users.
-
26de9ed
later reused the component only as the loading screen for a duplicated
`withFeatureFlag` wrapper. #23270
documents that the wrapper prevented the Newsletter tab from redirecting
before the alpha setting had loaded, and explicitly called the
duplication temporary.
- #23029 documents the rollout
model: `trafficAnalytics` selected beta users, while
`trafficAnalyticsAlpha` selected features still under development for
that beta.
-
f0a33b8
intentionally moved Newsletter analytics out of alpha. Its diff replaced
the protected route with the direct `Newsletter` route and made the
sidebar links unconditional;
#23294 states that purpose
directly. Production therefore stopped reaching the wrapper, and
consequently `PostAnalyticsView`, on May 12, 2025. Given the documented
flag semantics, this was an intentional promotion to the analytics beta
rather than an accidental bypass.
-
fb0790b
later restored the alpha flag for other design work but did not restore
Newsletter's route guard, corroborating that Newsletter's promotion was
deliberate.
-
566f8a9
removed the now-unreachable wrapper and its tests.
#29686 identifies those files as
duplicated dead code with no live importers. That deletion removed the
component's last source or test importer on July 30, 2026.

Inference: leaving `PostAnalyticsView` behind in that last cleanup was
an incomplete leaf cleanup. No historical source explicitly describes
the omission, but the dead-code PR's stated intent, the current
zero-reference result, and Knip's independent unused-file report support
that conclusion.

## Removal

Deleted the 33-line orphaned component. It had no dedicated tests,
export, dependency, configuration, or documentation to remove. Its
`EmptyStatView` and `PostAnalyticsContent` dependencies remain used by
live analytics screens.

## Verification

- `pnpm exec knip --workspace @tryghost/admin --include files --reporter
compact --no-progress` (the removed file is absent; four pre-existing
acceptance setup/config entries remain)
- `pnpm --dir apps/admin lint`
- `pnpm --dir apps/admin typecheck`
- `pnpm --dir apps/admin test:unit` (135 files, 1,604 tests)
- `pnpm nx run @tryghost/admin:build`
- `pnpm nx run-many -t test --exclude @tryghost/e2e --exclude
ghost-admin --exclude @tryghost/koenig-lexical` (35 projects, including
8,000 Ghost tests)

`pnpm check` completed repository-wide lint and documentation checks,
but its aggregate test phase could not run Koenig Lexical's browser
suite in this environment: Chromium was denied Mach port registration
and the configured Firefox executable is absent. The broader test run
above excludes only that environment-blocked package and passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant