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

Function to initialise google analytics html script #4

Merged
merged 37 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
6260d78
Added initialise google analytics function.
rmbielby Nov 8, 2023
23568ef
Added extra documentation info
rmbielby Nov 8, 2023
771a116
Resolve merge conflicts from main
rmbielby Mar 13, 2024
f64f95c
Added validation on the ga_code variable for the google analytics scr…
rmbielby Mar 13, 2024
cebb5bd
Added tests for initialise_analytics
rmbielby Mar 13, 2024
a9790e1
Updated documentation
rmbielby Mar 13, 2024
5bfede7
Added magrittr pipe load
rmbielby Mar 13, 2024
8dc456d
Added magrittr DESCRIPTION
rmbielby Mar 13, 2024
7cd6557
Added source package for str_trim
rmbielby Mar 13, 2024
bd7d0c4
Removed yml code that had crept in from another branch
rmbielby Mar 13, 2024
4906b65
Cleaning up documentation
rmbielby Mar 13, 2024
4467b91
Adding test r script to tidy code exclude list
rmbielby Mar 13, 2024
63ecfa0
Adding info into README on analytics initialiser
rmbielby Mar 27, 2024
b09328d
Cleaning up line lengths in initialisers
rmbielby Mar 27, 2024
f46e7e6
Cleaning up line lengths in tidy code
rmbielby Mar 27, 2024
5a45bf8
Updated installation guidance in readme
rmbielby Mar 27, 2024
a7c4d5b
Updated installation guidance in readme
rmbielby Mar 27, 2024
1bb8e70
Adjusting line lengths in analyics function
rmbielby Mar 27, 2024
84a3721
Adjusted messaging spacing in initialiser script
rmbielby Mar 27, 2024
07d1bb2
Tweaks to initialisers code
rmbielby Mar 27, 2024
e9e0d8f
Removed google analyics html
rmbielby Mar 27, 2024
1450aec
Merge branch 'main' into analytsics-init
rmbielby Mar 27, 2024
a212e57
Merge branch 'main' into analytsics-init
rmbielby Jul 22, 2024
f1343d5
Reconfigured analytics initialiser to pull template script from GitHub
rmbielby Jul 22, 2024
0a754ab
Rebuilt package after init_analytics updates
rmbielby Jul 22, 2024
4ee5c8c
Few minor updates around analytics initialisation.
rmbielby Jul 22, 2024
117cf35
Removed google-analytics.html
rmbielby Jul 22, 2024
39a7715
Corrected reference to google-analytics.html in .gitignore
rmbielby Jul 22, 2024
15479bc
Handful of PR change requests on analytics initiailser
rmbielby Jul 22, 2024
41179f5
Recommitting google analytics template sc
rmbielby Jul 22, 2024
6fc3f9a
Updating .gitignore to only ignore analytics html if found in project…
rmbielby Jul 22, 2024
af6d8d9
Few updates from analytics PR
rmbielby Jul 22, 2024
5d253e3
Updting references to init_analytics().
rmbielby Jul 22, 2024
2d8ea4c
Updating references from Stats Dev team to EESp team
rmbielby Jul 22, 2024
00694a2
Updating reference filename for analytics
rmbielby Jul 22, 2024
219e4bd
removing google-analytics.html
rmbielby Jul 22, 2024
9cd99fe
updating analytics references in .gitignore
rmbielby Jul 22, 2024
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
.Rhistory
.RData
.Ruserdata
google_analytics.html
3 changes: 3 additions & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ Description: R package containing preferred methods for creating official
DfE R-Shiny dashboards.
License: GPL (>= 3)
Imports:
dplyr,
magrittr,
shiny,
shinyGovstyle,
shinyjs,
stringr,
styler
Suggests:
diffviewer,
Expand Down
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@
export(cookie_banner_server)
export(cookie_banner_ui)
export(dfe_cookie_script)
export(initialise_analytics)
export(support_panel)
export(tidy_code)
importFrom(magrittr,"%>%")
108 changes: 108 additions & 0 deletions R/initialisers.R
cjrace marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
#' initialise_analytics
#'
cjrace marked this conversation as resolved.
Show resolved Hide resolved
#' @param ga_code The Google Analytics code
#' @importFrom magrittr %>%
#' @return TRUE if written, FALSE if not
#' @export
#'
#' @examples initialise_analytics(ga_code = "0123456789")
initialise_analytics <- function(ga_code) {
is_valid_ga4_code <- function(ga_code) {
stringr::str_length(ga_code) == 10 & typeof(ga_code) == "character"
}

if (is_valid_ga4_code(ga_code) == FALSE) {
stop(
'You have entered an invalid GA4 code in the ga_code argument.
Please enter a 10 digit code as a character string.
e.g. "0123QWERTY"'
)
}

html_script <- "<script>
// Define dataLayer and the gtag function.
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

// Default ad_storage to 'denied' as a placeholder
// Determine actual values based on your own requirements
gtag('consent', 'default', {
'ad_storage': 'denied',
'analytics_storage': 'denied'
});
</script>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src='https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX'></script>
Dismissed Show dismissed Hide dismissed
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

gtag('js', new Date());

gtag('config', 'G-XXXXXXXXXX');

/*
The custom trackers below can be tailored to match the inputs used in your dashboard.

Check notice

Code scanning / lintr

Lines should not be more than 80 characters. This line is 85 characters. Note

Lines should not be more than 80 characters. This line is 85 characters.
*/

$(document).on('change', 'select#selectPhase', function(e) {
gtag('event', 'select phase', {'event_category' : 'choose Phase',
'event_label' : document.querySelector('select#selectPhase').value
});
});

$(document).on('change', 'select#selectArea', function(e) {
gtag('event', 'select area', {'event_category' : 'choose Area',
'event_label' : document.querySelector('select#selectArea').value
});
});

$(document).on('click', 'ul#navlistPanel', function(e) {
gtag('event', 'navlistPanel', {'event_category' : 'navbar click',
'event_label' : document.querySelector('ul#navlistPanel > li.active > a').getAttribute('data-value')

Check notice

Code scanning / lintr

Lines should not be more than 80 characters. This line is 104 characters. Note

Lines should not be more than 80 characters. This line is 104 characters.
});
});

$(document).on('click', 'ul#tabsetpanels', function(e) {
gtag('event', 'tab panels', {'event_category' : 'tab panel clicks',
'event_label' : document.querySelector('ul#tabsetpanels > li.active > a').getAttribute('data-value')

Check notice

Code scanning / lintr

Lines should not be more than 80 characters. This line is 104 characters. Note

Lines should not be more than 80 characters. This line is 104 characters.
});
});


$(document).on('click', 'a#download_data', function(e) {
gtag('event', 'Download button', {'event_category' : 'Download button click'
});
});

$(document).on('shiny:disconnected', function(e) {
gtag('event', 'disconnect', {
'event_label' : 'Disconnect',
'event_category' : 'Disconnect'
});
});

</script>
" %>% gsub("XXXXXXXXXX", ga_code, .)
Dismissed Show dismissed Hide dismissed
Dismissed Show dismissed Hide dismissed
cjrace marked this conversation as resolved.
Show resolved Hide resolved
if (file.exists("google-analytics.html")) {
message("Analytics file already exists. If you have any customisations in that file, make sure you've backed those up before over-writing.")
cjrace marked this conversation as resolved.
Show resolved Hide resolved
user_input <- stringr::str_trim(readline(prompt = "Are you happy to overwrite the existing analytics script (y/N) "))
rmbielby marked this conversation as resolved.
Show resolved Hide resolved
if (user_input %in% c("y", "Y")) {
write_out <- TRUE
} else {
write_out <- FALSE
}
} else {
write_out <- TRUE
}
if (write_out) {
cat(html_script, file = "google-analytics.html")
cjrace marked this conversation as resolved.
Show resolved Hide resolved
message("Google analytics script created in google-analytics.html.")
message("You'll need to add the following line to your ui.R script to start
recording analytics:")
cjrace marked this conversation as resolved.
Show resolved Hide resolved
message('tags$head(includeHTML(("google-analytics.html"))),')
cjrace marked this conversation as resolved.
Show resolved Hide resolved
} else {
message("Original Google analytics html script left in place.")
}
}
9 changes: 7 additions & 2 deletions R/tidy_code.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
#' @param subdirs List of sub-directories to
#' (recursively search for R scripts to be styled)
#'
#' @return True or False value based on if scripts were changed
#' @return TRUE if any changes have been made to any scripts, FALSE if all passed.

Check notice

Code scanning / lintr

Lines should not be more than 80 characters. This line is 82 characters. Note

Lines should not be more than 80 characters. This line is 82 characters.
cjrace marked this conversation as resolved.
Show resolved Hide resolved
#' @export
#'
#' @examples
Expand All @@ -15,7 +15,12 @@
message("----------------------------------------")
message("App scripts")
message("----------------------------------------")
script_changes <- eval(styler::style_dir(recursive = FALSE)$changed)
script_changes <- eval(
styler::style_dir(
recursive = FALSE,
exclude_files = c("dfeshiny-Ex.R")
)$changed
)
for (dir in subdirs) {
if (dir.exists(dir)) {
message(paste(dir, "scripts"))
Expand Down
15 changes: 15 additions & 0 deletions README.md
cjrace marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@ If this works, then you will need to look for where that "GITHUB_PAT" variable i

## Using this package in a DfE data dashboard

### Adding analytics to your dashboard

For analytics to function on your dashboard, you will need to:

- request a Google Analytics key from the [Statistics Development Team](mailto:[email protected])
- create a html file with the javascript required for your dashboard to connect to Google Analytics
cjrace marked this conversation as resolved.
Show resolved Hide resolved

To create the latter, we provide the function `dfeshiny::initialise_analytics()`. You should run this code from the R console providing your Google Analytics code as follows:

```
initialise_analytics("ABCDE12345")
cjrace marked this conversation as resolved.
Show resolved Hide resolved
```

This will create the file [google-analytics.html](google-analytics.html) within the home directory of your R project. This html file can be edited to add customised analytics recorders for different shiny elements in your dashboard. Feel free to contact our team if you need support in adding additional functionality.

### Adding cookies to your dashboard

dfeshiny provides the facility to add a gov.uk styled cookie banner to your
Expand Down
66 changes: 66 additions & 0 deletions google-analytics.html
cjrace marked this conversation as resolved.
Show resolved Hide resolved
cjrace marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<script>
// Define dataLayer and the gtag function.
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

// Default ad_storage to 'denied' as a placeholder
// Determine actual values based on your own requirements
gtag('consent', 'default', {
'ad_storage': 'denied',
'analytics_storage': 'denied'
});
</script>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src='https://www.googletagmanager.com/gtag/js?id=G-012245trjh'></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

gtag('js', new Date());

gtag('config', 'G-012245trjh');

/*
The custom trackers below can be tailored to match the inputs used in your dashboard.
*/

$(document).on('change', 'select#selectPhase', function(e) {
gtag('event', 'select phase', {'event_category' : 'choose Phase',
'event_label' : document.querySelector('select#selectPhase').value
});
});

$(document).on('change', 'select#selectArea', function(e) {
gtag('event', 'select area', {'event_category' : 'choose Area',
'event_label' : document.querySelector('select#selectArea').value
});
});

$(document).on('click', 'ul#navlistPanel', function(e) {
gtag('event', 'navlistPanel', {'event_category' : 'navbar click',
'event_label' : document.querySelector('ul#navlistPanel > li.active > a').getAttribute('data-value')
});
});

$(document).on('click', 'ul#tabsetpanels', function(e) {
gtag('event', 'tab panels', {'event_category' : 'tab panel clicks',
'event_label' : document.querySelector('ul#tabsetpanels > li.active > a').getAttribute('data-value')
});
});


$(document).on('click', 'a#download_data', function(e) {
gtag('event', 'Download button', {'event_category' : 'Download button click'
});
});

$(document).on('shiny:disconnected', function(e) {
gtag('event', 'disconnect', {
'event_label' : 'Disconnect',
'event_category' : 'Disconnect'
});
});

</script>

20 changes: 20 additions & 0 deletions man/initialise_analytics.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion man/tidy_code.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions tests/testthat/test-initialise_analytics.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
test_that("Blank code throws error", {
expect_error(initialise_analytics())
})

test_that("Long code throws error", {
expect_error(initialise_analytics("G-qwertyuiop"))
})

test_that("Short code throws error", {
expect_error(initialise_analytics("qwerty"))
})

test_that("Numeric throws error", {
expect_error(initialise_analytics(1234567890))
})
Loading