URL Generation Workflow
Strategy

How a URL Shortening Application Works


Introduction

Typically, a long URL is a system-generated URL, usually containing multiple query parameters that may be encrypted/encoded to mask those parameters. The need for shortened URLs arises when long URLs have to be shared for various purposes, like sharing links via SMSs, Emails, media types, like Twitter or WhatsApp, etc.

A URL shortening service might sound like a simple service at first, but it poses a very interesting and challenging engineering problem. Please pause here and think about how you could design a system to generate an infinite number of short URLs for possibly all long URLs in the world. The interesting part of the problem is generating unique, random identifiers for these long URLs. The identifiers should be short enough to fit in the URL with an acceptable character set.

Short URLs

A typical short URL could be something like this https://ts.dz/qp7h3zi, where ts.dz is a short domain for a particular application, service, or company, and the last part in the URL qp7h3zi is a unique, random identifier. This part is called as the token. Tokens are alphanumeric strings and act as identifiers to the actual long URL. The length of a token typically varies from 6-9 characters. While designing the URL shortening service, we pay close attention to the length of the token and the characters it contains. To be URL safe, consider smaller case characters a-z and numbers from 0-9, we have a total character set of 36 character set. The number of unique tokens that can be generated using various token lengths are shown below.

Token Length Unique Token Combination Range
6 2,176,782,336 > 2 Billion
7 78,364,164,096 > 78 Billion
8 2,821,109,907,456 > 2 Trillion
9 101,559,956,668,416 > 100 Trillion

From the above table, we can choose the length of our token to be 7 characters long, which can accommodate more than 78 billion unique tokens. If we require a larger range, then setting the token length to 8 characters gives us a larger set, which comes to around 2 trillion (we can build a service possibly with almost all URLs in the world! ). The token generation is covered below, after the high-level design section.

You may also like:
Building Blocks of a Scalable Architecture.

High-Level Design

The High-Level Design (HLD) consists of two parts. 

  1. Short URL Generation — covers how to handle a request by the system to generate a short URL for an incoming long URL
  2. Short URL Redirection — covers how to handle a short URL click request by a user so that the user can be redirected to the actual location i.e. long URL

HLD – Short URL Generation

The URL Shortening service accepts a long URL as input, generates a short URL, and returns it. If the incoming long URL already exists in the system, then the previous generated short URL has to be returned. If the existing short URL has expired, then a new one has to be created and sent as a response.

URL Generation Workflow

URL Generation Workflow

HLD – Short URL Redirection

When a user clicks on the short URL, the request should be redirected to the URL Shortening Service, which would then redirect it to the actual long URL location. The short domain in the short URL has to be mapped to the service like below:

URL Redirection workflow

URL Redirection workflow

Token Generation

The logic to generate unique, random tokens can be tricky. The URL Shortening service must ensure that the token should not be assigned to two (or more) different long URLs. Otherwise, the system may incorrectly redirect the short URL to another location (long URL). Tokens can be generated by multiple strategies by using 3rd party libraries or using conventional methods like Base36 encoding. We’ll cover each of these cases individually.

Third-Party Library

A very reliable library that generates unique, random tokens (ids) is Hashids (which has support in more than 30 languages!). Hashids can create short, unique Ids from numbers (positive numbers and zero) and allows custom alphabets as well as salt, so Ids are unique only to you. The Ids generated are mangled and are not easy to guess. The code footprint is very minimal, and there are no external library dependencies.

Sample tokens generated for salt = ”this is my salt” and character set = “abcdefghijklmnopqrstuvwxyz1234567890”.

Base36 Encode

This is a very straightforward approach, and most languages have these functions. If you don’t need all the fancy extras Hashids has to offer, this method will work just fine. It’ll probably be faster too. The input range of numbers can be synchronized using a central Zookeeper service.

A high-level design for token generation using Hashids library is shown below. The input to the Hashids library is a number (long) that generates unique tokens. As the URL Shortening service will be working in a cluster with “N” nodes, the input numbers to the Hashids library should be non-repetitive. To handle this, we introduce a synchronization service, like Zookeeper, which can manage and handle the range of Ids (range of numbers) assigned to the URL Shortening application node. 

Every application node, on start-up, requests the Zookeeper service for a new range, and the same will be recorded by the Zookeeper. For every short URL request, the URL Shortening application node increments a number (from the range assigned by Zookeeper) and passes it to the Hashids library, which in-turn generates a unique token for a corresponding input number. This token will be saved into the database corresponding to the long URL. 

Once the assigned number range has been exhausted by the application node, the URL Shortening application requests for a new range from Zookeeper. This design gives us the flexibility to add any number of application nodes based on the incoming traffic.

Service workflow with Hashids

Service workflow with Hashids

The Zookeeper service can be replaced by an instance of DynamoDB, which can maintain a counter. The role of the Zookeeper service is to maintain the ranges that are already assigned to application nodes and assign new ones when requested. A simple table with a counter variable in DynamoDB can be stored. This counter variable is made atomic in nature so that any application node saving an incremental number value doesn’t clash (writes-reads don’t clash). See how to implement atomic counters in DynamoDB in this link. The DynamoDB can also be replaced by a MySQL table as well or any other system that offers atomic number generation like Redis INCR.

Complete System Design

The complete system design can be summarized, as shown below. The main points and how the work flows are maintained are described below the diagram.

Final architectural diagram

Final architectural diagram

Note: A Redis cache setup is added here to improve application performance, as newly generated short URLs can be responded to from the cache rather than querying the database. The cache entries (short URL and long URL map) can be configured with an expiry or an eviction policy, such as LRU (least recently used).

  1. The URL Shortening application nodes works in a cluster; whenever the application nodes start or when a new node is added to the cluster, they talk to a Zookeeper service.
  2. The Zookeeper service allocates a unique number range to each application node on request.
  3. A request to shorten a long URL reaches the Load Balancer, which then appropriately delegates the call to one of the URL Shortening application nodes in a round-robin fashion.
  4. The application checks if there is an existing short URL entry in the database/cache for the long URL. If an entry exists, and if the short URL is still valid (not expired), then the same short URL will be responded back with HTTP 200 OK.
  5. If the long URL does not exist in the database, then the URL Shortening application uses the next available number (from the range allotted by Zookeeper in step 2) and generates a new token by using the Hashid library. A short URL is generated using the token and the configured expiry is set and then saved to the database and to the cache. The short URL is sent back to the client with a status of HTTP 201 CREATED.
  6. Whenever the short URL is clicked (by any user), the request reaches the Load Balancer and is passed on to one of the URL Shortening application nodes.
  7. The application checks in the cache if a long URL exists for the short URL token and then goes to step 9.
  8. If there is no cache entry, then the application checks in the database and goes to step 9.
  9. Upon finding a long URL that the client has to be redirected to, the application responds with HTTP 302 with the long URL set in the HTTP header Location. This redirects the client from short URL to the actual location (i.e. long URL).
  10. If there is no such token found in the database/cache the application node responds with a status of HTTP 404 NOT FOUND.

Further Reading



Source link

How WebDriverIO Uses Selenium Locators in a Unique Way
Strategy

How WebDriverIO Uses Selenium Locators in a Unique Way


In any automation testing framework, finding elements is the most fundamental activity. We have to choose web elements very carefully so that automation script execution can handle static and dynamic elements for stable test results. WebDriverIO has many advanced Selenium locators/ selector strategies compared to other automation testing frameworks. Traditionally, each locator has a specific By method which identifies the locators during runtime. 

WebdriverIO has simplified these By methods and now we do not have to specify them explicitly. 

WebdriverIO has the intelligence to identify which locator has been passed. By the end of this WebdriverIO tutorial, you will learn how WebDriverIO is transforming the way of Selenium locator strategy and how easy to remember and write it.

You may also like: How Selenium 4 Relative Locator Can Change The Way You Test

Note: If you refer to the official documentation of the WebdriverIO framework, you will notice that they have referred to Locators as Selectors. You need not get confused if you are familiar with some other test automation framework in Selenium. For example, if you have worked with Selenium Locators in Java, then those locators in WebdriverIO are addressed as Selectors.

For the ease of understanding, I will refer to them as Selenium locators in this WebdriverIO tutorial. As it is a more standardized and familiar term around automation testing with Selenium.

What Are Selenium Locators In WebDriverIO?

Before we start off this WebdriverIO tutorial for Selenium locators/selectors, let us quickly understand what they are used for. Selenium locators are utilized to find elements on a web page through a Selenium WebDriver when a test automation script is executed. The Selector is a command in Selenium. Selenium library reads this command from the script, converts into an HTTP request and interacts with Web browsers lastly, it performs actions based on the command.

Selenium Locator Strategies

When you get hands-on Selenium automation testing using WebdriverIO, you should be aware of the correct strategy that works for locating unique elements on a web page. Finding elements by ID, Name and relative XPath would be the first choice to find a unique element from the website. If you could not find any of these ways then it is advisable to choose other types of the Selenium locators/ selector.

If you have performed Selenium automation testing with Java, you may have used findElement() and findElements() method to find the selector from DOM. However, WebdriverIO offers a unique way of Selenium testing with WebDriverIO. 

With WebdriverIO, you don’t have to mention the Selenium locator’s strategy as it will automatically understand which types of locator strategy should be used. We will look into each Selenium Locator in this WebdriverIO tutorial. Before we jump into a practical demonstration, make sure to note down the below methods for finding elements in WebDriverIO:

$(): Single dollar sign used to find single web element
$$(): Double dollar sign used to find multiple web elements

Apart from these two methods, WebDriverIO Support other methods which are:

custom$(): used to find a custom strategy for a single web element
custom$(): used to find a custom strategy for multiples web elements

react$(): used to find single React component by their given name and it gets filter by props and state
react$$(): used to find multiples React components by their given name and it gets filter by props and state

Note: react$ and react$$ command only works with applications using React v16.x

How To Find A Web Element In Browser?

To find a web element in the browser, User has to go to the browser’s developer tools by pressing F12 in windows and option+command+i in Mac Operating System or right-clicking on a website and select inspect option.

Browser Developer Tools

When you open the developer tool, you can see HTML tags under the “Elements” tab. This HTML tab calls DOM elements. To find particular Web Elements, select the selector icon( before the Elements tab) and hover over the element you wish to find in the DOM.

cross browser testing cloud

List Of Selenium Locators In WebDriverIO

Now that you have a good understanding of Selenium Locators, let us see the different types of Selenium Locators in this WebdriverIO tutorial. The following are the supported selectors by the WebdriverIO.

  • CSS Query Selector.
  • Link Text.
  • Partial Link Text.
  • Element with certain text.
  • Tag Name.
  • Name.
  • XPath.
  • ID.
  • JS Function.
  • Chain Selectors.
  • React Selectors.
  • Custom Selector.

Using $, $$, Custom$, Custom$$, react$ and react$$ methods the user can find the elements and perform desired operations. Let’s deep dive at each one of these Selenium Locators in this WebdriverIO tutorial for Selenium automation testing with examples of a sample DOM.

CSS Query Selector

The first locator in this WebdriverIO tutorial for Selenium automation testing is the CSS Query selector, which is used to find the element from DOM.

How Can You Find the CSS Query?

Go to developer tools and find the element and right-click on the Selected element in the DOM and copy CSS selector option.

lambda testing

Syntax: $(‘CSS Query’);

Example

Output

When you run the above script, you can find the console log and observed that WebdriverIO converted into findElement method with CSS selector strategy.

Remember, Sometimes using a CSS query selector could result in locating multiple elements as a CSS sheet used for the whole website. Now, let us head to the next Selenium locator in this WebdriverIO tutorial.

Link Text

A website is made up of different types of components e.g textbox, links, drop-down, etc. Even a single web page can have numerous links over it. Selecting a particular link for your Selenium automation testing script could become challenging. This is where Link Text as a Selenium Locators for WebdriverIO comes into play. If you want to find any hyperlink then use this link text selector strategy.

Syntax: $(‘=anchorText’);

Here, = equal to sign is used to find anchor element with ‘specific text’.

Example

When you run the above automation testing script, you can find the console log. If you notice the logs you will observe that WebdriverIO has automatically detected the findElement method with link text strategy.

Output

Be careful about the elements being selected by this Selenium Locator in WebdriverIO as it might lead to multiple anchors with the same link text. Now that we know of Link text, let us now head to the Partial link text locator in this WebdriverIO tutorial.

Partial Link Text

Partial link text is similar to link text but the only difference is that this helps when the starting few characters of a link are fixed and the rest is dynamic.

Syntax: $(‘=anchorMatchedText’);

*= start equal to sign is used to find an anchor element with the matched text’.

$("=Automa")

Example

When you run the above script, you can find the console log and observe that WebdriverIO converted into the findElement method with a partial link text strategy.

Output

Element With Certain Text

In HTML every tag is known as an element and few elements have the direct text and few elements wrapped around other tags. If you want to find the element which has a certain or partial text then this selector is preferred to use.

While Selenium automation testing using Java, you would use XPath with normalize-space() method to find text along with HTML tag if you want to find an HTML tag with some text but WebdriverIO uses the method below.

Syntax

This selector takes help from = (equal to) and *= (start equal to) sign.

cross browser testing cloud

For instance, to find Cross Browser Testing Cloud from below H1 tag, using this command:  $(“h1=Cross Browser Testing Cloud”)

 < h1 class="big_title text_shadow_black __web-inspector-hide-shortcut__">

Cross Browser Testing Cloud< /h1> 

The same thing will work for class and the ID attribute of the elements. For example:

$(‘#id=certain text’); used for fixed text
$(‘#id*=certain text’); used for partial text
$(‘.classname=certain text’); used for fixed text
$(‘.classname*=partial text’); used for partial text

Here, # is used when you want to find elements by ID and . (dot) used for the class name.

Example

When you run the above script, you can find the console log and observe that WebdriverIO converted into findElement method with “normalize-space()” and “contains()”.

Output

Now, let us have a look at the Tag Name locator in this WebdriverIO tutorial for Selenium automation testing.

Tag Name

We use the tag name selector to find the element using any HTML tag. This is a very rarely used Selenium locator. However, this is very important if you are dealing with tables or calendar elements. While Selenium automation testing, you can pass the Tag Name as either of < tag > or < tag />.

Syntax

$(‘<tag>’); $(‘<tag />’); 

Example

Here is the output when the above Selenium automation testing script is executed in WebdriverIO.

Output

Name

This Selenium locator is similar to the ID Locator in Selenium. Sometimes a web developer gives a name to the HTML node. If a node has a name attribute then it is preferred to incorporate the Name locator in Selenium automation testing. The name selector has to be within square brackets with the name attribute.

Syntax

$(‘[<name attribute>]’)  

Example

Output

XPath

An extremely pivotal Selenium locator of this WebdriverIO tutorial. In WebDriverIO also, you can write absolute XPath and relative XPath. Absolute XPath starts with / slash and relative starts with // slash. This is a very strong and frequently used selector/ locator for identifying elements through Selenium automation testing.

The following special characters are used while writing XPath.

. – Dot means selection starts from the current node
* – Star means select any node
/ – Single slash means starts with the root node and used for absolute XPath
// – Double slash means to search the node using relative XPath
[ ] – square bracket used for index and also used for searching XPath bypassing attribute and it’s value
@ – used for identify for HTML attribute in XPath

The syntax for Absolute XPath:

$(‘<starts with /body>’);  

The syntax for Relative XPath: 

$(‘<starts with .//>’); 

Example

When you run the above script, you can find the console log. Observe that WebdriverIO converted into the findElement method with “XPath”.

Output

ID

Another crucial Selenium Locator of this WebdriverIO tutorial. The ID is an extremely powerful selector to find an element from DOM. This is always a unique element in the DOM. One more important thing is that, if you want to speed up your automation execution then this is a must-use Locator for Selenium automation testing. The ID directly gets a search from DOM whereas XPath scan the documents based on a relative or absolute path which is a time-consuming method.

# sign used to find elements using the ID.

Syntax

$(#<idname>); 

Example

Now, here you should observe this output log. When you run the above script, you can see the ID selector internally converted into a CSS selector and finding the element.

Output

Now, we have covered the usual Selenium locators in WebdriverIO. Next, we look at the advanced Selenium Locators/ Selectors in this WebdriverIO tutorial.

Chain Selectors

Sometimes it gets difficult to find an element that has no ID, name and tables rows and cells, in such a case, this chain selector helps you to get your unique element. There is no specific symbol given for this but you just call $().$() until you find the desired element by period (.) sign.

Note: Chain Selector/Locator uses the parent-child concept. So the Next chain element should fall under the parent chain selector.

Syntax

$(selector).$(selector).$(selector) 

Example

When the script gets executed, each element starts finding elements one by one until it reaches the final element. Firstly it uses findElement() and then calls findElementFromElement().

Output

JS Function

WebdriverIO supports JS selector/locator to find the elements using a JavaScript.

Syntax

Example

Web Elements stored in the variable and then JS functions call with help if $(). It converted internally executeScript().

Output

React Selector

React is another one of the advanced locators in WebdriverIO which has been provided to create custom react components for mobile apps. WebDriverIO has provided a feature that you can directly find an element using the react$() method.

react$$() method helps to find an array of WebDriverIO elements.

Syntax

react$(‘ReactComponent’);
 

Let’s understand by below React Native Example: 

In the above example, ‘RootComponent’ is a react component and when it renders within HTML element with id=’root’.

This RootComponent can be found by react$() and below is the example:

Custom Selector

One of the most convenient Selenium locators/ selectors in WebdriverIO which comes handy when facing complex scenarios for Selenium automation testing. The Custom selector allows you to use a customized strategy declared by using browser.addLocatorStrategy.

custom$$() method helps to find an array of WebDriverIO elements.

Syntax

browser.custom$(strategyName, strategyArguments) 

browser.custom$(strategyName, strategyArguments) 

Example

With the help of addLocatorStrategy(), we have created ‘emailById’ custom selector for the email ID field and we can use emailById selector using the custom$() method. Internally, WebDriverIO converts custom$() into executeScript() and finds the element.

Note: In this WebdriverIO tutorial, we have discussed single $() which helps to deal with a single element. All these selectors can be used with $$() for the array of WebDriverIO.

Conclusion

WebDriverIO is one of the top JavaScript testing frameworks and when you look at the variety it offers for you to locate elements on a web page, you would be sure to make a note of it for your upcoming projects. It has a very unique selector choice including react$ and custom$ selectors.

WebDriverIO has a single way to find the element but has different signs for selector e.g * , *=, .(period) and # different. I am sure that this WebdriverIO tutorial will help you to take your knowledge of test automation to the next step.

Further Reading

An Overview of JavaScript Testing in 2019

How To Use Name Locator In Selenium Automation Script

Java Class Name Locator in Selenium



Source link

The React tree using a normal div
Strategy

Web Performance Calendar » The unseen performance costs of m…


CSS-in-JS is becoming a popular choice for any new front-end app out there, due to the fact that it offers a better API for developers to work with. Don’t get me wrong, I love CSS, but creating a proper CSS architecture is not an easy task. Unfortunately though, besides some of the great advantages CSS-in-JS boasts over traditional CSS, it may still create performance issues in certain apps. In this article, I will attempt to demystify the high-level strategies of the most popular CSS-in-JS libraries, discuss the performance issues they may introduce on occasion and finally consider techniques that we can employ to mitigate them. So, without further ado, let’s jump straight in.

Background

In my company we figured it would be useful to build a UI library in order to be able to re-use common UI pieces across different products and I was the one to volunteer to get this endeavor started. I chose to use a CSS-in-JS solution, since I was already really happy with the styled API that most of the popular libraries expose. As I was developing it, I wanted to be smart and have re-usable logic and shared props across my components, so I started composing them. For example, an <IconButton /> would extend the <BaseButton /> that in turn implements a simple styled.button. Unfortunately, the IconButton needed to have its own styling, so it was converted to a styled component along the lines of:

const IconButton = styled(BaseButton)`
  border-radius: 3px;
`;

As more and more components were added, more and more compositions took place and it didn’t feel awkward since React was built upon the concepts of this very notion. Everything was fine until I implemented a Table. I started noticing that the rendering felt slow, especially when the number of rows got more than 50. Thus, I opened my devtools to try and investigate it.

Well needless to say, the React tree was as big as Jack’s magical beanstalk. The amount of Context.Consumer components was so high, that it could easily keep me up at nights. You see, each time you render a single styled component using styled-components or emotion, apart from the obvious React Component that gets created, an additional Context.Consumer is added in order to allow the runtime script (that most CSS-in-JS libraries depend upon) to properly manage the generated styling rules. This normally shouldn’t be too much of a problem, but don’t forget that components need to have access to your theme. This translates to an additional Context.Consumer being rendered for each styled element in order to “read” the theme from the ThemeProvider component. All in all, when you create a styled component in an app with a theme, 3 components get created: the obvious StyledXXX component and two (2) additional consumer components. Don’t be too scared, React does its work fast and this won’t be too much of an issue most of the times, but what if we compose multiple styled components in order to create a more complex component? What if this complex component is part of a big list or a table, where at least 100 of those get rendered? That’s when problems arise…

Profiling

To test CSS-in-JS solutions I created the simplest of apps, which just renders 50 “Hello World” statements. On the first experiment, I wrapped the text in a traditional div element, while on the second one, I utilized a styled.div component instead. I also added a button that would force a react re-render on those 50 div elements whenever it was clicked. The code for both can be seen on the following gists:

After rendering the <App /> component, two different React trees got rendered. The outputted trees can be seen in the screenshots below:

The React tree using a normal divThe React tree using a normal div

The React tree using a styled.div elementThe React tree using a styled.div element

I then forced a re-render of the <App /> 10 times in order to gather some metrics with regards to the perf costs that these additional Context.Consumer components bring. The timings of the re-renders in development modecan be seen below:

Development render timings for simple div, Average: 2.54msDevelopment render timings for simple div. Average: 2.54ms

Development render timings for styled.div. Average: 3.98msDevelopment render timings for styled.div . Average: 3.98ms

So interestingly enough, on average, the CSS-in-JS implementation is 56.6% more expensive in this example. Let’s see if things are different in production mode. The timings of the re-renders in production mode can be seen below:

Production render timings for simple div, Average 1.06msProduction render timings for simple div. Average 1.06ms

Production render timings for styled.div. Average 2.27msProduction render timings for styled.div. Average 2.27ms

When production mode is on, the implementation with the simple div seems to benefit the most by dropping its rendering time by more than 50% compared to a 43%drop on the CSS-in-JS implementation. Still, the latter takes almost twice as much time to render than the former. So what exactly is it that makes it slower?

Runtime Analysis

The obvious answer would be “Erm… you just said CSS-in-JS libraries render two Context.Consumer per component”, but if you really think about it, a context consumer is nothing more than accessing a JS variable. Sure, React has to do its work to figure out where to read the value from, but that alone doesn’t justify the timings above. The real answer comes from analyzing the reason why those contexts exist in the first place. You see, most CSS-in-JS libraries depend on a runtime that helps them dynamically update the styles of a component. These CSS-in-JS libraries don’t create CSS classes at build-time, but instead dynamically generate and update <style> tags in the document whenever a component mounts and/or has its props changed. These style tags normally contain a single CSS class, whose hashed name is mapped to a single React component. Whenever this component’s props change, the associated <style> tag must change as well. This is done by re-evaluating the CSS rules that the style tag needs to have, creating a new hashed class name to hold the aforementioned CSS rules and updating the classname prop of the associated React component in order to point to the recently-created class.

Let’s take for example the styled-components library. Whenever you create a styled.div, the library assigns an internal ID to this component and adds an empty <style> tag to the HTML <head>. This tag contains a single comment that references the internal ID of the React component that’s related to it:

<style data-styled-components>  
  /* sc-component-id: sc-bdVaJa */
</style>

When the associated React component gets rendered, styled-components:

  1. Parses the styled component’s tagged template’s CSS rules.
  2. Generates the new CSS class name (or checks whether it should retain the existing one).
  3. Preprocesses the styles with stylis.
  4. Injects the preprocessed CSS into the associated <style> tag in the HTML <head>.

To be able to use the theme during step (1), a Context.Consumer is needed in order to read the theme’s values within the tagged template. In order to be able to be able to modify the associated <style> tag from within the React component, another Context.Consumer is needed to provide access to the stylesheet instance. That’s why we see those two (2) Consumers in most CSS-in-JS libraries.

In addition, because these computations will affect the UI, they have to be performed during the render phase of the component and cannot be performed as a React lifecycle side-effect (since they would be delayed and perceived by the user as lag). This is why the rendering takes longer in a simple styled.div than in a native one.

Now, the styled-components maintainers noticed that and added optimizations and early bailout techniques in order to bring down the time it takes for a component to re-render. Specifically, the library checks to see whether your styled component is “static”, meaning that its styling doesn’t depend on a theme or the component’s passed props. For example, the following component is static:

const StaticStyledDiv = styled.div`
  color:red
`;

while this isn’t:

const DynamicStyledDiv = styled.div`
  color: ${props => props.color}
`;

If the library detects a static component, it will skip steps 1– 4, since it can understand that the generated class name will never have to change (since there is no dynamic element to modify its related CSS rules). In addition, it won’t render a ThemeContext.Consumer around the styled component, since a theme dependence would have prevented the component from being “static” in the first place.

If you were really observant, you would have noticed that even in production mode, the screenshot above rendered 2 Context.Consumer components for each styled.div. Interestingly though, the component that got rendered was “static” since it didn’t have any dynamic CSS rules and we would expect styled-components to skip the Consumer that had to do with the theme. The reason you see 2 Consumers per component, is because the screenshots above were taken while utilizing emotion, another CSS-in-JS library. This library follows a similar approach, with minor differences. Again, it parses the tagged template, preprocesses it with stylis and updates the corresponding style tag. One key difference is that emotion always wraps all components with a ThemeContext.Consumer regardless of whether they are using a theme or not (which explains the screenshots above). Funnily enough, even though it renders more consumer components, it still outperforms styled-components, which denotes that the number of consumer isn’t the biggest contributor to a slow render. It should be noted that at the time of writing there is a beta version for the v5.x.x of styled-components, which will outperform emotion according to its maintainers.

So, to wrap up, the combination of multiple Context consumers (which means additional elements that React has to coordinate) and the inherent housekeeping that dynamic styling goes with, may be slowing down your app. It should also be mentioned, that the all the style tags that get added for each component never get removed at all. This is because the overhead associated with a DOM removal (e.g. browser reflows) is higher than the overhead of just keeping them there. To be honest, I’m unsure whether dangling style tags can create performance issues, since they only contain unused classes that are generated during runtime (e.g. don’t get shipped over the wire), but it’s something you should potentially consider for your app.

To be fair, those style tags are not created by all CSS-in-JS libraries, since not all of them are runtime-based. For example, linaria is a zero-runtime CSS-in-JS library that defines a set of fixed CSS classes during build time and maps all dynamic rules within a tagged template (i.e. CSS rules that depend on prop values) with CSS custom properties. Thus whenever a props changes, the CSS custom property changes and the UI updates. This makes it much faster than all runtime-based CSS-in-JS libraries, since the amount of work and housekeeping that needs to be done during a render is much less. Realistically, the only thing that it needs to do during render is to make sure to — potentially — update a CSS custom property. At the same time though, it’s not compatible with IE11, has limited support for the popular css prop and doesn’t offer theming capabilities out of the box. As with most libraries, there is no silver bullet.

Takeaways

CSS-in-JS was a revolutionary pattern which brought a better experience for many developers out there, while also solving many issues such as name collisions, vendor prefixing, etc. out of the box. The point of this article was to shed some light into the potentially unknown performance implications when using the most prominent CSS-in-JS libraries (e.g. the ones with a runtime). I want to stress that those perf considerations don’t always create problems for an app. In fact, most apps won’t even notice them unless they are relying on hundreds of concurrently rendered composed components. The benefits of CSS-in-JS typically outweigh the aforementioned perf implications, but these implications are something that developers of applications with tons of data and lots of rapidly changing UIs should definitely consider. Before you jump on any refactoring train though, please measure and judge for yourselves.

Finally, here are some techniques that you can employ in order to increase your app’s performance when using one of the popular runtime-based CSS-in-JS libraries:

  1. Don’t over-compose styled components
    Basically don’t do what I did and try to compose 3 individual styled instances, just to create a freaking button. If you want to “share” code, make use of the css prop and compose tagged templates. This will save you lots of unneeded Context consumers, which means fewer components for React to manage, which means that React’s runtime can do its work faster.
  2. Prefer “static” components
    Some CSS-in-JS libraries will optimize their execution when your CSS has no dependencies on theme or props. The more “static” your tagged templates are, the higher the chances that your CSS-in-JS runtime will execute faster.
  3. Avoid unneeded React re-renders
    Make sure to only render when you need to, so you can avoid work by both React’s and CSS-in-JS library’s runtimes. Realistically, that should only be needed in extreme scenarios where a lot of heavy components are being simultaneously rendered on the screen.
  4. Investigate whether a zero-runtime CSS-in-JS library can work for your project
    Sometimes we tend to prefer writing CSS in JS for the DX (developer experience) it offers, without a need to have access to an extended JS API. If you app doesn’t need support for theming and doesn’t make heavy and complex use of the css prop, then a zero-runtime CSS-in-JS library might be a good candidate. As a bonus you will shave ~12KB off your overall bundle size, since most CSS-in-JS libraries range between 10KB — 15KB, while zero-runtime ones (like linaria) are < 1KB.

That’s it! Thanks a lot for reading 🙂

P.S. If you’ve ever wondered why the CSS rules are not editable by the devtools inspector, it’s because they make use of CSSStyleSheet.insertRule(). This is a really performant way of modifying a stylesheet, but one of its downsides is that the associated stylesheet is no longer editable through the inspector.



Source link

growth of programming languages
Strategy

Why Has Python Become a Popular Choice for Mobile App Develo…


When it comes to popular programming languages for backend development, Python comes to the mind of most developers. This high level, interpreted and general-purpose dynamic programming language has fewer steps when compared to C and Java. This attribute of Python makes it a hot favorite among most of the developers. And, it is one of the fastest-growing and popular programming languages these days.

You may also like: Top 6 Programming Languages for Mobile App Development

growth of programming languages

Image Source: Stackflow
Python was also the biggest gainer in the 
Tiobe index
 of the popularity of programming languages in the year 2018, rising by 3.62% points from January 2018 to January 2019, with a rating of approx. 8.2% for this month.

But, is this programming language is also useful for the development of mobile applications? How we create secure, scalable and feature-packed mobile applications using the Python language? Which tools will help you to create the best in class mobile applications?

Let’s figure answer of all these questions through this blog.

Why Python Is a Leader in the Domain of Mobile App Development?

python

Python can be used for the development of APIs of mobile applications. The mobile app developers can create apps with this programming language as it is capable of running on several major operating systems. 

In addition to this, the increase in the number of mobile phone users and the increase in demand for applications led to the use of this programming language to develop mobile applications. In recent years, Python has evolved to become a crucial option in the app development market.

Python can be used in a wide array of mobile application areas. Easy to understand, interact and easy to implement, Python programming language is an elegant language that allows you to code the same program with much fewer lines than PHP. 

When you hire a software development company, you get professionals who have knowledge in a variety of frameworks with which they can provide the best custom mobile app development services at an affordable cost. Most people prefer Python due to its reliability and simplicity. It also helps you work faster and offers an excellent interactive environment for the developers.

Python is one of the most readable languages in the world right now. This language is very popular among developers and is widely used by many programmers in order to create mobile applications and programs. Particularly, if you compare Python with other languages, it is considered the simplest of all. 

The implementation of this programming language is simple and, at the same time, the language has a very clean structure as compared to other languages. Therefore, programmers and coders will be required to do less coding. In addition to this, the writing application code is faster and easier with the help of this programming language. 

Since Python programming language runs on many major operating systems, it is used by a variety of programmers. Python can be used to create mobile applications for Android, iOS, and Windows. Let’s talk specifically about the use of Python in the world of mobile application development.

Most Demanded Frameworks for Python Preferred for Mobile App Development

Kivy vs BeeWare

Custom mobile app development on iOS and Android was not Python’s strong suit in the past— but things are changing rapidly. In the early times, Python did not have a strong story when it came to writing GUI for mobile apps. In fact, iOS and Android mobile app development were pretty much out of the question with only Python. 

With the help of a number of developments in recent years which vastly enhanced the outlook on using Python for writing codes for mobile apps. Let’s take a look at a few latest options for custom mobile app development using Python. There are mainly 2 frameworks I would like to call out specifically: the BeeWare project and Kivy.

Kivy– Cross-Platform Python GUIs

Kivy, the open-source library of Python for creating GUI for mobile applications across various platforms. It allows the developers to create pure graphical Python applications that run on major platforms (Linux, Windows, macOS) as well as iOS and Android.

Now, every time anyone hears about a new toolkit of the graphical user interface, he or she always wants to know how it feels “authentic”. I think the big graphical user interface app should play with the strengths of that particular platform that it is running on. For instance, when someone uses an iPhone, he or she wants consistency between the mobile apps that they use. It is of great concern to use a mobile application designed with user interface styles from another platform.

Kivy comes with a custom user interface toolkit that offers its own versions of text stickers, buttons, text entry forms, to name a few. All this means that the tools are not represented using the native user interface controls. This has its pros and cons:

On the one hand, this tool makes sure the applicability and consistency of your mobile application from one platform to another platform. But, on the other hand, it means that the Android mobile app will not sound or look like an Android mobile app. 

However, depending on the type of mobile application you are considering, this may not be a big problem at all. For most games, for instance, the “cradle” of the user interface is not crucial. The same applies to different types of specialized mobile applications such as MIDI graphics controllers for creating music. But for other types of mobile applications, this has a great impact on usability.

Therefore, if you can work with a non-native UI toolkit in mobile apps, Kivy is a great choice for you. This tool allows you to create mobile applications using your skills of Python programming language without having to learn another platform language such as Apple Swift.

You can learn more about this tool from here 

BeeWare is the second graphical user interface and the mobile app development framework. It offers you a set of useful tools and an abstract layer that you can be used easily to write original-looking desktop and mobile applications using the Python programming language.

One of the main differences between BeeWare and Kivy is that BeeWare programs use the native user interface toolkit for all the platforms you are working on, while Kivy uses a custom user interface toolkit that uses the same kind of controls on all of the platforms.

With the BeeWare tool, the widgets that control your mobile application will be checkboxes, buttons, and form elements that are being provided by the base operating system. This means that you can create mobile applications that feel and look 100% original on each mobile (as well as desktop) platform.

One of the major drawbacks of using this tool is that the BeeWare project is still relatively new and is presently being led by Pythonista Russel Keith-Magee, a development leader. As with any other framework that has not yet had the opportunity to get matured for years, it means more work for you as a mobile app development company due to API changes (which may be frequent), lack of features and errors. 

You can learn more about this tool from here.

Is Python An Excellent Programming Language For Mobile Game Apps?

Python is one of the most advanced programming languages these days. It is even used to create sophisticated mobile games. Python is a very advanced unit for building mobile applications. Even recently, there have been many discussions going on in which mobile app developers have realized that even advanced mobile phone games can be created using the Python programming language. 

Being an open-source platform, Python app developers are free to adopt this without having to make any initial investment on it. The process of building mobile applications is pretty fast. Mobile application developers can easily build the latest multi-platform mobile phone games using this programming language. 

This language is great for mobile phone games. The Python is excellent for graphics and animations, with the help of GPU acceleration, images that can be improved. If you want to create a mobile game for Android or iOS, Python should be one of your favorite options.

Use Cases of Python for App Developmentpython for app development

Let’s have a quick glance over the top mobile apps that are created using advanced features of Python and why they chose Python for their app development process:

1. Pinterest

Pinterest is a renowned image sharing site that allows users to bookmark various images, collect and share these images with other users. As one of the most-used apps in the world wide web, this app relies on Django (a Python framework) to rapidly deal with a bunch of content. In fact, this web application has used Python since day one.

2. Instagram

This is one of the most famous apps that is built using Python. This app that changed the world of digital photography, more it accessible, made instant, and widespread. This app has expanded lines of creativity and defined new rules in social media marketing. It also allows users to take as well as edit pictures and share them online. With over 400 million active users every day, this app obviously negates any notion that custom mobile apps built using Python are not really scalable. 

3. Spotify

It is the world’s largest streaming service having annual revenue of more than €5 billion. This makes it a market leader and also one of the popular Python mobile applications among businesses and users. This company chose Python due to its advanced data analytics and development speed that the language provides. This enables the firm to manage several advanced functions such as Discover and Radio, which are totally based on the personal musical preferences of mobile phone users.

4. Disqus

This is a famous commenting plug-in which is an effective and simple way to engage audience and fuel discussion while controlling incoming comments by intelligently moderating the comments. Allowing cross-site notifications and multiple sign-in options, this commenting platform serves audiences with various kinds of preferences. This platform makes use of Django’s advanced security features and security patches in this plugin.

5. Dropbox

Another famous mobile app built in Python is Dropbox which is a file-hosting service and recently moved from Python 2.7 to Python 3. One of the famous desktop mobile apps in the world, Dropbox can also be installed on macOS, Windows, and some flavors of Linux operating systems. One of the best features of Python is that it is portable and works on a plethora of platforms, from Linux and PC to PlayStation.

6. Uber

This is a ride-hailing service that provides peer-to-peer ridesharing, food delivery, and bicycle-sharing (among various other services), Uber has a lot of options to offer to its users. The company operates in 785 metro areas all across the world and is estimated to have approximately 100 million users

Here again, Python handles a large amount of data and is pretty easy to learn and work with, which are the main reasons this programming language is so popular. All these advantages of Python make it a favorite choice for firms whose mobile applications need to be secure, reliable, and rely on mobile app developers around the world to maintain it.

7. Reddit

It is a social news aggregator headquartered in America. This online forum and discussion application run on Python, even though originally it was coded in Common Lisp. After looking for greater development flexibility and wider access to code libraries, Reddit made the switch to Python programming language. 

If you look at this, this web application is somewhat of an anthill. With more than 600 million monthly visitors, Reddit is one of the most impressive and popular Python app examples these days. All the registered users post content such as video, text, or pics in a plethora of categories, and vote it up and down.

Conclusion

No doubt, python has already taken place in the market of web application development. It turned out to be the best option. However, now, businesses are also interested in adopting Python to create custom mobile applications. In the near future, the use of Python to create mobile applications will increase rapidly, with the increased demand for mobile applications.

Now, if you are a programmer and want to create a mobile app with Python you can use both Kivy and BeeWare. And as far as considering the maturity level, the Kivy tool seems to be the more mature platform at present.

If you are a business owner and hire a mobile app developer, you can consider Python development companies for your project. These companies have skilled professionals who can create secure and feature-packed Python-based mobile applications as per your business requirements.

Further Reading



Source link

Post image
Strategy

How do I make a location autocomplete where user can type ci…


I have a spreadsheet. It’s a list of businesses and Google Maps link to each business.

I want to turn it into a website that goes like this:

  1. User types city or country or state or whatever in an autocomplete field.

  2. The suggestions should show like how Trip Advisor shows it (not necessarily, whatever gets the job done)

  3. User clicks search.

  4. Website returns a list of businesses located within that city/country/state that the user searched.

So.. how do I make this autocomplete? And how will that work with my Google Maps link, if it even works at all?

Sample from TripAdvisor:

Post image



Source link

Illustartor CC 2020 Blend Tool Issue
Strategy

Illustartor CC 2020 Blend Tool Issue


Illustartor CC 2020 Blend Tool Issue

So I am trying to take a letter, and make a path perfectly in the middle of the text. I am following a tutorial, but it is not working, as you can see in the video. Can you see if I'm doing anything wrong, or is there a different way to do this?

I am trying to get this effect:

The goal

What is happening

submitted by /u/JohnLillywhite
[comments]



Source link

Post image
Strategy

I made a generator for unique, royalty-free, repeatable SVG …


It’s one of a series of tools I’m making to help the internet be faster and more accessible and expressive. Hopefully you’ll find this useful. Here’s the link and and some examples of the kind of patterns you can create with it:

https://beautifuldingbats.com/pattern-generator/

Post image
Post image
Post image
Post image
Post image
Post image

If there are any features you’d like me to add, let me know! And please send me any patterns you make, I’d love to see them.



Source link