Best Website Builders CompanyBest Website Builders Company
    What's Hot

    SBI Amrit Kalash Fixed Deposit last date extended, 7.6% interest for Senior Citizens. Details here

    May 17, 2023

    Number of UHNWIs in India dip to 12,069 in 2022, to rise to 19,119 in 5 years: Knight Frank

    May 17, 2023

    Share market tomorrow: Nifty, Bank Nifty support, resistance for Thursday 18 May

    May 17, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website Builders CompanyBest Website Builders Company
    • Home
    • Web Builders
      1. Joomla
      2. WordPress
      3. CSS
      4. Web Design
      5. UX
      6. PHP
      7. View All

      For $50 you can host your website for life

      May 2, 2023

      California Department of Justice Investigating Shooting Involving CHP Officer in Glenn County Under AB 1506

      May 1, 2023

      Mariposa County Daily Sheriff and Reservation Report for Sunday, April 30, 2023

      May 1, 2023

      Top 10 Best Web Development Companies In India In 2023

      May 1, 2023

      Google Ads Sign Up – Easy Steps to Create Your Account

      May 17, 2023

      1Password puts users at ease after the horror of password change notifications

      May 3, 2023

      Samsung Galaxy S23 FE could feature a 50MP main camera, but we may have to wait until then

      May 3, 2023

      Titanfall director says Respawn is ‘looking forward to something new’

      May 3, 2023

      Implementing CSS with character and spirit: Union MoS Finance

      May 3, 2023

      Street Fighter 6’s unique character select screen animation really shows how much heart goes into the game

      May 3, 2023

      Make Google Chrome run faster with these 9 tips and tweaks

      May 3, 2023

      🅰️ New Angular 16 Goes Big in 2023: Everything You Need to Know | Vitaly Shevchuk | Oct 25, 2017 May 2023

      May 3, 2023

      18-Wheeler Accidents: Fatalities and Injuries

      May 6, 2023

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      The role of artificial intelligence in improving the user experience in online casinos.

      May 3, 2023

      Microsoft enhances user experience with Windows 11 ‘smart opt-out’ and improved emergency notifications

      May 3, 2023

      Nigeria’s Nestcoin Launches New Digital Financial Platform For Africans

      May 3, 2023

      ibi WebFOCUS 9.2 is ready for Modern Business Intelligence, the Cloud, and Driving User Experience – PCR.

      May 3, 2023

      Anthony Carrigan Reflects on That ‘Barry’ Scene from Season 4 Episode 4

      May 1, 2023

      TikToker Kat Abu is very happy that Tucker Carlson has been fired

      April 28, 2023

      How ‘Single Drunk Female’ Season 2 Tackled Emotional Sobriety

      April 24, 2023

      Trans-Missouri Residents Affected by Attorney General Order

      April 24, 2023

      Creating and Adding a Google Account: A Step-by-Step Guide

      May 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023
    • Realtoz
      • Our Other Sites
    • More News
    • Investments
    Best Website Builders CompanyBest Website Builders Company
    Home»CSS»Almost Bare Bone WebR Starter App
    CSS

    Almost Bare Bone WebR Starter App

    websitebuildersnowBy websitebuildersnowMarch 12, 2023No Comments9 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    Let’s see how to set up ~ a minimal HTML/JS/CS + WebR powered “app” on your own server. This will be vanilla JS (i.e. no React/Vue/npm/bundler) that you can hack freely.

    TL;DR: If you want to get started quickly, you can find the app source and track changes on GitHub.

    in the docs/ You can see an example of using this with GH Pages by placing it in the GH repository directory. Here is some information about what you need to do to do that.

    If all went well, here is the output of the call to WebR (it may take a few seconds).

    Set up your server

    I will try to keep this updated with new WebR releases. The current version is 0.1.0 and can be obtained from https://github.com/r-wasm/webr/releases/download/v0.1.0/webr-0.1.0.tar.gz.

    System-wide WebR

    You should read this section of the official WebR documentation before continuing.

    i am using the whole server /webr my directory rud.is It’s a domain, so you can use it on every page you serve.

    If not available, WebR performance will suffer SharedArrayBufferseconds.So, I have enabled these headers myself /webr directory:

    Cross-Origin-Opener-Policy: same-origin
    Cross-Origin-Embedder-Policy: require-corp
    

    I’m using nginx, so it looks like this:

    location ^~ /webr {
      add_header "Cross-Origin-Opener-Policy" "same-origin";
      add_header "Cross-Origin-Embedder-Policy" "require-corp";
    }
    

    YMMV.

    As a good precaution (and just in case you move things around), paste these headers into any app directory that uses WebR. However, it is not used server-wide.

    And they call it MIME. MIME!

    WebR is a JavaScript module. mjs The MIME type of the extension is text/javascriptor some browsers are not happy.

    A typical way for a web server to know how to communicate this is mime.types File. This is not true for all web servers. I’ll add instructions for anything that uses a different method to configure this. The entry looks like this:

    text/javascript  mjs;
    

    Testing the WebR setup

    If you go to that path on your web server in your browser, you should see the WebR console app. Then you can continue. If not, please leave an issue. I can help debug it, but it’s on a best effort basis for me.

    App installation

    We’ll talk more about this app later, but you probably want to see it in action, so let’s install this ~minimal app.

    My personal demo app is pinned off /webr-app on my rud.is web server. Here’s how to replicate it:

    # Go someplace safe
    $ cd $TMPDIR
    
    # Get the app bundle
    # You can also use the GH release version, just delete the README after installing it.
    $ curl -o webr-app.tgz https://rud.is/dl/webr-app.tgz
    
    # Expand it
    $ tar -xvzf webr-app.tgz
    x ./webr-app/
    x ./webr-app/modules/
    x ./webr-app/modules/webr-app.js
    x ./webr-app/modules/webr-helpers.js
    x ./webr-app/css/
    x ./webr-app/css/simple.min.css
    x ./webr-app/css/app.css
    x ./webr-app/main.js
    x ./webr-app/index.html
    
    # 🚨 GO THROUGH EACH FILE
    # 🚨 to make sure I'm not pwning you!
    # 🚨 Don't trust anything or anyone.
    
    # Go to the webserver root
    $ cd $PATH_TO_WEBSERVER_DOC_ROOT_PATH
    
    # Move the directory
    $ mv $TMPDIR/webr-app .
    
    # Delete the tarball (optional)
    $ rm $TMPDIR/webr-app.tgz
    

    follow that path your You should see what you see on my webserver.

    App structure using WebR

    .
    ├── css                  # CSS (obvsly)
    │   ├── app.css          # app-specific ones
    │   └── simple.min.css   # more on this in a bit
    ├── index.html           # The main app page
    ├── main.js              # The main app JS
    └── modules              # We use ES6 JS modules
        ├── webr-app.js      # Main app module
        └── webr-helpers.js  # Some WebR JS Helpers I wrote
    

    simple css

    If you’ve subscribed to my newsletter, you know I use a lot of tools and frameworks. Use whichever you prefer. I’ve included a copy of Simple CSS b/c for people who don’t normally do this kind of work. Simple use. If you continue to use it, use this resource to familiarize yourself with it.

    JavaScript modules

    When I’m in “hack” mode (like in the first few days after WebR’s release), I fall back into old bad habits. I will not duplicate them here.

    I am using JavaScript modules as my project structure. Not all R guys are experts in her JS tools, so we don’t “bundle” (all the app support files he puts together into one minified file). I also don’t use them because I don’t really need them. I like to keep things simple and have as few dependencies as possible.

    of index.html You should see the following line:

    <script type="module" src="https://securityboulevard.com/2023/03/almost-bare-bones-webr-starter-app/amp/./main.js"></script> 
    

    This tells the browser to load that JS file as if it were a module.As you read (you bottom Read the MDN link above. right?), the module provides protection from local scope names/objects/functions and subversion of imported names.

    Our main module contains all the great core functionality of the app.

    • Load WebR
    • It will tell you how fast it loads and instantiates
    • Yanks mtcars From an instantiated R session (mtcars It was the third “thing” I typed into R, so my brain typed it in by default).
    • Create an HTML table using D3.

    It’s small enough to include here.

    import { format } from "https://cdn.skypack.dev/d3-format@3";
    import * as HelpR from './modules/webr-helpers.js'; // WebR-specific helpers
    // import * as App from './modules/webr-app.js'; // our app's functions, if it had some
    
    console.time('Execution Time'); // keeps on tickin'
    const timerStart = performance.now();
    
    import { WebR } from '/webr/webr.mjs'; // service workers == full path starting with /
    
    globalThis.webR = new WebR({
        WEBR_URL: "/webr/", # our system-wide WebR
        SW_URL: "/webr/"    # what ^^ said
    }); 
    await globalThis.webR.init(); 
    
    // WebR is ready to use. So, brag about it!
    
    const timerEnd = performance.now();
    console.timeEnd('Execution Time');
    
    document.getElementById('loading').innerText = `WebR Loaded! (${format(",.2r")((timerEnd - timerStart) / 1000)} seconds)`;
    
    const mtcars = await HelpR.getDataFrame(globalThis.webR, "mtcars");
    console.table(mtcars);
    HelpR.simpleDataFrameTable("#tbl", mtcars);
    

    globalThis is a special JS object that allows you to push something into the global JS environment. It’s not 100% necessary, but if you want other app module blocks to use the same WebR context:

    Let’s focus on the last three lines.

    const mtcars = await HelpR.getDataFrame(globalThis.webR, "mtcars");
    

    This uses a helper function I wrote to get a dataframe object from R in a way that is more compatible with most JS and JS libraries than the default JS object WebR. toJs() The function converts all R objects to

    console.table(mtcars);
    

    This will create the appropriate table in your browser’s developer tools console. I’ve done this so that I can open the console and view it, but I also want it to examine the contents of the object (just type in it). mtcars Press Enter/Return) and check out this nice format.

    Pass a WebR context that you know works. Any R code that evaluates and returns a data frame. It’s all up to you (for now) to make sure the code runs and returns a data frame.

    Last line:

    HelpR.simpleDataFrameTable("#tbl", mtcars);
    

    Create a table by calling another helper function.

    Help R

    I may finally blow eloquently and completely on what’s in modules/webr-helpers.jsLet’s just focus on a few things for now. sweet JSDoc comments.

    First, let’s elaborate on these comments.

    I use VS Code for about 60% of my daily operations and I used it for this project as well. If you open the project root in VS Code and select/hover over simpleDataFrameTable The last line gives you nicely formatted help. Since VS Code is hooked up for this (as are other editors/IDEs), feel free to use his JSDoc comments in your own functions/modules.

    Let’s take a look behind the curtain getDataFrame:

    export async function getDataFrame(ctx, rEvalCode) {
        let result = await ctx.evalR(`${rEvalCode}`);
        let output = await result.toJs();
        return (Promise.resolve(webRDataFrameToJS(output)));
    }
    

    of export Tells the JS environment that the feature is available when properly imported.Without export Functions are local to the module.

    let result = await ctx.evalR(`${rEvalCode}`);
    

    Proper apps use JS try/catch Potential error. An example of this can be found in the fancy React app code on WebR’s site. We throw caution to the wind and value whatever is given to us. In theory, you should let R guarantee that it’s a data frame that can’t be done on the JS side after the line:

    let output = await result.toJs();
    

    the type list (B.C data.frameteeth lists).

    I might add more helpers to the more stand-alone helpers module, but I don’t spend much time at least externally because I think corporate R beats me.

    wait! wait!please tell me (about await)!

    Before talking about the last line:

    return (Promise.resolve(webRDataFrameToJS(output)));
    

    Let’s briefly discuss asynchronous operations in JS.

    The browser’s JavaScript environment is single-threaded. async-hronous ops passes code to threads to avoid blocking page operations. They run “whenever”, so what you get is empty, shallow promises about executing code that might return something.

    use explicitly await for when we TRUE I need to execute some code and in this case return something. You can keep chaining asynchronous function calls, but eventually if you need to make sure code is running and/or data is being returned, keep your promise to do so is needed. therefore, Promise.resolve.

    Serving WebR from a GitHub page

    of docs/ The directory of the repository shows working versions of the GH pages.

    main.js Some adjustments are required:

    // This will use Posit's CDN
    
    import('https://webr.r-wasm.org/latest/webr.mjs').then( // this wraps the main app code
        async ({ WebR }) => {
    
            globalThis.webR = new WebR({
                SW_URL: "/webr-app/"            // 👈🏼 needs to be your GHP main path
            });
            await globalThis.webR.init();
    
            const timerEnd = performance.now();
            console.timeEnd('Execution Time');
    
            document.getElementById('loading').innerText = `WebR Loaded! (${format(",.2r")((timerEnd - timerStart) / 1000)} seconds)`;
    
            const mtcars = await HelpR.getDataFrame(globalThis.webR, "mtcars");
            console.table(mtcars);
            HelpR.simpleDataFrameTable("#tbl", mtcars);
    
      }
    );
    

    more to come

    Launch this badly coded dashboard app to see more sophisticated usage. Convert it to a module and extend git a bit.

    *** This is a Security Bloggers Network syndicated blog on rud.is created by hrbrmstr. Read the original post: https://rud.is/b/2023/03/12/almost-bare-bones-webr-starter-app/



    Source link

    Share this:

    • Tweet
    • More
    • WhatsApp
    • Print
    • Share on Tumblr
    • Mastodon

    Related

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticlePlastic in oceans at unprecedented levels
    Next Article Defective, loose wheels at risk of derailment discovered on Norfolk Southern rail cars: Norfolk Southern first found the defective wheels in the cleanup at Springfield.
    websitebuildersnow
    • Website

    Related Posts

    Implementing CSS with character and spirit: Union MoS Finance

    May 3, 2023

    Street Fighter 6’s unique character select screen animation really shows how much heart goes into the game

    May 3, 2023

    Make Google Chrome run faster with these 9 tips and tweaks

    May 3, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Post Your Ad Free
    Advertisement
    Demo
    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    SBI Amrit Kalash Fixed Deposit last date extended, 7.6% interest for Senior Citizens. Details here

    May 17, 2023

    Number of UHNWIs in India dip to 12,069 in 2022, to rise to 19,119 in 5 years: Knight Frank

    May 17, 2023

    Share market tomorrow: Nifty, Bank Nifty support, resistance for Thursday 18 May

    May 17, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.

    x