Skip to content

Commit

Permalink
Merge branch 'main' into cookies-examples-update
Browse files Browse the repository at this point in the history
  • Loading branch information
cjrace authored Jul 23, 2024
2 parents d6fcc1e + 688c866 commit a55d36f
Show file tree
Hide file tree
Showing 11 changed files with 220 additions and 5 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
.Rhistory
.RData
.Ruserdata
google-analytics.html
tests/testthat/google-analytics.html
docs
inst/doc
www/
1 change: 1 addition & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Description: R package containing preferred methods for creating official
DfE R-Shiny dashboards.
License: GPL (>= 3)
Imports:
magrittr,
checkmate,
glue,
htmltools,
Expand Down
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ export(cookies_panel_server)
export(cookies_panel_ui)
export(custom_disconnect_message)
export(dfe_cookie_script)
export(init_analytics)
export(init_cookies)
export(support_panel)
export(tidy_code)
importFrom(htmltools,tagList)
importFrom(htmltools,tags)
importFrom(magrittr,"%>%")
72 changes: 72 additions & 0 deletions R/analytics.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#' init_analytics
#' @description
#' Creates the google-analytics.html script in order to allow the activation of
#' analytics via GA4. For the full steps required to set up analytics, please
#' refer to the documentation in the readme.
#'
#' @param ga_code The Google Analytics code
#' @importFrom magrittr %>%
#' @return TRUE if written, FALSE if not
#' @export
#'
#' @examples init_analytics(ga_code = "0123456789")
init_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"'
)
}

github_area <- "https://raw.githubusercontent.com/dfe-analytical-services/"
webpage <- RCurl::getURL(
paste0(
github_area,
"dfeshiny/main/inst/google-analytics.html"
)
)
tryCatch(
html_script <- gsub(
"XXXXXXXXXX",
ga_code,
readLines(tc <- textConnection(webpage))
),
error = function(e) {
return("Download failed")
},
message("Downloaded analytics template script")
)

close(tc)
if (file.exists("google-analytics.html")) {
message("Analytics file already exists.")
message("If you have any customisations in that file, make sure you've
backed those up before over-writing.")
user_input <- readline(
prompt = "Are you happy to overwrite the existing analytics script (y/N) "
) |>
stringr::str_trim()
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", sep = "\n")
message("")
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:")
message('tags$head(includeHTML(("google-analytics.html"))),')
} else {
message("Original Google analytics html script left in place.")
}
}
6 changes: 5 additions & 1 deletion R/cookies.R
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,10 @@ init_cookies <- function() {
}

tryCatch(
download.file(url = "https://raw.githubusercontent.com/dfe-analytical-services/dfeshiny/main/inst/cookie-consent.js", destfile = "www/cookie-consent.js"), # nolint: [line_length_linter]
utils::download.file(
url = "https://raw.githubusercontent.com/dfe-analytical-services/dfeshiny/main/inst/cookie-consent.js", # nolint: [line_length_linter]
destfile = "www/cookie-consent.js"
),
error = function(e) {
return("Download failed")
},
Expand Down Expand Up @@ -410,6 +413,7 @@ cookies_panel_ui <- function(id = "cookies_panel", google_analytics_key = NULL)
#' @inherit cookies examples
cookies_panel_server <- function(id = "cookies_panel",
input_cookies = reactive(input$cookies),

Check warning

Code scanning / lintr

no visible global function definition for 'reactive' Warning

no visible global function definition for 'reactive'

Check warning

Code scanning / lintr

no visible binding for global variable 'input' Warning

no visible binding for global variable 'input'

google_analytics_key = NULL) {
shiny::moduleServer(id, module = function(input, output, session) {
shiny::observeEvent(input_cookies(), {
Expand Down
10 changes: 8 additions & 2 deletions R/tidy_code.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
#' @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.
#' @export
#'
#' @examples
Expand All @@ -17,7 +18,12 @@ tidy_code <- function(subdirs = c("R", "tests")) {
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
26 changes: 25 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,15 @@ them meet the necessary standards required of public facing government services.

To install, run `renv::install("dfe-analytical-services/dfeshiny")`.

### Potential errors when installing
## Installing functionality in development from a branch

It can be useful when developing the package in particular to trial new or updated functionality in a shiny app. To do this, you can install the required branch using (replacing `branch-name` with the name of the branch you wish to install):

`renv::install("dfe-analytical-services/dfeshiny@branch-name")`

That will install the code from the named branch as dfeshiny in your app. You will need to restart your R session before it will start using the latest version that you've installed.

## Potential errors when installing

If you get `ERROR [curl: (22) The requested URL returned error: 401]`, and don't know why, try running `Sys.unsetenv("GITHUB_PAT")` to temporarily clear your GitHub PAT variable.

Expand All @@ -24,6 +32,22 @@ 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 [Explore Educaion Statisics platforms team](mailto:[email protected])
- create a html file with the javascript required for your dashboard to connect to Google Analytics
- add the line: `tags$head(includeHTML(("google-analytics.html"))),` to the ui.R file.

To create the latter, we provide the function `dfeshiny::init_analytics()`. You should run this code from the R console providing your Google Analytics code as follows (replacing `ABCDE12345` with the code obtained from the [Explore Education Statistics platforms]([email protected]) team):

```
init_analytics("ABCDE12345")
```

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 a custom disconect message to your dashboard

dfeshiny provides a function to add a custom disconnect message to your dashboard - this will appear when a dashboard would otherwise 'grey-screen' and will include options to refresh the page, go to overflow sites or visit the publication directly on Explore education statistics.
Expand Down
66 changes: 66 additions & 0 deletions inst/google-analytics.html
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-XXXXXXXXXX'></script>
<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.
*/

$(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>
22 changes: 22 additions & 0 deletions man/init_analytics.Rd

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

3 changes: 2 additions & 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(init_analytics())
})

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

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

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

0 comments on commit a55d36f

Please sign in to comment.