Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

August 11 2017

14:00

Kotlin From Scratch: Variables, Basic Types, and Arrays

Kotlin is a modern programming language that compiles to Java bytecode. It is free and open source, and promises to make coding for Android even more fun.

Kotlin is 100% interoperable with Java. In other words, it can be used together with Java in the same project. So you can refactor parts of your Java code to Kotlin and it won't break. In addition to that, it is concise, expressive, and has great tooling. Kotlin can be used on the back-end (server-side), but it's getting a lot of attention right now as a language for Android app development. Kotlin is now supported by Google as a first-class language for Android development, so the popularity of Kotlin is set to explode! 

In this first tutorial in the Kotlin From Scratch series, you'll learn about the language basics: comments, variables, simple types, arrays, and type inference. 

Prerequisites

To follow along with me, you will need the Kotlin plugin on Android Studio. Alternatively, you could use the online playground or IntelliJ IDEA Community Edition

1. Variables

In Kotlin, use val to declare a constant or var keywords to declare a variable. You can specify a type such as String or Int after the variable name. In the example below, we declared a constant firstName of type String with the val keyword.

But you'll soon realize that in Kotlin, it's often possible to omit the type from the declaration and the compiler won't complain. 

In the code above, you'll observe that we did not explicitly state the type String. The code above will still work because the compiler has implicitly inferred the type using type inference. We'll come back to this! 

The difference between the val and var keywords is that the former is immutable or read-only (its value cannot be changed), while the latter is mutable (its value can be changed). 

Note that for a variable declared with the var keyword which has its type inferred by the compiler, assigning another value of a different type won't work. In other words, the value of the variable can change, but its type cannot! For example:

It is highly recommended that you start by making your variables immutable by declaring them with the val keyword, so as not to maintain too many states. This makes your code safer for multithreading, because it ensures your variables cannot be modified by other threads unexpectedly.

Another thing you should know about the val keyword is that you can declare it with a type only and assign it a value later. But you can still only assign a value once.

In Java, it's possible to declare multiple variables of the same type on a single line, but this doesn't work in Kotlin. In Kotlin, all variable declarations must be on their own lines. 

2. Type Inference or Deduction

Kotlin is a strongly typed language that supports type inference or deduction. This is the mechanism employed by the compiler to find out types from context. Java doesn't have a type inference mechanism, which means you must explicitly declare the type of every function or variable. Type inference helps reduce the boilerplate code you have to write. 

The code above would compile even though we did not explicitly state the type for the variable country. The compiler is smart enough to know that the country is of type String, because the value, "Nigeria", is a string.  

3. Basic Types

In Java, we have two types of type—primitive (e.g. int, long, boolean, byte, char, etc.) and reference types (e.g. array, String). Java uses wrappers (like java.lang.Integer) to make primitive types behave like objects. But in Kotlin, there is no such distinction. Instead, all types are objects. 

Numbers

The integer types available in Kotlin are:

  • Long—64 bit
  • Int—32 bit
  • Short—16 bit
  • Byte—8 bit

The floating-point types are: 

  • Double—64 bit
  • Float—32 bit

You can observe that we created a Long literal by adding the suffix L, and for Float we added the suffix F or f.  Numbers can also be written in hexadecimal notation using the 0x or 0X prefix and in binary using the 0b or 0B prefix. Note that in all these cases, Kotlin can use type inference to know the type we want instead.

To convert a number from one type to another, you have to explicitly invoke the corresponding conversion function. In other words, there is no implicit conversion between types of numbers. 

Each number type has helper functions that convert from one number type to another: toByte(), toInt(), toLong(), toFloat(), toDouble(), toChar(), toShort().

In the code above, we are converting from an integer to a long. We can also do the reverse by using the method toInt() on the long variable. Note that this will truncate the value to fit the smaller size of an Int type if need be—so be careful when converting from larger types to smaller ones! 

You can also convert a String into a number type.

In the code above, we converted the variable stringNumber into an Int type by calling the method toInt() on the variable. We can write this more succinctly by instead calling the method directly on the string:

The Boolean Type

The Boolean type in Kotlin is the same as in Java. Its value can be either true or false. The operations disjunction (||), conjunction (&&), and negation (!) can be performed on boolean types, just like Java. 

Strings

Strings can be created with either double quotes or triple quotes. In addition to that, escape characters can be used with double quotes. 

To create a string that spans multiple lines in the source file, we use triple quotes:

Kotlin also supports string interpolation or string templates. This is an easier way to build dynamic strings than concatenation, which is what we use in Java. Using string templates, we can insert variables and expressions into a string. 

In the code above, we created a string literal, and inside it, we referred to a variable by the use of a $ character in front of the variable name. Note that if the variable is not correct or doesn't exist, the code won't compile. 

What about if you need to use $ in your string? You just escape it with \$! Also, you can call methods from an interpolated String directly; you have to add curly braces ${} to wrap it. 

Another cool thing you can do is to perform some logic inside the curly braces when creating a String literal. 

Arrays

In Kotlin, there are two main ways to create an array: using the helper function arrayOf() or the constructor Array()

The arrayOf() Function

For example, let's create an array with some elements using arrayOf().  

Now, to access any of the element, we can use its index: myArray[2]. Note that we can pass in values of different types into the arrayOf() as arguments and it will still work—it will be an array of mixed type. 

To enforce that all the array values have the same type, e.g. Int, we declare a type by calling arrayOf<Int>() or intArrayOf().

We also have other utility functions to create arrays of other types such as charArrayOf()booleanArrayOf()longArrayOf()shortArrayOf()byteArrayOf(), and so on. Behind the scenes, using these functions will create an array of their respective Java primitive types. In other words, intArrayOf() will compile to the regular Java primitive type int[], byteArrayOf() will be byte[], longArrayOf() will be long[], and so on. 

The Array() Constructor

Now let's see how to create an array with Array(). The constructor of this class requires a size and a lambda function. We'll learn more about lambda functions later in this series, but for now, just understand that it is a simple, inline way of declaring an anonymous function. In this case, the job of the lambda function is to initialize the array with elements. 

In the code above, we passed 5 as the size of the array in the first argument. The second argument takes in a lambda function, which takes the index of the array element and then returns the value to be inserted at that index in the array. So in the example above, we created an array with elements 0, 2, 4, 6, and 8.

4. Comments

This is an easy one. In Kotlin, comments are just the same as in Java. We can use either block or line comments:

Conclusion

In this tutorial, you learned the basics of the Kotlin programming language: variables, basic types, type inference, arrays, and comments. In the next tutorial in the Kotlin From Scratch series, you'll learn about loops, ranges, conditions, collections, and packages in Kotlin. See you soon!

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Kotlin tutorials here on Envato Tuts+.

  • Android SDK
    Quick Tip: Write Cleaner Code With Kotlin SAM Conversions
    Ashraff Hathibelagal
  • Android Studio
    Coding Functional Android Apps in Kotlin: Getting Started
    Jessica Thornsby
  • Android SDK
    Java vs. Kotlin: Should You Be Using Kotlin for Android Development?
    Jessica Thornsby

12:00

JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG

After completing the first three tutorials of the series, you should now be very comfortable with a lot of Anime.js features. The first tutorial showed you how to select target elements. In the second tutorial, you learned about different types of parameters that can be used to have fine control over the delay and duration of animations of different elements. The third tutorial focused on learning how to have greater control over the values of a single property during the course of the animation.

In this tutorial, you will learn about different callbacks that can be used to execute a function based on the progress of the animation. Almost every example in the previous tutorials used CSS properties to demonstrate how different methods and parameters work. This might have given you the idea that the library is more suited for animating CSS properties. This time, we will have a section dedicated to the creation of interesting SVG-related animations in Anime.js.

Callbacks

As I mentioned in the introduction, you can use callbacks to execute functions based on the progress of the animation. There are four different callbacks: begin, run, update, and complete. Each callback function is fired at a specific time, and each one accepts an animation object as its argument. 

The begin() function is called when the animation actually begins. This means that if an animation has a delay of 800ms, begin() will be called only after that delay is over. You can check if an animation has begun playing or not using animationName.begin, which will return true or false respectively.

The run callback can be used to execute a function in every frame after an animation actually starts playing. If you want to execute a function in every frame from the very beginning of the animation irrespective of its delay, you should use the update callback instead.

The complete callback is similar to begin except for the fact that it is called once the animation has finished playing. Just like begin, you can use animationName.complete to check if an animation has finished playing or not.

You have already seen in the first tutorial how to use the update callback while animating numerical values of a JavaScript object. In this tutorial, we will modify that example and see how to use all these callbacks together to provide more information to the user.

I have intentionally added some delay in this animation so that we can notice the difference in the timing of the execution of different callbacks. The update callback starts executing its function as soon as the animation instance begins. 

The actual animation starts playing after 1000ms, and that's when the begin function shows its "Starting the Scan..." message to the user. The run function also starts executing at the same time and updates the numerical values of the object after every frame. Once the animation has finished, the complete callback shows a "Scan Complete..." message to the user.

Easing Functions

Easing functions can be used to control how the value of a property transitions from its initial value to its final value. These easing functions can be specified using the easing parameter, which can accept strings as well as custom Bézier curve coordinates (in the form of an array). 

There are 31 different built-in easing functions. One of them is linear, and the other 30 consist of ten different variations of easeIn, easeOut, and easeInOut. There are three elastic easing equations called easeInElasticeaseOutElastic, and easeInOutElastic. You can control their elasticity using the elasticity parameter. The value of elasticity can be anywhere between 0 and 1000.

EaseIn equations accelerate the value change of the property starting from zero. This means that the change in value would be slow in the beginning and very quick at the end. The rate of change is zero in the beginning and maximum at the end. EaseOut equations decelerate the value change of the property starting from the maximum rate change. 

This means that the change in value would be very quick in the beginning and very slow at the end. EaseInOut equations accelerate the rate change in the beginning and decelerate it at the end. This means that the rate of change will be slow in the beginning as well as the end, and it will be fastest in the middle of the animation. The following demo shows the difference in the rate of change for each of these easing functions.

You can also add your own custom easing functions to the built-in list with the help of anime.easings. Here is an example of creating custom easing functions.

SVG-Based Animations

All the motion-related animations that we have created until now moved the target elements in straight lines. It is also possible in Anime.js to move an element along a complex SVG path with lots of curves. You can control both the position and the angle of the animating elements on the path. To move an element to the x coordinate of the path, you can use path(x). Similarly, an element can be moved according to the y coordinate of the path using path(y)

Unless the path is a straight line, it will almost always form an angle with respect to the horizontal base line. If you are rotating any non-circular element, it will feel more natural if the element follows the angle of the path. You can do so by setting the rotate property to be equal to path('angle'). Here is the code that animates four elements with different easing values along an SVG path.

You can see in the following demo that the red square with easeInCubic easing is slowest in the beginning and the fastest at the end. Similarly, the orange square with easeOutCubic is the fastest in the beginning and the slowest at the end.

You can also animate the morphing of different SVG shapes into one another using Anime.js. The only condition is that both the shapes should have the same number of points. This means that you can only morph triangles into other triangles and quadrilaterals into other quadrilaterals. Trying to morph between an unequal number of polygon points will result in an abrupt shape change. Here is an example of morphing a triangular shape.

One more interesting effect that you can create with SVG is line drawing. All you have to do is give Anime.js the path that you want to use for line drawing and other parameters that control its duration, delay, or easing. In the following demo, I have used the complete callback to fill the line drawing of the Font Awesome anchor icon with a yellow color.

Combining the knowledge of all the concepts that you have learned so far, you can create more complex line drawings with much better control over the way they are drawn. Here is an example in which I have written my own name using SVG.

I begin by assigning the value 2000 to the variable letterTime. This is the time that I want Anime.js to take while it draws each letter of my name. The delay property uses the function-based index parameter to set an appropriate delay value with the help of the letterTime variable. 

The index of the first letter "M" is zero, so Anime.js starts drawing it immediately. The letter "O" has a delay of 2000ms because that's the amount of time it takes to completely draw the letter "M".

Inside the begin callback, I have set the stroke value of all the letters to black and their fill values to none. This way we can clear all the color values applied inside the update callback so that the letters can return to their initial state when run in multiple loops. Try clicking the Write the Name button in the following demo to see the code in action.

Final Thoughts

In this tutorial, you learned about different callback functions that can be used to perform tasks like updating the DOM or changing the value of an attribute based on the animation progress. You also learned about different easing functions and how to create one of your own. The final section of the tutorial focused on creating SVG-based animations.

After completing all four tutorials of the series, you should now have enough knowledge of Anime.js to create some interesting effects for your next project. If you have any questions related to this tutorial, please let me know in the comments.

August 10 2017

12:00

JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback

In the previous tutorial of the Anime.js series, you learned about different kinds of parameters that control how different target elements should be animated. You also learned how to use function parameters to gradually change the delay or duration of the elements. 

In this tutorial we will go a step further and learn how to specify the property values themselves using regular numbers, function-based values, and keyframes. You will also learn how to play animations in sequence using timelines.

Specifying Property Values

Anime.js allows you to specify the final or end values for animatable properties of target elements. The initial or start value for the animation is the default value of that property. Any value specified in the CSS can also act as the start value. There are multiple ways of specifying an end value. 

It can also be a unitless number. In this case, the original or default units of the property are used while calculating any property values. You can also specify the value as a string, but the string must contain at least one numerical value. Examples of string values would be 10vh, 80%, and 9.125turn.

Instead of specifying an absolute value, you can also specify property values relative to their current value. For example, you can set the final translateY value to be 150px greater than the current value using +=150px as a value. Keep in mind that you can only use addition, multiplication and subtraction while specifying relative values.

While animating colors, you cannot use color names like red, black and blue to set a final color value for the animation. In such cases, the color animation won't happen at all, and the change will be instant. The only way to animate colors is to specify the values either as hex digits or in terms of RGB and HSL values.

As you might have noticed, we have not been specifying an initial value for our target elements to animate them. Anime.js automatically determines the initial value based on our CSS and the default values of those properties. However, you can specify an initial value other than the default value for a property using arrays. The first item in the array signifies the initial value, and the second item signifies the final value.

Instead of using the same final value for all your target elements, you can use functions to set different values for different parameters. The process is similar to specifying function-based property parameters.

For the translateY property, we are using the index of the element to set a translation value. Using 50 * (i + 1) increases the translateY value for each element by 50 pixels. 

The scaling animation also uses the index of the element along with the built-in Math.random() function to return a floating-point, pseudo-random number less than 1. This way the elements scale randomly, but the i/10 part of the property slightly increases the possibility of elements that occur in the end having a larger size.

Inside the code for rotation animation, we are using the anime.random(a, b) helper function to get random integers between -180 and 180. This function is helpful for assigning random integral values to properties like translateY and rotate. Using this function to assign random scale values will produce extreme results.

The border radius value for different elements is determined by calculating the width of target elements using the el function parameter. Finally, the last part of code assigns random values to the duration and delay parameters as well. 

You can see that the animation achieved by the last part is very random. There is no relation between the values of different properties of elements or their delay and duration values. In real life, it is more sensible to use values that can add some sense of direction to the animation.

It is also possible to animate different properties of your target elements using keyframes. Each keyframe consists of an array of the property object. You can use the object to specify the property value, duration, delay and easing for that part of the animation. The following code creates a keyframe-based translation animation.

You can also animate multiple properties at once by specifying different or the same values for all the parameters. In the second case, the global delay parameter applies an initial delay to all the elements based on their index. This delay is independent of the delay applied to each property inside the keyframes.

Creating and Manipulating Timelines

So far in the series, we have been using the delay parameter to play different animations in a specific sequence. To use delay for this purpose, we also need to know the duration of the previous animation. 

With the increasing complexity of the animation sequence, maintaining the right delay value becomes very tedious. Any change in the duration of one of the animations will force us to recalculate all the delay values to keep the animations in the original sequence.

A better solution to this problem is using timelines to control the animation sequence. You have to use the anime.timeline() function to create a timeline in Anime.js. You can also pass different parameters to this function as an object. These parameters can specify the direction in which the timeline is played, the number loops, and an autoplay parameter to determine if the animation should be auto-played. All these parameters have been discussed in detail in the parameters tutorial of this series.

You can add different animations to a timeline using the add() method. All the animations added to the timeline will be played in the order in which they were added. It is possible to specify absolute or relative offset values to control the order in which the animations are played. 

When relative offset values are used, the starting time of the current animation is determined relative to the timing of the previous animation. Relative offsets can be of three types:

  • +=offset: In this case, the current animation starts playing after offset number of milliseconds have passed since the end of the previous animation.
  • -=offset: In this case, the current animation starts playing offset number of milliseconds before the end of the previous animation.
  • *=offset: In this case, the current animation starts playing after milliseconds equal to offset times the animation duration of the previous animation have passed.

The following code shows how to create a basic timeline and a timeline with relative offset values.

Try clicking the Offset Timeline button in the above demo. You will see that there is a delay of 2 seconds between the end of the animation of red squares and the beginning of the animation of blue squares. 

We have not specified a duration for the red square animation. Therefore, a default value of 1000ms or 1s is used as duration. The multiplier offset of the blue square animation doubles that value, and this results in a delay of two seconds in the animation.

When absolute offset values are used, the starting time of the timeline is used as a reference point. It is possible to reverse the sequence in which the animations are played by using large offset values for animations that occur at the beginning of the timeline.

Playback Options

Anime.js has a variety of options to play, pause, restart or seek animations or timelines at any given point.

The play() function allows us to start the animation from its current progress. The pause() function will freeze the animation at the moment the function was called. The restart() function starts the animation from the beginning, irrespective of its current progress. The seek(value) function can be used to advance the animation by value number of milliseconds.

You should keep in mind that the play() function only resumes the animation from the time it was paused. If the animation has already reached its end, you cannot replay the animation using play(). To replay the animation, you will have to use the restart() function.

Note that we are not using seekInput.value to set a value for the seek function. This is because the max value for the range input has been set to 100 in the markup. Directly using the value for input range will allow us to only seek up to 100ms. Multiplying the range input value with the animation duration makes sure that we can seek the animation from the beginning to the end on our range slider.

Final Thoughts

In this tutorial, you learned how to animate different property values as numbers, functions, or keyframes. You also learned how to control and manipulate timelines in Anime.js to control the order in which an animation sequence is played.

If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

If you have any questions related to this tutorial, please let me know in the comments.

12:00

How to Get Started With CocoaPods

In this tutorial, you'll be learning about the CocoaPods dependency manager and how to implement it in your app. We'll go through the steps from creating an Xcode project all the way to importing frameworks. Along the way, we will learn about some basic Terminal commands and what they do.

About CocoaPods

Before we get into actually implementing CocoaPods in our Xcode project, let's talk a little bit about what it is and why you should use it in the first place.

What Is CocoaPods?

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. It has over 35 thousand libraries and is used in over 2.4 million apps. CocoaPods can help you scale your projects elegantly. — CocoaPods website

CocoaPods is getting increasingly popular nowadays for Cocoa Touch development—and with good reason. CocoaPods is an easy-to-use, easy-to-implement dependency manager for your apps written in Swift or Objective-C.

What the Heck Is a Dependency Manager?

Glad you asked! In short, a dependency manager is a tool used to manage third-party frameworks. In CocoaPods, dependencies are listed in a text file called a podfile (which we will get to shortly) with simple one-line statements. 

This solves the issue of having to download and add each framework manually to your Xcode project and then deleting and reinstalling outdated frameworks (that's just a pain). Some libraries even use their own frameworks in their SDK (such as Firebase), and every time they make a small update, you have to manually reinstall everything!

Why Should I Use CocoaPods?

While there are other dependency managers out there (such as Carthage), CocoaPods is still the most widely used, and therefore, has the most libraries available for your use. Since it is the most popular, there are also more discussions regarding it on StackOverflow and other forums—that's helpful in case you ever get stuck.

Let's think of a common scenario: something that CocoaPods (or any dependency manager) can solve. You set out to build an app. This app is huge, and you don't want to rewrite code that someone else has already written, so you create a list of libraries that you think would be good to have in your project. It would be nearly impossible to be able to correctly install all of them manually and future-proof your code at the same time! This is where CocoaPods comes in.

Using CocoaPods

CocoaPods is built with Ruby, which is installed by default on versions of macOS. In this tutorial, we will be using gem to install the necessary Ruby gems to get CocoaPods set up. Gems are Ruby packages, and since CocoaPods is a Ruby program, it needs to be installed with Ruby's package manager.

To start, open up a new terminal window. You can find this in Applications > Utilities or you can simply search for it in Spotlight Search (Command-Space).

1. Installation

Enter the following line of code in your Terminal.

Then, press Enter. You will be prompted to enter your password, and when you have done so, press Enter again. After you do so, CocoaPods will install, and when it is finished your terminal should look something like this:

CocoaPods installed successfully

2. Create an Xcode Project

CocoaPods can be added to any existing Xcode project, but for the purposes of this tutorial, let's create a new one. Please feel free to follow along with your own Xcode project and skip this step.

Launch Xcode

After launching Xcode, you will see three options. Click on the second option which says Create a new Xcode project. If you have used Xcode in the past, your recent projects will appear on the right.

Welcome to Xcode

Choose Your Application Type

For this project, we will choose a single view application, but you can choose any template you need to for your specific purposes.

Choose an app template

Configure Your Project

Now, name your project and choose Swift as the language. Here, you can also set the bundle identifier and choose the devices that your app would support. Again, it is up to you, but I will name it CocoaPods.

Configuring your project

3. Create a Podfile

After you have created an Xcode project, the next step is to navigate to it using the terminal. Many of you may be familiar with this, but let's go over it together; after all, practice makes perfect!

Find the Project Directory

Before you can navigate to the project directory using the command line, it is a good idea to locate your project using the Finder first. In this case, my project is on my desktop in a folder named Tuts+.

Basic Commands

  • sudo—a way to override your user's privileges and become a super-user of the computer. This is why it requires an admin password when using it. We used this command while installing CocoaPods earlier.
  • ls—lists all of the contents in the current directory. This command comes in handy if you don't want to use the Finder to browse files; you can simply list them using this command in your Terminal.
  • cd <directory name>—this command is used to change directories. If you write cd alone, you will move out of the current directory. After using ls (to see the directories), you can write the name of the directory you want to enter.
  • vim—this is one of my favorites. Remember the podfile that I mentioned earlier? You can edit this file using the default TextEdit, but I like to use the terminal. vim is a command line text editor which we will be using to edit our podfile.

Some bonus ones: These aren't necessary right now, but hey, why not learn some more cool things while you're at it?

  • mkdir <directory name>—you can kind of tell what this one does by its name; it makes a directory (now that wasn't so hard, was it?). You have to type the name of the directory after the keyword mkdir and voila, there you have a folder appear (almost) instantly.
  • help—this command is nice because (as the name suggests), it helps you out if you ever forget a command. Just type help into your Terminal window, and a list of basic commands will pop up with their meaning.

Initialize CocoaPods

Since you have already installed CocoaPods on your machine, the next thing to do is actually initialize your Xcode project. Find where your project is located on your hard drive and follow along in your own directory.

After you are done navigating to your project via the terminal, your window should look like this. I have highlighted my project name, and yours should appear in the same spot. It should look something like this:

Ready to initialize the Xcode project

Once you are in your project directory, you will need to initialize CocoaPods, resulting in a podfile being created. To do this, type the following line into your terminal window:

This will initialize CocoaPods in your project folder, and you will see a file called podfile show up.

4. Set Up the Libraries

Hurray! CocoaPods is now ready to manage your project's dependencies. The next step is to actually add the desired libraries into your Xcode project—after all, that's what we are here for.

Edit the Podfile

Remember vim, the text editor? We will be using it to add the desired frameworks to the app. Type the following line to edit your podfile:

To get into edit mode, you just type i, as in "insert."

Add Pods to the Podfile

In CocoaPods, there are two ways to get the command for the framework you want. You can usually find the podfile line in the framework's GitHub project description. If not, go to the CocoaPods website and search for the library there and their podfile lines.

Below, I have a line for Firebase. 

As I said, it doesn't really matter where you get them from. Find one of these and follow the steps below. Now, enter your line under the comment which says:

That's all that's needed to add frameworks. See how easy that was? Now, we need to exit the vim editor and move on to the next step.

Exiting the vim Editor

In order to save your changes and exit the vim editor, you need to:

  1. Press the Esc key to get out of edit mode.
  2. Type :x (the save and exit command).
  3. Press Enter.

Install CocoaPods

This step is another one-liner. All you need to do is, in your project directory, type the following command:

Installing all the project dependencies

This will download any frameworks you listed in your podfile and install them to your Xcode project. The pods should be now available to import just as a regular framework would be (by using import <framework name> at the top of your source file).

5. Conclusion

I hope this tutorial was helpful. We covered installing CocoaPods, basic terminal commands, and how to add pods to your podfile. CocoaPods is a fast, easy-to-use, and effective tool for managing your dependencies, and it is very commonly used.

And remember:

  • You'll need to access your project only through <your project>.xcworkspace and not <your project>.xcodeproj.
  • The podfile can be edited using any text editor, and can also be edited within your Xcode.
  • Run pod install from the terminal after changing your podfile so the dependencies will be removed or added.

While you're here, check out some of our other posts on coding iOS apps!

  • iOS
    Upgrade Your App to iOS 10
    Bart Jacobs
  • iOS SDK
    Realm Mobile Database for iOS
    Doron Katz
  • iOS SDK
    15 Best iOS App Templates of 2017
    Nona Blackman

August 09 2017

12:00

JavaScript-Based Animations Using Anime.js, Part 2: Parameters

In the first tutorial of the Anime.js series, you learned about different ways of specifying the target elements that you want to animate and the kinds of CSS properties and DOM attributes that can be animated. The animations in the previous tutorial were very basic. All the target elements were just moving a certain distance or changing the border radius at a fixed speed. 

Sometimes, you might need to animate the target elements in a more rhythmic manner. For example, you might have ten different elements that you want to move from left to right with a delay of 500ms between the start of the animation for each element. Similarly, you might want to increase or decrease the animation duration for each element based on its position.

In this tutorial, you will learn how to use Anime.js to properly time the animation of different elements using specific parameters. This will allow you to control the order in which an animation sequence is played for individual elements or all the elements.

Property Parameters

These parameters allow you to control the duration, delay and easing of individual properties or a group of properties at once. The duration and delay parameters are specified in milliseconds. The default value for duration is 1000ms or 1s. 

This means that unless specified otherwise, any animation applied to an element will be played for 1 second. The delay parameter specifies the amount of time the animation takes to begin once you have already triggered it. The default value for delay is 0. This means that the animations will begin as soon as they are triggered.

You can use the easing parameter to control the rate at which an animation is played for the duration it is active. Some animations start out slow, pick up pace in the middle, and then slow down again at the end. Others start at a good pace and then slow down for the rest of the time. 

However, in all the cases, the animation always completes within the time specified using the duration parameter. Anime.js provides a lot of easing functions that you can apply to your elements directly by only using their names. For some easing functions, you can also set a value for the elasticity parameter to control how much an element's value bounces back and forth like a spring. 

You will learn more about different easing functions in the final tutorial of the series. The following code snippet shows how to apply all these parameters to different animations.

As you can see, these parameters can be used independently of other parameters or in combination with them. The cubicAnimation has both the duration and easing parameter applied to it. If the duration had not been specified, the animation would have run for 1 second. Now, it will run for 1,200 milliseconds or 1.2 seconds.

One major limitation of property parameters in the above example was that all the animations of the target element will have the same duration, delay and easing values. 

This may or may not be the desired behavior. For example, instead of translating and changing the border radius of the target element at the same time, you might want to first translate the target element and then animate its border radius. Anime.js allows you to specify different values for the duration, delay, easing and elasticity parameters for individual properties. The following code and demo should make it clearer.

In the above code, all the properties that we want to animate have different values. The background color animation has a duration of 400ms, while the rotation and translation animations use the global duration value of 1500ms. 

The background color animation also has a delay so any change in the color only starts after 1500ms have passed. The rotate and translateY properties use the default value for the delay and easing parameters because we have neither provided a local nor a global value for them.

Function-Based Parameters

Property-based parameters are helpful when you want to change the order and duration for animating individual properties. However, the same duration and delay will still be applied for individual properties on all the target elements. Function-based parameters allow you to separately specify the duration, delay, elasticity and easing for different target elements in a compact manner. 

In this case, you set the values of different parameters using functions instead of numbers. These functions accept three parameters: target, index, and targetCount. The target parameter stores the reference to the current target element. The index parameter stores the index or position of the current target element. The targetCount parameter stores the total number of target elements.

The target parameter is useful when the animation values need to be set based on some attributes of the target element. For example, you can store the delay, duration or easing values for a target element in data attributes and then access them later. 

Similarly, you could access the background color of a target element and then manipulate it to set a final unique color value for individual elements. In this way, you could animate all the elements to have a background color that is 20% darker than their current color.

The index parameter gives you the position of the current target in our list of target elements. You can use it to gradually change the value for parameters like duration and delay for different elements. 

This is generally useful when you want to set the values in ascending order. You can also subtract the index from the targetCount to set the values in descending order. The following code snippet uses both these parameters to specify the values in ascending and descending order.

The following code sets a different easing value for each target element using the index parameter.

Animation Parameters

This last set of parameters allows you to specify the number of times an animation should be played and the direction in which it should be played. You can specify the number of times an animation should be played using the loop parameter. There is also an autoplay parameter which can be set to true or false. Its default value is true, but you can stop the animations from starting by themselves by setting it to false.

The direction parameter controls the direction in which the animation is played. It can have three values: normal, reverse, and alternate. The default value is normal, which keeps the animation playing normally from the start values to the finish values. Once the target elements reach the finishing value, if the loop value is greater than 1, the target elements jump back abruptly to the start values and then begin the animation again.

When the direction is set to reverse and the loop value is greater than 1, the animation gets reversed. In other words, the target elements start the animation from their final state and go backwards to reach the initial state. Once they are in the initial state, the elements jump back to the final state and then again start the reverse animation. The alternate direction value changes the animation direction after every loop.

In the following demo, I have set the number of loops to four so that you can easily notice the difference in animation of the elements in different modes.

Final Thoughts

In this tutorial, you learned about different kinds of parameters that can be used to control the animation of target elements in Anime.js. The property parameters are used to control the animation of individual properties. 

You can use them to control the sequence in which the animation is played for individual elements. The function parameters allow you to control the timing and rate of animation for individual elements with respect to the whole group. The animation parameters allow you to control how the animation itself is played for different elements.

If you have any questions related to this tutorial, please let me know in the comments.

August 08 2017

17:00

How to Create an Instant App Feature

Android instant apps are a powerful new way of getting your app in front of as many users as possible. 

Once you’ve added instant app support to your project, users don’t even need to have your app installed in order to access its contents and features—they’ll be able to load entire sections of your application on-demand, simply by tapping a URL. 

In this three-part series, I’m covering the entire process of adding instant app support to your Android projects, so by the time you’ve finished you’ll know exactly how to create Android applications that are discoverable and accessible for any location that supports URLs. 

In the first post, we looked at what instant apps are and how they work, as well as examining why this new feature is such big news for both Android developers and Android users. Previously, we took a few shortcuts and created an Android project that has instant app support built-in, but we didn’t look at how to add instant app support to an existing project—so this is what we’re going to be focusing on in this post. 

I’ll also be showing you how to implement App Links, so by the end of this article you’ll have created a fully functioning instant app that you can launch and test on any compatible Android device.

Downloading the Sample Project 

Adding instant app support to a project typically requires you to make some pretty drastic changes to how that project is structured. 

Chances are you’re not too keen on the idea of experimenting with a new feature by completely changing the structure of one of your own Android projects, so I’ve provided a sample app that you can download from GitHub. Throughout this article, we’ll be working on updating this specific project to support the instant apps feature. 

Download the MyLocation project from GitHub and open it in Android Studio. You’ll see that this is a pretty straightforward project, made up of a single app module that contains one Activity (MapsActivity). 

The MyLocation project displays your current location on a Google Map

Although you can install and launch this project in its current state, if MapsActivity is going to display any real content, then you’ll need to generate an API key and add it to this project: 

  • Open the project’s res/values/google_maps_api.xml file.
  • Generate your Google Maps API key, by following the instructions in this file.
  • Copy/paste the resulting key into the google_maps_api.xml file:

We’re going to update this project so that its single feature (i.e. the ability to display the user’s current location on a map) is available in instant app form. To achieve this, we’re going to complete the following steps:  

  • Create a base feature module containing all the code and resources that are required to deliver this single feature. 
  • Create an instant app module that’ll serve as the container for our instant app APK. 
  • Use App Links to map a specific URL to this base feature module.

Before we begin, there are also a few things you need to be aware of:

  • We won’t be adding any additional feature modules to this project until the next post. However, as you’ll see when we come to test MyLocation, it’s perfectly possible to add instant app support to a project by creating a base feature module and an instant app module—additional feature modules are an optional extra.
  • Since the MyLocation project consists of a single feature only, we pretty much need to include all of its code and resources in the base feature module. We can make this task much easier by turning this project’s app module into the base feature module, and then creating a new module to serve as a replacement app module. This is a handy shortcut that you may be able to use when adding instant app functionality to your own real-life Android projects. However, if this shortcut isn’t feasible for a particular project, then you’ll need to create a new module to act as your base feature module, and then spend some time moving all the relevant code and resources into this new base feature module. 

Convert the App Module Into a Base Feature Module

Our first task is converting MyLocation’s app module into a base feature module.

When you’re working with multiple modules, it helps to establish a naming convention early on, so throughout this article I’m going to be appending each module’s type (-app, -base, -instantapp, etc.) to the module’s name: 

  • Control-click the app directory and select Refactor > Rename…
Select Refactor  Rename from the context menu
  • In the Rename module window, enter mylocation-base and then click OK
  • Open your newly-renamed mylocation-base module’s build.gradle file. The first line reveals that this module is still using the default com.android.application plugin; however, all feature modules must use the com.android.feature plugin, so you’ll need to change this to apply plugin: 'com.android.feature.'.
  • Make it clear that this module is your project’s one and only base feature module, by adding the baseFeature true attribute to the android block of code. 
  • Any project that supports the instant app feature is inevitably going to consist of multiple modules, but you only need to declare the project’s applicationID once—and that’s in the app module. To avoid conflicts and confusion, you should remove this attribute from the rest of your project, so find the applicationID attribute in the mylocation-base build.gradle file, and delete it. 

After completing all these steps, your mylocation-base build.gradle file should look something like this:

Create Your Application Module 

At this point, MyLocation is missing an application module, so let’s create a replacement: 

  • Select New > New module… from the Android Studio toolbar.
  • In the window that appears, select Phone and Tablet, and then click Next.
  • Let’s stick to the naming convention we’ve established, and call this module mylocation-app. Click Next
  • This module should contain the code and resources that you want to include in your installable application, but to help keep things as straightforward as possible, click Add No Activity, and then click Finish.
  • Open your mylocation-app module’s Manifest file. If you think back to the project we created in the previous post, you’ll remember that the app module’s Manifest was pretty much empty, because eventually the contents of all the other Manifests scattered throughout this project would be merged with this file. This is exactly what’s going to happen with our MyLocation project, so to avoid any conflicts during the merging process, you should delete this Manifest’s entire application block. 
Delete the application block of code from your Manifest
  • Open the mylocation-app module’s build.gradle file. This module depends on our mylocation-base module, so remove all the code from the dependencies block, and replace it with the following: 
  • Remove all unused files and directories from your application module, by switching to Android Studio’s Project view and deleting the src/androidTest directory. Then, open the main directory and delete the Java, res and test directories. 
Delete the following files and directories srcandroidTest mainJava mainres and maintest

We’ve successfully moved all of MyLocation’s functionality into a shareable base feature module. Since this required us to make some pretty drastic changes to our project structure, you should check that MyLocation is still functioning as an installable app:

  • Launch the AVD (Android Virtual Device) we created in part one, or connect a physical Android device that’s compatible with the instant app feature—at the time of writing, this is limited to the Nexus 5X, Nexus 6P, Pixel, Pixel XL, or a Galaxy S7 that’s running Android 6.0 or higher.
  • Select Run > Run… from the Android Studio toolbar.
  • Select the mylocation-app module. 
  • The MyLocation app will appear onscreen and, assuming that you generated a Google Maps API key for this project, it should be displaying some Google Maps content. 

Creating the Instant App Module 

The instant app module fulfils the simple, but essential task of acting as a container for all the Instant App APKs that are generated by your project. To create this module:

  • Select File > New > New Module… from the Android Studio toolbar.
  • In the subsequent window, select Instant App and then click Next
  • Give this module the name mylocation-instantapp and click Finish
  • Since this instant app module exists solely to contain our base feature module, we need to open its build.gradle file and declare mylocation-base as a dependency: 

Adding App Links to Your Project

The user launches an instant app by tapping a URL that’s mapped to a base feature or feature module. This URL could be anywhere—maybe it’s a URL a friend has sent them directly via email or instant message; maybe it’s a URL they’ve spotted in a tweet, forum or in a comment thread, or a URL that’s popped up in their Google search results. 

Regardless of where it appears, when the user taps this link, Google Play will recognise that it’s associated with a base feature or feature module, and retrieves all the code and resources required to run this particular module on the user’s device.

In this section, we’re going to establish this relationship between our base feature module and a URL, using App Links. The Android App Links feature was originally introduced to help users bypass Android’s app selection dialog when they were trying to access content that could be handled by an app that’s already installed on their device. For example, if you tap a link to a YouTube video, then the system may display a dialog asking whether you want to open this link in the YouTube app.

In the context of instant apps, App Links allow you to map a feature module’s entry-point Activity to a specific URL. We explored entry-point Activities in part one, but as a recap, they’re the first Activity the user sees when they launch your base feature or “regular” feature module. 

When you’re adding instant app support to a real-life project, you’ll need to decide which Activity would make the most effective introduction to your instant app component, but since mylocation-base only has a single Activity, this decision has already been made for us! 

Digital Asset Links

In this section, we’re going to use Android Studio’s built-in App Links Assistant to associate MapsActivity with the URL www.example.com/maps, but first, a disclaimer:

Uploading a Digital Asset Links file to the domain you’re working with (in this instance, www.example.com) is a crucial step in the App Links process, as it’s how the system verifies that your app has permission to act as the default handler for all the links associated with this domain. 

Although I’ll be covering the process of generating and uploading a Digital Asset Links file, since we don’t own the www.example.com domain, we won’t actually be able to perform this step. However, strangely, at the time of writing it does seem possible to test an instant app component on an AVD, even if you haven’t uploaded a Digital Asset Link to the associated domain—you just need to make some tweaks to Android Studio’s runtime configuration. 

If you do have easy access to a domain where you can host a Digital Asset Links file, then I’d recommend replacing the www.example.com URLs with genuine URLs and uploading the resulting Digital Asset Links file to your website. However, even if you do use the www.example.com URLs then you should still be able to test MyLocation’s instant app component, by tweaking the runtime configuration.

Create the URL Mapping

Android Studio 2.3 and higher comes with a built-in App Links Assistant that makes adding App Links to your project much more straightforward: 

  • Select Tools > App Links Assistant from the Android Studio toolbar. The Assistant will open as a new panel along the right side of the Android Studio window. 
  • Give the Open URL Mapping Editor button a click.
  • In the URL-to-Activity mappings panel that appears, click the little + icon. 
  • In the Host field, enter the domain you want to associate with this project; I’m going to use www.example.com

The next step is entering the specific URL you want to use in your mapping. You have a few options here, so open the Path dropdown and choose from: 

  • Path. You should select this option if you want to map a single URL to your entry-point Activity. Since I only want MapsActivity to respond to the www.example.com/maps URL, I’m going to select Path from this dropdown menu. We’ve already associated the domain www.example.com with our project, so we just need to type the final part of the URL (/maps) into the accompanying text field. 
Select Path from the dropdown menu and enter maps in the accompanying text field
  • pathPattern. Similar to Path, this option lets you specify the exact URL that should launch your entry-point Activity. However, it also gives you a bit more flexibility, by allowing you to use wildcard characters in the accompanying text field. 

Next, you need to select MapsActivity as this module’s entry-point Activity:

  • Open the Activity dropdown menu.
  • Select .MapsActivity (mylocation-base).
  • Click OK.

The App Links Assistant helpfully updates your Manifest with all the code required to turn MapsActivity into this module’s entry-point Activity; if you take a look at your mylocation-base module’s Manifest, then you’ll see the following code: 

Next, we need to tell MapsActivity how to respond when it’s launched via this URL. Once again, the App Links Assistant can walk you through this process:

  • Back in the App Links Assistant, give the Select Activity button a click. 
  • Select the Activity you want to map to your URL, which in this instance is MapsActivity
  • Click Insert code, and the App Links Assistant will insert the following code into the MapsActivity

When you come to add instant app support to your own real-life projects, you’ll typically want to expand on this code, depending on how you want your Activity to react when it’s launched as an instant app, but for the purposes of our MyLocation project, these few lines get the job done. 

Associate Your App With Your Website

In this section I’m going to show you how to generate a Digital Asset Links file, and how to upload this file to your website. If you’re using www.example.com as a stand-in for genuine URLs, then you won’t be able to complete this step, but it’s still important to understand how to generate and upload this file, ready for when you’re adding instant app support to your own Android projects. 

To create this association between your domain and your application, you need to complete the following steps: 

  • In the App Links Assistant, click the Open the Digital Asset Links File Generator button.
  • Enter the domain you want to associate with this app, such as www.example.com.  
  • Enter your application ID.
  • Enter your app’s signing config, or select a keystore file. While it’s possible to use a debug config or keystore during testing, the generated Digital Asset Links file won’t be compatible with the release version of your app. If you do upload a Digital Asset Links file that uses a debug config or keystore, then before publishing your app you’ll need to generate and upload a new Digital Asset Links that uses your app’s release key.
  • Click the Generate Digital Asset Links file button. 
  • Download the Digital Asset File, by clicking the Save file button. In the Canary builds of Android Studio 3.0, this button is sometimes positioned offscreen, so you may need to resize your Android Studio window in order to bring the Save file button out of hiding. Clicking this button will download an assetlinks.json file to your computer. 
  • You must host the assetlinks.json file at the following address https://<yoursite>/.well-known/assetlinks.json, so upload your newly downloaded assetlinks.json file to this exact location. Also be aware that Android verifies the assetlinks.json file via an encrypted HTTPs protocol, so you’ll need to ensure this file is accessible over an HTTPS connection.
  • Back in Android Studio, click the App Link Assistant’s Link and verify button. If you’re following along with this tutorial using the www.example.com stand-in links, then Android Studio should report that you’ve successfully completed every step, except uploading the Digital Asset Links file.

Testing Your Instant App 

Now you’re finally ready to test MyLocation’s instant app component!

Specifically, we want to test that if a user doesn’t have MyLocation installed on their device, then tapping the www.example.com/maps link will give them access to the mylocation-base module:

  • Launch your instant app-compatible AVD.
  • Verify that the MyLocation app isn’t installed on your AVD by opening its launcher. If you do spot the MyLocation app, then uninstall it by dragging it to the device’s Uninstall icon. 
  • Next, you’ll need to make some tweaks to our project’s run configuration, especially if you’re using www.example.com/maps to trigger your mylocation-base module. Start by selecting Run > Edit configurations... from the Android Studio toolbar. 
  • Select mylocation-instantapp from the left-hand menu. 
  • Open the Launch dropdown and set it to URL.
  • Delete the <> text, and replace it with the URL you want to use, such as http://www.example.com/maps. When you select this run configuration, it’ll simulate the user tapping the www.example.com/maps link. 
Delete the Error text and replace it with wwwexamplecommaps
  • Click Apply, followed by OK
  • Select Run > Run… from the Android Studio toolbar.
  • Choose mylocation-instantapp as the component you want to launch. 
  • Select your target AVD, and click OK
  • If this is the first time you’re running an instant app on this particular AVD, then the device will prompt you to opt into the instant app program. Read the disclaimer, and if you’re happy to proceed, then click Yes, I’m in.

Android Studio will now simulate you tapping the www.example.com/maps link, and the AVD should respond by loading your base feature module. At this point, the MapsActivity will appear onscreen, and you’ll be able to interact with it exactly as though MyLocation was installed on this device. 

To verify that MyLocation really isn’t present on this device, minimise the MapsActivity and open the AVD’s launcher—the MyLocation app should be completely absent, and yet if you click the AVD’s Recents softkey, the MapsActivity is still visible and available on this device. 

You can download the MyLocation project, updated with full instant app support, from GitHub.

Troubleshooting

Instant apps is still very much a new feature, so it’s not all that unusual to encounter error messages, bugs and other strange behaviour, especially if you’re using one of the Preview or Canary builds of Android Studio 3.0.

The most common problem you’ll encounter is, when selecting Run > Run instantapp from the Android Studio toolbar, to have the AVD respond by displaying the app picker dialog or by opening the URL in its default browser. If this occurs, then it means the AVD isn’t properly recognising that your URL is mapped to an instant app module, and is handling it just like a regular URL.

Assuming that you’ve implemented instant app support correctly, there are a few possible reasons why your AVD may be refusing to cooperate: 

Is Your AVD Set Up to Allow Instant Apps?

Depending on the AVD you’ve created, it’s possible that you may need to explicitly tell your AVD to support instant apps:

  • Open the AVD’s Settings app.
  • Select Google.
  • Scroll to the Services section.
  • If you spot an Instant app option, then give it a tap.
  • On the subsequent screen, drag the slider into the On position. 
  • Repeat the process of trying to launch your instant app module on your AVD, to see whether this has fixed your problem.

Are Instant Apps Supported in Your Locale?

Instant apps aren’t supported in every locale, so check whether instant apps are currently available in your part of the world. If they aren’t, then you’ll need to use adb (Android Debug Bridge) commands to trick your AVD into thinking you’re in a different location:  

  • Open the Terminal (if you’re a Mac user) or Command Prompt, if you’re on Windows.
  • “Change directory” so the Terminal or Command Prompt is pointing at the adb program that’s included in your Android SDK, for example: 
  • Next, enter the following command:
  • Once a # appears in the Terminal or Command Prompt window, enter the next command: 
  • Your AVD will now reboot, and once it's restarted it’ll be using the new locale settings. You should now be able to successfully run instant apps on this device. 

If All Else Fails….

If none of the above fixes work, then you may get some positive results by triggering the instant app component from an adb command, rather than by navigating the various Android Studio menus: 

  • Open a Terminal or Command Prompt window.
  • Use the cd command so that the Terminal/Command Prompt is pointing at the adb program. 
  • Enter the following command, being sure to replace complete-url-path with the URL you want to use:

Side Loading Instant App Failed

Sometimes, Android Studio may outright refuse to even load an instant app component on your AVD, as some developers have reported encountering the following error whenever they try to launch an instant app:

Side loading instant app failed: Reading bundle timed out.

If you do encounter this error message in Android Studio, then you can usually resolve it by clearing the cache: 

  • Select Run > Edit configurations… from the Android Studio toolbar.
  • Select mylocation-instantapp from the left-hand menu.
  • Select Instant app provision (towards the bottom of this window).
  • Click the pencil icon.
  • Select Clear provisioned devices cache.
Select the Clear provisioned devices cache checkbox then click OK
  • Click OK, followed by Apply, and then hit OK once more. 
  • Attempt to relaunch your instant app component on your AVD—the problem should now be resolved. 

Conclusion 

In this article, we looked at how to update an existing Android project to support instant apps, by creating a base feature module and an instant app module, implementing App Links, and then testing this project on an AVD. 

At this point, you have all the information you need to add instant app functionality to your existing Android projects, but with one restriction: we’ve only created a single base feature module. This means that, currently, you’re limited to offering one instant app feature per project.

In the final post of this series, we’re going to rectify this by looking at how you’d add an extra feature module to the MyLocation project. That'll be out soon. While you're waiting, check out some of our other great posts on Android app development!

  • Android SDK
    Android O: Phone Number Verification With SMS Tokens
    Chike Mgbemena
  • Android Things
    Android Things: Creating a Cloud-Connected Doorman
    Paul Trebilcox-Ruiz
  • Android SDK
    Create an Intelligent App With Google Cloud Speech and Natural Language APIs
    Ashraff Hathibelagal


12:00

JavaScript-Based Animations Using Anime.js, Part 1: Targets and Properties

Anime.js is a lightweight JavaScript-based animation library. You can use it to animate different CSS properties, SVG or DOM attributes on a webpage. The library allows you to control all aspects of the animation and provides a lot of ways for you to specify the elements that you want to target or the properties that you want to animate. 

You have full control over the sequence in which the animations are played or how synchronized the animations of different elements are with respect to each other. The library supports all modern browsers, including IE10+. 

In this tutorial series, you will learn about all the features of Anime.js so that you can use them in real-life projects with ease.

Before diving deep into the topic, let's install the library first. You can use either npm or bower to perform the installation by running the following commands:

You can also download the library and include it in your project or directly link to the latest version of the library hosted on a CDN.

After a successful installation, you are now ready to use this library to add interesting animation to your elements. We will start with the basics of the library, focusing on one particular area at a time.

Specifying Target Elements

To create any animations using Anime.js, you will have to call the anime() function and pass it an object with key-value pairs that specify the target elements and properties that you want to animate, among other things. You can use the targets key to tell Anime.js which elements you want to animate. This key can accept values in different formats.

CSS Selectors: You can pass one or more CSS selectors as a value for the targets key. 

In the first case, Anime.js will animate all the elements with a blue class. In the second case, Anime.js will animate all the elements with either the red or blue class. In the third case, Anime.js will animate all the even children with a square class. In the last case, Anime.js will animate all the elements with a square class that don't have a red class.

DOM Node or NodeList: You can also use a DOM node or a NodeList as a value for the targets key. Here are a few examples of setting the targets as a DOM node.

In the first case, I have used the getElementById() function to get our special element. The querySelector() function is used to get the first element that has the blue class. The querySelectorAll() function is used to get all the elements within the document that match the specified group of selectors. 

There are a lot of other functions as well that you can use to select your target elements that you want to animate. For example, you can get all the elements with a given class name using the getElementsByClassName() function. Similarly, you can also get all the elements with a given tag name using the getElementsByTagName() function. 

Any function that returns a DOM node or a NodeList can be used to set the value of the targets key in Anime.js.

Object: You can also use a JavaScript object as a value for the targets key. The key of that object is used as an identifier, and the value is used as a number that needs to be animated. 

You can then show the animation inside another HTML element with the help of additional JavaScript. Here is the code to animate the values of two different keys of an object.

The above code will animate the scanned files count from 0 to 1,000 and the infected files count from 0 to 8. Keep in mind that you can only animate numerical values this way. Trying to animate a key from 'AAA' to 'BOY' will result in an error. 

We have also used a callback function for the update key that is called on every frame while the animation is running. We have used it here to update the count of scanned and infected files. However, you could go a step further and show users an error message when the number of infected files goes over a certain threshold. 

Array: The ability to specify a JavaScript array as the target comes in handy when you have to animate a bunch of elements that fall under different categories. For example, if you want to animate a DOM node, an object and a bunch of other elements based on CSS selectors, you can do so easily by putting all of them inside an array and then specifying that array as a value for the targets key. The following example should make it clearer:

Properties That Can Be Animated in Anime.js

Now that you know how to specify different elements that you want to animate, it is time to learn about all the properties and attributes that can be animated using the library.

CSS Properties: Anime.js lets you animate a lot of CSS properties, like the width, height, and color, for different target elements. The final values of different animatable properties like background-color and border-width are specified using a camel case version of that property. Therefore, background-color becomes backgroundColor, and border-width becomes borderWidth. The following code snippet shows how to animate the left position and the background color of a target element in Anime.js.

The properties can accept all kinds of values that they would have accepted when used in regular CSS. For example, the property left could be set to 50vh, 500px, or 25em. You could also specify the value as a bare number. In this case, the number would be converted to a pixel value. Similarly, the background color could be specified as a hexadecimal, RGB or HSL color value.

CSS Transforms: You can also animate different CSS transform properties using Anime.js. Translation along the x and y axes can be achieved using the translateX and translateY properties. Similarly, it is possible to scale, skew or rotate an element along a specific axis by using the scale, skew and rotate property corresponding to that specific axis. 

You can specify different angles either in terms or degrees or in terms of turn. The value of 1 turn is equal to 360°. This can make the calculation easier when you know how much you want to turn the elements in terms of complete rotations. The following example shows how to animate the scaling, translation or rotation of an element on an individual basis as well as all at once.

SVG Attributes: It is possible to animate attributes of different SVG elements using Anime.js. The only condition is that the value of those attributes should be numerical. This ability to animate different attributes opens up the possibility of creating some really cool effects. Since you are just starting to learn about Anime.js, we will keep the examples in this tutorial very basic. 

As we move forward, you will learn how to create more complex animations. Here is the code to animate the cx, cy and stroke-width attributes of a circle. Just like the CSS properties, you need to use a camel case version of stroke-width for the code to work.

DOM Attributes: You can also animate numerical DOM attributes just like you animated the SVG attributes. One situation where animating a DOM attribute can be useful is the HTML5 progress element. This element has two attributes, value and max. In our example, we will be animating the value attribute to show the progress of our file transfer process. Here is the code to animate the value attribute.

Final Thoughts

In this tutorial, you learned about all the ways of selecting target elements in Anime.js and how to animate different CSS properties and attributes related to them. At this point, we are not controlling anything related to the actual animation. 

JavaScript is arguably the language of the web. It’s not without its learning curves, of course, and there are plenty of frameworks and libraries to keep you busy, as you can tell. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

In the next tutorial of the series, you will learn how to control the easing, delay and duration of the animation for different properties as a group as well as individually. You will then learn how to control all these animation parameters for individual elements.

If there are any questions related to this tutorial or if you have used Anime.js in any interesting projects, please let us know in the comments.

August 07 2017

17:54

New Course: Code a Custom Drupal Module

Final product image What You'll Be Creating

If you want an easy way to create engaging, content-driven websites for you and your customers, you should give Drupal 8 a try. And Drupal modules allow you to take things a step further and create highly customized functionality for your site. 

In our new course, Code a Custom Drupal Module, Envato Tuts+ instructor Derek Jensen will get you up and running with modules in no time. You'll build a simple calculator module, and along the way you'll learn about creating routes, controllers, parameters, and more.

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 200,000+ photos and 26,000+ design assets and templates. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

 

Looking for a shortcut? Try downloading some of the ready-made Drupal themes on Envato Market.

16:50

Quick Tip: Write Cleaner Code With Kotlin SAM Conversions

If you are an experienced Android application developer, you're probably used to the verbosity of Java 7. As a result, you might be finding Kotlin's concise syntax, which is geared towards functional programmers, slightly unsettling.

One common problem beginners encounter while learning Kotlin is understanding how it expects you to work with Java interfaces that contain a single method. Such interfaces are ubiquitous in the Android world and are often referred to as SAM interfaces, where SAM is short for Single Abstract Method.

In this short tutorial, you'll learn everything you need to know to aptly use Java's SAM interfaces in Kotlin code.

1. What Is a SAM Conversion?

When you want to make use of a Java interface containing a single method in your Kotlin code, you don't have to manually create an anonymous class that implements it. Instead, you can use a lambda expression. Thanks to a process called SAM conversion, Kotlin can transparently convert any lambda expression whose signature matches that of the interface's single method into an instance of an anonymous class that implements the interface.

For example, consider the following one-method Java interface:

A naive and Java 7-like approach to using the above interface would involve working with an object expression and would look like this:

That's a lot of unnecessary code, which is also not very readable. By leveraging Kotlin's SAM conversion facility, however, you can write the following equivalent code instead:

As you can see, we've now replaced the anonymous class with a short lambda expression, which is prefixed with the name of the interface. Note that the number of arguments the lambda expression takes is equal to the number of parameters in the signature of the interface's method.

2. SAM Conversions in Function Calls

While working with Java classes having methods that take SAM types as their arguments, you can further simplify the above syntax. For example, consider the following Java class, which contains a method that expects an object implementing the Adder interface:

In your Kotlin code, you can now directly pass a lambda expression to the setAdder() method, without prefixing it with the name of the Adder interface.

It is worth noting that while calling a method that takes a SAM type as its only argument, you are free to skip the parenthesis to make your code even more concise.

3. SAM Conversions Without Lambdas

If you think lambda expressions are confusing, I've got good news for you: SAM conversions work just fine with ordinary functions too. For example, consider the following function whose signature matches that of the Adder interface's method:

Kotlin allows you to directly pass the myCustomAdd() function as an argument to the setAdder() method of the Calculator class. Don't forget to reference the method using the :: operator. Here's how:

4. The it Variable

Many times, SAM interfaces contain one-parameter methods. A one-parameter method, as its name suggests, has only one parameter in its signature. While working with such interfaces, Kotlin allows you to omit the parameter in your lambda expression's signature and use an implicit variable called it in the expression's body. To make things clearer, consider the following Java interface:

While using the Doubler interface in your Kotlin code, you don't have to explicitly mention the number parameter in your lambda expression's signature. Instead, you can simply refer to it as it.

5. SAM Interfaces in Kotlin

As a Java developer, you might be inclined to create SAM interfaces in Kotlin. Doing so, however, is usually not a good idea. If you create a SAM interface in Kotlin, or create a Kotlin method that expects an object implementing a SAM interface as an argument, the SAM conversion facility will not be available to you—SAM conversion is a Java-interoperability feature and is limited to Java classes and interfaces only.

Because Kotlin supports higher-order functions—functions that can take other functions as arguments—you'll never need to create SAM interfaces in it. For example, if the Calculator class is rewritten in Kotlin, its setAdder() method can be written such that it directly takes a function as its argument, instead of an object that implements the Adder interface.

While using the above class, you can set adder to a function or a lambda expression using the = operator. The following code shows you how:

Conclusion

Android's APIs are largely written in Java, and many use SAM interfaces extensively. The same can be said of most third-party libraries too. By using the techniques you learned in this tutorial, you can work with them in your Kotlin code in a concise and easy-to-read way.

To learn more about Kotlin's Java-interoperability features, do refer to the official documentation. And do check out some of our other tutorials on Android app development!

  • Android SDK
    Android O: Phone Number Verification With SMS Tokens
    Chike Mgbemena
  • Android Things
    Android Things: Creating a Cloud-Connected Doorman
    Paul Trebilcox-Ruiz
  • Android SDK
    Create an Intelligent App With Google Cloud Speech and Natural Language APIs
    Ashraff Hathibelagal

12:00

12 Indispensable Go Packages and Libraries

Go is an amazing language with a lot of momentum, and it's focused on simplicity. This approach is evident in its standard library, which provides all the essentials, but not much more. 

Fortunately, Go has a vibrant community that creates and shares a lot of third-party libraries. In this tutorial, I'll introduce you to 12 of Go's best packages and libraries. Some of them have relatively narrow scope and can be added to any projects, while others are huge projects that you can incorporate into massive, large-scale distributed systems.

Awesome Go

Before diving into the libraries themselves, let me introduce you to Awesome Go, a very active and curated list of Go libraries and other resources. You should visit every now and then and check what's new.

1. Golang-Set

Go has arrays, slices and maps, but it doesn't have a set data structure. You can mimic a set with a map of bools, but it's nice to have an actual data type with the right operations and semantics. This is where golang-set comes in. Here is a basic example of creating a new set, adding items and testing for membership:

Note that the package name is "mapset". In addition to the basics, you perform all set operations like union, intersection, and difference. You can also iterate over the set values: 

2. Color

Let's continue with the color theme. When writing command-line programs, it is useful to use colors to highlight important messages or distinguish between errors, successes, and warnings. 

The color package gives an easy way to add some color to your programs (see what I did there?). It uses ANSII escape codes and supports Windows too! Here is a quick example:

The color package supports mixing colors with background colors, styles like bold or italic, and sprinkling color with non-color output.

The color package has other useful features. Go ahead and explore more.

3. Now

Now is a very simple package that provides a convenience wrapper for the standard time package and makes it easy to work with various date and time constructs around the current time. 

For example, you can get the beginning of the current minute or the end of the Sunday closest to the current time. Here is how to use "now":

You can also parse times and even add your own formats (which will require updating the known formats). The Now type embeds time.Time, so you can use all of the time.Time methods directly on Now objects.

4. Gen

The gen tool generates code for you—in particular, type-aware code that tries to alleviate the gap of not having templates or generics in Go.

You annotate your types with a special comment, and gen generates source files that you include in your project. No runtime magic. Let's see an example. Here is an annotated type.

Running gen (make sure it's in your path) generates person_slice.go:

The code provides LINQ-like methods to operate on the PersonSlice type. It's simple to understand and nicely documented. 

Here is how you use it. In the main function, a PersonSlice is defined. The age() function selects the age field from its Person argument. The generated GroupByInt() function takes the age() function and returns the people from the slice grouped by their age (34 is just Jim, but 23 has both Jane and Kyle).

5. Gorm

Go is known for its spartan nature. Database programming is no different. Most popular DB libraries for Go are pretty low-level. Gorm brings the world of object-relational mapping to Go with the following features:

  • Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism)
  • Callbacks (Before/After Create/Save/Update/Delete/Find)
  • Preloading (eager loading)
  • Transactions
  • Composite Primary Key
  • SQL Builder
  • Auto Migrations
  • Logger
  • Extendable, write Plugins based on GORM callbacks

But it doesn't cover everything. If you come from Python, don't expect SQLAlchemy magic. For more fancy stuff, you'll have to go a lower level. Here is an example of how to use Gorm with sqlite. Note the embedded gorm.Model in the Product struct.

6. Goose

One of the most important tasks when working with relational databases is managing the schema. Modifying the DB schema is considered a "scary" change in some organizations. The goose package lets you perform schema changes and even data migrations if needed. You can goose up and goose down to go back and forth. Mind your data, though, and make sure it doesn't get lost or corrupted.

Goose works by versioning your schema and using migration files corresponding to each schema. The migration files can be SQL commands or Go commands. Here is an example of a SQL migration file that adds a new table:

The -- +goose up and -- +goose down comments tell goose what to do to upgrade or downgrade the schema.

7. Glide

Glide is a package manager for Go. Under a single GOPATH, you may have many programs that have conflicting dependencies. The solution is to have each program manage its own vendor directory of package dependencies. Glide helps with this task.

Here are the features of glide:

  • Support versioning packages including Semantic Versioning 2.0.0 support.
  • Support aliasing packages (e.g. for working with github forks).
  • Remove the need for munging import statements.
  • Work with all of the go tools.
  • Support all the VCS tools that Go supports (git, bzr, hg, svn).
  • Support custom local and global plugins.
  • Repository caching and data caching for improved performance.
  • Flatten dependencies, resolving version differences and avoiding the inclusion of a package multiple times.
  • Manage and install dependencies on-demand or vendored in your version control system. 

The dependencies are stored in glide.yaml, and glide provides several commands to manage dependencies:

8. Ginkgo

Ginkgo is a BDD (Behavior Driven Development) testing framework. It lets you write your tests in a syntax that resembles English and allow less technical people to review tests (and their output) and verify that they match the business requirements. 

Some developers like this style of test specification too. It integrates with Go's built-in testing package and is often combined with Gomega. Here is an example of a Ginkgo + Gomega test:

9. Etcd

Etcd is a reliable distributed Key-Value store. The server is implemented in Go, and the Go client interacts with it though gRPC.

It focuses on the following:

  • Simple: well-defined, user-facing API (gRPC).
  • Secure: automatic TLS with optional client cert authentication.
  • Fast: benchmarked 10,000 writes/sec.
  • Reliable: properly distributed using Raft.

Here is an example of connecting to the server, putting a value and getting it, including timeouts and cleanup.

10. NSQ

NSQ is a great distributed queue. I've used it successfully as a primary building block for large-scale distributed systems. Here are some of its features:

  • Support distributed topologies with no SPOF.
  • Horizontally scalable (no brokers, seamlessly add more nodes to the cluster).
  • Low-latency push based message delivery (performance).
  • Combination load-balanced and multicast style message routing.
  • Excel at both streaming (high-throughput) and job oriented (low-throughput) workloads.
  • Primarily in-memory (beyond a high-water mark messages are transparently kept on disk).
  • Runtime discovery service for consumers to find producers (nsqlookupd).
  • Transport layer security (TLS).
  • Data format agnostic.
  • Few dependencies (easy to deploy) and a sane, bounded, default configuration.
  • Simple TCP protocol supporting client libraries in any language.
  • HTTP interface for stats, admin actions, and producers (no client library needed to publish).
  • Integrates with statsd for real-time instrumentation.
  • Robust cluster administration interface (nsqadmin).

Here is how to publish a message to NSQ (error handling is elided):

And here is how to consume:

11. Docker

Docker is a household name now (if your family members are mostly DevOps people). You may not be aware that Docker is implemented in Go. You don't  typically use Docker in your code, but it is a significant project and deserves to be recognized as a hugely successful and popular Go project.

12. Kubernetes

Kubernetes is an open-source container orchestration platform for cloud-native applications. It is another monster distributed system implemented in Go. I recently wrote a book called Mastering Kubernetes where I go in detail over the most advanced aspects of Kubernetes. From the Go developer's point of view, Kubernetes is very flexible, and you can extend and customize it via plugins.

Conclusion

Go is a great language. Its design philosophy is to be a simple and approachable language. Its standard library is not as comprehensive as some other languages like Python. 

The Go community stepped up, and there are many high-quality libraries you can use in your programs. In this article, I introduced 12 libraries. I encourage you to look for other libraries before jumping in and implementing everything from scratch.

August 04 2017

12:00

20 Popular WordPress User Interface Elements

A user interface (UI) is defined as “the means by which the user and a computer system interact, in particular the use of input devices and software.” It is one of the more important web design concepts but is often overlooked.

Having a good user interface ensures website visitors can find what they are looking for, do what they came to do, and most importantly, stay on your website. The moment that your website user interface becomes difficult to use is the moment when the user takes their browser elsewhere.

In an effort to help you provide the best interface, let's take a look at 20 popular WordPress user interface elements that are sure to help you make your website user-friendly.

1. Responsive FlipBook Plugin

Deliver web content within a beautiful UI with this incredible WordPress plugin.

At first glance, the Responsive FlipBook Plugin looks like a nice way to display content with its cool bookshelf design.

But it's so much more.

Responsive FlipBook Plugin
“Create any FlipBook with ease. Comes with: bookshelf, zoom, print, PDF to FlipBook, table of content, hard covers, flat design, custom styles, lazy load.”

Features include:

  • mobile zoom
  • PDF Wizard
  • easy print
  • lazy load
  • and more!

Create and present a complete collection of online based eBooks with the Responsive FlipBook Plugin.

It's pretty amazing.

2. Content Timeline - Responsive WordPress Plugin for Displaying Posts/Categories in a Sliding Timeline

This WordPress user interface is unique, and I love it!

The Content Timeline - Responsive WordPress Plugin for Displaying Posts/Categories in a Sliding Timeline is the perfect solution for a large array of content presentation types.

Content Timeline - Responsive WordPress Plugin for Displaying PostsCategories in a Sliding Timeline

Included features:

  • fully responsive with SWIPE function
  • 7 embedded script control methods
  • 11 settings for easy customization
  • keyboard bindings
  • and more!

Your timeline doesn't have to be one single string, either. This plugin allows for more than one element per spot in your timeline.

The Content Timeline - Responsive WordPress Plugin for Displaying Posts/Categories in a Sliding Timeline is unique, beautifully designed, and the perfect WordPress user interface for presenting in a timeline format.

3. UberChart - WordPress Chart Plugin

If you want to share data visually, you'd be hard-pressed to find a better way to build and present it than UberChart - WordPress Chart Plugin.

It's highly customizable and ready to drop into your WordPress install.

UberChart - WordPress Chart Plugin
“UberChart is an advanced WordPress Chart Plugin which gives you the ability to create a great variety of charts with exceptional customizability.”

It's feature set includes:

  • 240 customizable options for each chart
  • embedded spreadsheet editor
  • import and export data
  • fully responsive

And it includes ten different chart types:

  1. Line
  2. Area
  3. Bar
  4. Horizontal Bar
  5. Pie
  6. Doughnut
  7. Radar
  8. Polar Area
  9. Scatter
  10. Bubble

UberChart - WordPress Chart Plugin is impressive.

4. Theia Post Slider for WordPress

Transform your multi-page posts into slides that are easy to use and easy to read.

Theia Post Slider for WordPress works with existing posts and includes 60 different slider themes.

Theia Post Slider for WordPress
“...Theia Post Slider for WordPress transforms your multi-page posts into slideshows, making them much more engaging and easier to browse.”

Supports:

  • uses AJAX with JavaScript fallback
  • vector icons and retina-ready
  • titles, headers, and footers
  • SEO optimized
  • and more

A lot of thought has been put into this WordPress user interface plugin. From SEO to speed and usability to customization, the Theia Post Slider for WordPress really delivers.

5. Progress Map WordPress Plugin

The Progress Map WordPress Plugin is feature rich. I most certainly can't do it justice with this short summary.

The vision behind this WordPress user interface plugin is this:

“The aim is to help users having websites like hotel listings, real estate listings, restaurant listings, job listings, store listings & more… to list their locations on Google map and to easily navigate through the map using a carousel.”
Progress Map Wordpress Plugin

And it delivers:

  • search filter and distance search
  • Custom Post Type support
  • custom markers
  • 70+ map styles
  • geo-targeting
  • retina ready
  • and much, much more

Progress Map WordPress Plugin is easily one of the most robust map plugins you're going to find.

This plugin is all over the map.

6. Slider Revolution Responsive WordPress Plugin

When you need a slider—especially if you want an easy way to build it—you have to consider the Slider Revolution Responsive WordPress Plugin.

Animations, color pickers, layers—it's got it all baked in.

Slider Revolution Responsive WordPress Plugin

Slide types include:

  • social media feeds
  • media galleries
  • hero blocks
  • carousels
  • sliders
  • and more

The number one feature that makes this slider appealing is the powerful visual editor. Sliders are sliders, but the Slider Revolution Responsive WordPress Plugin brings a complete, robust slide designer suite.

7. Slick Menu - Responsive WordPress Vertical Menu

Slick. Responsive. Vertical. Menu.

The Slick Menu - Responsive WordPress Vertical Menu is exactly that, with a little extra on the side.

Slick Menu - Responsive WordPress Vertical Menu
“Slick Menu is more than just a menu plugin. It can be used to create unlimited multi level push menus or content sidebars with rich content, multiple style options and animation effects.”

Customize your:

  • background colors
  • custom fonts
  • patterns
  • overlays
  • images
  • videos
  • and more

Each level is independently customizable, making it super easy to build great WordPress user interfaces without expensive design apps or code knowledge. 

Slick Menu - Responsive WordPress Vertical Menu is an awesome option for vertical menus and more!

8. Cool Timeline Pro - WordPress Timeline Plugin

Add a timeline to blog posts, organization history pages, and more with the Cool Timeline Pro - WordPress Timeline Plugin.

Create both horizontal and vertical timelines with its built-in designs and beautiful animation effects.

Cool Timeline Pro - WordPress Timeline Plugin

Features include:

  • convert any Post Type into a timeline
  • pagination for long timelines
  • create multiple timelines
  • add icons
  • and more

Simple, clean, and flexible.

The Cool Timeline Pro - WordPress Timeline Plugin is a great way to build a timeline from your current content or building a new, standalone timeline to help communicate to your reader.

9. LoftLoader Pro - Preloader Plugin for WordPress

Sometimes you need more time for something to load. Videos? Lots of HD images?

Easily add a loading animation to your pages with the LoftLoader Pro - Preloader Plugin for WordPress.

It's pretty fancy.

LoftLoader Pro - Preloader Plugin for WordPress

Features include:

  • adjust minimum load time
  • 18 CSS3 animations
  • works on all devices
  • built-in editor
  • and more

The LoftLoader Pro - Preloader Plugin for WordPress makes it easy to add an animated loading screen—no coding required.

10. Superfly — Responsive WordPress Menu Plugin

Replace your current WordPress menu or enhance it with the Superfly — Responsive WordPress Menu Plugin.

This plugin is power packed and easy to use.

Superfly  Responsive WordPress Menu Plugin
“Superfly is a responsive WordPress menu plugin that generates space efficient vertical push/sliding/static navigation, icon toolbar or fullscreen menu on your choice.”

Menu design options include:

  • side, skewed, and full screen menus
  • image backgrounds
  • static or anchored
  • iconbar
  • and more

The Superfly — Responsive WordPress Menu Plugin also includes display options, making it super easy to build the right menu for the right user interface.

11. Ultra WordPress Admin Theme

There's customizing the WordPress Admin. And then there's the Ultra WordPress Admin Theme.

This WordPress user interface takes Admin customizations to a whole new level.

Ultra WordPress Admin Theme

White label branding is just the start of it:

  • admin menu management
  • create your own theme
  • import/export settings
  • and much, much more

From the login screen to the admin top bar, the Ultra WordPress Admin Theme makes the entire WordPress Admin experience fully customizable.

12. Different Menu in Different Pages

If you need different menus in different pages, you'll want to use Different Menu in Different Pages.

It also supports bbPress, WPML, WooCommerce, and BuddyPress.

Different Menu in Different Pages

Easily create multiple menus and locations based on:

  • custom taxonomies
  • categories
  • pages
  • posts
  • and tags

It also includes a shortcode option to show your menu within content as well.

The Different Menu in Different Pages is lightweight and proves useful in any WordPress toolbox.

13. Popup Plugin for WordPress - Layered Popups

As much as I hate popups, sometimes you just need a popup. The Popup Plugin for WordPress - Layered Popups is the easiest way to build and display popups on your WordPress site.

Popup Plugin for WordPress - Layered Popups
“[The] internet is full of boring popups. So, it’s a time to break this trend.”

Features included, but certainly not limited to:

  • jQuery and CSS3 animations
  • social network integration
  • A/B campaign stats
  • 200+ popup library
  • mobile friendly
  • and much, much more

Popup types include:

  • OnLoad Popup
  • OnScroll Popup
  • OnClick Popup
  • OnExit Popup
  • OnIdle Popup

And also features:

  • Sidebar Widget
  • Link Locker
  • Inline Form
  • and more

The Popup Plugin for WordPress - Layered Popups is a robust solution that looks great to users and proves useful for admins.

14. The Team Pro - Team Showcase WordPress Plugin

The Team Pro - Team Showcase WordPress Plugin claims to be “the most versatile WordPress plugin available to create and manage your Team page.”

I think they're right.

The Team Pro - Team Showcase WordPress Plugin

Style options include:

  • slide-ins
  • drawer
  • circles
  • modal
  • table
  • cards
  • grid
  • list

With these 8 presets, over 20 style options, and clean designs, your team never looked so good with The Team Pro - Team Showcase WordPress Plugin.

15. UberMenu - WordPress Mega Menu Plugin

This is a WordPress user interface element that I really like but can be difficult to implement.

But it's easy with the UberMenu - WordPress Mega Menu Plugin!

UberMenu - WordPress Mega Menu Plugin

Your WordPress menu will never be the same again:

  • enhanced mobile experience
  • easily add images and icons
  • build beautiful menu layouts
  • columns, rows, maps, forms, and more

Tabbed submenus? Google Fonts? Vertical or horizontal? UberMenu - WordPress Mega Menu Plugin has it.

16. Floatton | WordPress Floating Action Button with Pop-up Contents for Forms or any Custom Contents

This isn't just another popup. While it does include a popup feature, it includes a number of unique features that get it on this list.

Floatton | WordPress Floating Action Button with Pop-up Contents for Forms or any Custom Contents has a clean design and is one of those plugins that's always nice to have in your WordPress toolbox.

Floatton  WordPress Floating Action Button with Pop-up Contents for Forms or any Custom Contents
“Floatton is a premium WordPress plugin that helps you create sticky Floating Action Button with tooltip-styled popup contents to give your user easily accessible contents throughout your website.”

Use it as a:

  • comment and contact form
  • cookie or legal consent
  • newsletter sign up
  • shopping cart lists
  • announcements
  • rating form
  • video code
  • login

And anything else you can think of!

Add some user interaction. Add Floatton | WordPress Floating Action Button with Pop-up Contents for Forms or any Custom Contents.

17. StickyVideo for WordPress

If you've used YouTube on a mobile device, you've experienced the great UI/UX feature whereby when you begin to scroll away from the video, it will snap the video into the corner, so you can continue to watch while you scroll through the content.

That's exactly what StickyVideo for WordPress does, pinning videos to the side when users begin to scroll away.

StickyVideo for WordPress
“Boost viewability rates using a technique employed by CNN, Daily Mail and the Washington Post that pins videos to the side while you scroll!”

This plugin will pin videos hosted by:

  • WordPress (Self hosted in Media Library)
  • YouTube
  • Vimeo
  • Dailymotion
  • Facebook
  • Brightcove
  • JW platform
  • Youku
  • Tudou
  • Wistia
  • SchoolTube
  • Break
  • Metacafe
  • LiveLeak
  • Archive.org

Install, configure, and your videos won't be scrolled past any longer with the StickyVideo for WordPress plugin.

18. Ultimate Image Hover Effects Plugin For WordPress

Nothing catches a user's eye more than a tasteful image hover effect. And the Ultimate Image Hover Effects Plugin For WordPress brings hover effects in spades.

Ultimate Image Hover Effects Plugin For WordPress

No matter which WordPress theme you're running, you'll enjoy:

  • grid and carousel layouts
  • 40 plus box animations
  • over 200 effects
  • fully responsive
  • and more

The Ultimate Image Hover Effects Plugin For WordPress comes with just enough options to be both easy to use and lightweight.

19. Testimonials Showcase - WordPress Plugin

Display and manage your client, customer, and supporter testimonials easily with the Testimonials Showcase - WordPress Plugin.

Testimonials never looked so good.

Testimonials Showcase - WordPress Plugin

Features include:

  • over 15 layout customization options
  • grid or slider layout
  • star rating system
  • and more

The Testimonials Showcase - WordPress Plugin also includes front-end submissions.

20. WP Logo Showcase Responsive Slider Pro

It's time to amp up your portfolio page. It's time for WP Logo Showcase Responsive Slider Pro.

This WordPress plugin is designed to showcase a designer's work, but it can also be used to display client and partner logos or anything else that fits within this type of user interface.

WP Logo Showcase Responsive Slider Pro

This responsive slider features:

  • includes both a slider and grid widget
  • tooltip and custom animation options
  • over 15 predefined designs
  • drag and drop admin
  • and more

Some sliders try to offer everything, while the WP Logo Showcase Responsive Slider Pro focuses on one particular niche and style of slider and nails it perfectly.

Conclusion

Having a good user interface can often make or break your website. You can have a great layout, great colors, and great content, but if you don't have a good interface, your users aren't going to use your website.

These 20 popular WordPress user interface elements from Envato Market are certainly worth a consideration, but if you still didn't find what would work best, you may want to dig into development with the WordPress Plugin Development Essentials, the WordPress Hacker's Guide to the Galaxy, or some helpful eBooks like Useful Tricks and Techniques for WordPress or Mastering WordPress.

What are your favorite and most effective WordPress user interface elements?

August 03 2017

12:00

Angular vs. React: 7 Key Features Compared

Angular vs React

Angular vs. React is a popular debate among front-end JavaScript developers and, more often than not, the discussion ends up being biased towards one technology or the other. Developed by Google and Facebook respectively, Angular and React are the two popular technologies used to build interactive single-page applications. 

A comprehensive comparison between Angular and React is imminent because there are certain places in which they significantly overlap in terms of what they offer, i.e. building the front-end view of your application and other places where their functionality remains incomplete unless helped by a third-party library. Adopting one technology over the other is a question of whether Angular or React better solves your problem and a bit of intuition. In this tutorial, we’ll compare and contrast seven key different features of Angular and React.

I am an ardent proponent of the code-first approach (code speaks louder than words, they say). Keeping this in mind, I’ve added code samples of Angular and React wherever possible so that you can build on your intuition and decide which works for you and which doesn’t.  Let’s get started.

Framework vs. Library

Angular is a framework, while React is a library. 

So what does this mean? React on its own won’t let you create a web application because it is designed to create views (hence the ‘V’ in MVC). What React can do is build component-based views for which data can be passed down to child views. To fill this void, Facebook has developed Flux, which is an architectural pattern that complements React. Flux architecture, when coupled with React, provides the following scenario:

  1. The user clicks on a React element. 
  2. An action is fired. This action is dispatched to a Store via a Dispatcher library.
  3. The Store keeps track of the application’s state and data retrieval methods. Any update to the state is reflected in the views, and this helps to keep the views consistent with the state of the application.

Doesn’t make sense? This figure should sort it out for you.

An image that depicts how the Flux architecture complements React Flux complements React and implements the concept of Unidirectional data flow.
Angular is a framework for building client applications.

AngularJS was firmly built on top of the MVC pattern, which separated the application into three different layers. The combination of model, view, and controller plus the added complexity involved in mastering directives, factories, services and other components to create a single-page application forced the developers at Google to shift towards a component-based architecture. 

But when your application starts to grow, it’s important to have a solid structure that keeps the business logic of your application away from the components. Being a framework, Angular allows you to enforce structural organization by moving the business rules into a domain model (using a combination of model classes and services) and injecting the model into your components via dependency injection.

Here is a sample of code that illustrates how the business logic is encapsulated inside a User model and a User service, and away from our component.

Component-Based Approach

Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components.

What are components? In Angular, components are TypeScript classes that have a @Component decorator marked over them. Moreover, inside these decorators, we can define what Angular calls the meta-data, which includes the template, styles, selectors and so forth.  

Component hierarchy in Angular is designed in such a way that you can associate structure and functionality under a single entity. Here is a high-level architectural overview of components and how this links to everything else in Angular. 

The architecture of Angular The architecture of Angular. Component at the center, and everything else revolves around it. 

Data sharing among components is possible by nesting components, as exemplified below.

The concept of components is deeply rooted in React, just as it is in Angular. Facebook calls React a component-based library that lets you build interactive user interfaces. However, unlike Angular, React components are just JavaScript functions with an arbitrary number of inputs and an output. The code below shows a component defined using a JavaScript function and using an ES6 class.

We will be adhering to the ES6 standards for composing components henceforth because that is what Facebook recommends. Each React component accepts an arbitrary number of inputs, which is stored inside an object named props

It also has a render method, and as the name suggests, this method determines what will be rendered when the component is invoked. Each component maintains an internal state (via this.state), and every time the state changes, the render function of that component is invoked again.

Language Features: TypeScript vs. ES6

Angular applications are written in TypeScript, which is a superset of ECMA2015 and uses a transpiler to compile your strongly typed .ts file to a plain .js file. TypeScript offers language extensions that are designed to make writing in JavaScript easier, and it associates type information with JavaScript entities to enforce type checking and enhance the development workflow.

Some of the key features of TypeScript include optional static typing and support for interfaces, classes, and decorators. (Decorators are functions that are prefixed with ‘@’ and immediately followed by a class, parameter, or a property.)

Let's dive into React, shall we? One of the important language features in React is evident in this code sample. 

Isn't this great? React lets you embed XML/HTML tags into your JavaScript file, and this is done through JSX, which offers syntax extension capability to JavaScript. We have to use a compiler like Babel, which compiles our JSX code into the JavaScript that browsers can understand. The above code compiles down to this:  

Although using JSX is recommended, you can stick with React.createElement() if you are against the idea of embedding HTML tags into JavaScript.

Furthermore, you can use either ES6 standards or the traditional form of JavaScript while working with React. Although ES6 is relatively new, it adds a lot of features such as classes, arrow functions, template literals, destructing, and the use of let and const. The only downside I can think of is that it adds a little bit of boilerplate code such as the need to call super() every time you call a constructor(), and that it doesn’t automatically bind event-handling methods with this.

Type Checking in Angular vs. PropTypes in React

Static type checking is performed at compile time. The compiler warns you about potential type mismatches and detects certain errors that would otherwise go unnoticed. Additionally, defining a contract on a variable, a property, or the parameters of a function can result in more readable and maintainable code.

Variable and function declarations are made more expressive by declaring their data types. You can read more about the different primitive data types in the TypeScript documentation.

Defining the signature of an API using an interface makes the code less ambiguous and easier to comprehend. The interface serves as a quick start guide that helps you get started with code immediately and saves time otherwise spent on reading the documentation or the actual implementation of the library.  

The type keyword in TypeScript can be used to create an alias for a type. You can then create new types which are a union or intersection of these primitive types.

React has limited support for type checking because the underlying ES6 doesn’t support it. Nevertheless, you can implement type checking using the prop-types library developed by the React team. Type checking the props of a component to check whether it is a string can be done as shown below.

But prop-types are not limited to strings, numbers, and boolean. You can do a lot more, as described in the prop-types library documentation. However, if you take static type checking seriously, you should use something like Flow, which is a static type-checker library for JavaScript.

Scaffolding: Angular CLI vs. create-react-app

Starting a project from the ground up might seem fun initially. However, the process of setting up the directory structure, writing boilerplate code for components, and getting the application bootstrapped is a futile and unproductive exercise. Your strategy should be to get on with it as quickly as possible and focus on the actual development of the application. Thanks to Google and Facebook, you have tools available to create and scaffold your applications with ease.

Setting up Angular-CLI for angular and create-react-app for React is straightforward using npm.

To create a new Angular application, you should use the following command:

But that's not it. The ng generate command lets you generate components, routes, pipes, directives, and services.

Angular CLI can do a lot more, like creating a build of your Angular app, commands for running unit tests, and end-to-end testing. You can read more about it on GitHub.

On the other hand, create-react-app is the officially supported way of creating a React app without any configuration files.

$ npm install -g create-react-app

This should create a functional React app with all the Babel and webpack dependencies taken care of. You can start running the app on your browser using npm start.

You can find the scripts available for the react app in the package.json file.

Data Binding: Two-Way Binding vs. Unidirectional Binding

Data binding is a feature that enables synchronization of data between the application state (model) and the view. In a one-way data binding routine, any change in the state of the application automagically updates the view. On the contrary, two-way data binding binds together properties and events under a single entity, i.e. any modification of the model updates the view and vice versa.  

In React, the properties are passed down from parent to child components, which is known as the unidirectional or top-down data flow. The state of a component is encapsulated and is not accessible to other components unless it is passed down to a child component as a prop, i.e. the state of a component becomes the prop of the child component. 

But what if you need to propagate the data up through the component tree? This is done through child events and parent callbacks. The React documentation includes a good example that deals with such a scenario.

Data binding techniques available in Angular are among a few features that make it interesting. Angular has out-of-the-box support for interpolation, one-way binding, two-way binding, and event binding.

Interpolation is the simplest way to bind your component property inside the text between your HTML tags and attribute assignments.  

<p>Welcome back {{currentUser.name}}!</p>

Property binding is similar to interpolation in the sense that you can bind the properties of your view elements to component properties. Property binding favors component communication and is identical to how props are passed down in React.

<img [src]="userImgUrl">

<user-child [user]="currentUser"></user-child>

Event bindings allow data flow in the opposite direction, i.e. from an element to a component. Here, click is a target event, and on the right, we have the onSave() method that gets invoked when the event occurs.  

<button (click)="onSave()">Save</button>

But the most important feature is the two-way binding using the [(ngModel)]. This merges the property binding and event binding under one directive and is particularly useful with forms and input fields. 

Server-Side Rendering

Server-side rendering is a traditional rendering technique. Here, the server returns the whole HTML file upon request, and the browser is left with the simple job of displaying it to the user. Client-side rendering, on the other hand, returns a bare-bones HTML document, the stylesheet, and a JavaScript file. 

The JavaScript makes subsequent requests to render the rest of the website using a browser. React, Angular and all other modern JavaScript front-end libraries are good examples of client-side rendering. This is evident if you view the source of your Angular/React application.

But client-side rendering has the drawbacks that it doesn’t work great for SEO and that it returns incomplete HTML content when you share your link on social media sites. Angular has a solution called Angular Universal that takes care of making your app search engine friendly and social media friendly. It’s a library built by the Angular team, and using it is definitely favored. 

Universal makes use of a pre-rendering technique where the whole website is rendered from the server first, and after a couple of seconds, the user is switched to the client-side rendering. Since all this happens under the hood, the user doesn’t notice anything different.

If you are using React with Redux, the Redux documentation has a good tutorial on setting up server rendering. You can also set up React to render from the server using the BrowserRouter and StaticRouter components available in the react-router library. You can read more about it in this Medium article. But if you are into performance and optimization, you can try next.js, which is a library for SSR in React.

Wrapping It Up

Comparing a full-blown, feature-rich framework to a robust UI library might not seem fair. However, they are advanced JavaScript technologies used to create interactive single-page applications, and in that regard, this article should help you decide on choosing one of them. 

What are your thoughts on Angular vs. React? Do share them in the comments below.

August 02 2017

14:11

How to Monetize Your Android Apps With AdMob

In this tutorial, you'll learn about how to integrate AdMob so you can make money from that awesome Android app you wrote—come on, who doesn't want that? AdMob is among the biggest mobile advertising platforms in the market, and it is owned by Google.

There are a few different ways to monetize your apps in Android: paid downloads, paid subscriptions, in-app purchases, and by displaying ads. You can combine them, but is recommended you pick a single model. In this tutorial, you'll learn about how to monetize your app by displaying ads. 

The kinds of ads you'll create in this tutorial are banner, interstitial, and native express ads. I'll explain each of them and show you how to implement them in your application. But before that, let's first of all see how to integrate the Mobile Ads SDK and initialize it. 

Create an Android Studio Project

In Android Studio, create a new project named MainActivity.

Android Studio add an activity dialog

Include the Mobile Ads SDK

To begin integration of AdMob with your app, you'll need to first include the Mobile Ads SDK to your app module build.gradle file:

If you are going to integrate Firebase into your app, then you should use the SDK which is part of Firebase:

Check out the some of our Firebase tutorials here on Envato Tuts+ if you need help getting started with Firebase:

  • Android SDK
    Get Started With Firebase for Android
    Ashraff Hathibelagal

Make sure you sync the project after adding it the SDKs so as to pull the libraries from the internet into your application. 

Initialize MobileAds

You need to initialize the Mobile Ads SDK before you can load ads on your Android app, so do this as early as possible. We create a class which extends the Application class, and then we initialize the MobileAds SDK in the onCreate() method of that class, because this method is called only once when the app is launched. 

The second argument supplied to the static method initialize() of the MobileAds class should be your AdMob application ID you got when you signed up for AdMob. In this case, we are using the public application ID provided by Google for demo purposes. 

Modify the Manifest File

We need to add the application class we created to the application tag name attribute in our AndroidManifest.xml file. 

While in this file, also make sure to include the INTERNET permission so that Google mobile ads can run. 

In the code snippet below, we added the AdActivity to our AndroidManifest.xml file within the application tag. 

This activity is provided by the SDK. It is useful in banner ads to fire up the ad to be viewed when the user clicks on the ad, while for an interstitial ad, it is used for displaying the ad when the user clicks on it.

1. Banner Ads

Banner ads cover a part of the currently visible screen. In other words, any content in your app and the ad are displayed together on the screen. This improves the user experience because your users can keep on using your app while the ad is showing, unlike an interstitial ad (just hang on, we'll get to that shortly). Note that a banner ad can be text or an image. 

Let's look at how to implement a banner ad. 

Include a Banner Ad in Your Layout

AdView is a custom ViewGroup that will contain the banner ad, so we need to edit our activity_banner_ad.xml layout file to include this view. 

We are defining the AdView size by using the attribute ads:adSize and setting it to BANNER. Other alternatives available are LARGE_BANNERFULL_BANNERSMART_BANNER, etc. 

The ads:adUnitId AdView attribute is set to a sample ad unit provided by Google. You'll have to update this with an ad unit associated with your account if you want to actually make money from your ads! 

The ad unit ID identifies an ad placement, and you can find it in the AdMob admin console. This ID will tell AdMob the kind of ad to be displayed on your app and also the display format (image, text, or video).

Load the Ad

For us to finally show the ad, we need to make a request and then show it in the AdView we created above in the BannerAdActivity class. 

We made an ad request by creating an instance of AdRequest using the builder. Then we used the method addTestDevice(), passing in a device id as an argument to receive test ads to the device, which in our case is the emulator. We then finally called the AdView method loadAd() that takes in this AdRequest instance and then loads the ad on a background thread (so as not to block the UI/main thread). 

Test the Ad

At this point, we can run our project and see the result. 

App showing banner ad

From the screenshot above, we can see that our test banner ad is showing below the view. Now interact with the ad by clicking on it. 

Listening for Ad Events With AdListener

Let's now explore the events or callbacks we can observe in an ad. These are the events available: 

  • onAdLoaded(): this method is fired when the ad is retrieved. 
  • onAdOpened(): this method is invoked when the ad is opened. 
  • onAdClosed(): this method is fired when the ad is closed.
  • onAdLeftApplication(): this method is invoked when the user has left the application.
  • onAdFailedToLoad(int errorCode): this is fired when a request for the ad fails. The code can be one of ERROR_CODE_NETWORK_ERRORERROR_CODE_INVALID_REQUESTERROR_CODE_NO_FILL, or ERROR_CODE_INTERNAL_ERROR.

After adding the listener, run the project again and interact with the ad. Observe the events being invoked by watching the toasts we created. 

2. Interstitial Ads

We have seen how easy it is to display a banner ad. Now let's look at how to create interstitial ads. 

Interstitial ads are ads that cover the whole screen of your application, giving no room for other views of your app to show (as we'll see shortly). Since this takes over the entire screen and also takes some time to load if the network is slow, you need to be careful not to irritate your users. So ideally these interstitial ads should be shown during natural breaks in your app, e.g. between levels in a game, and not when users are in the middle of some other task.

In the code above, we declared and initialized an instance of the class InterstitialAd in the InterstitialAdActivity class. We set the add unit id by passing the Google-provided one as the only argument into the method setAdUnitId()

Just like what we did for the banner ad, we want to listen for events on the ad, so we set a listener to fire the overloaded methods onAdLoaded() and onAdFailedToLoad(int i). We make an ad request by creating an instance of the AdRequest class using its builder and then call the method loadAd(), passing this request as an argument to the method. We use the method isLoaded() to determine when the ad has been loaded and then call the method show() to finally display it. 

You can also add an AdListener just like we did for the banner ad. 

Test the Ad

At this point now, we can run the app and see the result. 

App showing interstitial  ad

In the screenshot above, you can see that our test interstitial ad is now showing. 

3. Native Ads Express

Native Ads Express gives you (the publisher) the ability to customize the look and feel of ads so that they can fit naturally with your app. This customization is done by defining CSS templates in which you define your own fonts, colours, sizes, etc. from your AdMob account. You can't change the images, descriptions, and titles, though—these are set by the advertisers. 

The customized ads can be displayed in your app in a NativeExpressAdView

Include NativeExpressAdView in Your Layout

Below, we include the NativeExpressAdView, which is a ViewGroup, in our layout file. We also define the android:layout_height and android:layout_width to be wrap_content. The ads:adSize will be "320x300", and we'll use the Google-provided NativeExpress ad unit id (for demo purposes only). 

Load the Ad

Next, we build our AdRequest and then begin loading the ad to be displayed. We'll also add code to respond to the Activity lifecycle callbacks. You can also add an AdListener if you want, just like we did for the banner ad. 

Test the Ad

That's it! Now you can run the app and see your Native Express ad in action.

App showing NativeExpressAdView

Create Your Own AdMob Account

Now that we have learned about the different types of ads, you can go ahead and integrate them into your application. To begin showing real ads and making money, you'll need an AdMob account—with real ad unit ids that are linked to real ads from advertisers. Just visit the AdMob website to sign up! 

AdMob website home screen

Conclusion

In this tutorial, you learned about AdMob and how to integrate different AdMob ad formats such as banner, interstitial, and native express ads on Android. 

To learn more about AdMob on Android, do refer to the official documentation. And in the meantime, check out some of our other courses and tutorials on Android app development!

  • Android SDK
    Create an Intelligent App With Google Cloud Speech and Natural Language APIs
    Ashraff Hathibelagal
  • Android SDK
    Android O: Phone Number Verification With SMS Tokens
    Chike Mgbemena
  • Android Things
    Android Things: Creating a Cloud-Connected Doorman
    Paul Trebilcox-Ruiz

12:00

Create a Multiplayer Pirate Shooter Game: In Your Browser

Creating multiplayer games is challenging for several reasons: they can be expensive to host, tricky to design, and difficult to implement. With this tutorial, I hope to tackle that last barrier. 

This is aimed at developers who know how to make games and are familiar with JavaScript, but have never made an online multiplayer game. Once you're done, you should be comfortable implementing basic networking components into any game and be able to build on it from there! 

This is what we'll be building:

Screenshot of the Final Game - Two Ships Attacking Each Other

You can try out a live version of the game here! W or Up to move towards the mouse and click to shoot. (If no one else is online, try opening two browser windows on the same computer, or one on your phone, to watch how the multiplayer works). If you're interested in running this locally, the complete source code is also available on GitHub.

I put this game together using Kenney's Pirate Pack art assets and the Phaser game framework. You'll be taking on the role of a network programmer for this tutorial. Your starting point will be a fully functioning single-player version of this game, and it will be your job to write the server in Node.js, using Socket.io for the networking part. To keep this tutorial manageable, I'll be focusing on the multiplayer parts and skimming the Phaser and Node.js specific concepts.

There's no need to set up anything locally because we'll be making this game completely in the browser on Glitch.com! Glitch is an awesome tool for building web applications, including a back end, database and everything. It's great for prototyping, teaching and collaborating, and I'm excited to introduce you to it throughout this tutorial.

Let's dive in.

1. Setup

I've put up the starter kit on Glitch.com.

Some quick interface tips: at any time, you can see a live preview of your app by clicking on the Show button (top left).

The show button is at the top left on the Glitch interface

The vertical sidebar on the left contains all the files in your app. To edit this app, you'll need to "remix" it. This will create a copy of it on your account (or fork it in git lingo). Click on the Remix this button.

The remix button is at the top of the code editor

At this point, you'll be editing the app under an anonymous account. You can sign in (top-right) to save your work.

Now, before we go any further, it's important to become familiar with the code for the game you're trying to add multiplayer in. Take a look at index.html. There are three important functions to be aware of: preload (line 99), create (line 115), and GameLoop (line 142), in addition to the player object (line 35).

If you'd rather learn by doing, try these challenges to make sure you get the gist of how the game works:

  • Make the world bigger (line 29)note that there is a separate world size, for the in-game world, and a window size, for the actual canvas on the page.
  • Make SPACEBAR also thrust forward (line 53).
  • Change your player ship type (line 129).
  • Make the bullets move slower (line 155).

Installing Socket.io 

Socket.io is a library for managing real-time communication in the browser using WebSockets (as opposed to using a protocol like UDP if you're building a multiplayer desktop game). It also has fallbacks to make sure it still works even when WebSockets aren't supported. So it takes care of the messaging protocols and exposes a nice event-based message system for you to use.

The first thing we need to do is install the Socket.io module. On Glitch, you can do this by going to the package.json file and either typing in the module you want in the dependencies, or clicking Add package and typing in "socket.io".

The add package menu can be found at the top of the code editor when selecting the file packagejson

This would be a good time to point out the server logs. Click on the Logs button on the left to bring up the server log. You should see it installing Socket.io along with all of its dependencies. This is where you would go to see any errors or output from the server code.

The Logs button is on the left side of the screen

Now to go server.js. This is where your server code lives. Right now, it just has some basic boilerplate for serving up our HTML. Add this line at the top to include Socket.io:

Now we also need to include Socket.io on the client, so go back to index.html and add this at the top inside your <head> tag:

Note: Socket.io automatically handles serving up the client library on that path, so that's why this line works even though you don't see the directory /socket.io/ in your folders.

Now Socket.io is included and ready to go!

2. Detecting & Spawning Players

Our first real step will be to accept connections on the server and spawn new players on the client. 

Accepting Connections on the Server

At the bottom of server.js, add this code:

This tells Socket.io to listen for any connection event, which automatically gets triggered when a client connects. It will create a new socket object for each client, where socket.id is a unique identifier for that client.

Just to make sure this is working, go back to your client (index.html) and add this line somewhere in the create function:

If you launch the game and then look at your server log (click on the Logs button), you should see it log that connection event! 

Now, when a new player connects, we expect them to send us information about their state. In this case, we need to know at least the x, y and angle in order to properly spawn them in the right location. 

The event connection was a built-in event that Socket.io fires for us. We can listen for any custom-defined event we want. I'm going to call mine new-player, and I expect the client to send it as soon as they connect with information about their location. This would look like this:

You won't see anything in the server log yet if you run this. This is because we haven't told the client to emit this new-player event yet. But let's pretend that's taken care of for a moment, and keep going on the server. What should happen after we've received the location of the new player that joined? 

We could send a message to every other player connected to let them know that a new player has joined. Socket.io provides a handy function to do this:

Calling socket.emit would just send the message back to that one client. Calling socket.broadcast.emit sends it to every client connected to the server, except that one socket it was called on.

Using io.emit would send the message to every client connected to the server with no exceptions. We don't want to do that with our current setup because if you got a message back from the server asking you to create your own ship, there would be a duplicate sprite, since we already create the own player's ship when the game starts. Here's a handy cheatsheet for the different kinds of messaging functions we'll be using in this tutorial.

The server code should now look like this:

So each time a player connects, we expect them to send us a message with their location data, and we'll send that data right back to every other player so that they can spawn that sprite.

Spawning on the Client

Now, to complete this cycle, we know we need to do two things on the client:

  1. Emit a message with our location data once we connect.
  2. Listen for create-player events and spawn a player in that location.

For the first task, after we create the player in our create function (around line 135), we can emit a message containing the location data we want to send like this:

You don't have to worry about serializing the data you send. You can pass in any kind of object and Socket.io will handle it for you. 

Before moving forward, test that this works. You should see a message on the server logs saying something like:

We know that our server is receiving our announcement that a new player has connected, along with correctly getting their location data! 

Next, we want to listen in for a request to create a new player. We can place this code right after our emit, and it should look something like:

Now test it out. Open up two windows of your game and see if it works.

What you should see is that after opening two clients, the first client will have two spawned ships, whereas the second one will only see one.

Challenge: Can you figure out why this is happening? Or how you might fix it? Step through the client/server logic we've written and try to debug it.

I hope you've had a chance to think about it for yourself! What's happening is that when the first player connected, the server sent out a create-player event to every other player, but there was no other player around to receive it. Once the second player connects, the server again sends out its broadcast, and player 1 receives it and correctly spawns the sprite, whereas player 2 has missed player 1's initial connection broadcast. 

So the problem is happening because player 2 is joining late in the game and needs to know the state of the game. We need to tell any new player that's connecting what players already exist (or what has already happened in the world) so that they can catch up. Before we jump into fixing this, I have a brief warning.

A Warning About Syncing Game State

There are two approaches to keeping every player's game synced. The first one is to only send the minimal amount of information about what has been changed across the network. So each time a new player connects, you would send just the information for that new player to all other players (and send that new player a list of all other players in the world), and when they disconnect, you tell all other players that this individual client has disconnected.

The second approach is to send the entire game state. In that case, you would just send a full list of all the players to everyone each time a connect or disconnect occurs.

The first one is better in the sense that it minimizes the information sent across the network, but it can be very tricky and has the risk of players going out of sync. The second one guarantees players will always be in sync but involves sending more data with each message.

In our case, instead of trying to send messages when a new player has connected to create them, when they've disconnected to delete them, and when they've moved to update their position, we can consolidate all of that into one update event. This update event will always send the positions of every available player to all clients. That's all the server has to do. The client is then responsible for keeping its world up to date with that state it receives. 

 To implement this, I will:

  1. Keep a dictionary of players, with the key being their ID and the value being their location data.
  2. Add the player to this dictionary when they connect and send an update event.
  3. Remove the player from this dictionary when they disconnect and send an update event.

You can try to implement this on your own since these steps are fairly simple (the cheat sheet might come in handy). Here's what the full implementation might look like:

The client side is a little trickier. On one hand, we only have to worry about the update-players event now, but on the other hand, we have to account for creating more ships if the server sends us more ships than we know about, or destroying if we have too many.

Here's how I handled this event on the client:

I'm keeping track of the ships on the client in a dictionary called other_players that I simply have defined at the top of my script (not shown here). Since the server sends the player data to all players, I have to add a check so a client isn't creating an extra sprite for themselves. (If you're having trouble structuring this, here's the full code that should be in index.html at this point).

Now test this out. You should be able to create and close multiple clients and see the right number of ships spawning in the right positions!

3. Syncing Ship Positions

Here's where we get to the really fun part. We want to actually sync the positions of the ships across all the clients now. This is where the simplicity of the structure we've built up so far really shows. We already have an update event that can sync everyone's locations. All we need to do now is:

  1. Make the client emit every time they've moved with their new location.
  2. Make the server listen for that move message and update that player's entry in the players dictionary.
  3. Emit an update event to all clients.

And that should be it! Now it's your turn to try and implement this on your own.

If you get completely stuck and need a hint, you can look at the final completed project as reference.

Note on Minimizing Network Data

The most straightforward way to implement this is to update all players with the new locations every time you receive a move message from any player. This is great in that players will always receive the latest information as soon as it's available, but the number of messages sent across the network could easily grow to hundreds per frame. Imagine if you had 10 players, each sending a move message every frame, which the server then has to relay back to all the 10 players. That's already 100 messages per frame!

A better way to do it might be to wait until the server has received all messages from the players before sending out a big update containing all the information to all players. That way you squash the number of messages you're sending down to just the number of players you have in the game (as opposed to the square of that number). The problem with that, however, is that everyone will experience as much lag as the player with the slowest connection in the game. 

Another way to do it is to simply have the server send updates at a constant rate, regardless of how many messages it's received from players so far. Having the server update at around 30 times per second seems like a common standard.

However you decide to structure your server, be mindful of how many messages you're sending every frame early on as you develop your game.

4. Syncing Bullets

We're almost there! The last big piece will be to sync the bullets across the network. We could do it in the same way we synced the players:

  • Each client sends the positions of all its bullets every frame.
  • The server relays that to every player.

But there is a problem.

Securing Against Cheats

If you relay whatever the client sends you as the true position of the bullets, then a player could cheat by modifying their client to send you fake data, such as bullets that teleport to wherever the other ships are. You can easily try this out yourself by downloading the webpage, modifying the JavaScript, and running it again. This isn't just a problem for games made for the browser. In general, you can never really trust data coming from the client. 

To mitigate against this, we'll try a different scheme:

  • Client emits whenever they've fired a bullet with the location and direction.
  • Server simulates the motion of bullets.
  • Server updates each client with the location of all the bullets.
  • Clients render the bullets in the locations received by the server.

This way, the client is in charge of where the bullet spawns, but not how fast it moves or where it goes after that. The client may change the location of the bullets in their own view, but they can't alter what other clients see. 

Now, to implement this, I'll add an emit when you shoot. I'll no longer be creating the actual sprite either, since its existence and location is now determined completely by the server. Our new bullet shooting code in index.html should now look like this:

You can also now comment out this whole section that updates the bullets on the client:

Finally, we need to get the client to listen for bullet updates. I've opted to handle this the same way I do with players, where the server just sends an array of all the bullet locations in an event called bullets-update, and the client will create or destroy bullets to keep in sync. Here's what that looks like:

That should be everything on the client. I am assuming you know where to put these snippets and how to piece everything together at this point, but if you're running into any issues, remember you can always take a look at the final result for reference.

Now, on server.js, we need to keep track of and simulate the bullets. First, we create an array for keeping track of bullets, in the same way we have one for players:

Next, we listen for our shoot bullet event:

Now we simulate the bullets 60 times per second:

And the last step is to send the update event somewhere inside that function (but definitely outside the for loop):

Now you can actually test it! If all went well, you should see the bullets syncing across clients correctly. The fact that we did this on the server is more work, but also gives us a lot more control. For example, when we receive a shoot bullet event, we can check that the speed of the bullet is within a certain range, otherwise we know this player is cheating.

5. Bullet Collision

This is the last core mechanic we'll implement. Hopefully by now you've gotten used to the procedure of planning out our implementation, finishing the client implementation completely first before moving on to the server (or vice versa). This is a much less error-prone way than switching back and forth as you implement it.

Checking for collision is a crucial gameplay mechanic, so we'd like it to be cheat-proof. We'll implement it on the server in the same we did for the bullets. We'll need to:

  • Check if a bullet is close enough to any player on the server.
  • Emit an event to all clients whenever a certain player gets hit.
  • Have the client listen on the hit event and make the ship flash when hit.

You can try doing this one completely on your own. To make the player flash when hit, simply set their alpha to 0:

And it will ease back to full alpha again (this is done in the player update). For the other players, you would do a similar thing, but you'll have to take care of bringing their alpha back to one with something like this in the update function:

The only tricky part you might have to handle is making sure a player's own bullet can't hit them (otherwise you might always get hit with your own bullet every time you fire).

Notice that in this scheme, even if a client tries to cheat and refuses to acknowledge the hit message the server sends them, that will only change what they see on their own screen. All the other players will still see that that player got hit. 

6. Smoother Movement

If you followed all the steps up to this point, I'd like to congratulate you. You've just made a working multiplayer game! Go ahead, send it a friend and watch the magic of online multiplayer uniting players!

The game is fully functional, but our work doesn't stop there. There are a couple of issues that might impact the player's experience that we need to address:

  • Other players' movement will look really choppy unless everyone has a fast connection.
  • Bullets can feel unresponsive, since the bullet does not fire immediately. It waits for a message back from the server before it appears on the client's screen.

We can fix the first one by interpolating our position data for the ships on the client. So even if we're not receiving updates fast enough, we can smoothly move the ship towards where it should be as opposed to teleporting it there. 

The bullets will require a little more sophistication. We want the server to manage the bullets, because that way it's cheat-proof, but we also want to have the immediate feedback of firing a bullet and seeing it shoot. The best way is a hybrid approach. Both the server and the client can simulate the bullets, with the server still sending bullet position updates. If they're out of sync, assume the server is right and override the client's bullet position. 

Implementing the bullet system I described above is out of the scope for this tutorial, but it's good to know that this method exists.

Doing a simple interpolation for the positions of the ships is very easy. Instead of setting the position directly on the update event where we first receive the new position data, we simply save the target position:

Then, inside our update function (still in the client), we loop over all other players and push them towards this target:

This way you can have your server sending you updates 30 times per second, but still play the game at 60 fps and it will look smooth!

Conclusion

Phew! We just covered a lot of things. Just to recap, we've looked at how to send messages between a client and a server, and how to sync the state of the game by having the server relay it to all players. This is the simplest way to create an online multiplayer experience. 

We also saw how you can secure your game against cheating by simulating the important parts on the server and informing the clients of the results. The less you trust your client, the safer the game will be.

Finally, we saw how to overcome lag by interpolating on the client. Lag compensation is a broad topic and is of crucial importance (some games just become unplayable with high enough lag). Interpolating while waiting for the next update from the server is just one way to mitigate it. Another way is to try and predict the next few frames in advance, and correct once you receive the actual data from the server, but of course this can be very tricky.

A completely different way of mitigating the impact of lag is to just design around it. The benefit of having the ships turn slowly to move acts as both a unique movement mechanic and also a way to prevent sudden changes in movement. So even with a slow connection, it still wouldn't ruin the experience. Accounting for lag while designing the core elements of your game like this can make a huge difference. Sometimes the best solutions are not technical at all.

One final feature of Glitch you might find useful is that you can download or export your project by going into the advanced settings on the top left:

The advanced options menu allows you to import export or download your project

If you make something cool, please share it in the comments below! Or if you have any questions or clarifications about anything, I'd be more than happy to help. 

August 01 2017

13:46

How Tuts+ Has Helped People in Their Careers

People use Envato Tuts+ for all kinds of reasons. Sometimes it's just for fun or to pick up some creative skills as a hobby. But many people also use the site to help them in their careers. 

We ran a reader survey earlier this year, and some of the responses were quite inspiring. Here's a look at how some of your fellow learners have used the site to help them make progress in their careers.

Landing Their First Job

Quite a few of our learners are students who use Envato Tuts+ to help them supplement their formal school or university education with some extra practical skills.

Bartłomiej Szubert was one of those people. He started to learn web development from our courses and eBooks while studying, and after a few months he prepared his CV and applied for a web developer position at a company in his city. And he got the job!

Right now I'm a Mid-Level PHP Programmer / Senior Web Developer in another company, while my colleagues from university often haven't even found their first job. And that's all thanks to Envato Tuts+.

For Pouya Rezaei, it was after graduating from university in Economics & Finance that he realised he wanted to work in a different field. So he set out to teach himself everything he needed to know about designing websites. 

Two years later I began freelancing, six years on I am creating websites, design work, PHP, HTML, JavaScript ... Everything I learnt and all the CMS plugins I used for my clients when I first started, it ALL was with the help of you guys. I'm living my life doing what I LOVE. 
Pouya Rezaei Pouya Rezaei

Humaira Mahinur only started on the site a few months ago, but has already learned a lot and is moving towards a freelance career. 

I am a learner of web design and development, graphic design and other skills ... After completing some projects, by the will of Allah, I will start my career with Envato Studio and some freelance marketplace. 

And Michelle Silva is a graphic design student about to graduate and now working in a printing job to gain some experience. 

This website has definitely helped me improve in areas that I didn't understand or weren't covered in class and need to learn quickly to complete a job. Tuts+ guarantees that the ONE course you watch will help you learn what you need. 
Michelle Silva Michelle Silva

Finding Better Job Opportunities

Sometimes, people are already on the career ladder, but are not satisfied with the opportunities available to them in their current roles. 

Jenny Yamada, for example, says:

I'm using it to refresh my memory and apply for jobs I wouldn't qualify for otherwise. I was able to build out my website in WordPress from taking Adi's course. 

But you don't always need to move on to move up. Alexander Kozhurkin was already working as a full-time developer, but felt stuck at a junior level. By learning new skills, he was able to start working on more fulfilling projects.

Now I'm working on an enterprise-level business app. I realized that my success depends on my own efforts, and quality education is the key for this. Envato courses let me grow fast, it's like watching an expert coding over his shoulder. 

Making a Career Change

Envato Tuts+ is also helping people retrain so that they can make the career change they've always dreamed of.

Some, like Dave Perlman, are still in the early stages of a career change, but have accumulated skills that are moving them towards a dream job:

I'm closer now than I ever have been to having a career as a web developer and I've only put in about a year learning code.

Others are further along. Treighton Mauldin took a big risk several years ago by quitting his job in the construction industry to pursue a career in web development. 

I had no experience, and no clue where to start. When I found Tuts+ I was able to start learning rapidly, going through the free courses and tutorials, and within a year I had my first full-time job as a developer. Now I am a back end developer and am helping lead a development team of four people. 
Treighton Mauldin Treighton Mauldin

Another person who switched careers with the help of Tuts+ is Traci Brinling. After being laid off three years ago, she decided to follow her passion for animation and break into a new career. She used our online courses and tutorials to help her make the change.   

I did something right because I am working as an in-house animator and now just trying to build up my freelance client base. 

Meanwhile, Neeru Mokha is using the site to help her get back into work after a career break.

It's really helpful in updating my resume as I took 4 years of break but now I am getting very close to filling my gap. Videos posted are very knowledgeable and very helpful in improving your basic to advanced level skills.

And so is George Millard:

I have got back into software development after a number of years working in a different field. I am using it to get back up to speed and learn the new languages that are now popular.

Being More Effective as a Freelancer

Many freelancers use Envato Tuts+ to brush up on their skills and land better contracts. When Christian Nazha had a client ask for a Laravel site, he tried various other sites to get the information he needed, but none could help him. Some had bad English, poor sound quality, or even skipped the basics. 

Here I found the perfect combination of explanatory and quality videos.

Meanwhile, self-taught web developer Tracey Niblett is using Tuts+ to improve the quality of her work, resulting in big cost savings. 

Tuts+ has really helped to fill in the gaps in my knowledge so that my code has become more efficient and reliable. Reliable code means happy customers and less time supporting and more time developing new stuff so the money I have saved in time supporting has more than covered the cost of my subscription.

Being Their Own Boss

Lisette Marie McGrath has been struggling to set up an online business while grappling with health issues. The online courses and tutorials have helped her to keep her skills updated while working at her own pace. Now her health is improving and she's able to devote more time to her business, using the skills she's acquired.

Envato Tuts+ has kept me going for the last few years, keeping me interested, inspired and focussed on what matters the most to me.

Meanwhile, Martine Kerr says she went from 813 to over 10,000 Instagram followers in just over a year with videos she's created using skills learned on Tuts+, and now she's ready to design and film her own courses.

The skills allowed me to save a huge amount of time in filming and basic editing workflow. I'm now confident enough to create my own online courses.

Doing a Better Job

And finally, what better way to enhance your career than just being better at the day-to-day job you do?

Cassie Porcella got her first job as a corporate web developer/designer five years ago, and she used Tuts+ to help her thrive in the new role. When she started, the company website was very basic, and she used our courses and tutorials to learn the skills she needed to overhaul it.

I quickly started using Tuts+ and it helped me take my coding from basic HTML and CSS to full PHP, MySQL and JavaScript/jQuery. After a full redesign of the site design and architecture to align with our business objectives, I started using Tuts+ to refine the site and add user-friendly features. 

But as we all know, technology is an ever-changing industry, and a couple of years ago, Cassie updated her knowledge with the help of Kezz Bracey's explanations of responsive design

This course helped me to transform our site and its usability and help future-proof the design structure for the multitude of device sizes. Additionally, it really encouraged me to see a female coder getting recognition in a field where us gals are often the minority. Thanks for providing such helpful tutorials that have helped me excel in my job, which benefits my company, our team members and our customers! I look forward to refining my craft and boosting my skills with your help! 
Cassie Porcella Cassie Porcella

Over to You

How have you used Envato Tuts+ tutorials and courses? Have they helped you in your career? Let us know in the comments below. 

If you haven't tried our full membership yet, why not give it a go? As you can tell from these stories, many people enjoy the kind of career progress that quickly pays for the cost of the subscription. Try our new combined subscription to Envato Tuts+ and Envato Elements. For just $29 a month, you get unlimited video courses and eBooks, plus unlimited downloads from a huge library of professional-quality graphics, photos, web templates, and much more.

12:00

How to Write, Package and Distribute a Library in Python

Python is a great programming language, but packaging is one of its weakest points. It is a well-known fact in the community. Installing, importing, using and creating packages has improved a lot over the years, but it's still not on par with newer languages like Go and Rust that learned a lot from the struggles of Python and other mature languages. 

In this tutorial, you'll learn everything you need to know about writing, packaging and distributing your own packages. 

How to Write a Python Library

A Python library is a coherent collection of Python modules that is organized as a Python package. In general, that means that all modules live under the same directory and that this directory is on the Python search path. 

Let's quickly write a little Python 3 package and illustrate all these concepts.

The Pathology Package

Python 3 has an excellent Path object, which is a huge improvement over Python 2's awkward os.path module. But it's missing one crucial capability—finding the path of the current script. This is very important when you want to locate access files relative to the current script. 

In many cases, the script can be installed in any location, so you can't use absolute paths, and the working directory can be set to any value, so you can't use a relative path. If you want to access a file in a sub-directory or parent directory, you must be able to figure out the current script directory. 

Here is how you do it in Python:

To access a file called 'file.txt' in a 'data' sub-directory of the current script's directory, you can use the following code: print(open(str(script_dir/'data/file.txt').read())

With the pathology package, you have a built-in script_dir method, and you use it like this:

Yep, it's a mouthful. The pathology package is very simple. It derives its own Path class from pathlib's Path and adds a static script_dir() that always returns the path of the calling script. 

Here is the implementation:

Due to the cross-platform implementation of pathlib.Path, you can derive directly from it and must derive from a specific sub-class (PosixPath or WindowsPath). The script dir resolution uses the inspect module to find the caller and then its filename attribute.

Testing the Pathology Package

Whenever you write something that is more than a throwaway script, you should test it. The pathology module is no exception. Here are the tests using the standard unit test framework: 

The Python Path

Python packages must be installed somewhere on the Python search path to be imported by Python modules. The Python search path is a list of directories and is always available in sys.path. Here is my current sys.path:

Note that the first empty line of the output represents the current directory, so you can import modules from the current working directory, whatever it is. You can directly add or remove directories to/from sys.path. 

You can also define a PYTHONPATH environment variable, and there a few other ways to control it. The standard site-packages is included by default, and this is where packages you install using via pip go. 

How to Package a Python Library

Now that we have our code and tests, let's package it all into a proper library. Python provides an easy way via the setup module. You create a file called setup.py in your package's root directory. Then, to create a source distribution, you run: python setup.py sdist

To create a binary distribution called a wheel, you run: python setup.py bdist_wheel

Here is the setup.py file of the pathology package:

It includes a lot of metadata in addition to the 'packages' item that uses the find_packages() function imported from setuptools to find sub-packages.

Let's build a source distribution:

The warning is because I used a non-standard README.md file. It's safe to ignore. The result is a tar-gzipped file under the dist directory:

And here is a binary distribution:

The pathology package contains only pure Python modules, so a universal package can be built. If your package includes C extensions, you'll have to build a separate wheel for each platform:

For a deeper dive into the topic of packaging Python libraries, check out How to Write Your Own Python Packages.

How to Distribute a Python Package

Python has a central package repository called PyPI (Python Packages Index). When you install a Python package using pip, it will download the package from PyPI (unless you specify a different repository). To distribute our pathology package, we need to upload it to PyPI and provide some extra metadata PyPI requires. The steps are:

  • Create an account on PyPI (just once).
  • Register your package.
  • Upload your package.

Create an Account

You can create an account on the PyPI website. Then create a .pypirc file in your home directory:

For testing purposes, you can add a "pypitest" index server to your .pypirc file:

Register Your Package

If this is the first release of your package, you need to register it with PyPI. Use the register command of setup.py. It will ask you for your password. Note that I point it to the test repository here:

Upload Your Package

Now that the package is registered, we can upload it. I recommend using twine, which is more secure. Install it as usual using pip install twine. Then upload your package using twine and provide your password (redacted below):

For a deeper dive into the topic of distributing your packages, check out How to Share Your Python Packages.

Conclusion

In this tutorial, we went through the fully fledged process of writing a Python library, packaging it, and distributing it through PyPI. At this point, you should have all the tools to write and share your libraries with the world.

Additionally, don’t hesitate to see what we have available for sale and for study in the marketplace, and please ask any questions and provide your valuable feedback using the feed below.

July 31 2017

19:27

What Are Android Instant Apps?

Every time you release an Android app, you’ll have at least a rough idea of what you want this app to achieve. 

These goals could be very specific, such as generating a certain amount of ad revenue in the first quarter, or they could be more general, such as getting a high rating on Google Play.

Whatever else is on your wish-list, getting your app in front of as many users as possible is always going to feature somewhere on that list—and Android Instant Apps is a new feature that can help you do just that.

Instant Apps provide you with an entirely new way of reaching users who don’t currently have your app installed on their device, by making your app discoverable and accessible from any location that supports URLs, including emails, Google search results, posts on social media platforms, YouTube comments, and forums.

Essentially, Instant Apps allow you to separate each of your app’s features into a stand-alone module. Users can then load any of these instant app modules on-demand by tapping a URL that you’ve mapped to this specific module, and without having to install your app at any point.

In this three-part series, I’ll be showing you how to add Instant App support to your Android projects. By the end of this series, you’ll have created an application that consists of two separate Instant App feature modules, which you can launch and test on any compatible Android device. 

What We’re Going to Cover

In this first post, I'll focus on what Instant Apps are, how they work, and why you should care about them. To give you some first-hand experience of Instant Apps, we'll use Android Studio’s project creation wizard to generate an app that’s pre-configured with Instant App support, so you’ll be able to see all the different Instant App components, rather than simply reading about them.

While creating an app that’s pre-configured with Instant App support is the quickest and easiest way to use this feature, in reality you’re far more likely to add Instant App support to an existing project—so in part two I’ll show you how to do exactly that. I’ll supply an app that you can download from GitHub, and then take you through the step-by-step process of reconfiguring this project to support Instant Apps.

The final piece of the puzzle is creating a multi-featured Instant App, so in part three I’ll show you how to add a second feature module to your application, and how to use Android App Links to map this module to a different URL. 

What Are Instant Apps?

One of the best ways to describe Instant Apps is to look at an example of when you might use them.  

Imagine a friend has sent you a link to a cat video that they promise you’re going to love, but when you tap the link it becomes clear that you need to download an app before you can watch this particular video.  

Regardless of whether you end up downloading the app, or ignore the link and risk missing out on the best cat video the Internet has to offer, this is a bad user experience—and it’s a scenario that many Android users are familiar with. 

Most of us have had the experience of installing an app just to complete a one-off task. For example, you might download an app just to view an email attachment someone has sent you, to complete a purchase on a specific website, or to track a package that’s currently winging its way to your address.

Now let’s imagine our cat video scenario again, but this time the application’s developer has placed all the code and resources required to play video content inside its own instant app feature module, and mapped this module to the www.example.com/video URL. This time, when you tap www.example.com/video/cat-video, Google Play recognizes that this URL is associated with an instant app module and retrieves all the code and resources that you need to play this video. The end result? You can enjoy 20 seconds of a cat playing in a box without having to install anything, which is a much better user experience.  

Why Should I Start Using the Instant App Feature?

As you’ll see in the next post in this series, adding Instant App support to an existing project can be a daunting process, often requiring you to completely change the way your application is structured.

Since restructuring a project isn’t a decision you should ever take lightly, in this section I’m going to help you decide whether all that time and effort is really worth it, by covering all the major benefits of adding Instant App support to your projects:

  • It removes a barrier between your app and new users. Installing an application via Google Play isn’t a particularly difficult or time-consuming process, but it’s still the biggest barrier between your app and potential new users. No matter how much time you spend crafting a compelling Google Play page that’ll have the majority of users scrambling for that Install button, some people will always drop out at install time. 
  • It helps you reach new users. While you’ve always been able to promote your app on various locations around the web, such as your own website, blog or social media, connecting with new users has previously relied on them visiting your app’s Google Play page at some point (with the rare exception of users who prefer to sideload their apps). Instant apps remove this reliance on your app’s Google Play page, by making your application directly accessible from any location that supports URLs, giving you almost unlimited opportunities to connect with new users. 
  • It ensures that shared content is the best possible advert for your app. A user sharing your app’s content is one of the most effective ways of reaching a new audience, so you’ll want to make a good first impression! Previously, it’s been difficult to provide a consistent experience for users who don’t have your app installed on their device, but instant apps allow you to guarantee a seamless, native experience for everyone.
  • Helps users access your app, even in the face of Internet restrictions. While Internet coverage is improving all the time, you may still occasionally struggle to find a fast and reliable network, or perhaps you’re approaching your monthly data allowance and are worried about incurring additional charges. When you’re struggling with a slow or inconsistent Internet connection, downloading an entire app can be a time-consuming and frustrating process, and when you’re in danger of going over your data allowance, downloading a new app may be enough to incur additional charges. All instant app modules must be 4MB or less, so even if downloading an entire app is out of the question, then accessing an instant app module may still be a viable option. 
  • Increase the appeal of location and time-sensitive apps. While apps that are designed for a specific location or event aren’t a new concept, ask yourself: how likely am I to install an app that I know I’ll only be able to use for a limited period of time, or in a certain location? Instant apps can increase the appeal of time and location-sensitive apps, by allowing the user to access all of your app’s most important functionality at the tap of a URL. 

Restrictions and Limitations

Before we start our instant app journey, it’s worth noting that there are currently a few things that instant apps cannot do:

  • Access device identifiers like IMEI and MAC addresses.
  • Use background services.
  • Perform background notifications. 
  • Access the device’s external storage.
  • Access the list of apps that are installed on the user’s device—unless those applications have specifically made themselves discoverable to instant apps.

In addition, your application must: 

  • Be available to download for free from the Google Play store.
  • Use the new permissions model introduced in Android 6.0 (API level 23). Since the user doesn’t install an instant app, there’s no opportunity to request permissions up front. If your instant app feature module(s) require access to sensitive device capabilities or user information, then you’ll need to request these permissions at runtime. 
  • Support App Links. This is the mechanism that you’ll use to map each of your instant app modules to a specific URL. I’ll cover App Links in detail in the next post. 

Finally, if your app is part of the Designed for Families program, then you cannot offer it as an instant app. 

Setting Up Your Development Environment

Before you can create your first project with instant app support, you’ll need to have the following or higher installed:

  • Android Studio 3.0 Preview
  • Android SDK 6.0
  • Android SDK Build Tools 26.x
  • Android SDK Tools 25.x
  • Android SDK Platform Tools 25.x

You should also make sure you have the latest versions of the Android Support Library and Android Repository, so open Android Studio’s SDK Manager and install any available updates. 

Once you’ve installed all of the above, you’ll be able to download the Instant Apps Development SDK: 

  • Open the SDK Manager, and select the SDK Tools tab. 
  • Select Instant Apps Development SDK.
  • Click Apply.

Currently, you can only test instant apps on a Nexus 5X, Nexus 6P, Pixel, Pixel XL, or a Galaxy S7 that’s running Android 6.0 or higher. However, if you don’t own any of these devices then you can create an Android Virtual Device (AVD) that emulates one of these devices, with a few conditions: the AVD must use an x86 image, and it must include the Google APIs.

Since I don’t own any of these devices, I’m going to create an AVD that emulates a Pixel: 

  • Launch the AVD Manager.
  • Click the Create virtual device... button.
  • Select Pixel, and then click Next.
  • Select the x86 Images tab. 
  • Select a system image that’s running Android 6.0 and includes the Google APIs, for example Marshmallow / 23 / x86 / Android 6.0 (Google APIs).
  • Click Next.
  • Give your AVD a name, and click Finish.
  • Launch your AVD.

Finally, you’ll need to sign in to a Google account on your AVD:

  • Switch to your AVD, and open the device’s launcher.
  • Select the Google app.
  • Enter a Gmail address and password. This can either be your real-life account, or an account you’ve created solely for the purposes of testing your Android projects. 

Creating Your First Instant App 

In Android Studio 3.0 Preview 1 and higher, creating a project that has built-in Instant App support is as easy as selecting a checkbox, so rather than just describing Instant App features, we’re going to create an Instant App project and then spend the rest of this article getting some first-hand experience with its various components. 

Just be aware that this project doesn’t feature any App Links, so you won’t be able to test its Instant App components on your AVD (this is something we’ll be exploring in detail in part two).

To create your project:

  • Launch the project creation wizard, either by selecting File > New > New project… from the Android Studio toolbar, or by clicking Start a new Android Studio project from Android Studio’s Welcome screen. 
  • Give your project a name, and click Next
  • Set the Minimum SDK to Android 6.0 (Marshmallow). 
  • Select the Include Android Instant app support checkbox, and click Next
  • To help keep things simple, accept the default module name (feature) and then click Next.
  • Select Basic Activity and then click Next.
  • On the next screen, accept all the default values, and then click Finish.

Immediately, we can see that this project is structured very differently from your typical Android project, and consists of the following modules:

  • App. The installable app module, also known as an APK module. 
  • Base. The base feature module.
  • Feature. Although this particular project only has one, an application can consist of multiple feature modules.
  • Instantapp. The instant app module. 
Projects with instant app support are structured differently to regular installable-only projects

With the exception of the feature module, any project that supports instant apps must have all of the above modules, so let’s explore each of these modules in detail.  

1. Application Module

The concept of an application module may be nothing new, but when your project supports instant apps, the application module’s Manifest looks much emptier than you’re probably used to: 

There’s a reason why this file is so empty: when you build your project, the contents of all the other Manifest files located throughout your base feature and feature modules are merged with this file—so it’s not going to stay this empty forever! 

If you open this module’s build.gradle file, then you’ll notice two new elements: 

Here, we’re declaring that our application module has a dependency on the feature module and base module. 

When you add Instant App support to a project, you separate related code and resources into feature modules that can function independently of the installable application. However, these modules are still parts of your installable app, rather than separate entities, which is why our application module is declaring the feature and base modules as dependencies.

2. Base Feature Module

Every instant app project must include a single base feature module, which contains the code and resources that are used across all your application’s modules. For example, if you open our project’s base/res/mipmap folder, then you’ll see all of the application’s launcher icons, which are clearly going to be used across multiple modules. 

The base feature module includes the ic_launcher drawables

Since it contains common code and resources, all of your project’s feature modules depend on this single base feature module. 

Continuing this theme, the base feature module contains the Manifest entries that are used across your entire project. For example, your project’s base/src/main/AndroidManifest.xml file contains the settings for your application’s icon, theme, and label: 

The other notable element is the base module’s build.gradle file, which contains a few new attributes:

You’ll also notice that this particular build.gradle file is missing an applicationID attribute, and (spoiler alert) you’ll find exactly the same thing when we come to inspect our feature module’s build.gradle file. Our project’s applicationID is declared in the application module’s build.gradle file only.

The application project(:app) line in our base module’s build.gradle file (see above) ensures that the project’s single applicationID attribute is propagated across all of our build.gradle files, which is why this attribute is missing from the rest of our project. 

3. Feature Module

When you eventually come to add Instant App support to an existing project, your biggest task will be extracting each of your application’s features into its own feature module, as each feature module contains the code and resources that are required to deliver this feature only. 

If you open our project’s feature module, then you’ll see that it contains the MainActivity class, plus activity_main and content_main resource files—essentially all the components that are included in the Basic Activity template.  

The projects feature module contains all the code and resources that are specific to this feature

A single feature module can consist of multiple Activities, but each module must have at least one Activity that’s designated as this module’s entry-point Activity. 

Each entry-point Activity is mapped to a specific URL, so that when the user taps this URL it loads the associated Activity and the user has access to this particular feature module. 

You designate a module’s entry-point Activity via that module’s manifest. Essentially, you need to open this file and add the following to the Activity that you want to use as your entry-point: 

  • An intent filter, with the CATEGORY_LAUNCHER and ACTION_MAIN intents.
  • A <data> element containing all the information about the URL that you want to map to this entry-point Activity. 
  • The android:autoVerify attribute. This tells the system to check that your app has permission to act as the default handler for this particular URL. This is an important security mechanism that helps to protect website owners from malicious apps that might try to hijack their URLs.

If you open our feature module’s manifest file, then you’ll see that all of this code has already been added to our MainActivity declaration:

The final file we’re going to look at in this module is the build.gradle file, which contains a few lines of noteworthy code: 

Since all feature modules depend on the base feature module, the first time the user requests any feature from your application, they’ll receive the base feature module plus the feature module they’re actually trying to access. 

Note that although this particular project consists of a base feature module and a feature module, if your app only has one feature that you want to make available as an Instant App, then it’s possible to create a project that consists of a base feature module only. We'll be looking at both "types" of Instant App project throughout this series. 

4. Instant App Module

The Instant App module has a simple purpose: it acts as a container that takes all of your feature modules and turns them into Instant App APKs.

If you open this project’s Instant App module, then you’ll see that it’s pretty much empty apart from a build.gradle file, which simply declares your base feature module and your feature module as dependencies:

Testing Your App

Since this project doesn’t contain any App Links, we won’t be able to test its instant app components, but we can still run this project as an installable app. This might not seem particularly exciting, but bearing in mind that the bulk of our project’s code and resources are located in the instant app feature module, it’s important to test how our project functions as an installable application. 

Launch the AVD we created earlier or connect a compatible physical Android smartphone or tablet to your development machine, and then select Run > Run… > app from the Android Studio toolbar. 

Despite the fact that all of our MainActivity code is located in the feature module, once our app loads you’ll see the MainActivity’s floating action button (FAB) and Hello World message. What we're seeing here is our application module taking code and resources that are located in separate Instant App feature and base feature modules, and combining them into an installable app. 

Conclusion 

In this tutorial we took a high-level look at how Instant Apps work, and explored the various reasons why you might want to add Instant App support to your Android projects. 

In an ideal world, your decision to start exploring Instant Apps would perfectly coincide with the start of a new Android project, but unfortunately, being a developer is rarely this convenient! It’s far more likely that you’ll have to reconfigure an existing project to support Instant Apps, which isn’t quite as straightforward as selecting a checkbox in Android Studio’s project creation wizard! 

In the next post, we'll take an in-depth look at how to add instant app support to an existing project. I’ll also show you how to implement App Links, so by the end of the next post you’ll have created a fully-functioning Instant App that you can launch and test on any compatible AVD or Android device. 

Stay tuned! And in the meantime, check out some of our other posts on Android app development.

  • Android SDK
    How to Use Android O's Autofill Framework
    Ashraff Hathibelagal
  • Android SDK
    Google I/O 2017 Aftermath: Building Lifecycle-Aware Components
    Jessica Thornsby
  • Android SDK
    Adding Physics-Based Animations to Android Apps
    Ashraff Hathibelagal

13:00

10 Elegant CSS Pricing Tables for Your Latest Web Project

Pricing tables are an important tool for businesses promoting and selling their products or services on their website. As such they need to be simple and attractive in design, to highlight the most important information about each product or service and to clearly differentiate between available features, options and costs so that potential customers find it easy and intuitive to choose the most appropriate plan for their needs.

Here we’ve compiled a list of the 10 most tastefully designed CSS pricing tables to be found at CodeCanyon. Some are quite minimalist in their design, others provide a dizzying range of options, and others still take a somewhat more creative approach to design and function. No matter what you’re looking for, you’re bound to find a pricing table here that will suit your needs.

1. Comparative Responsive Pricing Tables

Comparative Responsive Pricing Tables offers a wide array of options for designing your pricing tables. Users can select any of 13 unique designs which they can then customise in variety of ways with a selection of hover animations, colour schemes, tooltips, etc. These tables, which are fully responsive, use Font Awesome icons and are also cross-browser compatible.

Customers reviewing this product have described it as a “very good product that comes with premium service.”

Comparative Responsive Pricing Tables

Best features:

  • 13 unique designs
  • tooltips with text and lists
  • multiple colour themes for each design
  • three types of hover animation
  • and much more

Comparative Responsive Pricing Tables is exactly what you need if you’re looking for feature-rich design options for creating your pricing tables.

2. CSS3 Responsive WordPress Compare Pricing Tables

CSS3 Responsive WordPress Compare Pricing Tables is a CodeCanyon bestseller and for good reason. Like Comparative Responsive Pricing Tables above, it offers a wide range of highly customisable design options from simple static tables to tables with sliding columns, crossfade animation columns, various hover features and tables with images. It also offers browsers support for the six most popular browsers on the market.

Customers like these pricing tables because they say they’re very flexible and “well designed for any kind of comparison with multiple adjustment options.”

CSS3 Responsive WordPress Compare Pricing Tables

Best features:

  • admin panel with live configuration
  • 20 predefined colour versions
  • unlimited number of columns and rows
  • ability to set different width values and font sizes for each column
  • and much more

A solid performer CSS3 Responsive WordPress Compare Pricing Tables will hold its place in the pricing tables market for years to come.

3. Responsive Multi Style Bootstrap Pricing Tables

Responsive Multi Style Bootstrap Pricing Tables is another good choice for users looking for pricing tables that offer a wide range of design possibilities.

Responsive Multi Style Bootstrap Pricing Tables comes with three different attractive designs, and each design can be configured in several different ways using 20 different colour schemes. Users can decide whether they want to use the pricing tables with or without Bootstrap.

Responsive Multi Style Bootstrap Pricing Tables

Best features:

  • three different designs
  • 20 colour themes for each design
  • hover effects
  • tooltips
  • Font Awesome icons
  • and much more

Responsive Multi Style Bootstrap Pricing Tables is not a WordPress plugin; however, WordPress users can purchase a WordPress version.

4. Pure CSS Responsive Pricing Tables for WordPress

Pure CSS Responsive Pricing Table for WordPress is a Bootstrap integrated plugin for WordPress that provides users with 15 predefined themes which are easy to use, highly customisable, and provide unlimited colours and styles to fit into your existing WordPress theme.

Support for the plugin is provided via email and includes answering technical questions about the item’s features and assistance with reported bugs and issues.

The Pure CSS Responsive Pricing Table for WordPress

Best features:

  • create unlimited tables
  • drag and drop column and row sorting
  • PayPal integrated
  • Google Fonts supported
  • and much more

Around since 2015, Pure CSS Responsive Pricing Tables for WordPress has been consistently updated to keep it a crowd favourite.

5. Pricing—Responsive CSS3 Pricing Table

Pricing—Responsive CSS3 Pricing Table is the latest pricing table plugin to arrive on CodeCanyon. It’s fully responsive, build on the Bootstrap framework and compatible with Firefox, Safari, Opera, Chrome, Edge, and IE10 and IE11 browsers.

These pricing tables are fully customisable but do not offer a wide variety of styling choices, so will appeal to users looking to create tables with simple and clean, yet attractive design.

Responsive CSS3 Pricing Table

Best features:

  • responsive and mobile-friendly layout
  • month/year pricing toggle included
  • button CSS3 effect, hover CSS3 effect
  • and much more

With its stripped-back design, Pricing—Responsive CSS3 Pricing Table is definitely the newcomer to watch.

6. Great Pricing Tables Framework

Another newcomer to CodeCanyon, Great Pricing Tables Framework’s strength is its simplicity and ease of use.

The plug features a responsive design and three style variations. Like the other plugins featured here, it uses standard HTML5 and CSS3 technology and has wide cross-browser compatibility.

Great Pricing Tables Framework

Best features:

  • easy to use
  • responsive design
  • Font Awesome included
  • Bootstrap supported
  • and much more

Great Pricing Tables Framework may not offer a lot of features, but its very clean and simple approach to pricing table design is definitely its strength.

7. 7 Responsive Flat Bootstrap Pricing Tables

7 Responsive Flat Bootstrap Pricing Tables provides users with seven distinctly different pricing tables in a minimalist style.

These tables support Bootstrap, with a promised Bootstrap 4 update coming later this year as well as free CSS and jQuery updates in the future. Customers praise the pricing table's  “sleek and modern design” that you “can copy and paste straight onto my site”.

7 Responsive Flat Bootstrap Pricing Tables

Best features:

  • minimalist design
  • responsive
  • horizontal and well as vertical tables
  • and much more

If clean and classic is what you’re looking for, then 7 Responsive Flat Bootstrap Pricing Tables is the right choice for you.

8. Round Pricing Tables

Round Pricing Tables is quite a unique offering among this list of pricing tables as it offers round pricing tables instead of rectangular ones.

Comparative prices are displayed in each circle and when visitors move their mouse over each circle, the list of features offered is displayed. Customers who’ve bought this pricing table found that it is an excellent product with “good code” that “doesn’t conflict with others, and is easy to edit.”

Round Pricing Table

Best features:

  • creative design
  • CSS3 animations
  • Google and Font Awesome supported
  • cross browser support
  • and much more

Round Pricing Tables obviously won’t appeal to every user, but for those users with less information to display and who are looking for a more creative approach to pricing tables, this pricing table is ideal.

9. Hexagon CSS Pricing Table

The Hexagon CSS Pricing Table is another pricing table that uses a cool and clever design to bring a bit of pizazz to your site.

Like Round Pricing Tables, this pricing table challenges the tradition pricing tables model, in this case by using hexagons instead of rectangles. Comparative prices are displayed in each hexagon, and when visitors hover over each hexagon, details of each pricing plan are revealed through any number of different animation effects.

 Hexagon CSS Pricing Table

Best features 

  • 16 different hover styles
  • 12 different colour schemes
  • cool animation effects
  • Google Font and Font Awesome supported 
  • and much more

As is the case with the Round Pricing Table Features, Hexagon CSS Pricing Table will appeal to users who are open to a more creative approach to pricing tables.

10. CSS Pricing Tables

CSS Pricing Tables has been trending recently on CodeCanyon, probably because users are drawn to its uncomplicated design. The plugin uses one design but allows users to customise the colours schemes used to create the right look for their site.

CSS Pricing Tables

Best features:

  • responsive design
  • hover effect
  • 361 icons included
  • easy to use
  • and much more

CSS Pricing Tables may not offer enough styling options for many users, but for those looking to get pricing tables up and ready to go in the shortest possible time, these tables are a great choice. 

Conclusion

These 10 elegant CSS pricing tables for your latest web project are by no means the only ones available at Envato Market. So if you haven’t found anything here that meets your needs, we have plenty of other great options on offer.

And if you want to improve your CSS skills, check out our ever so useful free CSS tutorials.

12:00

Getting Started With the Flux Architecture in React

Final product image What You'll Be Creating

In this tutorial, you will learn about Facebook’s Flux architecture and how it’s used to handle the data flow in React-based applications. We’ll begin by covering the basics of Flux and understanding the motivation behind its development, and then we'll practice what we’ve learned by building a simple virtual wallet application.

Throughout the tutorial, I will assume you’ve used React before, but have no experience with Flux. You might get something out of it if you already know the basics of Flux and are looking to gain a deeper understanding.

If you are completely new to the React scene, I recommend going through the Getting Started With React course by David East, here on Envato Tuts+. It's a fantastic course that will get you up to speed in no time.

What Is Flux?

Flux is mainly an application architecture concept developed by Facebook, but the same term also refers to a library that represents the official implementation.

Facebook came out with Flux as an attempt to solve the problems caused by the MVC pattern in their massive codebase. They struggled with issues where actions triggered cascading updates that led to unpredictable results and code that was hard to debug. This may sound familiar if you’ve used MVC frameworks before, as in most of them everything tends to be tightly coupled. Add watchers and two-way data binding to the mix, and you’ve got yourself a proper headache.

My advice is to avoid any attempt at finding common ground between Flux and MVC. It won’t help much, other than amping up your confusion. Flux attempts to solve things differently, and trying to compare it with other patterns won’t help.

Project Setup

If you'd like to follow along with the tutorial, first make sure you have the required software installed. When you have finished, clone the boilerplate branch from the GitHub repository I prepared to accompany this article.

Here are the software requirements and the versions I had installed at the time of writing this article:

  • Git: 2.11
  • Node.js: 6.9
  • NPM: 3.10
  • Yarn: 0.22
  • Your editor of choice

The boilerplate serves as a starting point for the upcoming small project that we will be building, a small virtual wallet app. It contains the Webpack configuration for transpiling the ES6 syntax to plain JavaScript and WDS for serving the files. It also has some CSS component styles so you can jump right into coding.

In order to install all the required dependencies, cd into the project directory and run yarn.

In the next section, you will be setting up the application’s core components before integrating Flux. I haven’t included them in the boilerplate as I believe it would create more confusion. If you’re not interested in building the app, you can skip these steps and jump to the next section.

Components Setup

Start by including the following code inside js/index.js, which serves as the application's entry point:

For the main <App /> component, create a new file inside js/components called App.js and add the following code:

The <App /> component wraps two other components, one for the form responsible for adding new items and another one for the list of items. To create the <AddNewItem /> component, create a new file AddNewItem.js inside js/components and add this code:

The component bundles some logic for updating the state when the form fields update and also some basic validation. Let’s finish off the components setup by creating the last one inside js/components/ItemsList.js for the items list, using this code:

That’s it! You’re done setting up the project’s components. The great part is that they also come with free styling.

Run yarn start and wait for the bundle to build. If you point your browser to localhost:8080, you should see the app without any functionality.

Next, we’ll cover what Flux is and how you can use it to add functionality to the virtual wallet application.

The Flux Building Blocks

At a high level, Flux breaks down into four major parts: actions, the dispatcher, stores, and views:

  • Actions describe an action that took place in the application.
  • The dispatcher is a singleton registry of callbacks. It acts as a middleman by passing the actions to all the stores that subscribed to it.
  • Stores manage the state and logic needed to update it for specific parts of the application.
  • Views are plain old React components.

In Flux, all data flows in a single direction:

  • Actions are passed to the dispatcher using convenience classes called action creators.
  • The dispatcher sends (is dispatching) the actions to all the stores that subscribed to it.
  • Finally, if the stores care about a particular action that was received (or more), they update their state and signal the views so they can re-render.

Below is a visual representation of this process.

Representation of how data flows in a Flux application

Actions

Data is sent “through the wire” in a single direction using plain JavaScript objects called actions. Their job is to describe an event that took place in the application and to transport the new data to the stores. Each action must have a type and an optional payload key that contains the data. An action looks similar to the one below:

The action’s type must be represented by a descriptive and consistent uppercase string—similar to the common convention of defining constants. They serve as unique IDs that stores will use to identify the action and respond accordingly.

A common practice is to define all action types in a constants object and reference that object instead across the application to maintain consistency. Our virtual wallet will support a single action, which adds items to the list—both expenses and financial gains will be treated as a single item—so our constants file will be very slim.

Create an index.js file in the js/constants folder and use the following code to create your first action type:

Actions are passed to the dispatcher using convenience class helpers called action creators that handle the simple task of creating and sending the action to the dispatcher. Before creating our action creator, let’s see what the dispatcher does first and understand its role in Flux.

The Dispatcher

The dispatcher is used to coordinate the communication between action creators and stores. You can use it to register a store’s actions handler callback and also to dispatch actions to the stores that subscribed.

The dispatcher’s API is simple, and it has only five methods available:

  • register(): Registers a store’s action handler callback.
  • unregister() : Unregisters a store’s callback.
  • waitFor(): Waits for the specified callback(s) to run first.
  • dispatch(): Dispatches an action.
  • isDispatching(): Checks if the dispatcher is currently dispatching an action.

The most important are register() and dispatch() as they’re used to handle most of the core functionality. Let’s see how they look and work behind the scenes.

This is, of course, the basic gist. The register() method stores all callbacks in a private _callbacks array and dispatch() iterates and calls each callback stored using the received action.

For simplicity, we won’t write our own dispatcher. Instead, we’ll use the one provided in Facebook’s library. I encourage you to check out Facebook’s GitHub repo and see how it’s implemented.

Inside the js/dispatcher folder, create a new file index.js and add this code snippet:

It imports the dispatcher from the flux library—which was installed using yarn earlier—and then exports a new instance of it.

Having the dispatcher ready now, we can get back to actions and set up our app’s action creator. Inside the js/actions folder, create a new file called walletActions.js and add the following code:

The WalletActions class is exposing an addNewItem() method that handles three basic tasks:

  • It receives an item as an argument.
  • It uses the dispatcher to dispatch an action with the ADD_NEW_ITEM action type we created earlier.
  • It then sends the received item as payload along with the action type.

Before putting this action creator to use, let’s see what stores are and how they fit in our Flux-powered application.

Stores

I know, I said you shouldn’t compare Flux with other patterns, but Flux stores are in a way similar to models in MVC. Their role is to handle the logic and store the state for a particular top-level component in your application.

All Flux stores must define an action handler method that will then be registered with the dispatcher. This callback function mainly consists of a switch statement on the received action type. If a specific action type is met, it acts accordingly and updates the local state. Finally, the store broadcasts an event to signal the views about the updated state so they can update accordingly.

In order to broadcast events, stores need to extend an event emitter’s logic. There are various event emitter libraries available, but the most common solution is to use Node’s event emitter. For a simple app like a virtual wallet, there’s no need for more than one store.

Inside the js/stores folder, create a new file called walletStore.js and add the following code for our app’s store:

We start by importing the required dependencies needed for the store, beginning with Node's event emitter, the dispatcher followed by the ActionTypes. You will notice that below it, there is a constant CHANGE, similar to the action types you learned about earlier. 

It’s actually not one, and it shouldn't be confused. It's a constant used for the event trigger when the store's data change. We will keep it in this file as it isn't a value used in other parts of the application.

When initialized, the WalletStore class starts by registering the _registerToAction() callback with the dispatcher. Behind the scenes, this callback will be added to the dispatcher's _callbacks array. 

The method has a single switch statement over the action's type received from the dispatcher when an action is dispatched. If it meets the ADD_NEW_ITEM action type, it then runs the _addNewItem() method and passes along the payload it received.

The _addNewItem() function sets an id for the item, pushes it to the list of existing items, and then emits a CHANGE event. Next, the getAllItems() and getTotalBudget() methods are basic getters, which we’ll use to retrieve the current store's state and the total budget.

The final two methods, addChangeListener() and removeChangeListener(), will be used to link the React components to the WalletStore so they get notified when the store's data change.

Controller Views

Using React allows us to break down parts of the application into various components. We can nest them and build interesting hierarchies that form working elements in our page.

In Flux, components located at the top of the chain tend to store most of the logic needed to generate actions and receive new data; therefore, they are called controller views. These views are directly hooked into stores and are listening for the change events triggered when the stores are updated.

When this happens, controller views call the setState method, which triggers the render() method to run and update the view and send data to child components through props. From there, React and the Virtual DOM do their magic and update the DOM as efficiently as possible.

Our app is simple enough and does not respect this rule by the book. However, depending on complexity, larger apps can sometimes require multiple controller views with nested sub-components for the major parts of the application.

Fitting It Together

We’ve finished covering the major parts of Flux, but the virtual wallet app is not yet completed. In this last section, we’ll review the entire flow from actions to views and fill in the missing code needed to complete Flux’s unidirectional data flow.

Dispatching an Action

Getting back to the <AddNewItem /> component, you can now include the WalletActions module and use it to generate a new action in the _addNewItem() method.

Now, when the form is submitted, an action is dispatched and all stores—one in our case—are notified about the new data.

Listening for Store Changes

In your WalletStore, currently when an item is added to the list its state changes and the CHANGE event is triggered, yet no one is listening. Let’s close the loop by adding a change listener inside the <ItemsList /> component.

The updated component closes Flux’s unidirectional data flow. Note that I skipped including the entire render() method to save some space. Let's go step by step through what's new:

  • The WalletStore module is included at the top.
  • The initial state is updated to use the store's state instead.
  • A new _onChange() method is used to update the state with the new data from the store.
  • Using React's lifecycle hooks, the _onChange() callback is added and removed as the store's change listener callback.

Conclusion

Congrats! You’ve finished building a working virtual wallet app powered by Flux. You’ve learned how all the Flux components interact with each other and how you can add structure to React apps using it.

When you’re feeling confident in your Flux skills, make sure you also check out other Flux implementations like Alt, Delorean, Flummox or Fluxxor and see which one feels right for you.

Let me know your thoughts in the comments below, I'd love to know what you think about Flux or assist if you're having difficulties following the tutorial. If you'd like, you can also reach me on Twitter @hiskio.

July 28 2017

12:00

10 React Applications for You to Use, Study, and Apply

React is an awesome way to create interactive UIs. This open-source JavaScript library “allows developers to create large web applications that use data which can change over time, without reloading the page.”

Created by Jordan Walke, an engineer at Facebook, it was first deployed in 2011 and later became open source a few years later. React is a “learn once, write anywhere” library that has become go-to for many mobile app developers.

Here are 10 React applications from Envato Market for you to use, study, and apply, for both pros and beginners alike.

1. Restaurant App Template - React Native

Developing a React UI for a restaurant may seem simple at first. But when you begin to think about the details and complications of a menu, you can easily see how a React application restaurant template is useful.

The Restaurant App Template - React Native handles all the nuances very well, and like any UI, it looks good.

Restaurant App Template - React Native
“Manage your menu, accept orders, send push notifications.”

Features you'll find:

  • orders management
  • multiple languages
  • push notification
  • and more

This React app pulls data from Google's Firebase Realtime Database, so you can manage your menu and make changes without needing to republish the app.

The Restaurant App Template - React Native is great for learning React and provides some nice features that are worth learning about.

2. BeoStore - Complete React Native Template for E-Commerce

Nothing can be quite as crazy as organizing and presenting eCommerce. There is usually a full taxonomy to handle, and each item requires a fairly high baseline of repetitive data depending on what is being sold: data such as sizes, quality, inventory, color, versions, etc.

With the third version released, the BeoStore - Complete React Native Template for E-Commerce is a beautiful example of a React application for eCommerce.

BeoStore - Complete React Native Template for E-Commerce
“Your products will appear clear and can be zoom without any format error.”

Features include:

  • two product list modes
  • flexible product filter
  • user profiles
  • and more

On its lowest level, the UI presented here is top notch. When you consider the depth of data that is being sorted and presented—not to mention the fundamental feature set—this is a React application worth looking at closely.

The BeoStore - Complete React Native Template for E-Commerce is amazing.

3. Tudu - A React Native Todo-List

What kind of list of React applications for you to use, study, and apply would this be without a good to-do application?

That's why I've included the very beautiful Tudu - A React Native Todo-List React application.

Tudu - A React Native Todo-List
“In this source code you have multiple useful features not only for a to-do list app, but for all kind of projects.”

Features you can use:

  • auto grow text input
  • offline storage
  • swipe actions
  • and more

This is a good example of a React application that makes good use of space. Everything is spaced well for mobile and is designed to feel good to the user. With its simple codebase, you can build out your own to-do application or use these design fundamentals to build something completely different. 

Tudu - A React Native Todo-List is one of my favorites.

4. gikApp - React Native Full Application

Being able to leverage a CMS into your React application is a huge plus. WordPress fuels a large portion of the web, while Shopify is one of the leading eCommerce solutions. Learning how to pull this into a mobile app can be a real game changer.

Enter gikApp - React Native Full Application, a full-featured React application.

gikApp - React Native Full Application
“A truly multipurpose native app for your business.”

You'll find features like:

  • multi-tab screen and multi-level menu
  • Shopify sorting and view options
  • cart and checkout system
  • and more

I am a strong supporter of applications that focus on one thing and do it well. However, having a React application that's a bit of an all-in-one solution certainly has its place.

The gikApp - React Native Full Application is ready to be used for just about anything you're cooking up for a business.

5. BeoNews - React Native Mobile App for WordPress

There's hardly a better example of funneling your WordPress-based website into a React mobile app.

Easily get your WordPress site into mobile app form and onto the AppStore and Google Play with BeoNews - React Native Mobile App for WordPress.

BeoNews - React Native Mobile App for WordPress
“BeoNews is an app that does magic for your website by converting your WordPress website into mobile true native app with customized contents within a fillip.”

Features include:

  • easy Facebook integration
  • swipe and animated UI/UX
  • multiple layouts
  • and more

If you're digging deeper into React or you want to get your WordPress-powered website into a mobile app store, this is an excellent place to start.

The BeoNews - React Native Mobile App for WordPress ticks all the right boxes.

6. Sky Webview - Android & IOS React Native App

As much as I like to get my hands dirty and learn how to build from the ground up, sometimes I find that it helps to use beginner-based tools. Once I can complete a project in “easy mode,” I can then dig deeper and learn the ins and outs more easily.

Sky Webview - Android & IOS React Native App can help you get started with React applications without having to dig deep into code.

Sky Webview - Android  IOS React Native App
“No coding required.”

Features you'll find:

  • online theme edit panel
  • unlimited color options
  • over 670 icons
  • and more

I particularly like the “pull to refresh” feature.

Sky Webview - Android & IOS React Native App is a wonderful first-time React application.

7. OpenTV - React Native App (Android/iOS) for TV Channels and Livestreams

If you haven't already needed to bring video to a mobile device, it's only a matter of time. Present live stream video into a React application using OpenTV - React Native App (Android/iOS) for TV Channels and Livestreams.

OpenTV - React Native App AndroidiOS for TV Channels and Livestreams
“You want a simple but complete application, native, allowing to watch TV channels or livestreams or your mobile? OpenTV is what you need!”

Helpful features include:

  • supports both HTTP live streaming and local files
  • player controls and customizable behaviors
  • multiple formats and languages
  • and more

OpenTV - React Native App (Android/iOS) for TV Channels and Livestreams is your React application answer to mobile video.

8. BeoUI - Complete Mobile UI Template for React Native

This is another beautiful UI with plenty of styles that can be used in many different applications.

The BeoUI - Complete Mobile UI Template for React Native will land you on iOS and Android with only one language.

BeoUI - Complete Mobile UI Template for React Native
“A complete mobile UI template for React Native.”

Features include:

  • flat design mixed with wonderful animation and parallax scrolling
  • multiple menu styles
  • WordPress support
  • and more

This Reactive application template packs plenty of punch. With good looks and flexibility, you can build just about anything with BeoUI - Complete Mobile UI Template for React Native.

9. gikFashion - React Native Full eCommerce UI Theme

The thing about fashion-centric solutions is that they need to:

  1. Look good
  2. Be easy to use
  3. Handle a large number of complex assets

gikFashion - React Native Full eCommerce UI Theme does all three of these.

gikFashion - React Native Full eCommerce UI Theme
“...a complete solution for Ecommerce...”

Includes:

  • supports social media sign up and sign in
  • full featured eCommerce
  • online documentation
  • and more

While this React application focuses on fashion, keep in mind that it can be crafted to do much more or less—while delivering some great UI and functionality.

If gikFashion - React Native Full eCommerce UI Theme was clothing, you'd want to wear it.

10. Currency Converter React Native App

A great example of a mobile app that needs to pack in a lot of information and is highly utilitarian is the Currency Converter React Native App.

Currency Converter React Native App
“It has stunning and attractive design and can easily be modified.”

Features include:

  • converts currency based on the current currency market rate
  • AdMob ready
  • ready for iOS and Android

Complete with flags from all countries, create a fully functional currency converter and deliver yourself straight onto the AppStore and Google Play.

The Currency Converter React Native App is worth every penny.

Conclusion

Using, studying, and applying these React applications and strategies is one of the best ways to become a React pro. Digging into complete work, looking close at UI/UX choices, and doing this while building something of your own is your best teacher.

Of course, I would be remiss if I didn't mention some great resources that can help you along the way. There are the React applications on Envato Market, of course, but I highly recommend these React how-to tutorials, React courses, and React eBooks.

Pairing something you want to build with a good template and resource material is a recipe for React application success.

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!

Schweinderl