Mobile-first Configurable Pin Code Input Component

Description:

A configurable, mobile-first pin code component for security code & password input.

Install & Download:

# Yarn
$ yarn add vue-pincode-input

# NPM
$ npm install vue-pincode-input --save

More Features:

  • Auto move focus when filling/removing.
  • Auto select Pincode input on focus.
  • Auto call for the native numeric keyboard on mobile devices.

How to use it:

  1. Install and import the pin code input component.
import PincodeInput from 'vue-pincode-input';

2. Create a pin code input component in your app template.

<PincodeInput
  v-model="code"
  placeholder="0"
/>

3 Register the component and done.

export default Vue.extend({
  name: 'App',
  components: {
    PincodeInput,
  },
  data: () => ({
    code: '',
  }),
});
  1. Determine whether or not to enable the auto focus on page load. Default: true.
<PincodeInput
  v-model="code"
  placeholder="0"
  :autofocus=false
/>

5.Determine the length of the pin code input. Default: 4.

<PincodeInput
  v-model="code"
  placeholder="0"
  :length="2"
/>

Download Details:

Author: Seokky

Live Demo: https://seokky.github.io/vue-pincode-input/

Download Link: https://github.com/Seokky/vue-pincode-input/archive/master.zip

Official Website: https://github.com/Seokky/vue-pincode-input

#vuejs #javascript #vue-js

What is GEEK

Buddha Community

Mobile-first Configurable Pin Code Input Component
Monty  Boehm

Monty Boehm

1675304280

How to Use Hotwire Rails

Introduction

We are back with another exciting and much-talked-about Rails tutorial on how to use Hotwire with the Rails application. This Hotwire Rails tutorial is an alternate method for building modern web applications that consume a pinch of JavaScript.

Rails 7 Hotwire is the default front-end framework shipped with Rails 7 after it was launched. It is used to represent HTML over the wire in the Rails application. Previously, we used to add a hotwire-rails gem in our gem file and then run rails hotwire: install. However, with the introduction of Rails 7, the gem got deprecated. Now, we use turbo-rails and stimulus rails directly, which work as Hotwire’s SPA-like page accelerator and Hotwire’s modest JavaScript framework.

What is Hotwire?

Hotwire is a package of different frameworks that help to build applications. It simplifies the developer’s work for writing web pages without the need to write JavaScript, and instead sending HTML code over the wire.

Introduction to The Hotwire Framework:

1. Turbo:

It uses simplified techniques to build web applications while decreasing the usage of JavaScript in the application. Turbo offers numerous handling methods for the HTML data sent over the wire and displaying the application’s data without actually loading the entire page. It helps to maintain the simplicity of web applications without destroying the single-page application experience by using the below techniques:

Turbo Frames: Turbo Frames help to load the different sections of our markup without any dependency as it divides the page into different contexts separately called frames and updates these frames individually.
Turbo Drive: Every link doesn’t have to make the entire page reload when clicked. Only the HTML contained within the tag will be displayed.
Turbo Streams: To add real-time features to the application, this technique is used. It helps to bring real-time data to the application using CRUD actions.

2. Stimulus

It represents the JavaScript framework, which is required when JS is a requirement in the application. The interaction with the HTML is possible with the help of a stimulus, as the controllers that help those interactions are written by a stimulus.

3. Strada

Not much information is available about Strada as it has not been officially released yet. However, it works with native applications, and by using HTML bridge attributes, interaction is made possible between web applications and native apps.

Simple diagrammatic representation of Hotwire Stack:

Hotwire Stack

Prerequisites For Hotwire Rails Tutorial

As we are implementing the Ruby on Rails Hotwire tutorial, make sure about the following installations before you can get started.

  • Ruby on Rails
  • Hotwire gem
  • PostgreSQL/SQLite (choose any one database)
  • Turbo Rails
  • Stimulus.js

Looking for an enthusiastic team of ROR developers to shape the vision of your web project?
Contact Bacancy today and hire Ruby developers to start building your dream project!

Create a new Rails Project

Find the following commands to create a rails application.

mkdir ~/projects/railshotwire
cd ~/projects/railshotwire
echo "source 'https://rubygems.org'" > Gemfile
echo "gem 'rails', '~> 7.0.0'" >> Gemfile
bundle install  
bundle exec rails new . --force -d=postgresql

Now create some files for the project, up till now no usage of Rails Hotwire can be seen.
Fire the following command in your terminal.

  • For creating a default controller for the application
echo "class HomeController < ApplicationController" > app/controllers/home_controller.rb
echo "end" >> app/controllers/home_controller.rb
  • For creating another controller for the application
echo "class OtherController < ApplicationController" > app/controllers/other_controller.rb
echo "end" >> app/controllers/home_controller.rb
  • For creating routes for the application
echo "Rails.application.routes.draw do" > config/routes.rb
echo '  get "home/index"' >> config/routes.rb
echo '  get "other/index"' >> config/routes.rb
echo '  root to: "home#index"' >> config/routes.rb
echo 'end' >> config/routes.rb
  • For creating a default view for the application
mkdir app/views/home
echo '<h1>This is Rails Hotwire homepage</h1>' > app/views/home/index.html.erb
echo '<div><%= link_to "Enter to other page", other_index_path %></div>' >> app/views/home/index.html.erb
  • For creating another view for the application
mkdir app/views/other
echo '<h1>This is Another page</h1>' > app/views/other/index.html.erb
echo '<div><%= link_to "Enter to home page", root_path %></div>' >> app/views/other/index.html.erb
  • For creating a database and schema.rb file for the application
bin/rails db:create
bin/rails db:migrate
  • For checking the application run bin/rails s and open your browser, your running application will have the below view.

Rails Hotwire Home Page

Additionally, you can clone the code and browse through the project. Here’s the source code of the repository: Rails 7 Hotwire application

Now, let’s see how Hotwire Rails can work its magic with various Turbo techniques.

Hotwire Rails: Turbo Drive

Go to your localhost:3000 on your web browser and right-click on the Inspect and open a Network tab of the DevTools of the browser.

Now click on go to another page link that appears on the home page to redirect from the home page to another page. In our Network tab, we can see that this action of navigation is achieved via XHR. It appears only the part inside HTML is reloaded, here neither the CSS is reloaded nor the JS is reloaded when the navigation action is performed.

Hotwire Rails Turbo Drive

By performing this action we can see that Turbo Drive helps to represent the HTML response without loading the full page and only follows redirect and reindeer HTML responses which helps to make the application faster to access.

Hotwire Rails: Turbo Frame

This technique helps to divide the current page into different sections called frames that can be updated separately independently when new data is added from the server.
Below we discuss the different use cases of Turbo frame like inline edition, sorting, searching, and filtering of data.

Let’s perform some practical actions to see the example of these use cases.

Make changes in the app/controllers/home_controller.rb file

#CODE

class HomeController < ApplicationController
   def turbo_frame_form
   end
   
   def turbo_frame submit
      extracted_anynumber = params[:any][:anynumber]
      render :turbo_frame_form, status: :ok, locals: {anynumber: extracted_anynumber,      comment: 'turbo_frame_submit ok' }
   end
end

Turbo Frame

Add app/views/home/turbo_frame_form.html.erb file to the application and add this content inside the file.

#CODE

<section>

    <%= turbo_frame_tag 'anyframe' do %>
            
      <div>
          <h2>Frame view</h2>
          <%= form_with scope: :any, url: turbo_frame_submit_path, local: true do |form| %>
              <%= form.label :anynumber, 'Type an integer (odd or even)', 'class' => 'my-0  d-inline'  %>
              <%= form.text_field :anynumber, type: 'number', 'required' => 'true', 'value' => "#{local_assigns[:anynumber] || 0}",  'aria-describedby' => 'anynumber' %>
              <%= form.submit 'Submit this number', 'id' => 'submit-number' %>
          <% end %>
      </div>
      <div>
        <h2>Data of the view</h2>
        <pre style="font-size: .7rem;"><%= JSON.pretty_generate(local_assigns) %></pre> 
      </div>
      
    <% end %>

</section>

Add the content inside file

Make some adjustments in routes.rb

#CODE

Rails.application.routes.draw do
  get 'home/index'
  get 'other/index'

  get '/home/turbo_frame_form' => 'home#turbo_frame_form', as: 'turbo_frame_form'
  post '/home/turbo_frame_submit' => 'home#turbo_frame_submit', as: 'turbo_frame_submit'


  root to: "home#index"
end
  • Next step is to change homepage view in app/views/home/index.html.erb

#CODE

<h1>This is Rails Hotwire home page</h1>
<div><%= link_to "Enter to other page", other_index_path %></div>

<%= turbo_frame_tag 'anyframe' do %>        
  <div>
      <h2>Home view</h2>
      <%= form_with scope: :any, url: turbo_frame_submit_path, local: true do |form| %>
          <%= form.label :anynumber, 'Type an integer (odd or even)', 'class' => 'my-0  d-inline'  %>
          <%= form.text_field :anynumber, type: 'number', 'required' => 'true', 'value' => "#{local_assigns[:anynumber] || 0}",  'aria-describedby' => 'anynumber' %>
          <%= form.submit 'Submit this number', 'id' => 'submit-number' %>
      <% end %>
  <div>
<% end %>

Change HomePage

After making all the changes, restart the rails server and refresh the browser, the default view will appear on the browser.

restart the rails serverNow in the field enter any digit, after entering the digit click on submit button, and as the submit button is clicked we can see the Turbo Frame in action in the below screen, we can observe that the frame part changed, the first title and first link didn’t move.

submit button is clicked

Hotwire Rails: Turbo Streams

Turbo Streams deliver page updates over WebSocket, SSE or in response to form submissions by only using HTML and a series of CRUD-like operations, you are free to say that either

  • Update the piece of HTML while responding to all the other actions like the post, put, patch, and delete except the GET action.
  • Transmit a change to all users, without reloading the browser page.

This transmit can be represented by a simple example.

  • Make changes in app/controllers/other_controller.rb file of rails application

#CODE

class OtherController < ApplicationController

  def post_something
    respond_to do |format|
      format.turbo_stream {  }
    end
  end

   end

file of rails application

Add the below line in routes.rb file of the application

#CODE

post '/other/post_something' => 'other#post_something', as: 'post_something'
Add the below line

Superb! Rails will now attempt to locate the app/views/other/post_something.turbo_stream.erb template at any moment the ‘/other/post_something’ endpoint is reached.

For this, we need to add app/views/other/post_something.turbo_stream.erb template in the rails application.

#CODE

<turbo-stream action="append" target="messages">
  <template>
    <div id="message_1">This changes the existing message!</div>
  </template>
</turbo-stream>
Add template in the rails application

This states that the response will try to append the template of the turbo frame with ID “messages”.

Now change the index.html.erb file in app/views/other paths with the below content.

#CODE

<h1>This is Another page</h1>
<div><%= link_to "Enter to home page", root_path %></div>

<div style="margin-top: 3rem;">
  <%= form_with scope: :any, url: post_something_path do |form| %>
      <%= form.submit 'Post any message %>
  <% end %>
  <turbo-frame id="messages">
    <div>An empty message</div>
  </turbo-frame>
</div>
change the index.html.erb file
  • After making all the changes, restart the rails server and refresh the browser, and go to the other page.

go to the other page

  • Once the above screen appears, click on the Post any message button

Post any message button

This action shows that after submitting the response, the Turbo Streams help the developer to append the message, without reloading the page.

Another use case we can test is that rather than appending the message, the developer replaces the message. For that, we need to change the content of app/views/other/post_something.turbo_stream.erb template file and change the value of the action attribute from append to replace and check the changes in the browser.

#CODE

<turbo-stream action="replace" target="messages">
  <template>
    <div id="message_1">This changes the existing message!</div>
  </template>
</turbo-stream>

change the value of the action attributeWhen we click on Post any message button, the message that appear below that button will get replaced with the message that is mentioned in the app/views/other/post_something.turbo_stream.erb template

click on Post any message button

Stimulus

There are some cases in an application where JS is needed, therefore to cover those scenarios we require Hotwire JS tool. Hotwire has a JS tool because in some scenarios Turbo-* tools are not sufficient. But as we know that Hotwire is used to reduce the usage of JS in an application, Stimulus considers HTML as the single source of truth. Consider the case where we have to give elements on a page some JavaScript attributes, such as data controller, data-action, and data target. For that, a stimulus controller that can access elements and receive events based on those characteristics will be created.

Make a change in app/views/other/index.html.erb template file in rails application

#CODE

<h1>This is Another page</h1>
<div><%= link_to "Enter to home page", root_path %></div>

<div style="margin-top: 2rem;">
  <%= form_with scope: :any, url: post_something_path do |form| %>
      <%= form.submit 'Post something' %>
  <% end %>
  <turbo-frame id="messages">
    <div>An empty message</div>
  </turbo-frame>
</div>

<div style="margin-top: 2rem;">
  <h2>Stimulus</h2>  
  <div data-controller="hello">
    <input data-hello-target="name" type="text">
    <button data-action="click->hello#greet">
      Greet
    </button>
    <span data-hello-target="output">
    </span>
  </div>
</div>

Make A changeMake changes in the hello_controller.js in path app/JavaScript/controllers and add a stimulus controller in the file, which helps to bring the HTML into life.

#CODE

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "name", "output" ]

  greet() {
    this.outputTarget.textContent =
      `Hello, ${this.nameTarget.value}!`
  }
}

add a stimulus controller in the fileGo to your browser after making the changes in the code and click on Enter to other page link which will navigate to the localhost:3000/other/index page there you can see the changes implemented by the stimulus controller that is designed to augment your HTML with just enough behavior to make it more responsive.

With just a little bit of work, Turbo and Stimulus together offer a complete answer for applications that are quick and compelling.

Using Rails 7 Hotwire helps to load the pages at a faster speed and allows you to render templates on the server, where you have access to your whole domain model. It is a productive development experience in ROR, without compromising any of the speed or responsiveness associated with SPA.

Conclusion

We hope you were satisfied with our Rails Hotwire tutorial. Write to us at service@bacancy.com for any query that you want to resolve, or if you want us to share a tutorial on your query.

For more such solutions on RoR, check out our Ruby on Rails Tutorials. We will always strive to amaze you and cater to your needs.

Original article source at: https://www.bacancytechnology.com/

#rails #ruby 

Background Fetch for React Native Apps

react-native-background-fetch

Background Fetch is a very simple plugin which attempts to awaken an app in the background about every 15 minutes, providing a short period of background running-time. This plugin will execute your provided callbackFn whenever a background-fetch event occurs.

There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently or if an iOS user disables background refresh they may not happen at all.

:new: Background Fetch now provides a scheduleTask method for scheduling arbitrary "one-shot" or periodic tasks.

iOS

  • There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently.
  • scheduleTask seems only to fire when the device is plugged into power.
  • ⚠️ When your app is terminated, iOS no longer fires events — There is no such thing as stopOnTerminate: false for iOS.
  • iOS can take days before Apple's machine-learning algorithm settles in and begins regularly firing events. Do not sit staring at your logs waiting for an event to fire. If your simulated events work, that's all you need to know that everything is correctly configured.
  • If the user doesn't open your iOS app for long periods of time, iOS will stop firing events.

Android

Installing the plugin

⚠️ If you have a previous version of react-native-background-fetch < 2.7.0 installed into react-native >= 0.60, you should first unlink your previous version as react-native link is no longer required.

$ react-native unlink react-native-background-fetch

With yarn

$ yarn add react-native-background-fetch

With npm

$ npm install --save react-native-background-fetch

Setup Guides

iOS Setup

react-native >= 0.60

Android Setup

react-native >= 0.60

Example

ℹ️ This repo contains its own Example App. See /example

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  FlatList,
  StatusBar,
} from 'react-native';

import {
  Header,
  Colors
} from 'react-native/Libraries/NewAppScreen';

import BackgroundFetch from "react-native-background-fetch";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      events: []
    };
  }

  componentDidMount() {
    // Initialize BackgroundFetch ONLY ONCE when component mounts.
    this.initBackgroundFetch();
  }

  async initBackgroundFetch() {
    // BackgroundFetch event handler.
    const onEvent = async (taskId) => {
      console.log('[BackgroundFetch] task: ', taskId);
      // Do your background work...
      await this.addEvent(taskId);
      // IMPORTANT:  You must signal to the OS that your task is complete.
      BackgroundFetch.finish(taskId);
    }

    // Timeout callback is executed when your Task has exceeded its allowed running-time.
    // You must stop what you're doing immediately BackgroundFetch.finish(taskId)
    const onTimeout = async (taskId) => {
      console.warn('[BackgroundFetch] TIMEOUT task: ', taskId);
      BackgroundFetch.finish(taskId);
    }

    // Initialize BackgroundFetch only once when component mounts.
    let status = await BackgroundFetch.configure({minimumFetchInterval: 15}, onEvent, onTimeout);

    console.log('[BackgroundFetch] configure status: ', status);
  }

  // Add a BackgroundFetch event to <FlatList>
  addEvent(taskId) {
    // Simulate a possibly long-running asynchronous task with a Promise.
    return new Promise((resolve, reject) => {
      this.setState(state => ({
        events: [...state.events, {
          taskId: taskId,
          timestamp: (new Date()).toString()
        }]
      }));
      resolve();
    });
  }

  render() {
    return (
      <>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <ScrollView
            contentInsetAdjustmentBehavior="automatic"
            style={styles.scrollView}>
            <Header />

            <View style={styles.body}>
              <View style={styles.sectionContainer}>
                <Text style={styles.sectionTitle}>BackgroundFetch Demo</Text>
              </View>
            </View>
          </ScrollView>
          <View style={styles.sectionContainer}>
            <FlatList
              data={this.state.events}
              renderItem={({item}) => (<Text>[{item.taskId}]: {item.timestamp}</Text>)}
              keyExtractor={item => item.timestamp}
            />
          </View>
        </SafeAreaView>
      </>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  body: {
    backgroundColor: Colors.white,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
});

export default App;

Executing Custom Tasks

In addition to the default background-fetch task defined by BackgroundFetch.configure, you may also execute your own arbitrary "oneshot" or periodic tasks (iOS requires additional Setup Instructions). However, all events will be fired into the Callback provided to BackgroundFetch#configure:

⚠️ iOS:

  • scheduleTask on iOS seems only to run when the device is plugged into power.
  • scheduleTask on iOS are designed for low-priority tasks, such as purging cache files — they tend to be unreliable for mission-critical tasks. scheduleTask will never run as frequently as you want.
  • The default fetch event is much more reliable and fires far more often.
  • scheduleTask on iOS stop when the user terminates the app. There is no such thing as stopOnTerminate: false for iOS.
// Step 1:  Configure BackgroundFetch as usual.
let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15
}, async (taskId) => {  // <-- Event callback
  // This is the fetch-event callback.
  console.log("[BackgroundFetch] taskId: ", taskId);

  // Use a switch statement to route task-handling.
  switch (taskId) {
    case 'com.foo.customtask':
      print("Received custom task");
      break;
    default:
      print("Default fetch task");
  }
  // Finish, providing received taskId.
  BackgroundFetch.finish(taskId);
}, async (taskId) => {  // <-- Task timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  BackgroundFetch.finish(taskId);
});

// Step 2:  Schedule a custom "oneshot" task "com.foo.customtask" to execute 5000ms from now.
BackgroundFetch.scheduleTask({
  taskId: "com.foo.customtask",
  forceAlarmManager: true,
  delay: 5000  // <-- milliseconds
});

API Documentation

Config

Common Options

@param {Integer} minimumFetchInterval [15]

The minimum interval in minutes to execute background fetch events. Defaults to 15 minutes. Note: Background-fetch events will never occur at a frequency higher than every 15 minutes. Apple uses a secret algorithm to adjust the frequency of fetch events, presumably based upon usage patterns of the app. Fetch events can occur less often than your configured minimumFetchInterval.

@param {Integer} delay (milliseconds)

ℹ️ Valid only for BackgroundFetch.scheduleTask. The minimum number of milliseconds in future that task should execute.

@param {Boolean} periodic [false]

ℹ️ Valid only for BackgroundFetch.scheduleTask. Defaults to false. Set true to execute the task repeatedly. When false, the task will execute just once.

Android Options

@config {Boolean} stopOnTerminate [true]

Set false to continue background-fetch events after user terminates the app. Default to true.

@config {Boolean} startOnBoot [false]

Set true to initiate background-fetch events when the device is rebooted. Defaults to false.

NOTE: startOnBoot requires stopOnTerminate: false.

@config {Boolean} forceAlarmManager [false]

By default, the plugin will use Android's JobScheduler when possible. The JobScheduler API prioritizes for battery-life, throttling task-execution based upon device usage and battery level.

Configuring forceAlarmManager: true will bypass JobScheduler to use Android's older AlarmManager API, resulting in more accurate task-execution at the cost of higher battery usage.

let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15,
  forceAlarmManager: true
}, async (taskId) => {  // <-- Event callback
  console.log("[BackgroundFetch] taskId: ", taskId);
  BackgroundFetch.finish(taskId);
}, async (taskId) => {  // <-- Task timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  BackgroundFetch.finish(taskId);
});
.
.
.
// And with with #scheduleTask
BackgroundFetch.scheduleTask({
  taskId: 'com.foo.customtask',
  delay: 5000,       // milliseconds
  forceAlarmManager: true,
  periodic: false
});

@config {Boolean} enableHeadless [false]

Set true to enable React Native's Headless JS mechanism, for handling fetch events after app termination.

  • 📂 index.js (MUST BE IN index.js):
import BackgroundFetch from "react-native-background-fetch";

let MyHeadlessTask = async (event) => {
  // Get task id from event {}:
  let taskId = event.taskId;
  let isTimeout = event.timeout;  // <-- true when your background-time has expired.
  if (isTimeout) {
    // This task has exceeded its allowed running-time.
    // You must stop what you're doing immediately finish(taskId)
    console.log('[BackgroundFetch] Headless TIMEOUT:', taskId);
    BackgroundFetch.finish(taskId);
    return;
  }
  console.log('[BackgroundFetch HeadlessTask] start: ', taskId);

  // Perform an example HTTP request.
  // Important:  await asychronous tasks when using HeadlessJS.
  let response = await fetch('https://reactnative.dev/movies.json');
  let responseJson = await response.json();
  console.log('[BackgroundFetch HeadlessTask] response: ', responseJson);

  // Required:  Signal to native code that your task is complete.
  // If you don't do this, your app could be terminated and/or assigned
  // battery-blame for consuming too much time in background.
  BackgroundFetch.finish(taskId);
}

// Register your BackgroundFetch HeadlessTask
BackgroundFetch.registerHeadlessTask(MyHeadlessTask);

@config {integer} requiredNetworkType [BackgroundFetch.NETWORK_TYPE_NONE]

Set basic description of the kind of network your job requires.

If your job doesn't need a network connection, you don't need to use this option as the default value is BackgroundFetch.NETWORK_TYPE_NONE.

NetworkTypeDescription
BackgroundFetch.NETWORK_TYPE_NONEThis job doesn't care about network constraints, either any or none.
BackgroundFetch.NETWORK_TYPE_ANYThis job requires network connectivity.
BackgroundFetch.NETWORK_TYPE_CELLULARThis job requires network connectivity that is a cellular network.
BackgroundFetch.NETWORK_TYPE_UNMETEREDThis job requires network connectivity that is unmetered. Most WiFi networks are unmetered, as in "you can upload as much as you like".
BackgroundFetch.NETWORK_TYPE_NOT_ROAMINGThis job requires network connectivity that is not roaming (being outside the country of origin)

@config {Boolean} requiresBatteryNotLow [false]

Specify that to run this job, the device's battery level must not be low.

This defaults to false. If true, the job will only run when the battery level is not low, which is generally the point where the user is given a "low battery" warning.

@config {Boolean} requiresStorageNotLow [false]

Specify that to run this job, the device's available storage must not be low.

This defaults to false. If true, the job will only run when the device is not in a low storage state, which is generally the point where the user is given a "low storage" warning.

@config {Boolean} requiresCharging [false]

Specify that to run this job, the device must be charging (or be a non-battery-powered device connected to permanent power, such as Android TV devices). This defaults to false.

@config {Boolean} requiresDeviceIdle [false]

When set true, ensure that this job will not run if the device is in active use.

The default state is false: that is, the for the job to be runnable even when someone is interacting with the device.

This state is a loose definition provided by the system. In general, it means that the device is not currently being used interactively, and has not been in use for some time. As such, it is a good time to perform resource heavy jobs. Bear in mind that battery usage will still be attributed to your application, and shown to the user in battery stats.


Methods

Method NameArgumentsReturnsNotes
configure{FetchConfig}, callbackFn, timeoutFnPromise<BackgroundFetchStatus>Configures the plugin's callbackFn and timeoutFn. This callback will fire each time a background-fetch event occurs in addition to events from #scheduleTask. The timeoutFn will be called when the OS reports your task is nearing the end of its allowed background-time.
scheduleTask{TaskConfig}Promise<boolean>Executes a custom task. The task will be executed in the same Callback function provided to #configure.
statuscallbackFnPromise<BackgroundFetchStatus>Your callback will be executed with the current status (Integer) 0: Restricted, 1: Denied, 2: Available. These constants are defined as BackgroundFetch.STATUS_RESTRICTED, BackgroundFetch.STATUS_DENIED, BackgroundFetch.STATUS_AVAILABLE (NOTE: Android will always return STATUS_AVAILABLE)
finishString taskIdVoidYou MUST call this method in your callbackFn provided to #configure in order to signal to the OS that your task is complete. iOS provides only 30s of background-time for a fetch-event -- if you exceed this 30s, iOS will kill your app.
startnonePromise<BackgroundFetchStatus>Start the background-fetch API. Your callbackFn provided to #configure will be executed each time a background-fetch event occurs. NOTE the #configure method automatically calls #start. You do not have to call this method after you #configure the plugin
stop[taskId:String]Promise<boolean>Stop the background-fetch API and all #scheduleTask from firing events. Your callbackFn provided to #configure will no longer be executed. If you provide an optional taskId, only that #scheduleTask will be stopped.

Debugging

iOS

🆕 BGTaskScheduler API for iOS 13+

  • ⚠️ At the time of writing, the new task simulator does not yet work in Simulator; Only real devices.
  • See Apple docs Starting and Terminating Tasks During Development
  • After running your app in XCode, Click the [||] button to initiate a Breakpoint.
  • In the console (lldb), paste the following command (Note: use cursor up/down keys to cycle through previously run commands):
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.transistorsoft.fetch"]
  • Click the [ > ] button to continue. The task will execute and the Callback function provided to BackgroundFetch.configure will receive the event.

Simulating task-timeout events

  • Only the new BGTaskScheduler api supports simulated task-timeout events. To simulate a task-timeout, your fetchCallback must not call BackgroundFetch.finish(taskId):
let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15
}, async (taskId) => {  // <-- Event callback.
  // This is the task callback.
  console.log("[BackgroundFetch] taskId", taskId);
  //BackgroundFetch.finish(taskId); // <-- Disable .finish(taskId) when simulating an iOS task timeout
}, async (taskId) => {  // <-- Event timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  print("[BackgroundFetch] TIMEOUT taskId:", taskId);
  BackgroundFetch.finish(taskId);
});
  • Now simulate an iOS task timeout as follows, in the same manner as simulating an event above:
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@"com.transistorsoft.fetch"]

Old BackgroundFetch API

  • Simulate background fetch events in XCode using Debug->Simulate Background Fetch
  • iOS can take some hours or even days to start a consistently scheduling background-fetch events since iOS schedules fetch events based upon the user's patterns of activity. If Simulate Background Fetch works, your can be sure that everything is working fine. You just need to wait.

Android

  • Observe plugin logs in $ adb logcat:
$ adb logcat *:S ReactNative:V ReactNativeJS:V TSBackgroundFetch:V
  • Simulate a background-fetch event on a device (insert <your.application.id>) (only works for sdk 21+:
$ adb shell cmd jobscheduler run -f <your.application.id> 999
  • For devices with sdk <21, simulate a "Headless JS" event with (insert <your.application.id>)
$ adb shell am broadcast -a <your.application.id>.event.BACKGROUND_FETCH

Download Details:
Author: transistorsoft
Source Code: https://github.com/transistorsoft/react-native-background-fetch
License: MIT license

#react  #reactnative  #mobileapp  #javascript 

Rahim Makhani

Rahim Makhani

1616669264

On-Demand Mobile App Development Services in USA

Mobile apps are developing day-by-day and the usage of mobile apps is also increasing. There are many mobile app development company that are providing services for on-demand mobile app development services.

One of the leading mobile app development company in the USA is Nevina Infotech. It is the best known for providing on-demand app development services till now.

Our On-Demand Mobile App Development Services:-

iPhone App Development
Android App Development
iPad App Development
Game App Development
ionic App Development
Wearable App Development
Flutter App Development

#mobile app development company #mobile app development services #mobile application development services #mobile application development company #mobile app development company usa

Felix Kling

Felix Kling

1683553906

Everything You Need to Know About CSS Variables

I'll be covering all you need to know about CSS variables. A complete guide To CSS Variables with examples. In this tutorial, we will explore what CSS variables are and how to use variables in CSS for creating beautiful responsive websites. 

Learn CSS Variables in 15 Minutes

In today's tutorial, I'll be covering all you need to know about CSS variables in 15 minutes. These include it's basic usage, combining it with the calc() function, fallback values and inheritence + psuedo classes.


A Complete Guide To CSS Variables [With Examples]

Variables are the basic building block of any software application. They reduce the redundant tasks for the developers in a program and hold values that have to be used in the entire program. Websites are a bit different. A novice in web programming may not be aware that variables exist at the front-end of web development as well as in CSS. Variables serve the same purpose as they serve when implementation is done using C++, Python, etc. Their work and complexities motivated us to come up with a dedicated blog on CSS variables.

CSS variables (also known as Custom Properties) is a modern CSS specification that is gaining prominence due to widespread browser support. It reduces coding and maintenance time and lets you develop cross browser compatible websites. It also helps in declaring values for reuse across a CSS file, which was previously possible only with preprocessors such as Sass and LESS.

In this blog, we will explore what CSS variables are and how to use variables in CSS for creating beautiful responsive websites. Finally, we will back it up with practical examples. So let’s begin!

What Are CSS Variables?

CSS variables are custom properties in which you can store a value and use it anywhere in the HTML code. They were introduced in Chrome 49 and have been extremely popular ever since. However, unlike programming languages that support simple initialization and substitution syntax, CSS variables need to be specifically defined whether they are being initialized or substituted. Hence, both of these things have their separate syntaxes.

CSS (4)

The initialization of the CSS variable is done by prefixing “–” to the variable name. For example, the following syntax initializes the variable “my_font” to 20px.

--my_font: 20px;

The “my_font” variable can now be used anywhere inside the code with a value of “20px”. Next comes the substitution part. The substitution of a property to the variable can be done only by the “var()” CSS property. Inside the “var(),” we spell the variable name as shown below:

selector {
    font-size : var(--my_font);
}

In the above syntax, the font size of the selector will become 20px due to the my_font variable. The “var()” takes another argument apart from the variable name – the fallback value. The fallback value works as a safety net in the variable substitution. In scenarios where the variable value is found to be inaccessible, the fallback value will be used in its place. The fallback value can be declared as shown below:

font-size: var(--my_font, 20px);

Fallback values work differently in different aspects. We will discuss this later in this post with some interesting illustrations related to web browsers.

Life Before CSS Variables – The SASS Preprocessor

Before understanding how to use variables in CSS and their importance in the website styling sheet, we need to understand what we used to do before variables in CSS. Before we had this awesome custom property to use, the web developers would use the SASS variables, which had similar intentions but were not smooth and flexible.

SASS variables work similarly to the backend languages where we copy-paste the variable name whenever substitution is required. The initialization, however, is done by prefixing the “$” to the variable name.

$my_font: 20px;

The substitution can be done as shown below:

font-size: $my_font;

The problem with SASS is that it is a preprocessor and not a custom property as a CSS variable. Therefore, any variable declared in SASS needs to be compiled before it can be executed. This makes the variable static and irresistible to change at runtime. A very common problem, therefore, arises when the developer tries to reinitialize the variable as follows.


$my_font: 20px;
 
selector1 {
 
   font-size: $my_font;
}
 
selector2 {
  
   $my_font : $my_font + 1;
   font-size: $my_font; 
  
}

This will now change the value of my_font to 21px. To reset the value back to 20px, we have to subtract one from it. This does not happen in CSS variables, as we get the advantage of the “calc” function, which we will cover later in this blog.

SASS Variables vs. CSS Variables

The following table will help you out to draw a clear picture between the two variables:

SASS VariableCSS Variable
Static allocationDynamic allocation
Media queries not supportedSupport for media queries
Requires preprocessorPreprocessor not required
An added layer of calculation and complexitySingle-layer and direct variable management

The SASS variables were commonly used before CSS variables. But the differences between them cannot be ignored. CSS variables are more useful as compared to SASS variables but also differ in many other aspects. Let’s see them in the next section.

Importance Of CSS Variables

Before we go ahead and understand how to use variables in CSS, let’s explore some of the benefits of using variables in CSS. As a web developer, you will be able to relate to it and retrospect on how your life would have been easier with them.

1. Remove Redundancy In Code

Variables remove the redundancy in the code. For example, let’s say we have a very small web page requirement with all the headings (the h tags) of the same “color: red.”

<html lang="en" dir="ltr">
    <head>
      <meta charset="utf-8">
      <title>CSS Variables</title>
      <style>
           h2 {
             color: red;
           }

           h3 {
             color: red;
           }

           h4 {
             color: red;
           }
      </style>
    </head>

    <body>
      <center>
      <h2>I am heading 2</h2>
      <h3>I am heading 3</h3>
      <h4>I am heading 4</h4>
    </center>
    </body>
  </html>

Up to this point, everything looks good, and we get the correct output on our webpage.

pasted image 0 (17)

Now let’s say the team decides to change the color to green for every heading. To do this, we have to go through “find and replace” three times on the page, which is acceptable. But what about constructing a real website where this would be done 100 times or more for just a single change

Variables in CSS eliminate this redundancy from the system where we would just need to change the color once – in the variable’s value.

--heading_color: red;
   h2 {
             color: var(--heading_color, black);
           }

           h3 {
             color: var(--heading_color, black);
           }

           h4 {
             color: var(--heading_color, black);
           }

In the above code, whenever a change arises, I just need to change the variable “heading__color” value from “red” to “green.”

2. No need For Preprocessors

Preprocessors are used for the compilation of variables. Now that we have variables in CSS, we can bid adieu to the processors and perform dynamic activities on the variables. So, in the above example, when I change the color from Red to Green or Cyan (or anything else), I don’t need to compile my page again. Instead, I just press F5, and the changes will be reflected on the web browser.

3. Super Flexible – Declare Anywhere

CSS variables are custom properties of CSS. Similar to other custom properties, you can use the variables in CSS wherever you want. Here is how you can use it with the style tag:

<style>
       h2 {
             color: var(--heading_color, black);
           }
      </style>

Using it inline can be another option:

< h2 style = "color: var(--heading_color, black)">I am heading 2</h2 >

4. Improved code readability

For developers, code readability is perhaps one of the most troubling pain points. Consider the following code where we apply color to the various elements on the web page:

h2 {
             color: rgb(194, 70, 48);
           }

           h3 {
             color: #c40808;
           }

           h4 {
             color: #8c1c06;
           }

Consider a case where 100 lines later, I choose the same h1 color for another paragraph because that was the team plan.

p {
             color: rgb(194, 70, 48);
           }

But is it predictable that the color used in this paragraph is the same as used in the heading? If color consistency is a point in your website development plan, you might have to look at both the values carefully and verify their similarities. This becomes a lot harder when we talk about maybe 10 or 20 such scenarios. Here is how you can improve the code readability and make it more predictable with variables in CSS:

:root {
        --heading_color: red;
        --other_color: rgb(194, 70, 48);
      }
           h2 {
             color: var(--heading_color, black);
           }

           h3 {
             color: var(--other_color, black);
           }

           p {
             color: var(--heading_color, black)
           }

Since the variable of “p” is similar to “h2”, they both have the same color. An add-on advantage of a readable code is that it becomes a lot easier to find typos. For example, let’s say later on you find out that “H2” and “p” were not supposed to be the same color?

To make them similar, you might have to go through the grilling task of finding and replacing the instances where you have read every value digit by digit. Instead, you can define CSS variables! In the above code, the class “root” defines the variables, which is one of the methods for defining variables in CSS.

CSS Variables and JavaScript

CSS variables can access the DOM of the web page, which is very helpful when dealing with JavaScript. This is a big advantage knowing that JavaScript can help us create awesome code by fetching the variable value and setting it to different values based on predefined conditions.

The end result (i.e., web page) is more dynamic, user-friendly, and gives a lot more control to the developer. The process and code for manipulating the variables with the help of JavaScript are defined in a separate section at the end of this blog.

Calc And CSS Variables

In the SASS variable section, I mentioned the calc function and how it gives the edge to variables in CSS. The calc function is a vital function for people who love to set things relative to each other. For example, if you are interested in fluid typography in web design, calc function would probably focus on your typography designs.

In addition, the calc function is a basic CSS function that lets us do calculations. For example, Calc functions are generally used to apply relative properties in HTML.

This is how I would make the heading to be 2.5 times larger than the paragraph’s font size.

font-size: calc(20 * 2.5)px;

But the problem here is that even though I have my requirements set properly, I still have to look at my paragraph size. This leads to redundancy in the source code. Variables in CSS can be used with the calc function just like any other property to minimize redundancy.

The approach described above can be replaced with the CSS variables as shown below:

:root {
        --paragraph_size: 20px;
      }
           h2 {
             font-size: calc(var(--paragraph_size) * 2.5);

Output:

pasted image 0 (16)

The second line is the original default font size of the “h2” tag. This code will be further discussed in the exceptions section to point out some of the common mistakes in CSS variables.

Scope In CSS Variables

In the implementation shown earlier, the root pseudo class (in which the variable is declared) and its significance in the CSS sheet look a bit questionable. However, this class is a part of “scopes,” and this section will highlight its importance in variables in CSS.

Global Scope – One declaration For All

The scope property is akin to a variable’s scope in the programming languages. The CSS variable’s scope is no different. This is how you can define a CSS variable under two scopes:

  • Global Scope – Accepted from the start till the end of the document
  • Local Scope – Accepted only within the selector

When a variable is defined with a global scope, its existence is defined in the complete document from the time of its declaration. But other programming languages like Python or C++ have an open field between functions where you have the option to define the global scope.

Unfortunately, CSS has no such area due to the lack of a preprocessor. Therefore, in CSS, we use the root pseudo class, which means that the variable is under the document’s root (i.e. global).

:root {
--my_variable: <value>
}

This variable can now be called in any of the selectors in the same document.


:root {
        --my_variable: <value>;
      }

div {

   <property>: var(--my_variable, fallback)

}

The root selector works because variables in CSS can access the DOM of the web app code. The root here represents the root of the DOM tree which passes the data to its branches (i.e., complete document).

Local Scope – Bounded By Selector Walls

The local scope of the variables in CSS is restricted by the boundaries of the selectors inside which it has been defined. For instance, in the below code, I have defined the background colour for a div box with id “first_div”:

div {
        width: 300px;
        height: 200px;
        color: white;
        font-weight: bold;
        font-size: 30px;
      }
      #first_div {
        --my_bg: #692a3c;
        background-color: var(--my_bg, black);
      }

  <body>
      <center>
      <div id = "first_div">I am a div</div>
    </center>
    </body>

Output:

pasted image 0 (14)

Let’s make another div and set the same background color as done with the above div.

#first_div {
        --my_bg: #692a3c;
        background-color: var(--my_bg, black);
      }
      #second_div {
        background-color: var(--my_bg, white);
      }
  <div id = "first_div">I am a div</div>
   <br><br>
   <div id = "second_div">I am a div too!!</div>

Output:

unnamed (1)

The fallback value is applied (i.e., black background color) to the second div. This happened because the scope of the variable “my_bg” is only within the #first_div tag. Thus, “my_bg” will not be accessible outside those brackets. Try rendering the same web page with “my_bg” defined in the root section and see how it looks!

Precedence And Inheritance

Now we know that when a variable is defined in the document’s root, it has a global scope and when defined inside any selector, it has a local scope. But, what if the same variable is declared at both places? Who takes the precedence, local or global CSS variable?

The following implementation demonstrates two different techniques to initialize the same CSS variable and its effect on the web page:

<style>
      :root {
        --my_bg : #692a3c;
      }
      div {
        width: 300px;
        height: 200px;
        color: white;
        font-weight: bold;
        font-size: 30px;
      }
      #first_div {
        --my_bg: #f42a3c;
        background-color: var(--my_bg, black);
      }

      #second_div {
        background-color: var(--my_bg, black);
      }

Output:

pasted image 0 (13)

None of the divs here has a black background color. This means none of the variables failed and fallback values were never used. Furthermore, if you read the code, the second div has used the global instance of the variable while the first div chose the local variable. Therefore, we can confirm that the local scope has precedence over the global scope in CSS variables.

As far as inheritance is concerned. CSS is infamous for inheritance, which confuses many web developers when things take values that were never defined within their scope. So, what does inheritance mean in CSS?

Inheritance is the relationship between elements that are nested in each other. For example, the following code shows a parent-child relationship:

<div>Hello, I am a parent
<div> Hello, I am a child</div>
</div>

Similarly, we can define other sibling relationships. But these relationships affect each other’s property (down the line from the top) when the value is either set to “inherit” or cannot be found. The following implementation demonstrates the parent-child relationship where the child does not have the CSS variable setting for its background color:

CSS:

#first_div {
        --my_bg: blue;
        background-color: var(--my_bg, black);
      }

      #second_div {
             background-color: var(--my_bg, black);
      }

      #third_div {
        --my_bg: green;
        background-color: var(--my_bg, black);
      }

      #fourth_div {
        background-color: var(--my_bg, black);
      }

HTML:

<div id = "first_div">
    <div id = "second_div">
      <div id = "third_div"></div>
      <div id = "fourth_div"></div>
    </div>
  </div>

If a variable is not found for the element, it inherits the variable value from its parent! Therefore, the above code will see the following background colors for all the div:

  • first_div: blue
  • second_div: blue – inherited from the parent.
  • third_div: green
  • fourth_div: blue – inherited from the parent that inherited from its parent.

All four values are predictable considering the inheritance logic in the above diagram.

Fallback Values In CSS Variables

Fallback values are the second argument used in the “var()” function, which denotes the substitution of a CSS variable. Fallback values take their name from the job they do – they are used when you fall back with the original variable values.

There are four possibilities through which a CSS variable goes during the substitution.

  • Browser does not support CSS variable property.
  • The browser supports the property, and the variable is set to correct values with scope.
  • The browser supports the property, but the variable is not set to any value.
  • The browser supports the property, and the variable is set to an invalid value.

What If The Browser Does Not Support CSS Variables?

If the browser does not support variables in CSS, the CSS line of code with “/var()” is ignored completely as the browser does not understand it. In such cases, the browser takes on the default values, i.e., transparent.

Let’s check the code on Google Chrome 46 that does not support the CSS variables.

<style>
      :root {
        --my_bg : #9e2e50;
      }
      div {
        width: 300px;
        height: 200px;
        color: black;
        font-weight: bold;
        font-size: 30px;
        background-color: var(--my_bg, black);
      }

      </style>
    </head>

    <body>
      <center>
  <div>
      I am a div box!!
  </div>
    </center>
    </body>
pasted image 0 (12)

The color I applied to the variable “my_bg” is not rendered on the div box. At the same time, the div box does exist here but only transparently.

pasted image 0 (11)

To demonstrate my web app, I have used an online cross browser testing platform LambdaTest. It provides 3000+ browsers and operating systems to test websites and web apps for cross browser compatibility issues.

Variable Is Set And Is In Scope!

If the variable is set to a valid value and is being called within its scope, it will be implemented correctly. So, for example, executing the above code on Google 47 and above will show correct results.

Variable Is Never Initialized

The next scenario comes when the variable is never initialized but is substituted in the code somewhere.

<style>
      div {
           background-color: var(--my_bg, black);
      }
   </style>

Output:

pasted image 0 (10)

The div box takes the fallback value in this case. The same thing happens when the variable is initialized but is called outside of its scope.

Variable Is Set To An Invalid Value

If the variable is set to an invalid value based on its usages, such as px or deg for color, the background becomes transparent.

 <style>
      :root {
        --my_bg : 20px;
      }
      div {
        background-color: var(--my_bg, black);
      }
      </style>

Output:/p>
pasted image 0 (9)

So the variable line is ignored by the browser.

Fallback values do not work every time the variable throws an error. Furthermore, it only works with a few of the scenarios that are described above. So, as a web developer, what can we do to manage the cross browser compatibility issues?

Implementing Two Fallbacks

The best method is to lay a safety net in the selector CSS code that can still place the value to the property in cases that the CSS variable fails.

<style>
      :root {
        --my_bg : #9e2e50;
      }
      div {
        background-color: #9e2e50;
        background-color: var(--my_bg, black);
      }

      </style>

If the variable is not initialized in the above code, the value will be taken from the first “background-color” initialization. However, if it is initialized, the value will be taken from the variable.

Although not necessarily a strict “fallback,” the variables in CSS can also perform fallback values for various exceptions using the cascading CSS variable methods.

background-color: var(variable_name, var(variable_name, fallback));

However, it has multiple layers of calculation and takes time to execute. This approach is therefore never recommended for a web developer.

Exceptions In CSS Variables

Once you know how to use variables in CSS, you will see it is flexible and easy to use. However, they do have a few exceptions that one should remember before declaring and substituting the variables.

Watch Cyclic Dependencies

Cyclic dependencies are explicit with their names. When dependencies are created with each other, the web developer should verify that the cycle is not created among the variables. If a cycle is created, the code execution could result in an infinite loop that can timeout the web page as it would never load completely.

--variable_name_1 : var(variable_name_2, fallback);
--variable_name_2 : var(variable_name_1, fallback);

A similar process will be seen when a variable will depend on itself during the time of initialization.

--variable_1 = var(variable_1, fallback);

Web developers should always take note of cyclic dependencies while initializing the variables.

CSS Variables Are Case-Sensitive

The CSS variables are case-sensitive. Therefore, the variables my_var and My_var are both different.

CSS Variable Cannot Be A Property Name

The CSS variable name cannot have a value as an existing property in CSS. So, for example, you cannot initialize a variable with the value “font-size.”

CSS Variables With JavaScript

One of the most attractive points for developers who love JavaScript is that variables in CSS can be handled and manipulated with the help of JavaScript easily. To use variables in CSS with JavaScript, you can fetch their current value similar to how JS handles other properties.

The following code fetches the CSS variable (used for the font size) and increases its font size to 40px as we press the button.

<html lang="en" dir="ltr">
    <head>
      <meta charset="utf-8">
      <title>CSS Variables</title>
      <style>
      :root {
      --fontSize: 20px;
      }

      div {
        width: 300px;
        height: 200px;
        color: white;
        font-weight: bold;
        font-size: var(--fontSize, 12px);
        background-color: #9e2e50;
      }
      </style>
      <script>
function changeFontSize() {
  var r = document.querySelector(':root');
  var rs = getComputedStyle(r);
  r.style.setProperty('--fontSize', '40px');
}
      </script>
    </head>

    <body>
      <center>
  <div>
      I am a div box!!
  </div>
  <br><br>
  <button onclick="changeFontSize()">Change Font Size</button>
    </center>
    </body>
  </html>

Output:

CSS_variables_with_Javascript

Browser Compatibility Of CSS Variables

CSS variables enjoy great support from every major browser. If you know how to use variables in CSS, you can ensure that exceptions and fallbacks are correctly working as per the code.

After implementing, you can use LambdaTest to perform browser compatibility testing to make sure it renders correctly on different browser versions and operating systems.

pasted image 0 (7)

How To Use LT Browser For Responsiveness Test Of CSS Variables

The most buzzed word of the web development world currently is responsiveness. With Google specifying the responsiveness wherever possible and multiple devices flooding the market, responsive web design has become a priority in itself.

Variables in CSS are not visual elements that can be tested with window resize functionality for responsiveness. But they do affect the components that are visual such as div, images, or anything else. Therefore, responsiveness test are important with the CSS media queries whether variables in CSS support them or not.

The following code implements the CSS media queries along with the CSS variables.

<html lang="en" dir="ltr">
    <head>
      <meta charset="utf-8">
      <title>CSS Variables</title>
      <style>
      :root {
        --my_color: red;
        --my_second_color: green;
      }


      @media only screen and (min-width: 641px) {
          #heading {
            color: var(--my_color);
          }
      }

      @media only screen and (max-width: 640px){
        #heading {
          color: var(--my_second_color);
        }
      }
      </style>
    </head>

    <body>
      <center>
      <h2 id = "heading">Wait for it!!!!</h2>
    </center>
    </body>
  </html>

Output:

media_queries_CSS_variables

The text is original of red color in the above code until the window size is greater than 640px. Else, the text color becomes green.

Performing a responsiveness test is not an easy job. You need various devices and owning or leasing every device is not a feasible approach. Instead, we need to choose smart solutions when dealing with responsiveness.

Conclusion

As a web developer, variables have always been a part of my styling sheet. I am sure after befriending them today, and you will start using them regularly too. Variables in CSS remove redundancy from the code, and the best thing is that they are just another property in CSS. However, after implementing CSS variables, you must perform a responsiveness test of your web design. You can follow the responsive web design checklist to ease up the entire responsiveness test process.

giphy

In this guide, we learned how to use variables in CSS from its implementation to responsiveness test. I hope variables in CSS are something that you enjoy and share with your fellow developers. If you have come across any interesting experiences with variables in CSS, please share them in the comment section below.

For your reference, check this out:
https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties 

#css #webdevelopment

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer