Skip to content

Commit

Permalink
#30820 Create Custom Hook for Page View Content Analytics Integration (
Browse files Browse the repository at this point in the history
…#30922)

### Proposed Changes
* Add Providers, Custom Hooks to consume DotContentAnalytics

### Checklist
- [x] Tests
- [ ] Translations
- [ ] Security Implications Contemplated (add notes if applicable)

### Additional Info
** any additional useful context or info **

### Screenshots
Pageview + Custom Track Event

https://github.com/user-attachments/assets/e4ab4554-70bd-4d52-abde-38dddad3be49
  • Loading branch information
oidacra authored Dec 19, 2024
1 parent de7ba14 commit 2f636df
Show file tree
Hide file tree
Showing 49 changed files with 7,884 additions and 6,321 deletions.
12 changes: 12 additions & 0 deletions core-web/libs/sdk/analytics/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"presets": [
[
"@nx/react/babel",
{
"runtime": "automatic",
"useBuiltIns": "usage"
}
]
],
"plugins": []
}
7 changes: 0 additions & 7 deletions core-web/libs/sdk/analytics/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,6 @@
{
"files": ["*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.json"],
"parser": "jsonc-eslint-parser",
"rules": {
"@nx/dependency-checks": "error"
}
}
]
}
29 changes: 0 additions & 29 deletions core-web/libs/sdk/analytics/.swcrc

This file was deleted.

109 changes: 89 additions & 20 deletions core-web/libs/sdk/analytics/README.md
Original file line number Diff line number Diff line change
@@ -1,39 +1,115 @@
# @dotcms/analytics

`@dotcms/analytics` is the official dotCMS JavaScript library for Content Analytics that helps track events and analytics in your webapps. Currently available as an IIFE (Immediately Invoked Function Expression) module for direct browser usage.
`@dotcms/analytics` is the official dotCMS JavaScript library for Content Analytics that helps track events and analytics in your webapps. Available for both browser and React applications.

## Features

- **Simple Browser Integration**: Easy to implement via script tags using IIFE implementation
- **React Support**: Built-in React components and hooks for seamless integration
- **Event Tracking**: Simple API to track custom events with additional properties
- **Automatic PageView**: Option to automatically track page views
- **Debug Mode**: Optional debug logging for development

## Installation

Include the script in your HTML page:
```bash
npm install @dotcms/analytics
```

Or include the script in your HTML page:

```html
<script src="analytics.iife.js"></script>
<script src="ca.min.js"></script>
```

## Configuration
## React Integration

The script can be configured using data attributes:
### Provider Setup

First, import the provider:

```tsx
import { DotContentAnalyticsProvider } from '@dotcms/analytics/react';
```

Wrap your application with the `DotContentAnalyticsProvider`:

```tsx
// Example configuration
const analyticsConfig = {
apiKey: 'your-api-key-from-dotcms-analytics-app',
server: 'https://your-dotcms-instance.com',
debug: false // Not required
};

function App() {
return (
<DotContentAnalyticsProvider config={analyticsConfig}>
<YourApp />
</DotContentAnalyticsProvider>
);
}
```

### Tracking Custom Events

Use the `useContentAnalytics` hook to track custom events:

```tsx
import { useContentAnalytics } from '@dotcms/analytics/react';

function Activity({ title, urlTitle }) {
const { track } = useContentAnalytics();

// First parameter: custom event name to identify the action
// Second parameter: object with properties you want to track

return <button onClick={() => track('btn-click', { title, urlTitle })}>See Details →</button>;
}
```

### Manual Page View Tracking

To manually track page views, first disable automatic tracking in your config:

```tsx
const analyticsConfig = {
apiKey: 'your-api-key-from-dotcms-analytics-app',
server: 'https://your-dotcms-instance.com',
autoPageView: false // Disable automatic tracking
};
```

Then use the `useContentAnalytics` hook in your layout component:

```tsx
import { useContentAnalytics } from '@dotcms/analytics/react';

- **data-analytics-server**: URL of the server where events will be sent. If not provided, it defaults to the current location (window.location.href).
- **data-analytics-debug**: Presence of this attribute enables debug logging (no value needed)
- **data-analytics-auto-page-view**: Presence of this attribute enables automatic page view tracking (no value needed)
- **data-analytics-key**: Required. API key for authentication with the analytics server. This key is provided by the DotCMS Analytics app.
function Layout({ children }) {
const { pageView } = useContentAnalytics();

## Usage
useEffect(() => {
pageView({
// Add any custom properties you want to track
myCustomValue: '2'
});
}, []);

### Automatic PageView Tracking
return <div>{children}</div>;
}
```

## Browser Configuration

The script can be configured using data attributes:

When `data-analytics-auto-page-view` is enabled, the library will automatically send a page view event to dotCMS when the page loads. If this attribute is not present, you'll need to manually track page views and other events using the tracking API.
- **data-analytics-server**: URL of the server where events will be sent. If not provided, the current domain will be used
- **data-analytics-debug**: Enables debug logging
- **data-analytics-auto-page-view**: Recommended for IIFE implementation. Enables automatic page view tracking
- **data-analytics-key**: **(Required)** API key for authentication

```html
<!-- Automatic page view tracking enabled & debug logging enabled -->
<!-- Example configuration -->
<script
src="ca.min.js"
data-analytics-server="http://localhost:8080"
Expand All @@ -53,14 +129,7 @@ When `data-analytics-auto-page-view` is enabled, the library will automatically

The following features are planned for future releases:

1. **Manual Event Tracking**

- Manual track events support for IIFE implementation

2. **Headless Support**

- React integration for event tracking
- Next.js integration for event tracking
- Angular integration for event tracking

## Contributing
Expand Down
35 changes: 14 additions & 21 deletions core-web/libs/sdk/analytics/jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,21 @@
/* eslint-disable */
import { readFileSync } from 'fs';

// Reading the SWC compilation config and remove the "exclude"
// for the test files to be compiled by SWC
const { exclude: _, ...swcJestConfig } = JSON.parse(readFileSync(`${__dirname}/.swcrc`, 'utf-8'));

// disable .swcrc look-up by SWC core because we're passing in swcJestConfig ourselves.
// If we do not disable this, SWC Core will read .swcrc and won't transform our test files due to "exclude"
if (swcJestConfig.swcrc === undefined) {
swcJestConfig.swcrc = false;
}

// Uncomment if using global setup/teardown files being transformed via swc
// https://nx.dev/nx-api/jest/documents/overview#global-setupteardown-with-nx-libraries
// jest needs EsModule Interop to find the default exported setup/teardown functions
// swcJestConfig.module.noInterop = false;

export default {
displayName: 'analytics',
displayName: 'sdk-analytics',
preset: '../../../jest.preset.js',
transform: {
'^.+\\.[tj]s$': ['@swc/jest', swcJestConfig]
'^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nx/react/plugins/jest',
'^.+\\.[tj]sx?$': [
'babel-jest',
{
presets: ['@nx/react/babel'],
plugins: [
['@babel/plugin-proposal-private-methods', { loose: true }],
['@babel/plugin-proposal-private-property-in-object', { loose: true }],
['@babel/plugin-proposal-class-properties', { loose: true }]
]
}
]
},
moduleFileExtensions: ['ts', 'js', 'html'],
testEnvironment: 'jsdom',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../../coverage/libs/sdk/analytics'
};
21 changes: 17 additions & 4 deletions core-web/libs/sdk/analytics/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dotcms/analytics",
"version": "0.0.1-alpha.38",
"version": "0.0.1-alpha.54",
"description": "Official JavaScript library for Content Analytics with DotCMS.",
"repository": {
"type": "git",
Expand All @@ -19,10 +19,23 @@
"url": "https://github.com/dotCMS/core/issues"
},
"homepage": "https://github.com/dotCMS/core/tree/main/core-web/libs/sdk/analytics/README.md",
"peerDependencies": {
"dependencies": {
"analytics": "^0.8.14",
"vite": "^5.0.0"
"vite": "~5.0.0"
},
"peerDependencies": {
"react": "^18.2.0"
},
"devDependencies": {
"@testing-library/jest-dom": "^6.1.6",
"@testing-library/react": "^14.0.0"
},
"main": "./index.cjs.js",
"module": "./index.esm.js"
"module": "./index.esm.js",
"exports": {
"./react": {
"import": "./react/index.js",
"types": "./src/lib/react/index.d.ts"
}
}
}
34 changes: 9 additions & 25 deletions core-web/libs/sdk/analytics/project.json
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
{
"name": "analytics",
"name": "sdk-analytics",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/sdk/analytics/src",
"projectType": "library",
"tags": ["type:lib", "scope:sdk", "feature:analytics"],
"targets": {
"build": {
"executor": "@nx/rollup:rollup",
"outputs": ["{options.outputPath}"],
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"outputPath": "dist/libs/sdk/analytics",
"main": "libs/sdk/analytics/src/index.ts",
"tsConfig": "libs/sdk/analytics/tsconfig.lib.json",
"project": "libs/sdk/analytics/package.json",
"compiler": "swc",
"format": ["esm", "cjs"]
"jestConfig": "libs/sdk/analytics/jest.config.ts"
}
},
"build:standalone": {
Expand All @@ -23,21 +19,9 @@
"outputPath": "../../core/dotCMS/src/main/resources/ca/html",
"main": "libs/sdk/analytics/src/lib/standalone.ts",
"tsConfig": "libs/sdk/analytics/tsconfig.lib.json",
"project": "libs/sdk/analytics/package.json"
}
},
"nx-release-publish": {
"options": {
"packageRoot": "dist/{projectRoot}"
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "libs/sdk/analytics/jest.config.ts"
"project": "libs/sdk/analytics/package.json",
"configFile": "libs/sdk/analytics/vite.standalone.config.mts"
}
}
},
"tags": ["type:lib", "scope:sdk", "feature:analytics"]
}
}
2 changes: 1 addition & 1 deletion core-web/libs/sdk/analytics/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './lib/analytics';
export * from './lib/react';
Loading

0 comments on commit 2f636df

Please sign in to comment.