Skip to content

Added dynamic data loading to page analytics - #22986

Merged
9larsons merged 13 commits into
mainfrom
ta-data-on-post-analytics
Apr 23, 2025
Merged

9larsons merged 13 commits into
mainfrom
ta-data-on-post-analytics

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

  • So far the React based post analytics skeleton was completely static. This PR added reading post and traffic data which makes it actually usable to beta users.

@coderabbitai

coderabbitai Bot commented Apr 22, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@9larsons has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 31 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 34bdd8c and 1cacf10.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (3)
  • apps/posts/src/providers/GlobalDataProvider.tsx (1 hunks)
  • apps/posts/src/utils/chart-helpers.ts (1 hunks)
  • apps/shade/package.json (2 hunks)

"""

Walkthrough

This set of changes introduces a statistics analytics feature across multiple packages, focusing on configuration, utility functions, and UI components for displaying post analytics. A new StatsConfig interface is added to the shared framework and exported for use in other packages. Utility functions for formatting dates, numbers, durations, and percentages are centralized in the @tryghost/shade package, replacing local implementations in the stats package. The posts app receives new providers, configuration modules, constants, and chart helper utilities to support analytics features. Several new React components are introduced for analytics UI, including selectors for audience and date range, KPI displays, sources, and locations tables. The analytics view for posts is refactored to use these new components and hooks for data fetching and state management. Development dependencies are updated to support charting and date handling. Imports throughout the stats app are updated to use the centralized utilities. Additionally, Ember admin routes and controllers are updated with injected services and conditional redirection logic based on user roles and configuration flags. Feature flag checks are added to conditionally render analytics components in the admin UI.

Possibly related PRs

  • Migrated to web analytics build to TB Forward #22859: Refactors how endpoint URLs and tokens are obtained in Ghost admin stats components by introducing utility functions that rely on a shared StatsConfig type; relates through shared config usage and helper functions.
  • Updated stats-x to use config for endpoints #22970: Adds and exports a new StatsConfig interface in the framework and refactors stats-x to use this unified config type and helper functions for endpoint URL and token retrieval, updating multiple components accordingly.

Suggested reviewers

  • peterzimon
    """

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 generate sequence diagram to generate a sequence diagram of the changes in 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 changed the title Ta data on post analytics Added dynamic data loading to page analytics Apr 22, 2025

@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: 15

🔭 Outside diff range comments (2)
apps/admin-x-framework/src/providers/FrameworkProvider.tsx (1)

19-36: 🛠️ Refactor suggestion

Integrate StatsConfig into the provider’s props and context.

You've defined StatsConfig but it's never passed through the context. Consumers (e.g. apps/posts or apps/stats) can't read it via useFramework(). You should add an optional statsConfig prop and include it in the default context value:

 export interface FrameworkProviderProps {
     ghostVersion: string;
     externalNavigate: (link: ExternalLink) => void;
     unsplashConfig: { /* … */ };
     sentryDSN: string | null;
     onUpdate: (dataType: string, response: unknown) => void;
     onInvalidate: (dataType: string) => void;
     onDelete: (dataType: string, id: string) => void;
+    /** Optional stats configuration for analytics */
+    statsConfig?: StatsConfig;
     children: ReactNode;
 }

 const FrameworkContext = createContext<FrameworkContextType>({
     ghostVersion: '',
     externalNavigate: () => {},
     unsplashConfig: { /* … */ },
     sentryDSN: null,
     onUpdate: () => {},
     onInvalidate: () => {},
     onDelete: () => {},
+    statsConfig: {}
 });

This ensures that any downstream component can call const {statsConfig} = useFramework(); to access analytics settings.

apps/stats/src/components/chart/CustomTooltipContent.tsx (1)

28-29: ⚠️ Potential issue

Fix invalid Tailwind class for the color swatch.

size-[10px] is not a default Tailwind utility. Use explicit width/height:

-                <span className='inline-block size-[10px] rounded-[2px]' style={{backgroundColor: 'hsl(var(--chart-1))'}}></span>
+                <span className='inline-block w-[10px] h-[10px] rounded-[2px]' style={{backgroundColor: 'hsl(var(--chart-1))'}}></span>

Without this change the dot will not render at the intended size.

🧹 Nitpick comments (30)
apps/admin-x-framework/src/providers/FrameworkProvider.tsx (1)

7-17: Add JSDoc to explain the purpose of StatsConfig.

Right now the inline comment on line 7 is minimal. Converting it to a JSDoc block will improve discoverability in IDEs and generated docs:

- // Stats-specific configuration
-export interface StatsConfig {
+/**
+ * Configuration for the statistics endpoints used by analytics features.
+ * - `endpoint`, `id`, `token`: top‑level API details.
+ * - `local`: optional overrides for local/dev mode.
+ */
+export interface StatsConfig {
apps/posts/src/utils/constants.ts (3)

1-9: Document the +1 arithmetic in STATS_RANGE_OPTIONS.

The expressions like 30 + 1 and 90 + 1 aren’t immediately obvious. Add a comment explaining why you add one (e.g., to include the current day):

-export const STATS_RANGE_OPTIONS = [
+/**
+ * Time ranges for analytics (in days).
+ * The `+ 1` ensures the current day is included in the range.
+ */
+export const STATS_RANGE_OPTIONS = [
     {name: 'Today', value: 1},
     {name: 'Last 7 days', value: 7},
     {name: 'Last 30 days', value: 30 + 1},
     {name: 'Last 3 months', value: 90 + 1},
     /* … */
 ];

13-30: Strongly type your label mappings.

Currently STATS_LABEL_MAPPINGS is an untyped object. Adding a type will catch typos and make consumers’ code safer:

-export const STATS_LABEL_MAPPINGS = {
+export const STATS_LABEL_MAPPINGS: Record<string, string> = {
     // Countries
     US: 'United States',
     TWN: 'Taiwan',
     /* … */
     'duckduckgo.com': 'DuckDuckGo'
 };

32-32: Consider externalizing the versioned icon URL.

Hard‑coding v5.0.0 may lead to stale assets if you bump Ghost’s version. Either:

  • Host a “latest” alias (e.g., …/images/globe-icon.svg), or
  • Inject the version dynamically from a central constant.
apps/posts/src/views/PostAnalytics/components/PostAnalyticsContent.tsx (1)

7-8: Consider cleaning up commented code

The layout has been changed from a grid-based approach to a flex-based column layout. While keeping the commented code might be helpful during development or for future reference, it's generally better to remove commented-out code before merging to production for cleaner codebase maintenance.

If this layout change is temporary or the sidebar might return in the future, consider adding a TODO comment explaining the reason for keeping the commented code.

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

52-52: Consider documenting the formatting utilities

Explicitly exporting these formatting utilities makes them more discoverable for consumers of the library, which is good. However, since you're centralizing these formatting functions and promoting their reuse across packages, consider adding JSDoc comments to their implementations to document their parameters, return values, and usage examples.

Note that having both the wildcard export (line 51) and the explicit exports (line 52) is technically redundant, but can serve as a form of documentation for highlighting the most commonly used utilities.

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

10-12: Consider type safety enhancement

While the conversion from string to number works, it might be better to handle this conversion more robustly:

-        <Select value={`${range}`} onValueChange={(value) => {
-            setRange(Number(value));
+        <Select value={`${range}`} onValueChange={(value) => {
+            const numValue = parseInt(value, 10);
+            if (!isNaN(numValue)) {
+                setRange(numValue);
+            }
        }}>

This would prevent potential issues if the value is somehow not a valid number.


6-6: Consider adding props for better component extensibility

While the component currently relies entirely on the global context, adding prop types (even as optional overrides) could make it more flexible for future use cases:

-const DateRangeSelect: React.FC = () => {
+interface DateRangeSelectProps {
+    className?: string;
+    defaultValue?: number;
+    onChange?: (value: number) => void;
+}
+
+const DateRangeSelect: React.FC<DateRangeSelectProps> = ({
+    className,
+    defaultValue,
+    onChange
+}) => {
    const {range, setRange} = useGlobalData();

    return (
-        <Select value={`${range}`} onValueChange={(value) => {
+        <Select 
+            className={className}
+            value={`${defaultValue ?? range}`} 
+            onValueChange={(value) => {
            setRange(Number(value));
+            onChange?.(Number(value));
        }}>

This would allow the component to be used in contexts where a local state is preferred over global state.

apps/posts/src/components/chart/CustomTooltipContent.tsx (1)

26-35: Consider adding accessibility attributes to the tooltip

The tooltip component lacks accessibility attributes which could make it difficult for screen reader users to understand the content.

Add ARIA attributes to improve accessibility:

    return (
-       <div className="min-w-[120px] rounded-lg border bg-background px-3 py-2 shadow-lg">
+       <div className="min-w-[120px] rounded-lg border bg-background px-3 py-2 shadow-lg" role="tooltip" aria-live="polite">
            {date && <div className="text-sm text-foreground">{formatDisplayDate(date)}</div>}
            <div className='flex items-center gap-1'>
-               <span className='inline-block size-[10px] rounded-[2px]' style={{backgroundColor: 'hsl(var(--chart-1))'}}></span>
+               <span className='inline-block size-[10px] rounded-[2px]' style={{backgroundColor: 'hsl(var(--chart-1))'}} aria-hidden="true"></span>
                <div className='flex grow items-center justify-between gap-3'>
                    {label && <div className="text-sm text-muted-foreground">{label}</div>}
                    <div className="font-mono font-medium">{displayValue}</div>
                </div>
            </div>
        </div>
    );
apps/posts/src/views/PostAnalytics/components/KpiTab.tsx (1)

20-27: Consider adding semantic HTML elements for better accessibility

The KPI value display could benefit from more semantic HTML elements to improve accessibility and SEO.

Consider using semantic elements for better structure:

const KpiTabValue: React.FC<KpiTabValueProps> = ({label, value}) => {
    return (
        <div className='flex w-full flex-col items-start'>
-           <span className='text-[1.5rem] tracking-tight'>{label}</span>
-           <span className='-mt-1 text-[2.3rem] tracking-[-0.04em]'>{value}</span>
+           <h3 className='text-[1.5rem] tracking-tight m-0'>{label}</h3>
+           <p className='-mt-1 text-[2.3rem] tracking-[-0.04em] m-0'>{value}</p>
        </div>
    );
};
apps/posts/src/providers/GlobalDataProvider.tsx (1)

30-31: Document the audience bitmask meaning

The comment mentions that 7 (binary 111) represents all audiences selected, but it's not clear what each bit represents.

Add more detailed documentation:

-    // Initialize with all audiences selected (binary 111 = 7)
+    // Initialize with all audiences selected (binary 111 = 7)
+    // Bit 1 (value 1): Members
+    // Bit 2 (value 2): Free members
+    // Bit 3 (value 4): Paid members
     const [audience, setAudience] = useState(7);
apps/posts/src/views/PostAnalytics/components/Web/Locations.tsx (3)

11-14: Move global code to module initialization

The countries.registerLocale(enLocale) call is in the global scope of the module, which means it runs every time the module is imported. This is generally fine for one-time initialization, but should be documented.

Add a comment explaining this is intentional:

+// Register English locale data once when this module is loaded
countries.registerLocale(enLocale);
const getCountryName = (label: string) => {
    return STATS_LABEL_MAPPINGS[label as keyof typeof STATS_LABEL_MAPPINGS] || countries.getName(label, 'en') || 'Unknown';
};

33-67: Simplify conditional rendering logic

The component has nested conditional rendering with empty string fallbacks, which makes the code harder to follow.

Simplify the conditional rendering logic:

- return (
-     <>
-         {isLoading ? '' :
-             <>
-                 {(data && data.length > 0) &&
-             <Card>
-                 <CardHeader>
-                     <CardTitle>Locations</CardTitle>
-                     <CardDescription>Where are the readers of this post</CardDescription>
-                 </CardHeader>
-                 <CardContent>
-                     <Table>
-                         <TableHeader>
-                             <TableRow>
-                                 <TableHead className='w-[80%]'>Country</TableHead>
-                                 <TableHead className='w-[20%] text-right'>Visitors</TableHead>
-                             </TableRow>
-                         </TableHeader>
-                         <TableBody>
-                             {data?.map((row) => {
-                                 const countryName = getCountryName(`${row.location}`) || 'Unknown';
-                                 return (
-                                     <TableRow key={row.location || 'unknown'}>
-                                         <TableCell className="font-medium">
-                                             <span title={countryName || 'Unknown'}>{getCountryFlag(`${row.location}`)} {countryName}</span>
-                                         </TableCell>
-                                         <TableCell className='text-right font-mono text-sm'>{formatNumber(Number(row.visits))}</TableCell>
-                                     </TableRow>
-                                 );
-                             })}
-                         </TableBody>
-                     </Table>
-                 </CardContent>
-             </Card>
-                 }
-             </>
-         }
-     </>
+ return (
+     <>
+         {isLoading && null}
+         
+         {!isLoading && data && data.length > 0 && (
+             <Card>
+                 <CardHeader>
+                     <CardTitle>Locations</CardTitle>
+                     <CardDescription>Where are the readers of this post</CardDescription>
+                 </CardHeader>
+                 <CardContent>
+                     <Table>
+                         <TableHeader>
+                             <TableRow>
+                                 <TableHead className='w-[80%]'>Country</TableHead>
+                                 <TableHead className='w-[20%] text-right'>Visitors</TableHead>
+                             </TableRow>
+                         </TableHeader>
+                         <TableBody>
+                             {data.map((row) => {
+                                 const countryName = getCountryName(`${row.location}`) || 'Unknown';
+                                 return (
+                                     <TableRow key={row.location || 'unknown'}>
+                                         <TableCell className="font-medium">
+                                             <span title={countryName || 'Unknown'}>{getCountryFlag(`${row.location}`)} {countryName}</span>
+                                         </TableCell>
+                                         <TableCell className='text-right font-mono text-sm'>{formatNumber(Number(row.visits))}</TableCell>
+                                     </TableRow>
+                                 );
+                             })}
+                         </TableBody>
+                     </Table>
+                 </CardContent>
+             </Card>
+         )}
+         
+         {!isLoading && (!data || data.length === 0) && (
+             <Card>
+                 <CardHeader>
+                     <CardTitle>Locations</CardTitle>
+                 </CardHeader>
+                 <CardContent>
+                     <p>No location data available.</p>
+                 </CardContent>
+             </Card>
+         )}
+     </>
  );

50-52: Memoize country name lookup for performance

The country name lookup is performed inside the render loop for each row, which could impact performance with large datasets.

Consider memoizing the country name lookup or moving it outside the component:

+ // Create a memoized version of getCountryName to improve performance
+ const memoizedGetCountryName = React.useMemo(() => {
+     const cache: Record<string, string> = {};
+     return (label: string) => {
+         if (!cache[label]) {
+             cache[label] = STATS_LABEL_MAPPINGS[label as keyof typeof STATS_LABEL_MAPPINGS] || 
+                          countries.getName(label, 'en') || 
+                          'Unknown';
+         }
+         return cache[label];
+     };
+ }, []);

// Later in the component:
{data?.map((row) => {
-   const countryName = getCountryName(`${row.location}`) || 'Unknown';
+   const countryName = memoizedGetCountryName(`${row.location}`);
    return (
        <TableRow key={row.location || 'unknown'}>
apps/posts/src/config/stats-config.ts (2)

3-3: Add documentation for the TB_VERSION constant.

The TB_VERSION constant is used in URL construction, but its purpose isn't documented. Adding a brief comment explaining what this version represents would improve code maintainability.

+// Tinybird version number used for stats API endpoints
 export const TB_VERSION = 8;

5-13: Validate the endpoint parameter.

The function constructs a URL even when the endpoint parameter is undefined, which could lead to malformed URLs. Consider adding validation to ensure the endpoint is provided.

 export const getStatEndpointUrl = (config?: StatsConfig | null, endpoint?: string, params = '') => {
-    if (!config) {
+    if (!config || !endpoint) {
         return '';
     }

     return config.local?.enabled ? 
         `${config.local?.endpoint || ''}/v0/pipes/${endpoint}.json?${params}` : 
         `${config.endpoint || ''}/v0/pipes/${endpoint}__v${TB_VERSION}.json?${params}`;
 };
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (3)

15-16: Replace empty interface with type alias.

The empty interface provides no value and is flagged by static analysis. Consider using a type alias instead or removing it entirely.

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

-const PostAnalytics: React.FC<postAnalyticsProps> = () => {
+const PostAnalytics: React.FC<PostAnalyticsProps> = () => {

24-29: Improve type safety in post data destructuring.

The destructuring of the posts array could be more type-safe with explicit typing and a clearer default value approach.

-    const {data: {posts: [post]} = {posts: []}, isLoading: isPostLoading} = useBrowsePosts({
+    const {data, isLoading: isPostLoading} = useBrowsePosts({
         searchParams: {
             filter: `id:${postId}`,
             fields: 'title,slug'
         }
     });
+    const post = data?.posts?.[0];

79-80: Use optional chaining for post title.

The current implementation checks if post exists before accessing the title property. Using optional chaining would make the code more concise.

-                    {post && post.title}
+                    {post?.title}
🧰 Tools
🪛 Biome (1.9.4)

[error] 79-79: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

apps/posts/src/views/PostAnalytics/components/Web/Sources.tsx (1)

45-84: Add empty state handling.

The component doesn't handle the case when data is available but empty. Consider adding a user-friendly message for this state.

                 <>
-                    {data!.length > 0 &&
+                    {data && data.length > 0 ?
                         <Card>
                             {/* Card content as is */}
                         </Card>
+                    : <Card>
+                        <CardHeader>
+                            <CardTitle>Top sources</CardTitle>
+                            <CardDescription>How did people find this post</CardDescription>
+                        </CardHeader>
+                        <CardContent>
+                            <div className="py-8 text-center text-gray-500">
+                                No source data available for this time period
+                            </div>
+                        </CardContent>
+                      </Card>
                     }
apps/shade/src/lib/utils.ts (3)

151-167: Consider internationalization for date formatting.

The month names are hardcoded in English. Consider using Intl.DateTimeFormat for better internationalization support.

 export const formatDisplayDate = (dateString: string): string => {
     const date = new Date(dateString);
     const today = new Date();
     const isToday = date.toDateString() === today.toDateString();
     const isCurrentYear = date.getFullYear() === today.getFullYear();
 
-    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
-    const day = date.getDate();
-    const month = months[date.getMonth()];
-    const year = date.getFullYear();
+    const formatter = new Intl.DateTimeFormat('en-US', { 
+        day: 'numeric', 
+        month: 'short', 
+        year: isCurrentYear ? undefined : 'numeric' 
+    });
+    
+    return formatter.format(date);
 
-    if (isToday) {
-        return `${day} ${month}`;
-    }
-
-    return isCurrentYear ? `${day} ${month}` : `${day} ${month} ${year}`;

170-172: Consider supporting different locales for number formatting.

The formatNumber function hardcodes the 'en-US' locale. Consider making the locale configurable for better internationalization.

-export const formatNumber = (value: number): string => {
-    return new Intl.NumberFormat('en-US').format(Math.round(value));
+export const formatNumber = (value: number, locale = 'en-US'): string => {
+    return new Intl.NumberFormat(locale).format(Math.round(value));
 };

191-193: Add option for decimal precision in percentage formatting.

The formatPercentage function currently rounds to whole numbers, which might not be precise enough for all use cases.

-export const formatPercentage = (value: number) => {
-    return `${Math.round(value * 100)}%`;
+export const formatPercentage = (value: number, decimals = 0) => {
+    const factor = Math.pow(10, decimals);
+    return `${Math.round(value * 100 * factor) / factor}%`;
 };
apps/posts/src/views/PostAnalytics/components/Web/Kpis.tsx (3)

106-107: Enhance the loading state UI

Currently, the loading state simply displays the text "Loading" without any styling or loading indicator. Consider using a styled loading component or spinner from your design system to improve user experience.

-            {isLoading ? 'Loading' :
+            {isLoading ? <div className="flex justify-center p-4"><LucideIcon.Loader className="animate-spin" /></div> :

74-81: Document the ponderation calculation logic

The weighted average calculation logic is complex and could benefit from clearer documentation explaining its purpose and mathematical basis.

-        // Sum total KPI value from the trend, ponderating using sessions
+        // Calculate weighted average of KPI values, using number of visits as weights
+        // This gives more importance to days with higher traffic volume
+        // Formula: weightedAvg = Σ(value_i * weight_i) / Σ(weight_i)
         const _ponderatedKPIsTotal = (kpi: keyof typeof data[0]) => {
             return data.reduce((prev, curr) => {
                 const currValue = Number(curr[kpi] ?? 0);
                 const currVisits = Number(curr.visits);
                 return prev + (currValue * currVisits / totalVisits);
             }, 0);
         };

143-143: Improve X-axis tick selection logic

The current implementation always shows exactly two ticks - the first and last date. This works for the current design but is not adaptable if you need more ticks in the future based on dataset size or chart width.

Consider implementing a more flexible approach:

-    ticks={chartData && chartData.length > 0 ? [chartData[0].date, chartData[chartData.length - 1].date] : []}
+    ticks={chartData && chartData.length > 0 ? 
+        (chartData.length <= 7 ? 
+            chartData.map(item => item.date) : 
+            [chartData[0].date, chartData[Math.floor(chartData.length / 2)].date, chartData[chartData.length - 1].date]) 
+        : []}
apps/posts/src/utils/chart-helpers.ts (2)

25-37: Extract magic numbers as constants

The function uses magic numbers (40, 20, 8) for width calculations. These should be extracted as named constants to improve code maintainability.

+// Width constants for Y-axis calculations
+const DEFAULT_AXIS_WIDTH = 40;
+const MIN_AXIS_WIDTH = 20;
+const CHAR_WIDTH_PX = 8;
+const AXIS_PADDING_PX = 8;
+
 export const calculateYAxisWidth = (ticks: number[], formatter: (value: number) => string): number => {
     if (!ticks.length) {
-        return 40;
+        return DEFAULT_AXIS_WIDTH;
     }

     // Get the longest formatted tick value
     const maxFormattedLength = Math.max(...ticks.map(tick => formatter(tick).length));

     // Approximate width based on character count (assuming monospace font)
     // Add padding for safety
-    const width = Math.max(20, maxFormattedLength * 8 + 8);
+    const width = Math.max(MIN_AXIS_WIDTH, maxFormattedLength * CHAR_WIDTH_PX + AXIS_PADDING_PX);
     return width;
 };

7-20: Enhance Y-axis tick calculation for better readability

The current implementation might generate too many ticks for large ranges or decimal values that aren't visually appealing. Consider enhancing it to create more human-friendly tick values.

The current algorithm works for basic cases, but for a more sophisticated implementation:

 export const getYTicks = (data: { value: number }[]): number[] => {
     if (!data?.length) {
         return [];
     }
     const values = data.map(d => Number(d.value));
     const max = Math.max(...values);
     const min = Math.min(...values);
-    const step = Math.pow(10, Math.floor(Math.log10(max - min)));
+    
+    // Calculate a nice step size that produces between 3-7 ticks
+    const range = max - min;
+    const magnitude = Math.pow(10, Math.floor(Math.log10(range)));
+    const normalizedRange = range / magnitude;
+    
+    // Choose a step size that creates a reasonable number of ticks
+    let step;
+    if (normalizedRange <= 1) step = magnitude * 0.2;
+    else if (normalizedRange <= 2) step = magnitude * 0.5;
+    else if (normalizedRange <= 5) step = magnitude;
+    else step = magnitude * 2;
+    
     const ticks = [];
-    for (let i = Math.floor(min / step) * step; i <= Math.ceil(max / step) * step; i += step) {
+    const firstTick = Math.floor(min / step) * step;
+    const lastTick = Math.ceil(max / step) * step;
+    
+    // Ensure we don't generate too many ticks
+    const maxTicks = 7;
+    const totalTicks = Math.floor((lastTick - firstTick) / step) + 1;
+    const skipFactor = totalTicks > maxTicks ? Math.ceil(totalTicks / maxTicks) : 1;
+    
+    for (let i = firstTick; i <= lastTick; i += step * skipFactor) {
         ticks.push(i);
     }
     return ticks;
apps/posts/src/views/PostAnalytics/components/AudienceSelect.tsx (2)

49-75: Simplify audience label logic

The getAudienceLabel function has complex conditional logic that could be simplified for better maintainability.

 const getAudienceLabel = () => {
     const selectedAudiences = [];

     if (isAudienceSelected(AUDIENCE_BITS.PUBLIC)) {
         selectedAudiences.push('Public visitors');
     }
     if (isAudienceSelected(AUDIENCE_BITS.FREE)) {
         selectedAudiences.push('Free members');
     }
     if (isAudienceSelected(AUDIENCE_BITS.PAID)) {
         selectedAudiences.push('Paid members');
     }

     if (selectedAudiences.length === 0) {
         return 'Select audience';
     }

     if (selectedAudiences.length === 3) {
         return 'All audiences';
     }

-    if (isAudienceSelected(AUDIENCE_BITS.FREE) && isAudienceSelected(AUDIENCE_BITS.PAID) && !isAudienceSelected(AUDIENCE_BITS.PUBLIC)) {
+    if (selectedAudiences.length === 2 && 
+        isAudienceSelected(AUDIENCE_BITS.FREE) && 
+        isAudienceSelected(AUDIENCE_BITS.PAID)) {
         return 'Members-only';
     }

     return selectedAudiences.join(' & ');
 };

80-81: Improve accessibility by adding an ARIA label

The dropdown button would benefit from an explicit ARIA label to improve accessibility.

-                <Button variant="dropdown"><LucideIcon.User2 /><span className='lowercase first-letter:capitalize'>{getAudienceLabel()}</span></Button>
+                <Button variant="dropdown" aria-label="Select audience filter"><LucideIcon.User2 /><span className='lowercase first-letter:capitalize'>{getAudienceLabel()}</span></Button>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4add6c1 and b58836acc6eb988db16b41f44e254a870fc5a954.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (29)
  • apps/admin-x-framework/src/api/posts.ts (1 hunks)
  • apps/admin-x-framework/src/index.ts (1 hunks)
  • apps/admin-x-framework/src/providers/FrameworkProvider.tsx (1 hunks)
  • apps/posts/package.json (1 hunks)
  • apps/posts/src/App.tsx (2 hunks)
  • apps/posts/src/components/chart/CustomTooltipContent.tsx (1 hunks)
  • apps/posts/src/config/stats-config.ts (1 hunks)
  • apps/posts/src/providers/GlobalDataProvider.tsx (1 hunks)
  • apps/posts/src/utils/chart-helpers.ts (1 hunks)
  • apps/posts/src/utils/constants.ts (1 hunks)
  • apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (2 hunks)
  • apps/posts/src/views/PostAnalytics/components/AudienceSelect.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/DateRangeSelect.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/EmptyStatView.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/KpiTab.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/PostAnalyticsContent.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/Web/Kpis.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/Web/Locations.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/Web/Sources.tsx (1 hunks)
  • apps/shade/package.json (1 hunks)
  • apps/shade/src/index.ts (1 hunks)
  • apps/shade/src/lib/utils.ts (2 hunks)
  • apps/stats/src/components/chart/CustomTooltipContent.tsx (1 hunks)
  • apps/stats/src/providers/GlobalDataProvider.tsx (1 hunks)
  • apps/stats/src/utils/data-formatters.ts (0 hunks)
  • apps/stats/src/views/Stats/Locations.tsx (1 hunks)
  • apps/stats/src/views/Stats/Sources.tsx (1 hunks)
  • apps/stats/src/views/Stats/Web.tsx (1 hunks)
  • apps/stats/src/views/Stats/components/WebKpis.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/stats/src/utils/data-formatters.ts
🧰 Additional context used
🧬 Code Graph Analysis (6)
apps/posts/src/views/PostAnalytics/components/KpiTab.tsx (1)
apps/shade/src/components/ui/tabs.tsx (1)
  • TabsTrigger (134-134)
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (8)
apps/posts/src/providers/GlobalDataProvider.tsx (1)
  • useGlobalData (18-24)
apps/posts/src/utils/chart-helpers.ts (1)
  • getRangeDates (42-47)
apps/admin-x-framework/src/index.ts (2)
  • useParams (10-10)
  • useNavigate (8-8)
apps/admin-x-framework/src/api/posts.ts (1)
  • useBrowsePosts (17-20)
apps/shade/src/index.ts (1)
  • formatQueryDate (52-52)
apps/posts/src/views/PostAnalytics/components/AudienceSelect.tsx (1)
  • getAudienceQueryParam (17-31)
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/admin-x-framework/src/providers/FrameworkProvider.tsx (1)
apps/admin-x-framework/src/index.ts (1)
  • StatsConfig (2-2)
apps/posts/src/views/PostAnalytics/components/AudienceSelect.tsx (2)
apps/shade/src/components/ui/dropdown-menu.tsx (4)
  • DropdownMenu (188-188)
  • DropdownMenuTrigger (189-189)
  • DropdownMenuContent (190-190)
  • DropdownMenuCheckboxItem (192-192)
apps/shade/src/components/ui/button.tsx (1)
  • Button (64-64)
apps/posts/src/utils/chart-helpers.ts (1)
ghost/admin/app/utils/stats.js (2)
  • d (88-88)
  • endDate (170-170)
apps/shade/src/lib/utils.ts (3)
apps/shade/src/index.ts (5)
  • formatQueryDate (52-52)
  • formatDisplayDate (52-52)
  • formatNumber (52-52)
  • formatDuration (52-52)
  • formatPercentage (52-52)
ghost/core/test/unit/server/adapters/storage/LocalImagesStorage.test.js (2)
  • month (16-16)
  • year (17-17)
ghost/admin/app/utils/stats.js (3)
  • seconds (193-193)
  • hours (198-198)
  • minutes (192-192)
🪛 Biome (1.9.4)
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx

[error] 14-15: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)


[error] 79-79: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

apps/posts/src/utils/chart-helpers.ts

[error] 53-54: This expression always returns false, because the string is converted and will never match

This call convert the string to upper case

... but this value is not in upper case

Unsafe fix: Use upper case string value.

(lint/correctness/noStringCaseMismatch)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Setup
🔇 Additional comments (25)
apps/stats/src/views/Stats/Sources.tsx (1)

6-6: Nice refactoring of imports!

The change to import formatNumber and formatQueryDate from the centralized @tryghost/shade package is a good improvement. This aligns with the broader effort to centralize utility functions across packages, promoting more maintainable and consistent code.

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

6-7: Good addition to support post analytics functionality.

Adding slug and title properties to the Post type is essential for the new analytics features. These fields are needed to properly identify and display post-specific analytics data.

apps/posts/src/views/PostAnalytics/components/EmptyStatView.tsx (1)

7-7: UI spacing improvement.

Removing the negative top margin improves the vertical spacing of the empty state icon container, resulting in better visual alignment within the analytics UI.

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

9-9: Consistent import refactoring.

Similar to other files in this PR, the change to import formatting utilities from the centralized @tryghost/shade package helps maintain consistency throughout the codebase. This is a good practice that reduces duplication and improves maintainability.

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

7-7: Clean refactoring of utility imports

The change to import formatting utilities directly from @tryghost/shade instead of local utility modules improves code maintainability by centralizing these functions in a shared package. This aligns with the broader effort to reduce duplication and standardize formatting across the codebase.

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

2-2: Good type sharing approach

Exporting the StatsConfig type from the framework package promotes type consistency across packages. This ensures that stats configuration follows a uniform structure throughout the application and centralizes type definitions, which is a good practice for maintainability.

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

1-1: Well-structured addition of global data provider

Adding the GlobalDataProvider at the application root level follows React best practices for state management. This approach makes statistics configuration and state available throughout the component tree without prop drilling, which is essential for the new analytics features.

Also applies to: 15-19

apps/stats/src/views/Stats/components/WebKpis.tsx (1)

3-3: Effective consolidation of utility imports

Similar to other files in this PR, the change to import formatting utilities from the shared @tryghost/shade package instead of local modules improves maintainability and consistency. This refactoring centralizes frequently used formatting functions that are used throughout the component (in KPI metrics definitions, chart data formatting, and axis labeling).

apps/stats/src/providers/GlobalDataProvider.tsx (1)

4-4: Good type centralization approach

Importing StatsConfig from the shared framework package rather than defining it locally helps maintain consistency across different parts of the application. This is a positive change that aligns with good practices for type sharing in a monorepo structure.

apps/posts/src/views/PostAnalytics/components/DateRangeSelect.tsx (1)

6-28: Well-structured component with good integration

The component is focused on a single responsibility and properly integrates with the global data context. The code is clean and follows React best practices.

apps/posts/src/views/PostAnalytics/components/KpiTab.tsx (1)

3-13: Good component composition pattern

The KpiTabTrigger component effectively extends TabsTrigger while providing custom styling. This is a good example of component composition.

apps/posts/src/config/stats-config.ts (2)

1-2: The import path looks good.

The import of StatsConfig from the GlobalDataProvider is correct and follows the project's import conventions.


15-17: Well-implemented token retrieval function.

The getToken function correctly handles the conditional logic for retrieving either local or remote tokens with proper null checking using optional chaining.

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

31-49: Well-implemented query parameters with proper memoization.

The useMemo hook is correctly implemented with appropriate dependencies to optimize performance. The parameter construction handles conditional logic based on post availability and correctly formats dates and audience filters.


51-51: Clean loading state derivation.

Combining config and post loading states into a single boolean is a clean approach that simplifies conditional rendering throughout the component.


1-11: Good organization of imports and component dependencies.

The component imports are well organized with related components grouped together. Using named imports for utility functions from @tryghost/shade keeps the code clean and maintainable.


18-20: Effective use of global data context.

The component correctly uses the useGlobalData hook to access shared state like stats configuration, loading state, range, and audience settings, which helps maintain consistency across the application.


53-86: Well-structured component header with appropriate navigation.

The ViewHeader component is well organized with breadcrumb navigation and action buttons for audience and date selection. The layout and styling classes are consistently applied.

🧰 Tools
🪛 Biome (1.9.4)

[error] 79-79: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

apps/posts/src/views/PostAnalytics/components/Web/Sources.tsx (4)

1-7: Good organization of imports and dependencies.

The component imports are well organized with clear separation between internal and external dependencies.


13-25: Clean implementation of the SourceRow component.

The SourceRow component has a clean implementation with good error handling for the favicon image.


61-78: Well-structured table row rendering with conditional content.

The table rows have good conditional rendering logic for different types of sources, with appropriate styling and formatting.


16-21:

Details

❓ Verification inconclusive

Consider security and reliability of external favicon service.

The component uses an external service (faviconextractor.com) for favicons. This introduces dependencies on a third-party service which may have availability or security implications.


🏁 Script executed:

#!/bin/bash
# Check if favicon service is available
echo "Testing favicon service availability..."
curl -sI "https://www.faviconextractor.com/favicon/github.com?larger=true" | head -n 1

# Check if there are any existing alternatives in the codebase
echo "Searching for alternative favicon handling in the codebase..."
rg -g "*.{ts,tsx,js,jsx}" "favicon" --exclude-dir="node_modules" | head -n 10

Length of output: 815


Review: External favicon service dependency

We’re currently fetching favicons from faviconextractor.com, which is returning HTTP/2 200 today, but introduces an external dependency with potential availability, performance, and privacy implications.

• We already handle failures by falling back to STATS_DEFAULT_SOURCE_ICON_URL, which is good.
• No alternative favicon solution exists in this repo—consider whether this external dependency and its SLA meet your requirements.
• To reduce referer leakage, you can add a referrerPolicy="no-referrer" attribute on the <img> tag.
• If reliability or security is a concern, consider hosting a simple proxy/cache internally or switching to a provider with a formal SLA.

Suggested diff:

 <img
   className="gh-stats-favicon"
   src={`https://www.faviconextractor.com/favicon/${source||'direct'}?larger=true`}
+  referrerPolicy="no-referrer"
   onError={(e) => {
     e.currentTarget.src = STATS_DEFAULT_SOURCE_ICON_URL;
   }}
/>

Please confirm that this external service is acceptable, or update to an internal or higher‑SLAd solution.

apps/shade/src/lib/utils.ts (2)

146-148: Well-implemented date formatting utility.

The formatQueryDate function provides a simple and effective way to format dates consistently for query parameters.


175-188: Well-implemented duration formatting.

The formatDuration function handles different time ranges effectively with appropriate formatting for hours, minutes, and seconds.

apps/posts/src/utils/chart-helpers.ts (1)

42-47:

Details

❓ Verification inconclusive

Consider timezone consistency with the backend

This function uses the browser's local timezone, which might differ from what the backend uses. Ensure this is consistent with how the rest of the application handles timezones, particularly for analytics data.


🏁 Script executed:

#!/bin/bash
# Search for timezone handling across the codebase to ensure consistency
echo "Checking how timezones are handled in other parts of the codebase:"

echo "\nTimezone usage in other utility functions:"
rg -A 2 -B 2 "DateTimeFormat\(\).resolvedOptions\(\).timeZone" --type ts

echo "\nTimezone handling in backend services:"
rg -A 2 -B 2 "timezone" --type ts | grep -i "api\|endpoint\|config"

Length of output: 2222


Confirm timezone consistency with the backend

It looks like both apps/stats/src/utils/chart-helpers.ts and apps/posts/src/utils/chart-helpers.ts use the browser’s local timezone via

Intl.DateTimeFormat().resolvedOptions().timeZone

but we couldn’t find any backend endpoints or configs that explicitly handle or return a timezone. Please verify:

  • How the analytics endpoints on the server side interpret dates (are they UTC, a fixed zone, or do they accept a timezone parameter?).
  • Whether statsConfig or any other global settings supply a timezone to the client.
  • If needed, align the frontend helper (or include the correct zone in requests) so that start/end date ranges match what the backend expects.

Comment thread apps/posts/package.json Resolved
Comment thread apps/shade/package.json Resolved
Comment on lines 37 to 39

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

Use error boundaries instead of throwing in render

Throwing errors during render will crash the entire React tree. This approach doesn't provide a good user experience.

Consider using React Error Boundaries instead:

- if (error) {
-     throw error;
- }
+ // Handle errors gracefully using an error state
+ const [fetchError, setFetchError] = useState<Error | null>(null);
+ 
+ useEffect(() => {
+     if (error) {
+         setFetchError(error);
+         console.error("Error loading global data:", error);
+     }
+ }, [error]);
+ 
+ if (fetchError) {
+     return <div>Error loading data. Please try again later.</div>;
+ }

Then wrap this component with an error boundary at a higher level.

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

Comment thread apps/shade/src/lib/utils.ts Outdated
Comment on lines 151 to 167

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

Add error handling for invalid date strings.

The formatDisplayDate function doesn't handle invalid date strings, which could lead to unexpected behavior or exceptions.

 export const formatDisplayDate = (dateString: string): string => {
+    if (!dateString) {
+        return '';
+    }
+    
     const date = new Date(dateString);
+    // Check if date is valid
+    if (isNaN(date.getTime())) {
+        return 'Invalid date';
+    }
     
     const today = new Date();
     const isToday = date.toDateString() === today.toDateString();
     const isCurrentYear = date.getFullYear() === today.getFullYear();
📝 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
export const formatDisplayDate = (dateString: string): string => {
const date = new Date(dateString);
const today = new Date();
const isToday = date.toDateString() === today.toDateString();
const isCurrentYear = date.getFullYear() === today.getFullYear();
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const day = date.getDate();
const month = months[date.getMonth()];
const year = date.getFullYear();
if (isToday) {
return `${day} ${month}`;
}
return isCurrentYear ? `${day} ${month}` : `${day} ${month} ${year}`;
};
export const formatDisplayDate = (dateString: string): string => {
if (!dateString) {
return '';
}
const date = new Date(dateString);
// Check if date is valid
if (isNaN(date.getTime())) {
return 'Invalid date';
}
const today = new Date();
const isToday = date.toDateString() === today.toDateString();
const isCurrentYear = date.getFullYear() === today.getFullYear();
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const day = date.getDate();
const month = months[date.getMonth()];
const year = date.getFullYear();
if (isToday) {
return `${day} ${month}`;
}
return isCurrentYear ? `${day} ${month}` : `${day} ${month} ${year}`;
};

Comment on lines 48 to 53

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

Add error handling for API requests

The component doesn't handle API errors. If the query fails, users won't receive any feedback.

-    const {data, loading} = useQuery({
+    const {data, loading, error} = useQuery({
         endpoint: getStatEndpointUrl(statsConfig, 'api_kpis'),
         token: getToken(statsConfig),
         params: queryParams
     });

+    // Show error state if query fails
+    if (error) {
+        return <div className="text-red-500">Failed to load analytics data: {error.message}</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
const {data, loading} = useQuery({
endpoint: getStatEndpointUrl(statsConfig, 'api_kpis'),
token: getToken(statsConfig),
params: queryParams
});
const {data, loading, error} = useQuery({
endpoint: getStatEndpointUrl(statsConfig, 'api_kpis'),
token: getToken(statsConfig),
params: queryParams
});
// Show error state if query fails
if (error) {
return <div className="text-red-500">
Failed to load analytics data: {error.message}
</div>;
}

Comment thread apps/posts/src/utils/chart-helpers.ts Resolved
Comment on lines 62 to 75

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

Use audience type names from constants to avoid duplication

The audience names are duplicated in both AUDIENCE_TYPES and in the getAudienceLabel function. This could lead to inconsistencies if one is updated but not the other.

 if (selectedAudiences.length === 0) {
     return 'Select audience';
 }

 if (selectedAudiences.length === 3) {
     return 'All audiences';
 }

-if (isAudienceSelected(AUDIENCE_BITS.FREE) && isAudienceSelected(AUDIENCE_BITS.PAID) && !isAudienceSelected(AUDIENCE_BITS.PUBLIC)) {
+// Check if only free and paid members are selected (members-only)
+if (isAudienceSelected(AUDIENCE_BITS.FREE) && 
+    isAudienceSelected(AUDIENCE_BITS.PAID) && 
+    !isAudienceSelected(AUDIENCE_BITS.PUBLIC)) {
     return 'Members-only';
 }

 return selectedAudiences.join(' & ');

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

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

Rename confusing audience value 'undefined'

Using the string 'undefined' as a value is confusing and could lead to bugs, especially when used in API queries. Consider using a more descriptive value like 'public' to match the audience type.

-    {name: 'Public visitors', value: 'undefined'},
+    {name: 'Public visitors', value: 'public'},
📝 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
{name: 'Public visitors', value: 'undefined'},
- {name: 'Public visitors', value: 'undefined'},
+ {name: 'Public visitors', value: 'public'},

@peterzimon
peterzimon force-pushed the ta-data-on-post-analytics branch from 4afee6f to d7c68c4 Compare April 23, 2025 05:09
@peterzimon
peterzimon enabled auto-merge (squash) April 23, 2025 05:12

@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: 1

♻️ Duplicate comments (2)
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (1)

88-96: Enhance loading state and add error handling.

The loading state is currently just a string 'Loading', and there's no error handling for failed data fetching operations.

apps/posts/src/utils/chart-helpers.ts (1)

53-54: Fix the case mismatch in string comparison

The static analysis correctly identified that this comparison will always be false because 'ᴺᵁᴸᴸ' is not in uppercase. This is a subtle bug.

-    if (!countryCode || countryCode === null || countryCode.toUpperCase() === 'ᴺᵁᴸᴸ') {
+    if (!countryCode || countryCode === null || countryCode.toUpperCase() === 'NULL') {
         return '🏳️';
     }
🧰 Tools
🪛 Biome (1.9.4)

[error] 53-54: This expression always returns false, because the string is converted and will never match

This call convert the string to upper case

... but this value is not in upper case

Unsafe fix: Use upper case string value.

(lint/correctness/noStringCaseMismatch)

🧹 Nitpick comments (8)
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (4)

15-15: Replace empty interface with type alias

The empty interface doesn't provide any constraints or additional information. This causes the static analysis tool to flag it as an issue.

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

Additionally, consider using PascalCase for consistency with React component naming conventions:

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

[error] 14-15: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)


24-29: Refactor destructuring for better readability

The current destructuring pattern is unnecessarily complex. It can be simplified for better readability while maintaining the same functionality.

-    const {data: {posts: [post]} = {posts: []}, isLoading: isPostLoading} = useBrowsePosts({
+    const {data, isLoading: isPostLoading} = useBrowsePosts({
         searchParams: {
             filter: `id:${postId}`,
             fields: 'title,slug'
         }
     });
+    const post = data?.posts?.[0];

79-80: Use optional chaining for accessing post title

Use optional chaining to make the code more concise and more resilient to null/undefined values.

-                    <H1 className='mt-0.5 min-h-[35px] indent-0'>
-                        {post && post.title}
-                    </H1>
+                    <H1 className='mt-0.5 min-h-[35px] indent-0'>
+                        {post?.title}
+                    </H1>
🧰 Tools
🪛 Biome (1.9.4)

[error] 79-79: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


91-94: Improve responsive layout for smaller screens

The current grid layout with fixed grid-cols-2 might not render well on smaller screens. Consider making the layout more responsive to different screen sizes.

-                        <div className='grid grid-cols-2 gap-8'>
+                        <div className='grid grid-cols-1 md:grid-cols-2 gap-8'>
                             <Sources queryParams={params} />
                             <Locations queryParams={params} />
                         </div>
apps/posts/src/utils/chart-helpers.ts (4)

7-20: Consider optimizing tick calculation for large datasets

The getYTicks function calculates min and max values by iterating over the entire dataset, which could be inefficient for very large datasets. For charts with thousands of data points, consider optimizing this calculation.

 export const getYTicks = (data: { value: number }[]): number[] => {
     if (!data?.length) {
         return [];
     }
-    const values = data.map(d => Number(d.value));
-    const max = Math.max(...values);
-    const min = Math.min(...values);
+    // More efficient for large datasets
+    let min = Number.MAX_VALUE;
+    let max = Number.MIN_VALUE;
+    
+    for (const d of data) {
+        const value = Number(d.value);
+        if (value < min) min = value;
+        if (value > max) max = value;
+    }
     
     const step = Math.pow(10, Math.floor(Math.log10(max - min)));
     const ticks = [];
     for (let i = Math.floor(min / step) * step; i <= Math.ceil(max / step) * step; i += step) {
         ticks.push(i);
     }
     return ticks;
 };

42-47: Consider accepting a timezone parameter

The getRangeDates function uses the browser's timezone by default. In some cases, it might be beneficial to allow overriding this with a specific timezone parameter, especially for users viewing analytics from different regions.

-export const getRangeDates = (range: number) => {
-    const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+export const getRangeDates = (range: number, customTimezone?: string) => {
+    const timezone = customTimezone || Intl.DateTimeFormat().resolvedOptions().timeZone;
     const endDate = moment().tz(timezone).endOf('day');
     const startDate = moment().tz(timezone).subtract(range - 1, 'days').startOf('day');
     return {startDate, endDate, timezone};
 };

56-57: Add error handling for invalid country codes

The current implementation assumes that all valid country codes are exactly two characters. If an invalid country code (like a three-letter code) is passed, it could produce unexpected results.

-    return countryCode.toUpperCase().replace(/./g, char => String.fromCodePoint(char.charCodeAt(0) + 127397)
-    );
+    // Ensure we have a valid 2-letter country code
+    if (countryCode.length !== 2) {
+        return '🏳️';
+    }
+    
+    // Convert to regional indicator symbols (flag emoji)
+    return countryCode.toUpperCase().replace(/./g, char => 
+        String.fromCodePoint(char.charCodeAt(0) + 127397)
+    );

66-72: Extract hardcoded strings into constants

The function contains hardcoded strings for period names, which could be extracted into constants for easier maintenance and potential internationalization.

+const PERIOD_PREFIXES = {
+    RELATIVE: 'in the',
+    ALL_TIME: '(all time)'
+};
+
+const RELATIVE_PERIODS = ['Last 7 days', 'Last 30 days', 'Last 3 months', 'Last 12 months'];
+
 export const getPeriodText = (range: number): string => {
     const option = STATS_RANGE_OPTIONS.find((opt: {value: number; name: string}) => opt.value === range);
     if (option) {
-        if (['Last 7 days', 'Last 30 days', 'Last 3 months', 'Last 12 months'].includes(option.name)) {
-            return `in the ${option.name.toLowerCase()}`;
+        if (RELATIVE_PERIODS.includes(option.name)) {
+            return `${PERIOD_PREFIXES.RELATIVE} ${option.name.toLowerCase()}`;
         }
         if (option.name === 'All time') {
-            return '(all time)';
+            return PERIOD_PREFIXES.ALL_TIME;
         }
         return option.name.toLowerCase();
     }
     return '';
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4afee6fc396bff8bb5daea591447a14bacc018a7 and d7c68c444a7fb52fe7f70cee17df1ceffc1d8cb1.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (30)
  • apps/admin-x-framework/src/api/posts.ts (1 hunks)
  • apps/admin-x-framework/src/index.ts (1 hunks)
  • apps/admin-x-framework/src/providers/FrameworkProvider.tsx (1 hunks)
  • apps/posts/package.json (1 hunks)
  • apps/posts/src/App.tsx (2 hunks)
  • apps/posts/src/components/chart/CustomTooltipContent.tsx (1 hunks)
  • apps/posts/src/config/stats-config.ts (1 hunks)
  • apps/posts/src/providers/GlobalDataProvider.tsx (1 hunks)
  • apps/posts/src/utils/chart-helpers.ts (1 hunks)
  • apps/posts/src/utils/constants.ts (1 hunks)
  • apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (2 hunks)
  • apps/posts/src/views/PostAnalytics/components/AudienceSelect.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/DateRangeSelect.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/EmptyStatView.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/KpiTab.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/PostAnalyticsContent.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/Web/Kpis.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/Web/Locations.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/Web/Sources.tsx (1 hunks)
  • apps/shade/package.json (1 hunks)
  • apps/shade/src/index.ts (1 hunks)
  • apps/shade/src/lib/utils.ts (2 hunks)
  • apps/stats/src/components/chart/CustomTooltipContent.tsx (1 hunks)
  • apps/stats/src/config/stats-config.ts (2 hunks)
  • apps/stats/src/providers/GlobalDataProvider.tsx (1 hunks)
  • apps/stats/src/utils/data-formatters.ts (0 hunks)
  • apps/stats/src/views/Stats/Locations.tsx (1 hunks)
  • apps/stats/src/views/Stats/Sources.tsx (1 hunks)
  • apps/stats/src/views/Stats/Web.tsx (1 hunks)
  • apps/stats/src/views/Stats/components/WebKpis.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/stats/src/utils/data-formatters.ts
✅ Files skipped from review due to trivial changes (6)
  • apps/posts/src/views/PostAnalytics/components/EmptyStatView.tsx
  • apps/stats/src/views/Stats/Web.tsx
  • apps/stats/src/views/Stats/Sources.tsx
  • apps/shade/src/index.ts
  • apps/admin-x-framework/src/index.ts
  • apps/posts/src/utils/constants.ts
🚧 Files skipped from review as they are similar to previous changes (21)
  • apps/stats/src/components/chart/CustomTooltipContent.tsx
  • apps/stats/src/config/stats-config.ts
  • apps/shade/package.json
  • apps/admin-x-framework/src/providers/FrameworkProvider.tsx
  • apps/stats/src/views/Stats/components/WebKpis.tsx
  • apps/admin-x-framework/src/api/posts.ts
  • apps/posts/src/views/PostAnalytics/components/DateRangeSelect.tsx
  • apps/posts/package.json
  • apps/stats/src/views/Stats/Locations.tsx
  • apps/posts/src/views/PostAnalytics/components/KpiTab.tsx
  • apps/posts/src/providers/GlobalDataProvider.tsx
  • apps/posts/src/components/chart/CustomTooltipContent.tsx
  • apps/posts/src/config/stats-config.ts
  • apps/posts/src/views/PostAnalytics/components/PostAnalyticsContent.tsx
  • apps/posts/src/App.tsx
  • apps/stats/src/providers/GlobalDataProvider.tsx
  • apps/shade/src/lib/utils.ts
  • apps/posts/src/views/PostAnalytics/components/Web/Sources.tsx
  • apps/posts/src/views/PostAnalytics/components/Web/Locations.tsx
  • apps/posts/src/views/PostAnalytics/components/Web/Kpis.tsx
  • apps/posts/src/views/PostAnalytics/components/AudienceSelect.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/posts/src/utils/chart-helpers.ts (1)
ghost/admin/app/utils/stats.js (2)
  • d (88-88)
  • endDate (170-170)
🪛 Biome (1.9.4)
apps/posts/src/utils/chart-helpers.ts

[error] 53-54: This expression always returns false, because the string is converted and will never match

This call convert the string to upper case

... but this value is not in upper case

Unsafe fix: Use upper case string value.

(lint/correctness/noStringCaseMismatch)

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

[error] 14-15: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)


[error] 79-79: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Setup

Comment thread apps/posts/src/utils/chart-helpers.ts Outdated
Comment on lines 33 to 36

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

Revisit width calculation assumptions

The width calculation assumes a monospace font with a fixed character width of 8 pixels, which might not be accurate for all fonts and styling contexts. Consider a more dynamic approach or provide a way to configure the character width.


🏁 Script executed:

#!/bin/bash
# Check if the application uses monospace fonts for chart labels
rg -A 5 -B 5 "font-family|fontFamily" --glob "*.{tsx,css,scss}"

Length of output: 115937


🏁 Script executed:

#!/bin/bash
# Display the first 60 lines of chart-helpers.ts for context
sed -n '1,60p' apps/posts/src/utils/chart-helpers.ts

Length of output: 1967


🏁 Script executed:

#!/bin/bash
# Find all usages of calculateYAxisWidth
rg "calculateYAxisWidth" -n apps/posts/src

Length of output: 517


🏁 Script executed:

#!/bin/bash
# Search for chart library imports
rg -n "Chart" -n apps/posts/src/views/PostAnalytics/components/Web/Kpis.tsx

Length of output: 693


Refine Y‑axis width calculation

The current logic in apps/posts/src/utils/chart-helpers.ts assumes a monospace font at 8 px/character, but our charts inherit the site’s default sans‑serif (variable‑width) font. This can under‑ or over‑estimate the real label widths.

Suggestions:

  • In calculateYAxisWidth (lines 33–36), replace the hard‑coded multiplier with a measurement using CanvasRenderingContext2D.measureText or accept a configurable charWidth.
  • Update the call in apps/posts/src/views/PostAnalytics/components/Web/Kpis.tsx (around line 162) to pass through a custom width or use the new measurement logic.

Example change:

export const calculateYAxisWidth = (
  ticks: number[],
  formatter: (v: number) => string,
  charWidth?: number
): number => {
  if (!ticks.length) return 40;
  const labels = ticks.map(formatter);
  const width = charWidth
    ? Math.max(20, Math.max(...labels.map(l => l.length)) * charWidth + 8)
    : // dynamically measure longest label
      (() => {
        const ctx = document.createElement('canvas').getContext('2d')!;
        ctx.font = getComputedStyle(document.body).font;
        return Math.max(20, Math.max(...labels.map(l => ctx.measureText(l).width)) + 8);
      })();
  return width;
};

@peterzimon
peterzimon disabled auto-merge April 23, 2025 05:13
@peterzimon
peterzimon force-pushed the ta-data-on-post-analytics branch from a358c11 to 888753d Compare April 23, 2025 05:52
@peterzimon
peterzimon enabled auto-merge (squash) April 23, 2025 05:52

@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: 0

🧹 Nitpick comments (1)
ghost/admin/app/routes/posts-x.js (1)

9-23: Comprehensive access control implementation

The beforeModel hook implements appropriate role-based and configuration-based access control:

  • Contributors are redirected to 'posts'
  • Non-admins are redirected to 'site'
  • All users are redirected if stats configuration is missing

The code is well-structured and includes helpful comments explaining the authorization logic.

Consider extracting common access control logic

While this implementation works correctly, there is some duplication of access control logic between this file and routes/posts/analytics.js. Consider extracting this shared logic into a mixin or utility function if more routes need similar checks in the future.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d7c68c444a7fb52fe7f70cee17df1ceffc1d8cb1 and a358c11e06806b9f616b76cd05495863add37893.

📒 Files selected for processing (4)
  • ghost/admin/app/controllers/posts-x.js (1 hunks)
  • ghost/admin/app/routes/posts-x.js (1 hunks)
  • ghost/admin/app/routes/posts/analytics.js (2 hunks)
  • ghost/admin/app/templates/posts-x.hbs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Ghost-CLI tests
  • GitHub Check: Signup-form tests
  • GitHub Check: Admin-X Settings tests
  • GitHub Check: Comments-UI tests
  • GitHub Check: Database tests (Node 20.11.1, sqlite3)
  • GitHub Check: Unit tests (Node 22.13.1)
  • GitHub Check: Unit tests (Node 20.11.1)
  • GitHub Check: Regression tests (Node 20.11.1, sqlite3)
  • GitHub Check: Unit tests (Node 18.12.1)
  • GitHub Check: Database tests (Node 22.13.1, mysql8)
  • GitHub Check: Regression tests (Node 20.11.1, mysql8)
  • GitHub Check: Database tests (Node 20.11.1, mysql8)
  • GitHub Check: Database tests (Node 18.12.1, mysql8)
  • GitHub Check: i18n
  • GitHub Check: Lint
  • GitHub Check: Admin tests - Chrome
🔇 Additional comments (9)
ghost/admin/app/templates/posts-x.hbs (1)

1-3: Proper feature flag implementation for the analytics feature

The new feature flag check correctly prevents rendering the AdminX::Posts component unless the "statsX" feature is enabled. This is an appropriate pattern for controlling access to beta features.

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

2-3: Appropriate service imports for feature control

The imports are correctly set up to bring in the necessary decorators for dependency injection.


5-9: Proper service injection implementation

The controller correctly injects the feature, session, and config services which will enable access control and feature flagging.

ghost/admin/app/routes/posts/analytics.js (4)

2-2: Correct import for config injection

The import for the custom inject decorator is appropriately added.


6-7: Config service properly injected

The config service is correctly injected to enable configuration-based access control.


14-24: Formatted include list

The formatting changes to the include list improve readability.


50-62: Well-implemented role-based access control

The added conditional logic correctly implements role-based and configuration-based access control for the posts-x analytics route. The code clearly handles three scenarios:

  1. Contributors are redirected to 'posts'
  2. Non-admin users are redirected to 'site'
  3. Users are redirected to 'home' if stats configuration is missing

The code is also well-commented, explaining the reasoning behind each check.

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

2-3: Appropriate service imports

The imports are correctly set up for the necessary dependency injection.


6-7: Required services properly injected

The config and session services are correctly injected to support the authorization checks.

@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: 0

♻️ Duplicate comments (3)
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (1)

88-96: Enhance loading state and add error handling.

The loading state is currently just a string 'Loading', and there's no error handling for failed data fetching operations.

-                {isLoading ? 'Loading' :
+                {isLoading ? <div className="flex justify-center py-8">Loading analytics data...</div> :
                     <>
                         <Kpis queryParams={params} />
                         <div className='grid grid-cols-2 gap-8'>
                             <Sources queryParams={params} />
                             <Locations queryParams={params} />
                         </div>
                     </>
apps/posts/src/utils/chart-helpers.ts (2)

52-55: ⚠️ Potential issue

Fix the case mismatch in string comparison.

The current comparison will always be false because 'ᴺᵁᴸᴸ' is not in uppercase. This creates a subtle bug where null country codes aren't properly handled.

-    if (!countryCode || countryCode === null || countryCode.toUpperCase() === 'ᴺᵁᴸᴸ') {
+    if (!countryCode || countryCode === null || countryCode.toUpperCase() === 'NULL') {
         return '🏳️';
     }
🧰 Tools
🪛 Biome (1.9.4)

[error] 53-54: This expression always returns false, because the string is converted and will never match

This call convert the string to upper case

... but this value is not in upper case

Unsafe fix: Use upper case string value.

(lint/correctness/noStringCaseMismatch)


33-36: 💡 Verification agent

🧩 Analysis chain

Refine Y-axis width calculation.

The current logic assumes a monospace font at 8 px/character, but charts typically inherit the site's default sans-serif (variable-width) font. This can lead to inaccurate width calculations.

-    // Approximate width based on character count (assuming monospace font)
-    // Add padding for safety
-    const width = Math.max(20, maxFormattedLength * 8 + 8);
+    // Use a more accurate width calculation method
+    const width = (() => {
+        // Try to use canvas text measurement if in browser environment
+        if (typeof document !== 'undefined') {
+            try {
+                const ctx = document.createElement('canvas').getContext('2d');
+                if (ctx) {
+                    // Use the document's font or fallback to a reasonable default
+                    ctx.font = getComputedStyle(document.body).font || '14px sans-serif';
+                    const maxWidth = Math.max(...ticks.map(tick => 
+                        ctx.measureText(formatter(tick)).width
+                    ));
+                    return Math.max(20, maxWidth + 16); // Add padding
+                }
+            } catch (e) {
+                console.warn('Canvas text measurement failed, falling back to estimation', e);
+            }
+        }
+        // Fallback to estimation if canvas measurement fails or in SSR
+        return Math.max(20, maxFormattedLength * 8 + 8);
+    })();

I'm suggesting using CanvasRenderingContext2D.measureText for more accurate text width calculations when possible, with a fallback to the current estimation method for server-side rendering or if canvas measurement fails.


🌐 Web query:

How accurate is Canvas measureText for calculating text width in browser?

💡 Result:

Accuracy of Canvas measureText() for Calculating Text Width in Browsers

Summary:
The CanvasRenderingContext2D.measureText() method provides a reasonably accurate measurement of text width in pixels for many routine browser applications, but its accuracy can be affected by the choice of font, font size, font style (e.g., italic), and browser rendering differences. For precise alignment—especially in scenarios involving non-standard fonts or complex glyphs—additional properties should be considered.


Key Points:

  • What measureText().width Returns:
    The measureText() method on a canvas 2D context returns a TextMetrics object. The most commonly used property for width is metrics.width, which represents the advance width of the text string[1][4][10]. This is the distance that the next string would begin if you rendered the given text.

  • Limitations of metrics.width:
    The width property doesn't always represent the true visual width of the rendered text. Some glyphs (especially in italic fonts or those with overhanging elements) may extend beyond this advance width. As a result, metrics.width may underestimate the visual space required for the text[2][9].

  • More Accurate Measurement – Bounding Boxes:
    To get a more accurate measurement of the visual width (the space the text actually occupies), combine actualBoundingBoxLeft and actualBoundingBoxRight:

    [
    \text{visual width} = |\text{actualBoundingBoxLeft}| + |\text{actualBoundingBoxRight}|
    ]

    This sum accounts for overhanging glyphs and better matches what you see on the canvas, especially with italic or decorative fonts[2][9].

  • Browser and Font Variability:
    The accuracy may further vary between browsers and fonts. While most modern browsers (Chrome, Firefox, Edge, Safari) use similar methods and produce similar results, subtle differences can still exist—particularly for small font sizes or when rendering special characters[3][8].

    "Safari/Chrome/Edge are fairly synoptic in their renderings, with Firefox as the oddball... For smaller font sizes it might make sense to measure text at a larger (say x2) size then halve the result to get the consistency needed."[3]

  • Performance versus Alternatives:
    Canvas measureText() is much faster than DOM-based measurement approaches (like creating a hidden span), but may be a bit less accurate for boundary cases[8][5]. For routine UI work, this method is considered sufficient and standard practice[1][6][7].


Practical Recommendations

  • For most web UI tasks and moderate font sizes, measureText().width provides acceptable accuracy[4][6][10].
  • For pixel-perfect layouts, text cropping, or handling special glyphs, use actualBoundingBoxLeft and actualBoundingBoxRight from the TextMetrics object for a more faithful measurement[2][9].
  • If you notice inconsistencies at small font sizes, consider measuring at a larger scale and normalizing, as browser rendering can be non-linear at very small sizes[3].
  • Always ensure the canvas context's font property matches the style you intend to measure, as differences here will change measurements[1][4][10].

Example

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.font = 'italic 50px serif';
const metrics = ctx.measureText('Some text, but at what length?');

// Less accurate:
console.log(metrics.width);

// More accurate (visual bounding box):
const visualWidth = Math.abs(metrics.actualBoundingBoxLeft) + Math.abs(metrics.actualBoundingBoxRight);
console.log(visualWidth);

[2][9]


Conclusion:
CanvasRenderingContext2D.measureText() is a fast, widely-supported method that gives a good approximation of text width in most web development scenarios. For high precision, especially with complex or slanted fonts, use the bounding box properties provided by the TextMetrics object. Browser differences are minor but worth considering in cross-browser or cross-platform applications.

Citations:


Use Canvas text metrics for precise Y‑axis width calculation

To improve accuracy, switch from a fixed monospace approximation to CanvasRenderingContext2D.measureText(), and—for true visual width—combine the bounding‑box properties. Fallback to the existing estimation for SSR or measurement failures.

• File: apps/posts/src/utils/chart-helpers.ts
Lines: ~33–36

-    // Approximate width based on character count (assuming monospace font)
-    // Add padding for safety
-    const width = Math.max(20, maxFormattedLength * 8 + 8);
-    return width;
+    // Calculate width using canvas text metrics (with bounding boxes), fallback to estimation
+    const width = (() => {
+      if (typeof document !== 'undefined') {
+        try {
+          const canvas = document.createElement('canvas');
+          const ctx = canvas.getContext('2d');
+          if (ctx) {
+            // Match the site’s font or use a sensible default
+            ctx.font = getComputedStyle(document.body).font || '14px sans-serif';
+            // Measure each tick label’s visual width (accounts for overhangs)
+            const maxWidth = Math.max(
+              ...ticks.map(tick => {
+                const text = formatter(tick);
+                const m = ctx.measureText(text);
+                return Math.abs(m.actualBoundingBoxLeft) + Math.abs(m.actualBoundingBoxRight);
+              })
+            );
+            return Math.max(20, maxWidth + 16); // padding
+          }
+        } catch (e) {
+          console.warn('Canvas text measurement failed, falling back to estimation', e);
+        }
+      }
+      // SSR or canvas unsupported
+      return Math.max(20, maxFormattedLength * 8 + 8);
+    })();
+    return width;

This uses actualBoundingBoxLeft and actualBoundingBoxRight for a more faithful visual measurement while maintaining a safe fallback.

🧹 Nitpick comments (6)
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (4)

15-15: Replace empty interface with type alias.

The empty interface doesn't provide any value and is equivalent to {}.

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

Also, consider using PascalCase for type/interface names to follow TypeScript naming conventions.

🧰 Tools
🪛 Biome (1.9.4)

[error] 14-15: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)


17-20: Consolidate multiple useGlobalData calls.

You're calling useGlobalData twice to extract different properties. Consolidate these calls for better readability and performance.

-    const {statsConfig, isLoading: isConfigLoading} = useGlobalData();
-    const {range, audience} = useGlobalData();
+    const {statsConfig, isLoading: isConfigLoading, range, audience} = useGlobalData();

24-29: Simplify data destructuring for better readability.

The current destructuring pattern is complex and might be harder to understand at a glance. Consider breaking it down into more readable steps.

-    const {data: {posts: [post]} = {posts: []}, isLoading: isPostLoading} = useBrowsePosts({
+    const {data, isLoading: isPostLoading} = useBrowsePosts({
         searchParams: {
             filter: `id:${postId}`,
             fields: 'title,slug'
         }
     });
+    const post = data?.posts?.[0];

79-80: Use optional chaining for cleaner code.

Using optional chaining operator would make this code more concise.

-                    <H1 className='mt-0.5 min-h-[35px] indent-0'>
-                        {post && post.title}
-                    </H1>
+                    <H1 className='mt-0.5 min-h-[35px] indent-0'>
+                        {post?.title}
+                    </H1>
🧰 Tools
🪛 Biome (1.9.4)

[error] 79-79: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

apps/posts/src/utils/chart-helpers.ts (2)

7-20: Handle edge cases in Y-axis tick calculation.

The current implementation might produce suboptimal tick values when all data points are the same or when the range is very small.

 export const getYTicks = (data: { value: number }[]): number[] => {
     if (!data?.length) {
         return [];
     }
     const values = data.map(d => Number(d.value));
     const max = Math.max(...values);
     const min = Math.min(...values);
+    // Handle case where all values are the same
+    if (max === min) {
+        return [0, Math.ceil(max * 1.1)];
+    }
     const step = Math.pow(10, Math.floor(Math.log10(max - min)));
     const ticks = [];
     for (let i = Math.floor(min / step) * step; i <= Math.ceil(max / step) * step; i += step) {
         ticks.push(i);
     }
+    // Ensure we have a reasonable number of ticks
+    if (ticks.length > 10) {
+        const reducedTicks = [];
+        const skipFactor = Math.ceil(ticks.length / 10);
+        for (let i = 0; i < ticks.length; i += skipFactor) {
+            reducedTicks.push(ticks[i]);
+        }
+        return reducedTicks;
+    }
     return ticks;
 };

56-58: Simplify the country code to flag emoji conversion.

The current implementation is functional but can be simplified and made more readable.

-    return countryCode.toUpperCase().replace(/./g, char => String.fromCodePoint(char.charCodeAt(0) + 127397)
-    );
+    // Convert country code to flag emoji using regional indicator symbols
+    return Array.from(countryCode.toUpperCase())
+        .map(char => String.fromCodePoint(char.charCodeAt(0) + 127397))
+        .join('');
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a358c11e06806b9f616b76cd05495863add37893 and 888753d.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (34)
  • apps/admin-x-framework/src/api/posts.ts (1 hunks)
  • apps/admin-x-framework/src/index.ts (1 hunks)
  • apps/admin-x-framework/src/providers/FrameworkProvider.tsx (1 hunks)
  • apps/posts/package.json (1 hunks)
  • apps/posts/src/App.tsx (2 hunks)
  • apps/posts/src/components/chart/CustomTooltipContent.tsx (1 hunks)
  • apps/posts/src/config/stats-config.ts (1 hunks)
  • apps/posts/src/providers/GlobalDataProvider.tsx (1 hunks)
  • apps/posts/src/utils/chart-helpers.ts (1 hunks)
  • apps/posts/src/utils/constants.ts (1 hunks)
  • apps/posts/src/views/PostAnalytics/PostAnalytics.tsx (2 hunks)
  • apps/posts/src/views/PostAnalytics/components/AudienceSelect.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/DateRangeSelect.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/EmptyStatView.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/KpiTab.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/PostAnalyticsContent.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/Web/Kpis.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/Web/Locations.tsx (1 hunks)
  • apps/posts/src/views/PostAnalytics/components/Web/Sources.tsx (1 hunks)
  • apps/shade/package.json (1 hunks)
  • apps/shade/src/index.ts (1 hunks)
  • apps/shade/src/lib/utils.ts (2 hunks)
  • apps/stats/src/components/chart/CustomTooltipContent.tsx (1 hunks)
  • apps/stats/src/config/stats-config.ts (2 hunks)
  • apps/stats/src/providers/GlobalDataProvider.tsx (1 hunks)
  • apps/stats/src/utils/data-formatters.ts (0 hunks)
  • apps/stats/src/views/Stats/Locations.tsx (1 hunks)
  • apps/stats/src/views/Stats/Sources.tsx (1 hunks)
  • apps/stats/src/views/Stats/Web.tsx (1 hunks)
  • apps/stats/src/views/Stats/components/WebKpis.tsx (1 hunks)
  • ghost/admin/app/controllers/posts-x.js (1 hunks)
  • ghost/admin/app/routes/posts-x.js (1 hunks)
  • ghost/admin/app/routes/posts/analytics.js (2 hunks)
  • ghost/admin/app/templates/posts-x.hbs (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/stats/src/utils/data-formatters.ts
✅ Files skipped from review due to trivial changes (7)
  • apps/stats/src/components/chart/CustomTooltipContent.tsx
  • apps/posts/src/views/PostAnalytics/components/EmptyStatView.tsx
  • ghost/admin/app/templates/posts-x.hbs
  • apps/stats/src/views/Stats/Web.tsx
  • apps/posts/src/config/stats-config.ts
  • apps/posts/src/utils/constants.ts
  • apps/shade/src/index.ts
🚧 Files skipped from review as they are similar to previous changes (24)
  • apps/stats/src/views/Stats/Sources.tsx
  • apps/posts/package.json
  • apps/shade/package.json
  • apps/stats/src/views/Stats/components/WebKpis.tsx
  • apps/stats/src/views/Stats/Locations.tsx
  • apps/admin-x-framework/src/index.ts
  • apps/posts/src/App.tsx
  • apps/posts/src/views/PostAnalytics/components/PostAnalyticsContent.tsx
  • ghost/admin/app/controllers/posts-x.js
  • apps/stats/src/config/stats-config.ts
  • apps/stats/src/providers/GlobalDataProvider.tsx
  • apps/admin-x-framework/src/api/posts.ts
  • apps/admin-x-framework/src/providers/FrameworkProvider.tsx
  • apps/posts/src/components/chart/CustomTooltipContent.tsx
  • ghost/admin/app/routes/posts/analytics.js
  • ghost/admin/app/routes/posts-x.js
  • apps/posts/src/views/PostAnalytics/components/Web/Sources.tsx
  • apps/posts/src/views/PostAnalytics/components/Web/Kpis.tsx
  • apps/posts/src/views/PostAnalytics/components/DateRangeSelect.tsx
  • apps/posts/src/providers/GlobalDataProvider.tsx
  • apps/shade/src/lib/utils.ts
  • apps/posts/src/views/PostAnalytics/components/KpiTab.tsx
  • apps/posts/src/views/PostAnalytics/components/AudienceSelect.tsx
  • apps/posts/src/views/PostAnalytics/components/Web/Locations.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
apps/posts/src/views/PostAnalytics/PostAnalytics.tsx

[error] 14-15: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)


[error] 79-79: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

apps/posts/src/utils/chart-helpers.ts

[error] 53-54: This expression always returns false, because the string is converted and will never match

This call convert the string to upper case

... but this value is not in upper case

Unsafe fix: Use upper case string value.

(lint/correctness/noStringCaseMismatch)

⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Ghost-CLI tests
  • GitHub Check: Signup-form tests
  • GitHub Check: Database tests (Node 20.11.1, sqlite3)
  • GitHub Check: Database tests (Node 22.13.1, mysql8)
  • GitHub Check: Regression tests (Node 20.11.1, sqlite3)
  • GitHub Check: Unit tests (Node 22.13.1)
  • GitHub Check: Database tests (Node 20.11.1, mysql8)
  • GitHub Check: Regression tests (Node 20.11.1, mysql8)
  • GitHub Check: Database tests (Node 18.12.1, mysql8)
  • GitHub Check: Unit tests (Node 20.11.1)
  • GitHub Check: Comments-UI tests
  • GitHub Check: Unit tests (Node 18.12.1)
  • GitHub Check: Admin-X Settings tests
  • GitHub Check: i18n
  • GitHub Check: Admin tests - Chrome
  • GitHub Check: Lint

@peterzimon
peterzimon disabled auto-merge April 23, 2025 06:01
@peterzimon
peterzimon requested review from 9larsons and cmraible April 23, 2025 06:02
@codecov

codecov Bot commented Apr 23, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 0% with 15 lines in your changes missing coverage. Please review.

Project coverage is 71.55%. Comparing base (5b4d134) to head (1cacf10).
Report is 75 commits behind head on main.

Files with missing lines Patch % Lines
ghost/admin/app/routes/posts-x.js 0.00% 8 Missing ⚠️
ghost/admin/app/routes/posts/analytics.js 0.00% 6 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #22986      +/-   ##
==========================================
- Coverage   71.84%   71.55%   -0.29%     
==========================================
  Files        1443     1443              
  Lines       99986    99879     -107     
  Branches    12306    12277      -29     
==========================================
- Hits        71836    71472     -364     
- Misses      27152    27421     +269     
+ Partials      998      986      -12     
Flag Coverage Δ
admin-tests 47.42% <0.00%> (-0.80%) ⬇️
e2e-tests 76.49% <ø> (-0.17%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

const {postId} = useParams();
const navigate = useNavigate();

const {data: {posts: [post]} = {posts: []}, isLoading: isPostLoading} = useBrowsePosts({

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm using this from admin-x-framework to get the selected post. I think this is correct but I'd like to just get a doublecheck pls.

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.

LGTM.

return this.replaceWith(returnRoute);
}

if (this.routeName === 'posts.analytics.posts-x') {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is for preventing non-admins or sites without the config to be able to view the new Post Analytics

@peterzimon peterzimon left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@9larsons @cmraible — I left a few comments inline to highlight the parts I'd like you to take a look at. Thank you 🙏

9larsons and others added 4 commits April 23, 2025 08:11
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@9larsons
9larsons enabled auto-merge (squash) April 23, 2025 20:53
@9larsons
9larsons merged commit 54d993b into main Apr 23, 2025
@9larsons
9larsons deleted the ta-data-on-post-analytics branch April 23, 2025 21:05
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.

2 participants