# Site analytics

As with any other service offered on the web, understanding how your project documentation is actually used can be an essential success factor. Zensical natively integrates with [Google Analytics](<https://developers.google.com/analytics>) and offers a customizable [cookie consent](<https://zensical.org/docs/setup/data-privacy/#cookie-consent>) and a [feedback widget](<#was-this-page-helpful>).

> [!NOTE]
>
> **We're overhauling our analytics integration**
>
> The analytics integration is inherited from Material for MkDocs and is currently being overhauled to better fit into Zensical's ecosystem, and to allow for more customization options. Join our [newsletter](<https://zensical.org/about/newsletter/>) to stay updated.

## Configuration

### Google Analytics

Zensical integrates natively with Google Analytics 4. If you already set up Google Analytics and have a property, enable it by adding the following lines to your configuration:

```toml
[project.extra.analytics]
provider = "google"
property = "G-XXXXXXXXXX"
```

```yaml
extra:
  analytics:
    provider: google
    property: G-XXXXXXXXXX
```

> [!NOTE]
>
> **How to measure site search usage?**
>
> Besides page views and events, [site search](<https://zensical.org/docs/setup/search/index.md>) can be tracked to better understand how people use your documentation and what they expect to find. In order to enable site search tracking, the following steps are required:
>
> 1. Go to your Google Analytics **admin settings**
> 2. Select the property for the respective tracking code
> 3. Select the **data streams** tab and click the corresponding URL
> 4. Click the gear icon within the **enhanced measurement** section
> 5. Ensure that **site search** is enabled

### Was this page helpful?

A simple [feedback widget](<#feedback>) can be included at the bottom of each page, encouraging users to give instant feedback whether a page was helpful or not. Add the following lines to your configuration:

```toml
[project.extra.analytics.feedback]
title = "Was this page helpful?"

[[project.extra.analytics.feedback.ratings]]
icon = "material/emoticon-happy-outline"
name = "This page was helpful"
data = 1
note = "Thanks for your feedback!"

[[project.extra.analytics.feedback.ratings]]
icon = "material/emoticon-sad-outline"
name = "This page could be improved"
data = 0
note = """
  Thanks for your feedback! Help us improve this page by
  using our <a href="..." target="_blank" rel="noopener">feedback form</a>.
"""
```

```yaml
extra:
  analytics:
    provider: google
    property: G-XXXXXXXXXX
    feedback:
      title: Was this page helpful?
      ratings:
        - icon: material/emoticon-happy-outline
          name: This page was helpful
          data: 1
          note: >-
            Thanks for your feedback!
        - icon: material/emoticon-sad-outline
          name: This page could be improved
          data: 0
          note: >-
            Thanks for your feedback! Help us improve this page by
            using our <a href="..." target="_blank" rel="noopener">feedback form</a>.
```

Both properties, `title` and `ratings`, are required. Note that it's possible to define more than two ratings, e.g. to implement a 1-5 star rating. You can add arbitrary HTML tags to the note which is shown after the user submitted the feedback, e.g., to link to a feedback form.

Since the feedback widget sends data to a third-party service, it is, of course, natively integrated with the [cookie consent](<https://zensical.org/docs/setup/data-privacy/#cookie-consent>) feature. If the user doesn't accept the `analytics` cookie, the feedback widget is not shown.

This feature uses [Google Analytics](<#google-analytics>), which is why `provider` and `property` are also required. However, it's also possible to provide a [custom feedback integration](<#custom-site-feedback>).

> [!NOTE]
>
> **How to visualize the collected feedback ratings?**
>
> To visualize feedback ratings you'll need to create a custom report with [Google Analytics](<https://developers.google.com/analytics>) that will quickly show you the worst- and best-rated pages of your project documentation.
>
> 1. Go to your Google Analytics **dashboard**
> 2. Go to the **Admin** page on the left hand menu (at the bottom), then select **custom definitions** on the **Data display** card
> 3. Click the **custom metrics** tab and then **create custom metrics**, enter the following values:
>
>    - Metric name: Page helpful
>    - Description: Was this page helpful?
>    - Event parameter: `data`
>    - Unit of measurement: Standard
> 4. Go to the **explore** page on the left hand menu, create a new **blank exploration**
> 5. Configure the report as follows:
>
>    - Dimensions: Add `Event name` and `Page location`
>    - Metrics: Add `Event count` and `Page helpful` (the custom metric created in step 3)
>    - Rows: `Page location`
>    - Values: Drag in both `Event count` and `Page helpful`
>    - Filters: Add a new filter for `Event name / exactly matches / feedback`
>
> > **Delay in data availability**
> >
> > The report may take 24 hours or longer to begin displaying data

The following properties are available for each rating:

**`analytics.feedback.ratings.icon`**

This property must point to a valid icon path referencing [any icon bundled with the theme](<https://github.com/squidfunk/mkdocs-material/tree/master/material/templates/.icons>), or the build will not succeed. Some popular combinations:

- \+ – `material/emoticon-happy-outline` + `material/emoticon-sad-outline`
- \+ – `material/thumb-up-outline` + `material/thumb-down-outline`
- \+ – `material/heart` + `material/heart-broken`

**`analytics.feedback.ratings.name`**

The value of this property is shown on user interaction (i.e. keyboard focus or mouse hover), explaining the meaning of the rating behind the icon.

**`analytics.feedback.ratings.data`**

The value of this property is sent as a data value with the custom event that is transmitted to Google Analytics[^/docs/setup/analytics/#3] (or any custom integration).

**`analytics.feedback.ratings.note`**

The value of this property is shown after the user selected the rating. It may contain arbitrary HTML tags, which is especially useful to ask the user to provide more detailed feedback for the current page through a form. It's also possible to pre-fill forms with the URL and title of the current page by using the following placeholders:

- `{url}` – Page URL
- `{title}` – Page title

```text
https://github.com/.../issues/new/?title=[Feedback]+{title}+-+{url}
```

In this example, when clicking the link, the user is redirected to the "new issue" form of your repository, with a pre-filled title including the path of the current document, e.g.:

```text
[Feedback] Setting up site analytics – /setup/setting-up-site-analytics/
```

An alternative to GitHub issues is [Google Forms](<https://www.google.com/forms/about/>).

## Usage

### Hide the feedback widget

The [feedback widget](<#was-this-page-helpful>) can be hidden for a document with the front matter `hide` property. Add the following lines at the top of a Markdown file:

```yaml
---
hide:
  - feedback
---

# Page title
...
```

## Customization

### Custom site analytics

In order to integrate another analytics service provider offering a JavaScript-based tracking solution, just follow the guide on [theme extension](<https://zensical.org/docs/customization/#extending-the-theme>) and create a new partial in the `overrides` folder. The name of the partial is used to configure the custom integration:

```html
<script>
  /* Add custom analytics integration here, e.g. */
  var property = "{{ config.extra.analytics.property }}" // (1)!

  /* Wait for page to load and application to mount */
  document.addEventListener("DOMContentLoaded", function() {
    location$.subscribe(function(url) {
      /* Add custom page event tracking here */ // (2)!
    })
  })
</script>
```

1. As an example, this variable receives the value set in `mkdocs.yml`, which is `"foobar"` for `property`.
2. If you're using [instant navigation](<https://zensical.org/docs/setup/navigation/#instant-navigation>), you can use the `location$` observable to listen for navigation events, which always emits the current `URL`.

```toml
[project.extra.analytics]
provider = "custom"
property = "foobar"
```

```yaml
extra:
  analytics:
    provider: custom
    property: foobar
```

You can add arbitrary key-value combinations to configure your custom integration. This is especially useful if you're sharing the custom integration across multiple repositories.

### Custom site feedback

A custom feedback widget integration just needs to process the events that are generated by users interacting with the feedback widget with the help of some [additional JavaScript](<https://zensical.org/docs/customization/#additional-javascript>):

```js
document$.subscribe(function() {
  var feedback = document.forms.feedback
  if (typeof feedback === "undefined") return

  feedback.hidden = false // (1)!

  feedback.addEventListener("submit", function(ev) {
    ev.preventDefault()

    var page = document.location.pathname // (2)!
    var data = ev.submitter.getAttribute("data-md-value")

    console.log(page, data) // (3)!

    feedback.firstElementChild.disabled = true // (4)!

    var note = feedback.querySelector(
      ".md-feedback__note [data-md-value='" + data + "']"
    )
    if (note)
      note.hidden = false // (5)!
  })
}
```

1. The feedback widget is hidden by default so that it does not appear when people have JavaScript turned off. So, it needs to be turned on here.
2. Retrieve page and feedback value.
3. Replace this with the code that sends the data off to your analytics provider.
4. Disable the form after submission.
5. Show the configured notes. Which one is shown depends on the user feedback.

```toml
[project]
extra_javascript = [
  "javascripts/feedback.js",
]
```

```yaml
extra_javascript:
  - javascripts/feedback.js
```

[^/docs/setup/analytics/#3]: Note that for Google Analytics, the data value must be an integer.
