Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#328: add flourish analytics to pages with embeds. #344

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions modules/wri_media/js/flourish_analytics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Ensure the Flourish global object exists before loading the script.
if (typeof window.Flourish === "undefined") {
window.Flourish = {};
}

// Function to add the analytics listener when Flourish is ready.
function addAnalyticsListener() {
if (typeof window.Flourish.addAnalyticsListener === "function") {
window.Flourish.addAnalyticsListener(function (event) {
var action = event.action;

var category = "flourish_engagement";
var label = event.story_id
? "Flourish story " + event.story_id
: "Flourish visualization " + event.visualisation_id;

var dataLayerEvent = {
event: action,
event_category: category,
event_label: label,
event_action: action,
};

// Include additional data from the event object.
Object.keys(event).forEach(function (key) {
if (key !== "action") {
dataLayerEvent[key] = event[key];
}
});

// Push the event to the dataLayer.
window.dataLayer = window.dataLayer || [];
window.dataLayer.push(dataLayerEvent);
});
} else {
console.warn("Flourish.addAnalyticsListener is not available.");
}
}

// Wait for DOMContentLoaded to ensure Flourish script has run.
document.addEventListener("DOMContentLoaded", function () {
// Add the analytics listener after the embed script has initialized.
if (typeof window.Flourish.addAnalyticsListener === "function") {
addAnalyticsListener();
} else {
console.warn(
"Flourish.addAnalyticsListener is not available after DOMContentLoaded."
);
}
});

// Dynamically load the Flourish embed script if not already loaded.
if (!document.querySelector('script[src="https://public.flourish.studio/resources/embed.js"]')) {
var script = document.createElement('script');
script.src = "https://public.flourish.studio/resources/embed.js";
script.async = true;
script.onload = function () {
// Add the listener if Flourish is ready after script load.
addAnalyticsListener();
};
document.head.appendChild(script);
}
38 changes: 31 additions & 7 deletions modules/wri_media/wri_media.module
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
* WRI media functions.
*/

use Drupal\ckeditor5\Plugin\CKEditor5PluginDefinition;
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FormatterInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\ckeditor5\Plugin\CKEditor5PluginDefinition;
use Drupal\file\Entity\File;

/**
Expand Down Expand Up @@ -58,18 +58,42 @@ function wri_media_preprocess_details(&$variables) {
* Implements hook_preprocess_HOOK().
*/
function wri_media_preprocess_media(&$variables) {
// We've set the thumbnail to show during ckeditor use, and the embed code
// to show other times. This keeps the embed code from interfering with the
// js on the ckeditor page.
// Determine the current route to differentiate CKEditor previews.
$current_route = \Drupal::routeMatch()->getRouteName();

// Prevent embed code from interfering on CKEditor preview.
if ($current_route == 'media.filter.preview') {
// Unset embed when we're previewing within the CKeditor.
$variables["content"]["field_media_embed_code"]['#access'] = FALSE;
}
elseif (isset($variables["content"]["field_media_embed_code"])) {
// If both the thumbnail and the embed code are set to show, hide the
// thumbnail.
// Hide the thumbnail when embed code is shown.
$variables["content"]["thumbnail"]['#access'] = FALSE;

// Load the media entity.
$media = $variables['elements']['#media'];

if ($media && $media->hasField('field_media_embed_code')) {
// Get the embed code.
$embed_code = $media->get('field_media_embed_code')->value;

// Check if it's a Flourish embed.
if (strpos($embed_code, 'flourish-embed') !== FALSE) {
$module_path = \Drupal::service('extension.path.resolver')->getPath('module', 'wri_media');

// Add custom Flourish analytics script inline.
$script_path = $module_path . '/js/flourish_analytics.js';
if (file_exists($script_path)) {
$variables['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#attributes' => ['type' => 'text/javascript'],
'#value' => file_get_contents($script_path),
],
'flourish_analytics',
];
}
}
}
}
}

Expand Down