---
title: "Internationalization"
output: rmarkdown::html_vignette
description: >
  Teach in your own language! learnr provides translations for its interface in
  a few languages thanks to volunteers who have contributed translations. You
  can also use the language features of learnr to customize the language used in
  your tutorials according to your preferences.
vignette: >
  %\VignetteIndexEntry{multilang}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## Language codes and names borrowed from BootBox
# library(rvest)
# read_html("https://bootboxjs.com/v5.x/documentation.html") %>%
#   html_table() %>%
#   .[[6]] %>%
#   {dplyr::bind_rows(.[, 1:2], .[, 3:4])}

languages <- c("Arabic","Bulgarian","Czech",
    "German","English","Estonian","Farsi / Persian",
    "French / Français","Croatian","Indonesian","Japanese",
    "Korean","Latvian","Norwegian","Portuguese","Slovak",
    "Albanian","Swahili","Thai","Ukrainian",
    "Chinese (People's Republic of China)","Azerbaijani",
    "Portuguese - Brazil","Danish","Greek","Spanish / Español","Basque",
    "Finnish","Hebrew","Hungarian","Italian","Georgian",
    "Lithuanian","Dutch","Polish","Russian","Slovenian",
    "Swedish","Tamil","Turkish","Vietnamese",
    "Chinese (Taiwan / Republic of China)")

names(languages) <- c("ar","bg_BG","cs","de","en",
  "et","fa","fr","hr","id","ja","ko","lv","no",
  "pt","sk","sq","sw","th","uk","zh_CN","az","br",
  "da","el","es","eu","fi","he","hu","it","ka","lt",
  "nl","pl","ru","sl","sv","ta","tr","vi","zh_TW")


i18n_custom_language_defaults <- function(parent_key, docs = TRUE) {
  default <- learnr:::i18n_translations()$en$translation
  parent_key <- match.arg(parent_key, names(default))
  x <- default[[parent_key]]
  if (!isTRUE(docs)) return(x)
  paste0(
    parent_key, ":\n",
    paste0("  ", names(x), ": ", unname(unlist(x)), collapse = "\n"),
    sep = ""
  )
}

learnr_langs <- setdiff(names(learnr:::i18n_translations()), "emo")
learnr_supported_languages <- knitr::combine_words(paste0('`"', learnr_langs, '"`'))
bb_langs_code <- paste0("`", names(languages), "`")
```

## Choosing a Tutorial's Language

To change the language of the UI element, you can use the following parameter in your YAML:

    output:
      learnr::tutorial:
        language: fr

Currently, `r length(learnr_langs)` language translations are supported:

```{r echo=FALSE, results="asis"}
for (lng in learnr_langs) {
  lng_name <- if (lng %in% names(languages)) paste(" for", languages[lng])
  if (lng == "en") 
    lng_name <- paste(lng_name, "(default)")
  if (lng == "zh")
    lng_name <- " for Chinese"
  cat("\n- `", lng, "`", lng_name, sep = "")
}
```

Note that `"no"` needs to be quoted because it is a reserved word in YAML.

## Customizable UI elements:

There are many elements whose language can be translated or customized, each identified by a *key*.
Note that you do not need to customize *all* of the keys, the UI will fall back to the default tutorial language for keys that are not specifically customized.

The keys are organized into 2 groups: button and text.

### Buttons

The following keys are available for translating button text:

``` yaml
`r i18n_custom_language_defaults("button")`
```

### Text

The following keys are available for translating text elements:

``` yaml
`r i18n_custom_language_defaults("text")`
```

## Format of `language` Option in YAML Header:

There are several ways that you can use the `language` option to choose a language translation or to customize the phrasing used in a particular language.

### Default Language

Chose the default language for the tutorial.
learnr currently provides complete translations for `r learnr_supported_languages`.
A translation does not need to be available for you to use as the default language, in particular if you are providing a custom translation for a language without an available complete translation.

If you only want to change the default language, use:

``` yaml
language: "fr"
```

If you are also providing language customizations, the first language in the list of customizations will be the default language.

### Customizing a Single Language

To customize the displayed text for a single language, use the following format.
In this format the customization will be applied to the English translation, which will also be the default language of the tutorial.

``` yaml
language:
  en:
    button:
      runcode: Run!
    text:
      startover: Restart!
```

### Customizing Multiple Languages

To provide custom display text for multiple languages, provide a list containing `button` and/or `text` custom labels.
In the example below, the default tutorial language will be Spanish (`es`).

``` yaml
language:
  es:
    button:
      runcode: Ejecutar
  en:
    button:
      runcode: Run!
    text:
      startover: Restart!
```

Note that only the first language and its customizations are used in the rendered tutorial.
In the future, we may extend the multi-language features of learnr to accommodate dynamic localization.

### Store Customizations in a JSON File

If you intend to reuse the same custom language repeatedly, it may be helpful to store the custom language parameters in a JSON file and simply import the file.
In this case, you can set the language code item to the path to a single JSON file, written with the same structure as the YAML.

For example, you could write Spanish language customizations to `tutorial_es.json` with the following R code:

```{r eval=FALSE}
jsonlite::write_json(
  list(
    button = list(runcode = "Ejecutar"),
    text = list(startover = "Empezar de nuevo")
  ),
  path = "tutorial_es.json",
  auto_unbox = TRUE
)
```

You could then load customizations from this file by referencing it in the YAML header.

``` yaml
language:
  es: tutorial_es.json
```

Similarly, you can store the entire `language` list in a JSON file and provide the path to the JSON file to the `language` key.

```{r eval=FALSE}
jsonlite::write_json(
  list(
    en = list(
      button = list(runcode = "Run the code"),
      text = list(startover = "Restart the tutorial")
    ),
    es = list(
      button = list(runcode = "Ejecutar"),
      text = list(startover = "Empezar de nuevo")
    )
  ),
  path = "custom_language.json",
  auto_unbox = TRUE
)
```

The R code above writes the custom text for `en` and `es` languages into `custom_language.json`, which we then reference in the YAML header:

``` yaml
language: custom_language.json
```

## Complete Translations

Complete translations are provided by the internal function `i18n_translations()`.
To contribute a complete translation for a language not currently provided by learnr, please submit a pull request to [github.com/rstudio/learnr](https://github.com/rstudio/learnr) updating the list in `data-raw/i18n_translations.yml`, following the format described in that file.

Note that for the language to be available inside the alert boxes of learnr, you'll need to set the language to one of the [language codes used by bootbox](https://bootboxjs.com/v5.x/documentation.html)[^1].
If your language is not available for `bootbox`, then the buttons will default to English.

[^1]: `r knitr::combine_words(bb_langs_code, and = " or ")`
