diff --git a/_freeze/posts/tmap/index/execute-results/html.json b/_freeze/posts/tmap/index/execute-results/html.json new file mode 100644 index 0000000..f5f6dae --- /dev/null +++ b/_freeze/posts/tmap/index/execute-results/html.json @@ -0,0 +1,15 @@ +{ + "hash": "cd08df506bbb267085d3940755c8b699", + "result": { + "engine": "knitr", + "markdown": "---\ntitle: \"Pimping your {shiny} app with a JavaScript library : an example using sweetalert2\"\nauthor: \"Yohann Mansiaux\"\ndate: \"2024-04-30\"\ncategories: [shiny, javascript]\nimage: \"image.jpg\"\n---\n\n\n\n\n\n**You think that some of the components of `{shiny}` are not very functional or downright austere? Are you looking to implement some feature in your app but it is not available in the `{shiny}` toolbox? Take a look at JavaScript!** \n\nJavaScript is a very popular programming language that is often used to add features to web pages. With HTML and CSS, JavaScript is an essential language for web developers. The size of its user community means that if you are looking to implement a particular feature, there is a good chance that someone has already had the same need as you and has shared their code!\n\nAn other positive point (and essential for us in this case) : it is possible to integrate JavaScript libraries into a `{shiny}` application to add features that are not available by default. In addition to that, `{golem}` will help us to set everything up.\n\nNo more excuses to back down, let's go ! 🚀\n\n\n\n## TL;DR\n\n- Going further in `{shiny}` by integrating a JavaScript library is possible!\n - We take the example of sweetalert2, which allows to display alerts that are more visually appealing than the basic ones\n - `{golem}` has several functions to make it easier for us to integrate JavaScript libraries into a `{shiny}` app\n - This example is rather simple. The integration of libraries is sometimes harder because the documentation might be scarse or the library might be more complex to use \n\n## Import sweetalert2 into a `{shiny}` app created with `{golem}`\n\n### sweetalert2\n\n- sweetalert2 is a JavaScript library that allows you to display alerts that are more visually appealing than the basic ones\n- It is very well documented\n- It is very popular (more than 16000 \"stars\" on GitHub at the time of publication of this article)\n\nLet's take a look at the possibilities offered by sweetalert2: https://sweetalert2.github.io/\n\n\n\n\n\n::: {.cell}\n::: {.cell-output-display}\n![](./img/01-sweetalertaccueil.png){width=70%}\n:::\n:::\n\n\n\n\n\nIf you click on \"Show normal alert\", you will see a classic alert while clicking on \"Show success message\", you will see a sweetalert2 alert.\n\nThe first one has a rather austere design while the second one is more modern and more pleasant to the eye, it will probably offer a better user experience.\n\nFeel free to play with the different types of alerts offered by sweetalert2 to get an idea of what is possible with this library by visiting the examples section.\n\n### Add the necessary dependencies to the `{shiny}` app\n\n**The following sections assume that you have already created a `{shiny}` app with `{golem}`.**\n\nIf this is not the case and you want to know more about `{golem}`, I invite you to consult the official documentation.\n\nTo add sweetalert2 to your `{shiny}` app, you will need to find a way to incorporate the files needed for its operation into your application.\n\nTwo solutions are available to you:\n\n- Use a \"CDN\" (Content Delivery Network) to load the files from a third-party server. The CDN will be the equivalent of a CRAN for JavaScript libraries. Concretely, we will ask our application to point to the sources of sweetalert2, hosted on a remote server.\n\n- Download the files needed for its operation and integrate them directly into your application. If your application is intended to be used on a machine that is not connected to the Internet, you will inevitably have to go through this step.\n\n**Don't panic! We will see both methods**\n\n#### Where to find the elements I need?\n\nThe sweetalert2 documentation is very well done. You will find all the information you need to integrate the library into your application from the Download section.\n\nHowever, you will need to learn how to identify the elements you need to integrate sweetalert2 into your application.\n\n**Looking for the CDN**\n\nIn the \"Download & Install\" section, you will find a link to the sweetalert2 CDN. This is the link that we will have to add to our application in order to use the library.\n\n\n\n\n\n::: {.cell}\n::: {.cell-output-display}\n![](img/02-cdn.png){width=80%}\n:::\n:::\n\n\n\n\n\nWhen you click on the link, you will arrive on a page that looks like this:\n\n\n\n\n\n::: {.cell}\n::: {.cell-output-display}\n![](img/03-cdn_site.png){width=100%}\n:::\n:::\n\n\n\n\n\nWhat we are interested in here is the link in the ` + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ +
+
+
+

How Github Copilot and ChatGPT have changed my life as an R developer

+
+
shiny
+
javascript
+
+
+
+ + +
+ +
+
Author
+
+

Yohann Mansiaux

+
+
+ +
+
Published
+
+

November 9, 2024

+
+
+ + +
+ + +
+ + + + +
+ + + + + +

The world of development is evolving rapidly, and artificial intelligence (AI) is playing an increasingly crucial role in developers’ daily lives. With the rise of AI tools, R developers can now automate repetitive tasks, speed up their workflow, and even discover new methods for analysis and visualization.

+

I’ll focus on a specific AI tool that can significantly assist R developers: GitHub Copilot. Copilot offers a variety of features, from code generation to programming assistance, automatic documentation, and problem-solving.

+

I’ll also give a quick feedback about my usage of ChatGPT.

+
+

GitHub Copilot

+

GitHub Copilot is an AI tool that assists developers in their daily work by generating code and other code-related elements (such as documentation) based on context. Copilot can be used as an extension for VSCode. Since the release of version 2023.09.0, GitHub Copilot is also available in RStudio. Copilot can be used to generate R code, comments, unit tests, documentation, and more.

+
+

What Are the Prerequisites for Using GitHub Copilot?

+

To use GitHub Copilot, you need a GitHub account and a Copilot license. This tool is paid (see pricing options), but students, teachers, and maintainers of popular open-source projects can get a free license.

+
+
+

GitHub Copilot in RStudio

+

To use GitHub Copilot in RStudio, install the latest version of RStudio (2023.09.0 or later). Once installed, activate Copilot by going to Tools > Global Options > Copilot and checking the box Enable GitHub Copilot.

+

+

If you want Copilot to base its suggestions not only on the current file but also on other project files, check the box Index project files with GitHub Copilot.

+
+
+

GitHub Copilot in VSCode

+

To use GitHub Copilot in VSCode, install the GitHub Copilot extension. Once the extension is installed, enable Copilot by logging into your GitHub account.

+
+
+

GitHub Copilot in Positron

+

Currently, GitHub Copilot is not available in Positron.

+
+
+
+

GitHub Copilot for R Development

+

We’ll review GitHub Copilot’s features for R development. Some features are available in both RStudio and VSCode, while others can only be used in VSCode.

+
+

Code Completion: Writing Functions

+

Let’s say we’re developing an R package and want to write a function to clean text by removing spaces and special characters.

+

We start with a comment describing the function’s intent and provide an empty function skeleton:

+
# Function to clean text by removing spaces and special characters
+clean_text <- function(text) {  
+}
+

After a few seconds, Copilot suggests an implementation for clean_text. Suggestions appear in gray and can be accepted by pressing the Tab key.

+

+

The initial function comment isn’t mandatory, but it helps Copilot better understand the context and suggest more relevant code.

+

Code completion also works seamlessly in VSCode.

+

+

Interestingly, in both cases, a step to convert text to lowercase is suggested, even though I didn’t request it. This could be useful, but make sure this step fits your use case. Remember, Copilot isn’t perfect and may sometimes generate incorrect or inappropriate code. Always review and modify the generated code as necessary.

+

You can continue in RStudio to generate the function’s documentation with Roxygen tags, for instance. Again, starting with a comment indicating your intention allows Copilot to suggest documentation.

+

+

RStudio usage is limited to code completion, so we’ll switch to VSCode to showcase more advanced features and a fuller development experience.

+
+
+

How to Access GitHub Copilot Features in VSCode?

+

There are multiple ways to access Copilot’s interface in VSCode. Right-clicking on an open file allows you to access the Copilot option in the context menu. You can also use the shortcut Ctrl + Shift + P (on Windows) to open the command palette, then type Copilot to access the interface. Recently, a Copilot icon was also added to the VSCode toolbar.

+

+
+
+

Chat

+

Copilot can be used as a chatbot to get information on functions or packages, or to write code, as we did before.

+

+

+

Again, providing as much context as possible will lead to more relevant suggestions.

+

You can also use the chat to modify the code Copilot initially generated, for example, to change the packages used.

+

+
+
+

Code Explanation

+

Copilot can also explain code. For example, if you don’t understand some code, you can ask Copilot to explain it.

+

+

Note: This feature is also accessible via chat by typing “/explain”.

+
+
+

Code Correction

+

Following the same process, select the “Fix” option to detect errors in the code. Here, Copilot didn’t detect an error but suggested an enhancement. Our code didn’t initially trim leading and trailing spaces. Copilot offers a solution to fix this.

+

+

Note: This feature is also accessible via chat by typing “/fix”.

+
+
+

Code Review

+

The “Review and Comment” feature suggests improvements for style or performance.

+

+
+
+

Documentation

+

The “Generate Doc” feature creates a Roxygen documentation skeleton for the function. The generated documentation is often generic, so you’ll usually need to complete it, particularly for parameter explanations or reproducible examples. For instance, it may omit an @export tag, which could cause issues during a devtools::check() of your package!

+

+

Note: This feature is also accessible via chat by typing “/doc”.

+
+
+

Unit Tests

+

The “Generate Tests” option generates unit tests for the function. It works well but has the drawback of adding the test file in the package’s R/ folder. You’ll need to move the content into a chosen file in the testthat/tests/ folder.

+

Note: This feature is also accessible via chat by typing “/tests”.

+
+
+

What About {shiny}?

+

Though we’ve focused on R package development, Copilot can also be used to develop Shiny applications. For example, to generate a simple Shiny app, start with a comment describing the app, and let Copilot generate the code. This is very useful for quickly setting up a UI, but as always, you’ll need to refine the code to meet specific needs.

+

+

For a Shiny development assistant, you can also check out ShinyAssistant.

+
+
+

Summary of the R Developer Experience with GitHub Copilot

+

GitHub Copilot is a powerful tool that can greatly accelerate R package development. It can generate code, documentation, unit tests, and more. However, remember that Copilot isn’t perfect and can sometimes produce incorrect or unsuitable code. It’s essential to review and adjust the generated code as needed. It’s equally important to revise generated documentation and tests for accuracy and relevance.

+

To ensure sufficient unit tests, it’s recommended to check package coverage using the {covr} package.

+

Moreover, there’s no magic behind this tool—GitHub Copilot bases its suggestions on the current file’s content and other project files. The more precise the context, the more relevant the suggestions will be. Taking extra care with function and parameter names makes suggestions as suitable as possible (this is true for development even without Copilot!).

+
+
+
+

How can I use ChatGPT as an R developer?

+

I also often rely on ChatGPT for R-programming related tasks.

+

More often, I’ll use ChatGPT in advance of a task, to compare its suggestions with the way I would have approached the problem. This allows me to see if I’ve forgotten something, or if I couldn’t have done things differently.

+

I’ll also use his knowledge to give me information on a package I don’t know, or to give me examples of code. It’s a great complement to the official documentation.

+

In the same way, I’ll ask him to explain errors I encounter, or concepts I don’t understand.

+

Finally, as with Github Copilot, the key lies in the quality of the question asked. The more precise the question, the more relevant the answer.

+

I often tend to start my queries with: “I’m an R developer and I prefer using tidyverse packages. I’d like to know what I can do to…”. Telling him if you’re a user of specific packages can help refine the suggestions.

+

Explain how a conversational assistant can answer specific questions, help with debugging, generate code examples and provide detailed explanations of errors or package usage.

+
+

Did you know that some R-specific GPT’s are available?

+

I recently discovered that some R-specific GPT’s are available. They are trained on R-specific data and can provide more relevant answers to R-related questions. I haven’t had the opportunity to test them yet, but I’m looking forward to it.

+

Here is the way to access them:

+

+

+

+

Among the many R-specific GPT’s available, I recommend using R Wizard, which seems to be the most popular among R developers.

+ + +
+
+ +
+ +
+ + + + + \ No newline at end of file diff --git a/docs/posts/tmap/image.jpg b/docs/posts/tmap/image.jpg new file mode 100644 index 0000000..16093a1 Binary files /dev/null and b/docs/posts/tmap/image.jpg differ diff --git a/docs/posts/tmap/img/01-sweetalertaccueil.png b/docs/posts/tmap/img/01-sweetalertaccueil.png new file mode 100644 index 0000000..a7d6ac7 Binary files /dev/null and b/docs/posts/tmap/img/01-sweetalertaccueil.png differ diff --git a/docs/posts/tmap/img/02-cdn.png b/docs/posts/tmap/img/02-cdn.png new file mode 100644 index 0000000..3346844 Binary files /dev/null and b/docs/posts/tmap/img/02-cdn.png differ diff --git a/docs/posts/tmap/img/03-cdn_site.png b/docs/posts/tmap/img/03-cdn_site.png new file mode 100644 index 0000000..9072d50 Binary files /dev/null and b/docs/posts/tmap/img/03-cdn_site.png differ diff --git a/docs/posts/tmap/img/04-import_ok.png b/docs/posts/tmap/img/04-import_ok.png new file mode 100644 index 0000000..51af427 Binary files /dev/null and b/docs/posts/tmap/img/04-import_ok.png differ diff --git a/docs/posts/tmap/img/05-console_js.png b/docs/posts/tmap/img/05-console_js.png new file mode 100644 index 0000000..7487726 Binary files /dev/null and b/docs/posts/tmap/img/05-console_js.png differ diff --git a/docs/posts/tmap/img/06_swal_fire.png b/docs/posts/tmap/img/06_swal_fire.png new file mode 100644 index 0000000..78c9754 Binary files /dev/null and b/docs/posts/tmap/img/06_swal_fire.png differ diff --git a/docs/posts/tmap/img/07_exemple_alert1.png b/docs/posts/tmap/img/07_exemple_alert1.png new file mode 100644 index 0000000..fcd4850 Binary files /dev/null and b/docs/posts/tmap/img/07_exemple_alert1.png differ diff --git a/docs/posts/tmap/img/08_exemple_alert2.png b/docs/posts/tmap/img/08_exemple_alert2.png new file mode 100644 index 0000000..559d069 Binary files /dev/null and b/docs/posts/tmap/img/08_exemple_alert2.png differ diff --git a/docs/posts/tmap/img/09_demo.gif b/docs/posts/tmap/img/09_demo.gif new file mode 100644 index 0000000..cd5d41a Binary files /dev/null and b/docs/posts/tmap/img/09_demo.gif differ diff --git a/docs/posts/tmap/img/10_demo2.gif b/docs/posts/tmap/img/10_demo2.gif new file mode 100644 index 0000000..0b06cbb Binary files /dev/null and b/docs/posts/tmap/img/10_demo2.gif differ diff --git a/docs/posts/tmap/img/11_demo3.gif b/docs/posts/tmap/img/11_demo3.gif new file mode 100644 index 0000000..259907d Binary files /dev/null and b/docs/posts/tmap/img/11_demo3.gif differ diff --git a/docs/posts/tmap/index.html b/docs/posts/tmap/index.html new file mode 100644 index 0000000..91221ce --- /dev/null +++ b/docs/posts/tmap/index.html @@ -0,0 +1,988 @@ + + + + + + + + + + + +Pimping your {shiny} app with a JavaScript library : an example using sweetalert2 – Yohann’s blog + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ +
+
+
+

Pimping your {shiny} app with a JavaScript library : an example using sweetalert2

+
+
shiny
+
javascript
+
+
+
+ + +
+ +
+
Author
+
+

Yohann Mansiaux

+
+
+ +
+
Published
+
+

April 30, 2024

+
+
+ + +
+ + +
+ + + + +
+ + + + + +

You think that some of the components of {shiny} are not very functional or downright austere? Are you looking to implement some feature in your app but it is not available in the {shiny} toolbox? Take a look at JavaScript!

+

JavaScript is a very popular programming language that is often used to add features to web pages. With HTML and CSS, JavaScript is an essential language for web developers. The size of its user community means that if you are looking to implement a particular feature, there is a good chance that someone has already had the same need as you and has shared their code!

+

An other positive point (and essential for us in this case) : it is possible to integrate JavaScript libraries into a {shiny} application to add features that are not available by default. In addition to that, {golem} will help us to set everything up.

+

No more excuses to back down, let’s go ! 🚀

+
+

TL;DR

+
    +
  • Going further in {shiny} by integrating a JavaScript library is possible! +
      +
    • We take the example of sweetalert2, which allows to display alerts that are more visually appealing than the basic ones
    • +
    • {golem} has several functions to make it easier for us to integrate JavaScript libraries into a {shiny} app
    • +
    • This example is rather simple. The integration of libraries is sometimes harder because the documentation might be scarse or the library might be more complex to use
    • +
  • +
+
+
+

Import sweetalert2 into a {shiny} app created with {golem}

+
+

sweetalert2

+
    +
  • sweetalert2 is a JavaScript library that allows you to display alerts that are more visually appealing than the basic ones
  • +
  • It is very well documented
  • +
  • It is very popular (more than 16000 “stars” on GitHub at the time of publication of this article)
  • +
+

Let’s take a look at the possibilities offered by sweetalert2: https://sweetalert2.github.io/

+
+
+
+
+

+
+
+
+
+

If you click on “Show normal alert”, you will see a classic alert while clicking on “Show success message”, you will see a sweetalert2 alert.

+

The first one has a rather austere design while the second one is more modern and more pleasant to the eye, it will probably offer a better user experience.

+

Feel free to play with the different types of alerts offered by sweetalert2 to get an idea of what is possible with this library by visiting the examples section.

+
+
+

Add the necessary dependencies to the {shiny} app

+

The following sections assume that you have already created a {shiny} app with {golem}.

+

If this is not the case and you want to know more about {golem}, I invite you to consult the official documentation.

+

To add sweetalert2 to your {shiny} app, you will need to find a way to incorporate the files needed for its operation into your application.

+

Two solutions are available to you:

+
    +
  • Use a “CDN” (Content Delivery Network) to load the files from a third-party server. The CDN will be the equivalent of a CRAN for JavaScript libraries. Concretely, we will ask our application to point to the sources of sweetalert2, hosted on a remote server.

  • +
  • Download the files needed for its operation and integrate them directly into your application. If your application is intended to be used on a machine that is not connected to the Internet, you will inevitably have to go through this step.

  • +
+

Don’t panic! We will see both methods

+
+

Where to find the elements I need?

+

The sweetalert2 documentation is very well done. You will find all the information you need to integrate the library into your application from the Download section.

+

However, you will need to learn how to identify the elements you need to integrate sweetalert2 into your application.

+

Looking for the CDN

+

In the “Download & Install” section, you will find a link to the sweetalert2 CDN. This is the link that we will have to add to our application in order to use the library.

+
+
+
+
+

+
+
+
+
+

When you click on the link, you will arrive on a page that looks like this:

+
+
+
+
+

+
+
+
+
+

What we are interested in here is the link in the <script> tag and the link in the <link> tag. The link to the file with the .js extension corresponds to the sweetalert2 JavaScript file. The link to the file with the .css extension corresponds to the sweetalert2 styles file.

+

Copy them and let’s go back to our app!

+
+
+

Method 1: Add dependencies to sweetalert2 via the CDN

+

Let’s open the R/app_ui.R file of our application and add the two links we copied earlier to the body of the golem_add_external_resources() function.

+
golem_add_external_resources <- function() {
+  add_resource_path(
+    "www",
+    app_sys("app/www")
+  )
+
+  tags$head(
+    favicon(),
+    bundle_resources(
+      path = app_sys("app/www"),
+      app_title = "golemsweetalert"
+    ),
+    # sweetalert2
+    tags$script(src = "https://cdn.jsdelivr.net/npm/sweetalert2@11.10.7/dist/sweetalert2.all.min.js"),
+    tags$link(href = "https://cdn.jsdelivr.net/npm/sweetalert2@11.10.7/dist/sweetalert2.min.css",
+              rel="stylesheet")
+ 
+  )
+}
+

We find here a call to tags$script and a call to tags$link corresponding respectively to the <script> and <link> tags seen on the links provided by the CDN.

+

We copy-paste the elements being careful about the parameter names src, href and rel and remembering to separate them with commas. We are indeed moving from HTML code (where elements are separated by spaces) to R code.

+
+
+

Method 2: Add dependencies to sweetalert2 locally

+

The links identified earlier will also be useful to download the files needed to use sweetalert2.

+

The link to the JavaScript file will be passed to the golem::use_external_js_file() function while the link to the CSS file will be passed to the golem::use_external_css_file() function.

+

To keep a record of this, we will save the following commands in the dev/02_dev.R file in the “External resources” section.

+
golem::use_external_js_file("https://cdn.jsdelivr.net/npm/sweetalert2@11.10.7/dist/sweetalert2.all.min.js")
+golem::use_external_css_file("https://cdn.jsdelivr.net/npm/sweetalert2@11.10.7/dist/sweetalert2.min.css")
+

Both files are now present in the inst/app/www folder of our application project.

+
+
+
+
+

+
+
+
+
+

Everything is ok, we can continue our journey đź‘Ť.

+
+
+
+

How to know if sweetalert2 is correctly imported into my {shiny} app?

+

To check that sweetalert2 is correctly imported into our application, we open our browser and then the development console.

+

Before that, let’s launch our app with golem::run_dev()!

+

NB: The following screenshots were taken with the Google Chrome browser.

+

On the window of our application, we right-click and select “Inspect”. In the new window that opens, we choose the “Console” tab and then type the command Swal.fire("Hello sweetalert2!"). This console allows us to execute JavaScript code, which will be interpreted by our browser.

+

If everything went well, we should see a sweetalert2 alert appear! Otherwise, we might have an error message in red (which we will have to learn to decipher, as with an R console :-)).

+
+
+
+
+

+
+
+
+
+

It works! 🎉

+
+

How did I know I had to type Swal.fire(" .... ")?

+

Thanks to the documentation! By going to the sweetalert2 page, we find many examples of using the library. In this case, to display an alert, you have to use the Swal.fire() function. As for learning a new R package, we see that documentation (when it exists …) is of paramount importance for the handling of JavaScript libraries.

+
+
+
+
+

+
+
+
+
+
+
+
+
+

Create a sweetalert2 alert in our {shiny} app

+

Now that we have imported sweetalert2 into our application and checked that the import went well, we are going to create a function that will allow us to call sweetalert2 from our application.

+

We are going to try to incorporate the “A title with a text under” alert into our application.

+
+
+
+
+

+
+
+
+
+

Three elements can be set here: - The title of the alert - The text of the alert - The type of alert (success, error, warning, info, question) and its associated icon

+
+
+
+
+

+
+
+
+
+

We can easily imagine how to modify these elements directly in the JavaScript code but we don’t know yet how to create this alert via R code. Let’s go!

+
+

Create a JavaScript file to call sweetalert2

+

In order to call sweetalert2 from our application, we are going to create a JavaScript file in which we will write a function that will allow us to create an alert.

+

Let’s create a inst/app/www/sweet_alert.js file in which we will paste the code to create the alert selected earlier. We could have created this file manually, but we will take advantage of the features offered by {golem} to do so.

+

Let’s go to the dev/02_dev.R file! We add the following line in the “External Resources” section:

+
golem::add_js_handler("sweet_alert")
+

The file name doesn’t matter, but it is important to respect the .js extension so that the file is correctly interpreted as JavaScript code. We could have also created subfolders if we had had many imports and files to manage. The only prerequisite is that everything is located in the inst/app/www directory.

+

We obtain a slightly strange skeleton, which will in fact be the skeleton of a JavaScript function, usable in our {shiny} application:

+
$( document ).ready(function() {
+  Shiny.addCustomMessageHandler('fun', function(arg) {
+ 
+  })
+});
+

We are going to substitute the term 'fun' with the name of the function we want to call in our {shiny} application and add the code to create the sweetalert2 alert.

+

We therefore obtain the following code:

+
$( document ).ready(function() {
+  Shiny.addCustomMessageHandler('alert_title_and_text_under', function(arg) {
+    Swal.fire({
+      title: "The Internet?",
+      text: "That thing is still around?",
+      icon: "question"
+    });
+  })
+});
+

Our parameters “title”, “text” and “icon” are fixed, we need to find a way to make them vary according to the choices of the user. We can notice the existence of a “arg” parameter in the Shiny.addCustomMessageHandler() function. It is this parameter that will allow us to transmit information to our JavaScript function.

+

Let’s modify our code:

+
$( document ).ready(function() {
+  Shiny.addCustomMessageHandler('alert_title_and_text_under', function(arg) {
+    Swal.fire({
+      title: arg.title,
+      text: arg.text,
+      icon: arg.icon
+    });
+  })
+});
+

The notation to use here will be arg.parameter_name to access the values transmitted by our {shiny} application. The notation with the “.” is a JavaScript convention for accessing object properties. To make the parallel with R, it’s a bit like if we were doing arg$parameter_name.

+

Our JavaScript code is ready! Let’s move back to the R side!

+
+
+

What if we tested all this in our {shiny} app (FINALLY!)?

+

We are going to add a button in the R/app_ui.R file:

+
app_ui <- function(request) {
+  tagList(
+    # Leave this function for adding external resources
+    golem_add_external_resources(),
+    # Your application UI logic
+    fluidPage(
+      h1("golemsweetalert"),
+      actionButton(inputId = "show_alert",
+                   label = "Alert demo")
+    )
+  )
+}
+

On the server side, we add an observeEvent() in the R/app_server.R file, which will call our JavaScript function to generate an alert when the user clicks on the “Alert demo” button.

+

Once more, {golem} will make our life easier! We will use the golem::invoke_js() function to call our JavaScript function.

+

Two parameters are passed to golem::invoke_js():

+
    +
  • the first parameter corresponds to the name of the JavaScript function to call
  • +
  • the second parameter corresponds to a list of parameters, the JavaScript equivalent of our arg object which will be used to transmit the information necessary to create the sweetalert2 alert. The names used in the list here must correspond to the names used in the JavaScript function for the arg parameter (“title”, “text” and “icon”).
  • +
+
app_server <- function(input, output, session) {
+  # Your application server logic
+  observeEvent(
+    input$show_alert,{
+      golem::invoke_js(
+        "alert_title_and_text_under",
+        list(
+          title = "Title",
+          text = "Text",
+          icon = "success"
+        ))
+    }
+  )
+}
+

We run a call to golem::run_dev() to see our application in action!

+
+
+
+
+

+
+
+
+
+

Congratulations! đź‘Ź

+

To make everything more elegant, we can create an R function that will call golem::invoke_js().

+
+
+

Create an R function to call sweetalert2

+

We are going to go through {golem} to create our function. To do this, we will add the following line in the dev/02_dev.R file of our application:

+
golem::add_fct("create_alert_title_and_text_under")
+

We obtain a R/fct_create_alert_title_and_text_under.R file in which we will be able to write our function, which will call the JavaScript code created in the previous step.

+
#' create_alert_title_and_text_under
+#'
+#' @description Creates an alert with a title, a text and an icon
+#' @param title alert title
+#' @param text alert text
+#' @param icon alert icon
+#' @return side effect : creates an alert
+#'
+#' @noRd
+create_alert_title_and_text_under <- function(
+    title = "Title",
+    text = "Text",
+    icon = "success"
+    ) {
+  golem::invoke_js(
+    "alert_title_and_text_under",
+    list(
+      title = title,
+      text = text,
+      icon = icon
+    )
+  )
+}
+

Let’s modify both the R/app_ui.R and R/app_server.R files to be able to define the parameters of our alert through choices made by the user.

+
app_ui <- function(request) {
+  tagList(
+    # Leave this function for adding external resources
+    golem_add_external_resources(),
+    # Your application UI logic
+    fluidPage(
+      h1("golemsweetalert"),
+      textInput(inputId = "title",
+                label = "title"),
+      textInput(inputId = "text",
+                label = "text"),
+      radioButtons(inputId = "icon",
+                   label = "icon",
+                   choices = c("warning", "error", "success", "info", "question")),
+      actionButton(inputId = "show_alert",
+                   label = "Alert demo")
+    )
+  )
+}
+

To define the list of possible “choices” for the radioButtons, we took the possible values for the icon parameter of sweetalert2, as indicated in the official documentation: https://sweetalert2.github.io/#icon.

+
app_server <- function(input, output, session) {
+  # Your application server logic
+  observeEvent(
+    input$show_alert,{
+      create_alert_title_and_text_under(
+        title = input$title,
+        text = input$text,
+        icon = input$icon
+      )
+    }
+  )
+}
+

Let’s finally call golem::run_dev()!

+
+
+
+
+

+
+
+
+
+

Bravo ! đź‘Ź

+
+
+
+

And a more complex example?

+

Following the previous steps, it is relatively easy to add additional elements to an alert, such as an image or confirmation / cancellation buttons. A slightly deeper dive into the sweetalert2 documentation will help you understand how to add these elements.

+

Let’s see what is possible to achieve:

+
+
+
+
+

+
+
+
+
+

You are curious to know more? Go to this project source code.

+
+
+

Conclusion

+
    +
  • Integrating JavaScript libraries into a {shiny} application is possible!
  • +
  • {golem} makes it easier for us
  • +
  • It is quite easy when the library is well documented
  • +
  • It is important to read the documentation of the library you want to integrate (but this is also true in R!)
  • +
  • The browser inspector is a very useful tool to check that everything is going well
  • +
  • To integrate more complex libraries, minimal JavaScript skills will probably be required
  • +
+

If you want more examples of the use of sweetalert2, but also other JavaScript libraries (Grid.js and Chart.js), you can consult the mycomicslibrary application and take a look at its source code.

+

Thanks for reading this tutorial and have fun in the wonderful world of JavaScript! 🚀

+ + +
+ +
+ +
+ + + + + \ No newline at end of file diff --git a/docs/posts/vscodeR/index.html b/docs/posts/vscodeR/index.html index a1a00e2..6e88126 100644 --- a/docs/posts/vscodeR/index.html +++ b/docs/posts/vscodeR/index.html @@ -155,7 +155,7 @@

VSCode for R users

-

A few months ago, I switched from RStudio to Visual Studio Code for my R programming. I was a bit reluctant at first, but I am now convinced that it was a good move. Here are a few reasons why I think VSCode is a great tool for R users.

+

A few months ago, I switched from RStudio to Visual Studio Code for my R programming. I was a bit reluctant at first, but I am now convinced that it was a good move.

Currently I have 3 articles dedicated to VSCode for R users. They are only available in French for the moment.

I’ll update and translate them soon.

You can find them here:

diff --git a/docs/search.json b/docs/search.json index 7cd5882..bb1a013 100644 --- a/docs/search.json +++ b/docs/search.json @@ -11,7 +11,7 @@ "href": "index.html", "title": "blog", "section": "", - "text": "Welcome To My Blog\n\n\n\n\n\n\nnews\n\n\n\n\n\n\n\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nVSCode for R users\n\n\n\n\n\n\ndev\n\n\nvscode\n\n\n\n\n\n\n\n\n\nNov 9, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nInclude a demo dataset in a R package (video tutorial)\n\n\n\n\n\n\ndevelopment\n\n\npackage\n\n\n\n\n\n\n\n\n\nNov 6, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nBeyond Functions: How to Enrich an R Package with Data\n\n\n\n\n\n\ndevelopment\n\n\npackage\n\n\n\n\n\n\n\n\n\nOct 14, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nBoost your shiny app with sparkling data visualizations: A deep dive into Chart.js JavaScript library\n\n\n\n\n\n\nshiny\n\n\njavascript\n\n\n\n\n\n\n\n\n\nSep 3, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nPimping your {shiny} app with a JavaScript library : an example using sweetalert2\n\n\n\n\n\n\nshiny\n\n\njavascript\n\n\n\n\n\n\n\n\n\nApr 30, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\nNo matching items" + "text": "Welcome To My Blog\n\n\n\n\n\n\nnews\n\n\n\n\n\n\n\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nHow Github Copilot and ChatGPT have changed my life as an R developer\n\n\n\n\n\n\nshiny\n\n\njavascript\n\n\n\n\n\n\n\n\n\nNov 9, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nVSCode for R users\n\n\n\n\n\n\ndev\n\n\nvscode\n\n\n\n\n\n\n\n\n\nNov 7, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nInclude a demo dataset in a R package (video tutorial)\n\n\n\n\n\n\ndevelopment\n\n\npackage\n\n\n\n\n\n\n\n\n\nNov 6, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nBeyond Functions: How to Enrich an R Package with Data\n\n\n\n\n\n\ndevelopment\n\n\npackage\n\n\n\n\n\n\n\n\n\nOct 14, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nBoost your shiny app with sparkling data visualizations: A deep dive into Chart.js JavaScript library\n\n\n\n\n\n\nshiny\n\n\njavascript\n\n\n\n\n\n\n\n\n\nSep 3, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nPimping your {shiny} app with a JavaScript library : an example using sweetalert2\n\n\n\n\n\n\nshiny\n\n\njavascript\n\n\n\n\n\n\n\n\n\nApr 30, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\n\n\n\n\n\n\nPimping your {shiny} app with a JavaScript library : an example using sweetalert2\n\n\n\n\n\n\nshiny\n\n\njavascript\n\n\n\n\n\n\n\n\n\nApr 30, 2024\n\n\nYohann Mansiaux\n\n\n\n\n\n\nNo matching items" }, { "objectID": "about.html", @@ -207,6 +207,76 @@ "href": "posts/vscodeR/index.html", "title": "VSCode for R users", "section": "", - "text": "A few months ago, I switched from RStudio to Visual Studio Code for my R programming. I was a bit reluctant at first, but I am now convinced that it was a good move. Here are a few reasons why I think VSCode is a great tool for R users.\nCurrently I have 3 articles dedicated to VSCode for R users. They are only available in French for the moment.\nI’ll update and translate them soon.\nYou can find them here:\n\nFaire du R dans VSCode ? Même pas peur !\nPoursuivons notre route avec VSCode : les projets, les scripts, les notebooks … tout est là !\nCréer un package R et le versionner avec VSCode ? Mission possible !\n\nStay tuned!" + "text": "A few months ago, I switched from RStudio to Visual Studio Code for my R programming. I was a bit reluctant at first, but I am now convinced that it was a good move.\nCurrently I have 3 articles dedicated to VSCode for R users. They are only available in French for the moment.\nI’ll update and translate them soon.\nYou can find them here:\n\nFaire du R dans VSCode ? Même pas peur !\nPoursuivons notre route avec VSCode : les projets, les scripts, les notebooks … tout est là !\nCréer un package R et le versionner avec VSCode ? Mission possible !\n\nStay tuned!" + }, + { + "objectID": "posts/tmap/index.html", + "href": "posts/tmap/index.html", + "title": "Pimping your {shiny} app with a JavaScript library : an example using sweetalert2", + "section": "", + "text": "You think that some of the components of {shiny} are not very functional or downright austere? Are you looking to implement some feature in your app but it is not available in the {shiny} toolbox? Take a look at JavaScript!\nJavaScript is a very popular programming language that is often used to add features to web pages. With HTML and CSS, JavaScript is an essential language for web developers. The size of its user community means that if you are looking to implement a particular feature, there is a good chance that someone has already had the same need as you and has shared their code!\nAn other positive point (and essential for us in this case) : it is possible to integrate JavaScript libraries into a {shiny} application to add features that are not available by default. In addition to that, {golem} will help us to set everything up.\nNo more excuses to back down, let’s go ! 🚀" + }, + { + "objectID": "posts/tmap/index.html#tldr", + "href": "posts/tmap/index.html#tldr", + "title": "Pimping your {shiny} app with a JavaScript library : an example using sweetalert2", + "section": "TL;DR", + "text": "TL;DR\n\nGoing further in {shiny} by integrating a JavaScript library is possible!\n\nWe take the example of sweetalert2, which allows to display alerts that are more visually appealing than the basic ones\n{golem} has several functions to make it easier for us to integrate JavaScript libraries into a {shiny} app\nThis example is rather simple. The integration of libraries is sometimes harder because the documentation might be scarse or the library might be more complex to use" + }, + { + "objectID": "posts/tmap/index.html#import-sweetalert2-into-a-shiny-app-created-with-golem", + "href": "posts/tmap/index.html#import-sweetalert2-into-a-shiny-app-created-with-golem", + "title": "Pimping your {shiny} app with a JavaScript library : an example using sweetalert2", + "section": "Import sweetalert2 into a {shiny} app created with {golem}", + "text": "Import sweetalert2 into a {shiny} app created with {golem}\n\nsweetalert2\n\nsweetalert2 is a JavaScript library that allows you to display alerts that are more visually appealing than the basic ones\nIt is very well documented\nIt is very popular (more than 16000 “stars” on GitHub at the time of publication of this article)\n\nLet’s take a look at the possibilities offered by sweetalert2: https://sweetalert2.github.io/\n\n\n\n\n\n\n\n\n\nIf you click on “Show normal alert”, you will see a classic alert while clicking on “Show success message”, you will see a sweetalert2 alert.\nThe first one has a rather austere design while the second one is more modern and more pleasant to the eye, it will probably offer a better user experience.\nFeel free to play with the different types of alerts offered by sweetalert2 to get an idea of what is possible with this library by visiting the examples section.\n\n\nAdd the necessary dependencies to the {shiny} app\nThe following sections assume that you have already created a {shiny} app with {golem}.\nIf this is not the case and you want to know more about {golem}, I invite you to consult the official documentation.\nTo add sweetalert2 to your {shiny} app, you will need to find a way to incorporate the files needed for its operation into your application.\nTwo solutions are available to you:\n\nUse a “CDN” (Content Delivery Network) to load the files from a third-party server. The CDN will be the equivalent of a CRAN for JavaScript libraries. Concretely, we will ask our application to point to the sources of sweetalert2, hosted on a remote server.\nDownload the files needed for its operation and integrate them directly into your application. If your application is intended to be used on a machine that is not connected to the Internet, you will inevitably have to go through this step.\n\nDon’t panic! We will see both methods\n\nWhere to find the elements I need?\nThe sweetalert2 documentation is very well done. You will find all the information you need to integrate the library into your application from the Download section.\nHowever, you will need to learn how to identify the elements you need to integrate sweetalert2 into your application.\nLooking for the CDN\nIn the “Download & Install” section, you will find a link to the sweetalert2 CDN. This is the link that we will have to add to our application in order to use the library.\n\n\n\n\n\n\n\n\n\nWhen you click on the link, you will arrive on a page that looks like this:\n\n\n\n\n\n\n\n\n\nWhat we are interested in here is the link in the <script> tag and the link in the <link> tag. The link to the file with the .js extension corresponds to the sweetalert2 JavaScript file. The link to the file with the .css extension corresponds to the sweetalert2 styles file.\nCopy them and let’s go back to our app!\n\n\nMethod 1: Add dependencies to sweetalert2 via the CDN\nLet’s open the R/app_ui.R file of our application and add the two links we copied earlier to the body of the golem_add_external_resources() function.\ngolem_add_external_resources <- function() {\n add_resource_path(\n \"www\",\n app_sys(\"app/www\")\n )\n\n tags$head(\n favicon(),\n bundle_resources(\n path = app_sys(\"app/www\"),\n app_title = \"golemsweetalert\"\n ),\n # sweetalert2\n tags$script(src = \"https://cdn.jsdelivr.net/npm/sweetalert2@11.10.7/dist/sweetalert2.all.min.js\"),\n tags$link(href = \"https://cdn.jsdelivr.net/npm/sweetalert2@11.10.7/dist/sweetalert2.min.css\",\n rel=\"stylesheet\")\n \n )\n}\nWe find here a call to tags$script and a call to tags$link corresponding respectively to the <script> and <link> tags seen on the links provided by the CDN.\nWe copy-paste the elements being careful about the parameter names src, href and rel and remembering to separate them with commas. We are indeed moving from HTML code (where elements are separated by spaces) to R code.\n\n\nMethod 2: Add dependencies to sweetalert2 locally\nThe links identified earlier will also be useful to download the files needed to use sweetalert2.\nThe link to the JavaScript file will be passed to the golem::use_external_js_file() function while the link to the CSS file will be passed to the golem::use_external_css_file() function.\nTo keep a record of this, we will save the following commands in the dev/02_dev.R file in the “External resources” section.\ngolem::use_external_js_file(\"https://cdn.jsdelivr.net/npm/sweetalert2@11.10.7/dist/sweetalert2.all.min.js\")\ngolem::use_external_css_file(\"https://cdn.jsdelivr.net/npm/sweetalert2@11.10.7/dist/sweetalert2.min.css\")\nBoth files are now present in the inst/app/www folder of our application project.\n\n\n\n\n\n\n\n\n\nEverything is ok, we can continue our journey 👍.\n\n\n\nHow to know if sweetalert2 is correctly imported into my {shiny} app?\nTo check that sweetalert2 is correctly imported into our application, we open our browser and then the development console.\nBefore that, let’s launch our app with golem::run_dev()!\nNB: The following screenshots were taken with the Google Chrome browser.\nOn the window of our application, we right-click and select “Inspect”. In the new window that opens, we choose the “Console” tab and then type the command Swal.fire(\"Hello sweetalert2!\"). This console allows us to execute JavaScript code, which will be interpreted by our browser.\nIf everything went well, we should see a sweetalert2 alert appear! Otherwise, we might have an error message in red (which we will have to learn to decipher, as with an R console :-)).\n\n\n\n\n\n\n\n\n\nIt works! 🎉\n\nHow did I know I had to type Swal.fire(\" .... \")?\nThanks to the documentation! By going to the sweetalert2 page, we find many examples of using the library. In this case, to display an alert, you have to use the Swal.fire() function. As for learning a new R package, we see that documentation (when it exists …) is of paramount importance for the handling of JavaScript libraries." + }, + { + "objectID": "posts/tmap/index.html#create-a-sweetalert2-alert-in-our-shiny-app", + "href": "posts/tmap/index.html#create-a-sweetalert2-alert-in-our-shiny-app", + "title": "Pimping your {shiny} app with a JavaScript library : an example using sweetalert2", + "section": "Create a sweetalert2 alert in our {shiny} app", + "text": "Create a sweetalert2 alert in our {shiny} app\nNow that we have imported sweetalert2 into our application and checked that the import went well, we are going to create a function that will allow us to call sweetalert2 from our application.\nWe are going to try to incorporate the “A title with a text under” alert into our application.\n\n\n\n\n\n\n\n\n\nThree elements can be set here: - The title of the alert - The text of the alert - The type of alert (success, error, warning, info, question) and its associated icon\n\n\n\n\n\n\n\n\n\nWe can easily imagine how to modify these elements directly in the JavaScript code but we don’t know yet how to create this alert via R code. Let’s go!\n\nCreate a JavaScript file to call sweetalert2\nIn order to call sweetalert2 from our application, we are going to create a JavaScript file in which we will write a function that will allow us to create an alert.\nLet’s create a inst/app/www/sweet_alert.js file in which we will paste the code to create the alert selected earlier. We could have created this file manually, but we will take advantage of the features offered by {golem} to do so.\nLet’s go to the dev/02_dev.R file! We add the following line in the “External Resources” section:\ngolem::add_js_handler(\"sweet_alert\")\nThe file name doesn’t matter, but it is important to respect the .js extension so that the file is correctly interpreted as JavaScript code. We could have also created subfolders if we had had many imports and files to manage. The only prerequisite is that everything is located in the inst/app/www directory.\nWe obtain a slightly strange skeleton, which will in fact be the skeleton of a JavaScript function, usable in our {shiny} application:\n$( document ).ready(function() {\n Shiny.addCustomMessageHandler('fun', function(arg) {\n \n })\n});\nWe are going to substitute the term 'fun' with the name of the function we want to call in our {shiny} application and add the code to create the sweetalert2 alert.\nWe therefore obtain the following code:\n$( document ).ready(function() {\n Shiny.addCustomMessageHandler('alert_title_and_text_under', function(arg) {\n Swal.fire({\n title: \"The Internet?\",\n text: \"That thing is still around?\",\n icon: \"question\"\n });\n })\n});\nOur parameters “title”, “text” and “icon” are fixed, we need to find a way to make them vary according to the choices of the user. We can notice the existence of a “arg” parameter in the Shiny.addCustomMessageHandler() function. It is this parameter that will allow us to transmit information to our JavaScript function.\nLet’s modify our code:\n$( document ).ready(function() {\n Shiny.addCustomMessageHandler('alert_title_and_text_under', function(arg) {\n Swal.fire({\n title: arg.title,\n text: arg.text,\n icon: arg.icon\n });\n })\n});\nThe notation to use here will be arg.parameter_name to access the values transmitted by our {shiny} application. The notation with the “.” is a JavaScript convention for accessing object properties. To make the parallel with R, it’s a bit like if we were doing arg$parameter_name.\nOur JavaScript code is ready! Let’s move back to the R side!\n\n\nWhat if we tested all this in our {shiny} app (FINALLY!)?\nWe are going to add a button in the R/app_ui.R file:\napp_ui <- function(request) {\n tagList(\n # Leave this function for adding external resources\n golem_add_external_resources(),\n # Your application UI logic\n fluidPage(\n h1(\"golemsweetalert\"),\n actionButton(inputId = \"show_alert\",\n label = \"Alert demo\")\n )\n )\n}\nOn the server side, we add an observeEvent() in the R/app_server.R file, which will call our JavaScript function to generate an alert when the user clicks on the “Alert demo” button.\nOnce more, {golem} will make our life easier! We will use the golem::invoke_js() function to call our JavaScript function.\nTwo parameters are passed to golem::invoke_js():\n\nthe first parameter corresponds to the name of the JavaScript function to call\nthe second parameter corresponds to a list of parameters, the JavaScript equivalent of our arg object which will be used to transmit the information necessary to create the sweetalert2 alert. The names used in the list here must correspond to the names used in the JavaScript function for the arg parameter (“title”, “text” and “icon”).\n\napp_server <- function(input, output, session) {\n # Your application server logic\n observeEvent(\n input$show_alert,{\n golem::invoke_js(\n \"alert_title_and_text_under\",\n list(\n title = \"Title\",\n text = \"Text\",\n icon = \"success\"\n ))\n }\n )\n}\nWe run a call to golem::run_dev() to see our application in action!\n\n\n\n\n\n\n\n\n\nCongratulations! 👏\nTo make everything more elegant, we can create an R function that will call golem::invoke_js().\n\n\nCreate an R function to call sweetalert2\nWe are going to go through {golem} to create our function. To do this, we will add the following line in the dev/02_dev.R file of our application:\ngolem::add_fct(\"create_alert_title_and_text_under\")\nWe obtain a R/fct_create_alert_title_and_text_under.R file in which we will be able to write our function, which will call the JavaScript code created in the previous step.\n#' create_alert_title_and_text_under\n#'\n#' @description Creates an alert with a title, a text and an icon\n#' @param title alert title\n#' @param text alert text\n#' @param icon alert icon\n#' @return side effect : creates an alert\n#'\n#' @noRd\ncreate_alert_title_and_text_under <- function(\n title = \"Title\",\n text = \"Text\",\n icon = \"success\"\n ) {\n golem::invoke_js(\n \"alert_title_and_text_under\",\n list(\n title = title,\n text = text,\n icon = icon\n )\n )\n}\nLet’s modify both the R/app_ui.R and R/app_server.R files to be able to define the parameters of our alert through choices made by the user.\napp_ui <- function(request) {\n tagList(\n # Leave this function for adding external resources\n golem_add_external_resources(),\n # Your application UI logic\n fluidPage(\n h1(\"golemsweetalert\"),\n textInput(inputId = \"title\",\n label = \"title\"),\n textInput(inputId = \"text\",\n label = \"text\"),\n radioButtons(inputId = \"icon\",\n label = \"icon\",\n choices = c(\"warning\", \"error\", \"success\", \"info\", \"question\")),\n actionButton(inputId = \"show_alert\",\n label = \"Alert demo\")\n )\n )\n}\nTo define the list of possible “choices” for the radioButtons, we took the possible values for the icon parameter of sweetalert2, as indicated in the official documentation: https://sweetalert2.github.io/#icon.\napp_server <- function(input, output, session) {\n # Your application server logic\n observeEvent(\n input$show_alert,{\n create_alert_title_and_text_under(\n title = input$title,\n text = input$text,\n icon = input$icon\n )\n }\n )\n}\nLet’s finally call golem::run_dev()!\n\n\n\n\n\n\n\n\n\nBravo ! 👏" + }, + { + "objectID": "posts/tmap/index.html#and-a-more-complex-example", + "href": "posts/tmap/index.html#and-a-more-complex-example", + "title": "Pimping your {shiny} app with a JavaScript library : an example using sweetalert2", + "section": "And a more complex example?", + "text": "And a more complex example?\nFollowing the previous steps, it is relatively easy to add additional elements to an alert, such as an image or confirmation / cancellation buttons. A slightly deeper dive into the sweetalert2 documentation will help you understand how to add these elements.\nLet’s see what is possible to achieve:\n\n\n\n\n\n\n\n\n\nYou are curious to know more? Go to this project source code." + }, + { + "objectID": "posts/tmap/index.html#conclusion", + "href": "posts/tmap/index.html#conclusion", + "title": "Pimping your {shiny} app with a JavaScript library : an example using sweetalert2", + "section": "Conclusion", + "text": "Conclusion\n\nIntegrating JavaScript libraries into a {shiny} application is possible!\n{golem} makes it easier for us\nIt is quite easy when the library is well documented\nIt is important to read the documentation of the library you want to integrate (but this is also true in R!)\nThe browser inspector is a very useful tool to check that everything is going well\nTo integrate more complex libraries, minimal JavaScript skills will probably be required\n\nIf you want more examples of the use of sweetalert2, but also other JavaScript libraries (Grid.js and Chart.js), you can consult the mycomicslibrary application and take a look at its source code.\nThanks for reading this tutorial and have fun in the wonderful world of JavaScript! 🚀" + }, + { + "objectID": "posts/iaforr/index.html", + "href": "posts/iaforr/index.html", + "title": "How Github Copilot and ChatGPT have changed my life as an R developer", + "section": "", + "text": "The world of development is evolving rapidly, and artificial intelligence (AI) is playing an increasingly crucial role in developers’ daily lives. With the rise of AI tools, R developers can now automate repetitive tasks, speed up their workflow, and even discover new methods for analysis and visualization.\nI’ll focus on a specific AI tool that can significantly assist R developers: GitHub Copilot. Copilot offers a variety of features, from code generation to programming assistance, automatic documentation, and problem-solving.\nI’ll also give a quick feedback about my usage of ChatGPT." + }, + { + "objectID": "posts/iaforr/index.html#github-copilot", + "href": "posts/iaforr/index.html#github-copilot", + "title": "How Github Copilot and ChatGPT have changed my life as an R developer", + "section": "GitHub Copilot", + "text": "GitHub Copilot\nGitHub Copilot is an AI tool that assists developers in their daily work by generating code and other code-related elements (such as documentation) based on context. Copilot can be used as an extension for VSCode. Since the release of version 2023.09.0, GitHub Copilot is also available in RStudio. Copilot can be used to generate R code, comments, unit tests, documentation, and more.\n\nWhat Are the Prerequisites for Using GitHub Copilot?\nTo use GitHub Copilot, you need a GitHub account and a Copilot license. This tool is paid (see pricing options), but students, teachers, and maintainers of popular open-source projects can get a free license.\n\n\nGitHub Copilot in RStudio\nTo use GitHub Copilot in RStudio, install the latest version of RStudio (2023.09.0 or later). Once installed, activate Copilot by going to Tools > Global Options > Copilot and checking the box Enable GitHub Copilot.\n\nIf you want Copilot to base its suggestions not only on the current file but also on other project files, check the box Index project files with GitHub Copilot.\n\n\nGitHub Copilot in VSCode\nTo use GitHub Copilot in VSCode, install the GitHub Copilot extension. Once the extension is installed, enable Copilot by logging into your GitHub account.\n\n\nGitHub Copilot in Positron\nCurrently, GitHub Copilot is not available in Positron." + }, + { + "objectID": "posts/iaforr/index.html#github-copilot-for-r-development", + "href": "posts/iaforr/index.html#github-copilot-for-r-development", + "title": "How Github Copilot and ChatGPT have changed my life as an R developer", + "section": "GitHub Copilot for R Development", + "text": "GitHub Copilot for R Development\nWe’ll review GitHub Copilot’s features for R development. Some features are available in both RStudio and VSCode, while others can only be used in VSCode.\n\nCode Completion: Writing Functions\nLet’s say we’re developing an R package and want to write a function to clean text by removing spaces and special characters.\nWe start with a comment describing the function’s intent and provide an empty function skeleton:\n# Function to clean text by removing spaces and special characters\nclean_text <- function(text) { \n}\nAfter a few seconds, Copilot suggests an implementation for clean_text. Suggestions appear in gray and can be accepted by pressing the Tab key.\n\nThe initial function comment isn’t mandatory, but it helps Copilot better understand the context and suggest more relevant code.\nCode completion also works seamlessly in VSCode.\n\nInterestingly, in both cases, a step to convert text to lowercase is suggested, even though I didn’t request it. This could be useful, but make sure this step fits your use case. Remember, Copilot isn’t perfect and may sometimes generate incorrect or inappropriate code. Always review and modify the generated code as necessary.\nYou can continue in RStudio to generate the function’s documentation with Roxygen tags, for instance. Again, starting with a comment indicating your intention allows Copilot to suggest documentation.\n\nRStudio usage is limited to code completion, so we’ll switch to VSCode to showcase more advanced features and a fuller development experience.\n\n\nHow to Access GitHub Copilot Features in VSCode?\nThere are multiple ways to access Copilot’s interface in VSCode. Right-clicking on an open file allows you to access the Copilot option in the context menu. You can also use the shortcut Ctrl + Shift + P (on Windows) to open the command palette, then type Copilot to access the interface. Recently, a Copilot icon was also added to the VSCode toolbar.\n\n\n\nChat\nCopilot can be used as a chatbot to get information on functions or packages, or to write code, as we did before.\n\n\nAgain, providing as much context as possible will lead to more relevant suggestions.\nYou can also use the chat to modify the code Copilot initially generated, for example, to change the packages used.\n\n\n\nCode Explanation\nCopilot can also explain code. For example, if you don’t understand some code, you can ask Copilot to explain it.\n \nNote: This feature is also accessible via chat by typing “/explain”.\n\n\nCode Correction\nFollowing the same process, select the “Fix” option to detect errors in the code. Here, Copilot didn’t detect an error but suggested an enhancement. Our code didn’t initially trim leading and trailing spaces. Copilot offers a solution to fix this.\n\nNote: This feature is also accessible via chat by typing “/fix”.\n\n\nCode Review\nThe “Review and Comment” feature suggests improvements for style or performance.\n\n\n\nDocumentation\nThe “Generate Doc” feature creates a Roxygen documentation skeleton for the function. The generated documentation is often generic, so you’ll usually need to complete it, particularly for parameter explanations or reproducible examples. For instance, it may omit an @export tag, which could cause issues during a devtools::check() of your package!\n\nNote: This feature is also accessible via chat by typing “/doc”.\n\n\nUnit Tests\nThe “Generate Tests” option generates unit tests for the function. It works well but has the drawback of adding the test file in the package’s R/ folder. You’ll need to move the content into a chosen file in the testthat/tests/ folder.\nNote: This feature is also accessible via chat by typing “/tests”.\n\n\nWhat About {shiny}?\nThough we’ve focused on R package development, Copilot can also be used to develop Shiny applications. For example, to generate a simple Shiny app, start with a comment describing the app, and let Copilot generate the code. This is very useful for quickly setting up a UI, but as always, you’ll need to refine the code to meet specific needs.\n \nFor a Shiny development assistant, you can also check out ShinyAssistant.\n\n\nSummary of the R Developer Experience with GitHub Copilot\nGitHub Copilot is a powerful tool that can greatly accelerate R package development. It can generate code, documentation, unit tests, and more. However, remember that Copilot isn’t perfect and can sometimes produce incorrect or unsuitable code. It’s essential to review and adjust the generated code as needed. It’s equally important to revise generated documentation and tests for accuracy and relevance.\nTo ensure sufficient unit tests, it’s recommended to check package coverage using the {covr} package.\nMoreover, there’s no magic behind this tool—GitHub Copilot bases its suggestions on the current file’s content and other project files. The more precise the context, the more relevant the suggestions will be. Taking extra care with function and parameter names makes suggestions as suitable as possible (this is true for development even without Copilot!)." + }, + { + "objectID": "posts/iaforr/index.html#how-can-i-use-chatgpt-as-an-r-developer", + "href": "posts/iaforr/index.html#how-can-i-use-chatgpt-as-an-r-developer", + "title": "How Github Copilot and ChatGPT have changed my life as an R developer", + "section": "How can I use ChatGPT as an R developer?", + "text": "How can I use ChatGPT as an R developer?\nI also often rely on ChatGPT for R-programming related tasks.\nMore often, I’ll use ChatGPT in advance of a task, to compare its suggestions with the way I would have approached the problem. This allows me to see if I’ve forgotten something, or if I couldn’t have done things differently.\nI’ll also use his knowledge to give me information on a package I don’t know, or to give me examples of code. It’s a great complement to the official documentation.\nIn the same way, I’ll ask him to explain errors I encounter, or concepts I don’t understand.\nFinally, as with Github Copilot, the key lies in the quality of the question asked. The more precise the question, the more relevant the answer.\nI often tend to start my queries with: “I’m an R developer and I prefer using tidyverse packages. I’d like to know what I can do to…”. Telling him if you’re a user of specific packages can help refine the suggestions.\nExplain how a conversational assistant can answer specific questions, help with debugging, generate code examples and provide detailed explanations of errors or package usage.\n\nDid you know that some R-specific GPT’s are available?\nI recently discovered that some R-specific GPT’s are available. They are trained on R-specific data and can provide more relevant answers to R-related questions. I haven’t had the opportunity to test them yet, but I’m looking forward to it.\nHere is the way to access them:\n\n\n\nAmong the many R-specific GPT’s available, I recommend using R Wizard, which seems to be the most popular among R developers." } ] \ No newline at end of file diff --git a/posts/datainpkgs_video/index.qmd b/posts/datainpkgs_video/index.qmd index 99a2385..3dd560d 100644 --- a/posts/datainpkgs_video/index.qmd +++ b/posts/datainpkgs_video/index.qmd @@ -6,7 +6,7 @@ categories: [development, package] image: "image.jpg" --- -Didn't have time to read [my article on adding data to an R package](https://ymansiaux.github.io/yohann-data/datainpkgs)? +Didn't have time to read [my article on adding data to an R package](https://ymansiaux.github.io/yohann-data/posts/datainpkgs/)? Don't worry! Here's a short video to sum it all up: diff --git a/posts/iaforr/image.jpg b/posts/iaforr/image.jpg new file mode 100644 index 0000000..b31823d Binary files /dev/null and b/posts/iaforr/image.jpg differ diff --git a/posts/iaforr/img/01-copilot_rstudio.png b/posts/iaforr/img/01-copilot_rstudio.png new file mode 100644 index 0000000..a93f5e6 Binary files /dev/null and b/posts/iaforr/img/01-copilot_rstudio.png differ diff --git a/posts/iaforr/img/02-copilot_suggestion.png b/posts/iaforr/img/02-copilot_suggestion.png new file mode 100644 index 0000000..dafb755 Binary files /dev/null and b/posts/iaforr/img/02-copilot_suggestion.png differ diff --git a/posts/iaforr/img/03-copilot_suggestion_vscode.png b/posts/iaforr/img/03-copilot_suggestion_vscode.png new file mode 100644 index 0000000..d3bfe83 Binary files /dev/null and b/posts/iaforr/img/03-copilot_suggestion_vscode.png differ diff --git a/posts/iaforr/img/04-copilot_suggestion_doc_rstudio.png b/posts/iaforr/img/04-copilot_suggestion_doc_rstudio.png new file mode 100644 index 0000000..677122d Binary files /dev/null and b/posts/iaforr/img/04-copilot_suggestion_doc_rstudio.png differ diff --git a/posts/iaforr/img/05-copilot_vscode.png b/posts/iaforr/img/05-copilot_vscode.png new file mode 100644 index 0000000..47aa43d Binary files /dev/null and b/posts/iaforr/img/05-copilot_vscode.png differ diff --git a/posts/iaforr/img/06-copilot_vscode2.png b/posts/iaforr/img/06-copilot_vscode2.png new file mode 100644 index 0000000..902103a Binary files /dev/null and b/posts/iaforr/img/06-copilot_vscode2.png differ diff --git a/posts/iaforr/img/07-copilot_chat.png b/posts/iaforr/img/07-copilot_chat.png new file mode 100644 index 0000000..2108f8d Binary files /dev/null and b/posts/iaforr/img/07-copilot_chat.png differ diff --git a/posts/iaforr/img/08-bis_copilot_chat_result2.png b/posts/iaforr/img/08-bis_copilot_chat_result2.png new file mode 100644 index 0000000..7baeec1 Binary files /dev/null and b/posts/iaforr/img/08-bis_copilot_chat_result2.png differ diff --git a/posts/iaforr/img/08-copilot_chat_result.png b/posts/iaforr/img/08-copilot_chat_result.png new file mode 100644 index 0000000..0e52066 Binary files /dev/null and b/posts/iaforr/img/08-copilot_chat_result.png differ diff --git a/posts/iaforr/img/09-copilot_explain.png b/posts/iaforr/img/09-copilot_explain.png new file mode 100644 index 0000000..bb65d9f Binary files /dev/null and b/posts/iaforr/img/09-copilot_explain.png differ diff --git a/posts/iaforr/img/10-copilot_explain_result.png b/posts/iaforr/img/10-copilot_explain_result.png new file mode 100644 index 0000000..10622b8 Binary files /dev/null and b/posts/iaforr/img/10-copilot_explain_result.png differ diff --git a/posts/iaforr/img/11-copilot_fix.png b/posts/iaforr/img/11-copilot_fix.png new file mode 100644 index 0000000..dce410a Binary files /dev/null and b/posts/iaforr/img/11-copilot_fix.png differ diff --git a/posts/iaforr/img/12-copilot_fix_result.png b/posts/iaforr/img/12-copilot_fix_result.png new file mode 100644 index 0000000..151382a Binary files /dev/null and b/posts/iaforr/img/12-copilot_fix_result.png differ diff --git a/posts/iaforr/img/13-copilot_review.png b/posts/iaforr/img/13-copilot_review.png new file mode 100644 index 0000000..56571ef Binary files /dev/null and b/posts/iaforr/img/13-copilot_review.png differ diff --git a/posts/iaforr/img/14-copilot_doc.png b/posts/iaforr/img/14-copilot_doc.png new file mode 100644 index 0000000..74828e9 Binary files /dev/null and b/posts/iaforr/img/14-copilot_doc.png differ diff --git a/posts/iaforr/img/15-copilot_tests.png b/posts/iaforr/img/15-copilot_tests.png new file mode 100644 index 0000000..8409258 Binary files /dev/null and b/posts/iaforr/img/15-copilot_tests.png differ diff --git a/posts/iaforr/img/16-shiny_app.png b/posts/iaforr/img/16-shiny_app.png new file mode 100644 index 0000000..fe64c39 Binary files /dev/null and b/posts/iaforr/img/16-shiny_app.png differ diff --git a/posts/iaforr/img/17-shiny_app2.png b/posts/iaforr/img/17-shiny_app2.png new file mode 100644 index 0000000..fa630de Binary files /dev/null and b/posts/iaforr/img/17-shiny_app2.png differ diff --git a/posts/iaforr/img/18-othergpt.png b/posts/iaforr/img/18-othergpt.png new file mode 100644 index 0000000..797af06 Binary files /dev/null and b/posts/iaforr/img/18-othergpt.png differ diff --git a/posts/iaforr/img/19-rgpt.png b/posts/iaforr/img/19-rgpt.png new file mode 100644 index 0000000..2b877df Binary files /dev/null and b/posts/iaforr/img/19-rgpt.png differ diff --git a/posts/iaforr/img/20-rwizard.png b/posts/iaforr/img/20-rwizard.png new file mode 100644 index 0000000..88cc147 Binary files /dev/null and b/posts/iaforr/img/20-rwizard.png differ diff --git a/posts/iaforr/index.qmd b/posts/iaforr/index.qmd new file mode 100644 index 0000000..bdc979e --- /dev/null +++ b/posts/iaforr/index.qmd @@ -0,0 +1,192 @@ +--- +title: "How Github Copilot and ChatGPT have changed my life as an R developer" +author: "Yohann Mansiaux" +date: "2024-11-09" +categories: [shiny, javascript] +image: "image.jpg" +--- + + +The world of development is evolving rapidly, and artificial intelligence (AI) is playing an increasingly crucial role in developers' daily lives. With the rise of AI tools, R developers can now automate repetitive tasks, speed up their workflow, and even discover new methods for analysis and visualization. + +I'll focus on a specific AI tool that can significantly assist R developers: GitHub Copilot. Copilot offers a variety of features, from code generation to programming assistance, automatic documentation, and problem-solving. + +I'll also give a quick feedback about my usage of ChatGPT. + +## GitHub Copilot + +GitHub Copilot is an AI tool that assists developers in their daily work by generating code and other code-related elements (such as documentation) based on context. Copilot can be used as an extension for VSCode. Since the release of version 2023.09.0, GitHub Copilot is also available in RStudio. Copilot can be used to generate R code, comments, unit tests, documentation, and more. + +### What Are the Prerequisites for Using GitHub Copilot? + +To use GitHub Copilot, you need a GitHub account and a Copilot license. This tool is paid ([see pricing options](https://github.com/features/copilot/plans)), but students, teachers, and maintainers of popular open-source projects can get a free license. + +### GitHub Copilot in RStudio + +To use GitHub Copilot in RStudio, install the latest version of RStudio (2023.09.0 or later). Once installed, activate Copilot by going to `Tools > Global Options > Copilot` and checking the box `Enable GitHub Copilot`. + +![](img/01-copilot_rstudio.png) + +If you want Copilot to base its suggestions not only on the current file but also on other project files, check the box `Index project files with GitHub Copilot`. + +### GitHub Copilot in VSCode + +To use GitHub Copilot in VSCode, install the GitHub Copilot extension. Once the extension is installed, enable Copilot by logging into your GitHub account. + +### GitHub Copilot in Positron + +Currently, GitHub Copilot is not available in Positron. + +## GitHub Copilot for R Development + +We’ll review GitHub Copilot's features for R development. Some features are available in both RStudio and VSCode, while others can only be used in VSCode. + +### Code Completion: Writing Functions + +Let’s say we’re developing an R package and want to write a function to clean text by removing spaces and special characters. + +We start with a comment describing the function’s intent and provide an empty function skeleton: + +```r +# Function to clean text by removing spaces and special characters +clean_text <- function(text) { +} +``` + +After a few seconds, Copilot suggests an implementation for `clean_text`. Suggestions appear in gray and can be accepted by pressing the `Tab` key. + +![](img/02-copilot_suggestion.png) + +The initial function comment isn’t mandatory, but it helps Copilot better understand the context and suggest more relevant code. + +Code completion also works seamlessly in VSCode. + +![](img/03-copilot_suggestion_vscode.png) + +Interestingly, in both cases, a step to convert text to lowercase is suggested, even though I didn’t request it. This could be useful, but make sure this step fits your use case. Remember, Copilot isn’t perfect and may sometimes generate incorrect or inappropriate code. Always review and modify the generated code as necessary. + +You can continue in RStudio to generate the function’s documentation with Roxygen tags, for instance. Again, starting with a comment indicating your intention allows Copilot to suggest documentation. + +![](img/04-copilot_suggestion_doc_rstudio.png) + +RStudio usage is limited to code completion, so we’ll switch to VSCode to showcase more advanced features and a fuller development experience. + +### How to Access GitHub Copilot Features in VSCode? + +There are multiple ways to access Copilot’s interface in VSCode. Right-clicking on an open file allows you to access the `Copilot` option in the context menu. You can also use the shortcut `Ctrl + Shift + P` (on Windows) to open the command palette, then type `Copilot` to access the interface. Recently, a Copilot icon was also added to the VSCode toolbar. + +![](img/06-copilot_vscode2.png) + +### Chat + +Copilot can be used as a chatbot to get information on functions or packages, or to write code, as we did before. + +![](img/07-copilot_chat.png) + +![](img/08-copilot_chat_result.png) + +Again, providing as much context as possible will lead to more relevant suggestions. + +You can also use the chat to modify the code Copilot initially generated, for example, to change the packages used. + +![](img/08-bis_copilot_chat_result2.png) + +### Code Explanation + +Copilot can also explain code. For example, if you don’t understand some code, you can ask Copilot to explain it. + +![](img/09-copilot_explain.png) +![](img/10-copilot_explain_result.png) + +Note: This feature is also accessible via chat by typing "/explain". + +### Code Correction + +Following the same process, select the "Fix" option to detect errors in the code. Here, Copilot didn’t detect an error but suggested an enhancement. Our code didn’t initially trim leading and trailing spaces. Copilot offers a solution to fix this. + +![](img/12-copilot_fix_result.png) + +Note: This feature is also accessible via chat by typing "/fix". + +### Code Review + +The "Review and Comment" feature suggests improvements for style or performance. + +![](img/13-copilot_review.png) + +### Documentation + +The "Generate Doc" feature creates a Roxygen documentation skeleton for the function. The generated documentation is often generic, so you’ll usually need to complete it, particularly for parameter explanations or reproducible examples. For instance, it may omit an `@export` tag, which could cause issues during a `devtools::check()` of your package! + +![](img/14-copilot_doc.png) + +Note: This feature is also accessible via chat by typing "/doc". + +### Unit Tests + +The "Generate Tests" option generates unit tests for the function. It works well but has the drawback of adding the test file in the package’s `R/` folder. You’ll need to move the content into a chosen file in the `testthat/tests/` folder. + +Note: This feature is also accessible via chat by typing "/tests". + +### What About `{shiny}`? + +Though we’ve focused on R package development, Copilot can also be used to develop Shiny applications. For example, to generate a simple Shiny app, start with a comment describing the app, and let Copilot generate the code. This is very useful for quickly setting up a UI, but as always, you’ll need to refine the code to meet specific needs. + +![](img/16-shiny_app.png) +![](img/17-shiny_app2.png) + +For a Shiny development assistant, you can also check out [ShinyAssistant](https://shiny.posit.co/blog/posts/shiny-assistant/). + +### Summary of the R Developer Experience with GitHub Copilot + +GitHub Copilot is a powerful tool that can greatly accelerate R package development. It can generate code, documentation, unit tests, and more. However, remember that Copilot isn’t perfect and can sometimes produce incorrect or unsuitable code. It’s essential to review and adjust the generated code as needed. It’s equally important to revise generated documentation and tests for accuracy and relevance. + +To ensure sufficient unit tests, it’s recommended to check package coverage using the `{covr}` package. + +Moreover, there’s no magic behind this tool—GitHub Copilot bases its suggestions on the current file’s content and other project files. The more precise the context, the more relevant the suggestions will be. Taking extra care with function and parameter names makes suggestions as suitable as possible (this is true for development even without Copilot!). + + +## How can I use ChatGPT as an R developer? + +I also often rely on ChatGPT for R-programming related tasks. + +More often, I'll use ChatGPT in advance of a task, to compare its suggestions with the way I would have approached the problem. This allows me to see if I've forgotten something, or if I couldn't have done things differently. + +I'll also use his knowledge to give me information on a package I don't know, or to give me examples of code. It's a great complement to the official documentation. + +In the same way, I'll ask him to explain errors I encounter, or concepts I don't understand. + +Finally, as with Github Copilot, the key lies in the quality of the question asked. The more precise the question, the more relevant the answer. + +I often tend to start my queries with: "I'm an R developer and I prefer using tidyverse packages. I'd like to know what I can do to...". Telling him if you're a user of specific packages can help refine the suggestions. + +Explain how a conversational assistant can answer specific questions, help with debugging, generate code examples and provide detailed explanations of errors or package usage. + +### Did you know that some R-specific GPT's are available? + +I recently discovered that some R-specific GPT's are available. They are trained on R-specific data and can provide more relevant answers to R-related questions. I haven't had the opportunity to test them yet, but I'm looking forward to it. + +Here is the way to access them: + +You should click on "Explore GPTs" in the ChatGPT interface, then type "R programming" in the search menu. + +![](img/18-othergpt.png) + +![](img/19-rgpt.png) + +![](img/20-rwizard.png) + +Among the many R-specific GPT's available, I recommend using R Wizard, which seems to be the most popular among R developers. + +## Conclusion + +For R programmers, GitHub Copilot and ChatGPT can complement each other effectively. Copilot shines for in-context code generation, while ChatGPT is ideal for answering questions, exploring R libraries, and understanding errors. By combining these tools, R developers can boost productivity, streamline repetitive coding tasks, and expand their knowledge—all while enhancing their coding efficiency and accuracy. + +The main takeaway is that these tools are here to help you, not replace you. They can save you time and provide new insights, but they can't replace your expertise and creativity. Always review the generated code, documentation, and tests to ensure they meet your project’s requirements. Have fun ! + +## Ressources + +- [Github Copilot documentation](https://docs.github.com/en/copilot) +- [Github Copilot in RStudio](https://docs.posit.co/ide/user/ide/guide/tools/copilot.html) +- [VSCode extension for Github Copilot](https://marketplace.visualstudio.com/items?itemName=GitHub.copilot) +- [R Wizard GPT](https://chatgpt.com/g/g-TgjKDuQwZ-r-wizard) \ No newline at end of file diff --git a/posts/tmap/image.jpg b/posts/tmap/image.jpg new file mode 100644 index 0000000..16093a1 Binary files /dev/null and b/posts/tmap/image.jpg differ diff --git a/posts/tmap/img/01-sweetalertaccueil.png b/posts/tmap/img/01-sweetalertaccueil.png new file mode 100644 index 0000000..a7d6ac7 Binary files /dev/null and b/posts/tmap/img/01-sweetalertaccueil.png differ diff --git a/posts/tmap/img/02-cdn.png b/posts/tmap/img/02-cdn.png new file mode 100644 index 0000000..3346844 Binary files /dev/null and b/posts/tmap/img/02-cdn.png differ diff --git a/posts/tmap/img/03-cdn_site.png b/posts/tmap/img/03-cdn_site.png new file mode 100644 index 0000000..9072d50 Binary files /dev/null and b/posts/tmap/img/03-cdn_site.png differ diff --git a/posts/tmap/img/04-import_ok.png b/posts/tmap/img/04-import_ok.png new file mode 100644 index 0000000..51af427 Binary files /dev/null and b/posts/tmap/img/04-import_ok.png differ diff --git a/posts/tmap/img/05-console_js.png b/posts/tmap/img/05-console_js.png new file mode 100644 index 0000000..7487726 Binary files /dev/null and b/posts/tmap/img/05-console_js.png differ diff --git a/posts/tmap/img/06_swal_fire.png b/posts/tmap/img/06_swal_fire.png new file mode 100644 index 0000000..78c9754 Binary files /dev/null and b/posts/tmap/img/06_swal_fire.png differ diff --git a/posts/tmap/img/07_exemple_alert1.png b/posts/tmap/img/07_exemple_alert1.png new file mode 100644 index 0000000..fcd4850 Binary files /dev/null and b/posts/tmap/img/07_exemple_alert1.png differ diff --git a/posts/tmap/img/08_exemple_alert2.png b/posts/tmap/img/08_exemple_alert2.png new file mode 100644 index 0000000..559d069 Binary files /dev/null and b/posts/tmap/img/08_exemple_alert2.png differ diff --git a/posts/tmap/img/09_demo.gif b/posts/tmap/img/09_demo.gif new file mode 100644 index 0000000..cd5d41a Binary files /dev/null and b/posts/tmap/img/09_demo.gif differ diff --git a/posts/tmap/img/10_demo2.gif b/posts/tmap/img/10_demo2.gif new file mode 100644 index 0000000..0b06cbb Binary files /dev/null and b/posts/tmap/img/10_demo2.gif differ diff --git a/posts/tmap/img/11_demo3.gif b/posts/tmap/img/11_demo3.gif new file mode 100644 index 0000000..259907d Binary files /dev/null and b/posts/tmap/img/11_demo3.gif differ diff --git a/posts/tmap/index.qmd b/posts/tmap/index.qmd new file mode 100644 index 0000000..6c6abba --- /dev/null +++ b/posts/tmap/index.qmd @@ -0,0 +1,407 @@ +--- +title: "Pimping your {shiny} app with a JavaScript library : an example using sweetalert2" +author: "Yohann Mansiaux" +date: "2024-04-30" +categories: [shiny, javascript] +image: "image.jpg" +--- + +**You think that some of the components of `{shiny}` are not very functional or downright austere? Are you looking to implement some feature in your app but it is not available in the `{shiny}` toolbox? Take a look at JavaScript!** + +JavaScript is a very popular programming language that is often used to add features to web pages. With HTML and CSS, JavaScript is an essential language for web developers. The size of its user community means that if you are looking to implement a particular feature, there is a good chance that someone has already had the same need as you and has shared their code! + +An other positive point (and essential for us in this case) : it is possible to integrate JavaScript libraries into a `{shiny}` application to add features that are not available by default. In addition to that, `{golem}` will help us to set everything up. + +No more excuses to back down, let's go ! 🚀 + + + +## TL;DR + +- Going further in `{shiny}` by integrating a JavaScript library is possible! + - We take the example of sweetalert2, which allows to display alerts that are more visually appealing than the basic ones + - `{golem}` has several functions to make it easier for us to integrate JavaScript libraries into a `{shiny}` app + - This example is rather simple. The integration of libraries is sometimes harder because the documentation might be scarse or the library might be more complex to use + +## Import sweetalert2 into a `{shiny}` app created with `{golem}` + +### sweetalert2 + +- sweetalert2 is a JavaScript library that allows you to display alerts that are more visually appealing than the basic ones +- It is very well documented +- It is very popular (more than 16000 "stars" on GitHub at the time of publication of this article) + +Let's take a look at the possibilities offered by sweetalert2: https://sweetalert2.github.io/ + +```{r, echo = FALSE, out.width="70%"} +knitr::include_graphics("./img/01-sweetalertaccueil.png") +``` + +If you click on "Show normal alert", you will see a classic alert while clicking on "Show success message", you will see a sweetalert2 alert. + +The first one has a rather austere design while the second one is more modern and more pleasant to the eye, it will probably offer a better user experience. + +Feel free to play with the different types of alerts offered by sweetalert2 to get an idea of what is possible with this library by visiting the examples section. + +### Add the necessary dependencies to the `{shiny}` app + +**The following sections assume that you have already created a `{shiny}` app with `{golem}`.** + +If this is not the case and you want to know more about `{golem}`, I invite you to consult the official documentation. + +To add sweetalert2 to your `{shiny}` app, you will need to find a way to incorporate the files needed for its operation into your application. + +Two solutions are available to you: + +- Use a "CDN" (Content Delivery Network) to load the files from a third-party server. The CDN will be the equivalent of a CRAN for JavaScript libraries. Concretely, we will ask our application to point to the sources of sweetalert2, hosted on a remote server. + +- Download the files needed for its operation and integrate them directly into your application. If your application is intended to be used on a machine that is not connected to the Internet, you will inevitably have to go through this step. + +**Don't panic! We will see both methods** + +#### Where to find the elements I need? + +The sweetalert2 documentation is very well done. You will find all the information you need to integrate the library into your application from the Download section. + +However, you will need to learn how to identify the elements you need to integrate sweetalert2 into your application. + +**Looking for the CDN** + +In the "Download & Install" section, you will find a link to the sweetalert2 CDN. This is the link that we will have to add to our application in order to use the library. + +```{r, echo = FALSE, out.width="80%"} +knitr::include_graphics("img/02-cdn.png") +``` + +When you click on the link, you will arrive on a page that looks like this: + +```{r, echo = FALSE, out.width="100%"} +knitr::include_graphics("img/03-cdn_site.png") +``` + +What we are interested in here is the link in the `