Quantcast
Channel: Envato Tuts+ Code
Viewing all 4704 articles
Browse latest View live

Getting Started With Cloud Firestore for iOS

$
0
0

Mobile coders have been taking advantage of Google’s Mobile Backend as a Service (MBaaS) platform Firebase Realtime Database for many years, helping them focus on building features for their apps without having to worry about the back-end infrastructure and database. By making it easy to store and persist data in the cloud and take care of authentication and security, Firebase allows coders to focus on the client side. 

Last year, Google announced yet another back-end database solution, Cloud Firestore, built from the ground up with the promise of greater scalability and intuitiveness. However, this introduced some confusion as to its place in relation to Google’s already existing flagship product, Firebase Realtime Database. This tutorial will outline the differences between the two platforms and the distinct advantages of each. You will learn how to work with Firestore document references, as well as reading, writing, updating and deleting data in real time, by building a simple reminders app.

Objectives of This Tutorial

This tutorial will expose you to Cloud Firestore. You'll learn how to leverage the platform for real-time database persistence and synchronization. We'll cover the following topics:

  • what Cloud Firestore is
  • the Firestore data model
  • setting up Cloud Firestore
  • creating and working with Cloud Firestore references
  • reading data in real time from Cloud Firestore
  • creating, updating and deleting data
  • filtering and compound queries

Assumed Knowledge

This tutorial assumes you have had some exposure to Firebase and a background developing with Swift and Xcode.

What Is Cloud Firestore?

Like Firebase Realtime Database, Firestore provides mobile and web developers with a cross-platform cloud solution to persist data in real time, regardless of network latency or internet connectivity, as well as seamless integration with the Google Cloud Platform suite of products. Along with these similarities, there are distinct advantages and disadvantages that differentiate one from the other. 

Data Model

On a fundamental level, Realtime Database stores data as one large, monolithic, hierarchical JSON tree, whereas Firestore organizes data in documents and collections, as well as sub-collections. This requires less denormalization. Storing data in one JSON tree has the benefits of simplicity when it comes to working with simple data requirements; however, it becomes more cumbersome at scale when working with more complex hierarchical data. 

Offline Support

Both products offer offline support, actively caching data in queues when there is latent or no network connectivity—synchronising local changes back to the back end when possible. Firestore supports offline synchronisation for web apps in addition to mobile apps, whereas the Realtime Database only enables mobile synchronization.

Queries and Transactions 

Realtime Database only supports limited sorting and filtering capabilities—you can only sort or filter on a property level, but not both, in a single query. Queries are also deep, meaning they return a large sub-tree of results back. The product only supports simple write and transaction operations which require a completion callback. 

Firestore, on the other hand, introduces index queries with compound sorting and filtering, allowing you to combine actions to create chain filters and sorting. You can also execute shallow queries returning sub-collections in lieu of the entire collection you would get with Realtime Database. Transactions are atomic in nature, whether you send a batch operation or single, with transactions repeating automatically until concluded. Additionally, Realtime Database only supports individual write transactions, whereas Firestore affords batch operations atomically.

Performance and Scalability

The Realtime Database, as you would expect, is quite robust and has low latency. However, databases are restricted to single regions, subject to zonal availability. Firestore, on the other hand, houses data horizontally across multiple zones and regions to ensure true global availability, scalability, and reliability. In fact, Google has promised that Firestore will be more reliable than Realtime Database. 

Another shortcoming of the Realtime Database is the limitation to 100,000 concurrent users (100,000 concurrent connections and 1,000 writes/second in a single database) after which you would have to shard your database (split your database into multiple databases) in order to support more users. Firestore automatically scales across multiple instances without you having to intervene. 

Designed from the ground up with scalability in mind, Firestore has a new schematic architecture that replicates data across multiple regions, takes care of authentication, and handles other security-related matters all within its client-side SDK. Its new data model is more intuitive than Firebase's, more closely resembling other comparable NoSQL database solutions like MongoDB, while providing a more robust querying engine. 

Security 

Finally, Realtime Database, as you know from our previous tutorials, manages security through cascading rules with separate validation triggers. This works with Firebase Database Rules, validating your data separately. Firestore, on the other hand, provides a simpler yet more powerful security model taking advantage of Cloud Firestore Security Rules and Identity and Access Management (IAM), with data validation excepted automatically.

The Firestore Data Model

Firestore is a NoSQL document-based database, consisting of collections of documents, each of which contains data. As it's a NoSQL database, you won’t get tables, rows, and other elements you would find in a relational database, but instead sets of key/value pairs that you would find within documents. 

You create documents and collections implicitly by assigning data to a document, and if the document or collection doesn’t exist, it will automatically be created for you, as the collection always has to be the root (first) node. Here is a simple Tasks example schema of the project you will be working on shortly, consisting of the Tasks collection, as well as numerous documents containing two fields, the name (string), and a flag for whether the task is done (boolean).

simple Tasks example schema of the project

Let’s decompose each of the elements so you can understand them better. 

Collections

Synonymous with database tables in the SQL world, collections contain one or more documents. Collections have to be the root elements in your schema and can only contain documents, not other collections. However, you can refer to a document which in turn refers to collections (sub-collections).

Diagram of document and collections

In the diagram above, a task consists of two primitive fields (name and done) as well as a sub-collection (sub-task) which consists of two primitive fields of its own. 

Documents

Documents consist of key/value pairs, with the values having one of the following types: 

  • primitive fields (such as strings, numbers, boolean)
  • complex nested objects (lists or arrays of primitives)
  • sub-collections

Nested objects are also called maps and can be represented as follows, within the document. The following is an example of a nested object and array, respectively:

For more information on the supported data types, refer to Google’s Data Types documentation. Next, you will set up a project to work with Cloud Firestore.

Setting Up the Project

If you have worked with Firebase before, a lot of this should be familiar to you. Otherwise, you will need to create an account in Firebase and follow the instructions in the ‘Set Up the Project’ section of our previous tutorial, Get Started With Firebase Authentication for iOS . 

To follow along with this tutorial, clone the tutorial project repo. Next, include the Firestore library byadding the following to your Podfile:

Enter the following in your terminal to build your library:

Next, switch to Xcode and open up the .xcworkspace file. Navigate to the AppDelegate.swift file and enter the following within the application:didFinishLaunchingWithOptions: method:

In your browser, go to the Firebase console and select the Database tab on the left. 

Database tab in the Firebase console

Make sure you select the option to Start in Test Mode so that you don’t have any security issues while we experiment, and heed the security notice when you do move your app into production. You are now ready to create a collection and some sample documents.

Adding a Collection and Sample Document

To start off, create an initial collection, Tasks, by selecting the Add Collection button and naming the collection, as illustrated below:

naming the collection

For the first document, you are going to leave the Document ID blank, which will auto-generate an ID for you. The document will simply consist of two fields: name and done.

Document with two fields

Save the document, and you should be able to confirm the collection and document along with the auto-generated ID:

collection and document with the auto-generated ID

With the database set up with a sample document in the cloud, you are ready to start implementing the Firestore SDK in Xcode.

Creating & Working With Database References

Open up the MasterViewController.swift file in Xcode and add the following lines to import the library:

Here you are simply creating a listener variable that will allow you to trigger a connection to the database in real time when there is a change. You are also creating a DocumentSnapshot reference that will hold the temporary data snapshot.

Before continuing with the view controller, create another swift file, Task.swift, which will represent your data model:

The code snippet above includes a convenience property (dictionary) and method (init) that will make populating the model object easier. Switch back to the view controller, and declare a global setter variable which will constrain the base query to the top 50 entries in the tasks list. You will also be removing the listener once you set the query variable, as denoted in the didSet property below:

Reading Data in Real Time From Cloud Firestore

With the document reference in place, in viewWillAppear(_animated: Bool), associate the listener you created earlier with the results of the query snapshot, and retrieve a list of documents. This is done by calling the Firestore method query?.addSnapshotListener:

The closure above assigns the snapshot.documents by mapping the array iteratively and wrapping it to a new Task model instance object for each data item in the snapshot. So with just a few lines, you have successfully read in all the tasks from the cloud and assigned them to the global tasks array. 

To display the results, populate the followingTableViewdelegate methods:

At this stage, build and run the project and in the Simulator you should be able to observe data appearing in real time. Add data via the Firebase console and you should see it appear instantaneously in the app simulator. 

Data appearing in the app simulator

Creating, Updating and Deleting Data

After successfully reading content from the back-end, next you will create, update and delete data. The next example will illustrate how to update data, using a contrived example where the app will only let you mark an item as done by tapping on the cell. Note the collection.document(item.id).updateData(["done": !item.done]) closure property, which simply references a specific document ID, updating each of the fields in the dictionary:

To delete an item, call the document(item.id).delete() method:

Creating a new task will involve adding a new button in your Storyboard and connecting its IBAction to the view controller, creating an addTask(_ sender:) method. When a user presses the button, it will bring up an alert sheet where the user can add a new task name:

Complete the final part of the app by entering the following:

Build and run the app once more and, when the simulator appears, try adding in a few tasks, as well as marking a few as done, and finally test the delete function by removing some tasks. You can confirm that the stored data has been updated in real time by switching over to your Firebase database console and observing the collection and documents.

collection and documents in the console

Filtering and Compound Queries

So far, you've only worked with a simple query, without any specific filtering capabilities. To create slightly more robust queries, you can filter by specific values by making use of a whereField clause:

You can order and limit your query data, by making use of the order(by: ) and limit(to: ) methods as follows:

In the FirebaseDo app, you already made use of limit with the base query. In the above snippet, you also made use of another feature, compound queries, where both the order and limit are chained together. You can chain as many queries as you want, such as in the following example:

Conclusion

In this tutorial, you explored Google’s new MBaaS product, Cloud Firestore, and in the process created a simple task reminder app that demonstrates how easy it is for you to persist, synchronize, and query your data in the cloud. You learned about Firestore’s data schema structure in comparison to Firebase Realtime Database, and how to read and write data in real time, as well as updating and deleting data. You also learned how to perform simple as well as compound queries, and how to filter data. 

Cloud Firestore was created with the aim of providing the robustness of Firebase Realtime Database without many of the limitations mobile developers had to endure, especially as pertains to scalability and querying. We only scratched the surface of what you can accomplish with Firestore, and it's certainly worth exploring some of the more advanced concepts, such as Paginating Data with Query CursorsManaging Indexes, and Securing Your Data.


New Course: Convert a jQuery App to Vue.js

$
0
0
Final product image
What You'll Be Creating

Front-end web frameworks have taken component-based development and kicked it into high gear. Vue.js is one of the newest and most popular frameworks and is a great choice for new projects. But a lot of existing code has been written in older technologies, such as jQuery. You'll learn how to deal with that problem in our new short course, Convert a jQuery App to Vue.js.

What You’ll Learn

In this course, Jeremy McPeak will show you how to rewrite your existing jQuery code for Vue.js. You'll learn some of the reasons to upgrade to a modern web framework—and reasons for choosing Vue in particular. 

Converting a jQuery app to Vue

With some simple, step-by-step examples, you'll learn how to handle common tasks like migrating jQuery forms to Vue and converting jQuery plugins.

Watch the Introduction

 

Take the Course

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 580,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

Highlights of Google I/O 2018

$
0
0

And that’s a wrap! This year’s Google I/O has come to a close, and as usual there were lots of announcements and releases for developers to get excited about.

Let’s look at some of the biggest news from Google I/O 2018.

A Major Fix for One of Google’s Core Products

Google kicked things off with a huge announcement, within the first few seconds of their opening keynote. “It came to my attention that we had a major bug in one of our core products,” said Google CEO Sundar Pichai. “We got the cheese wrong in our burger emoji.” Now fixed!

Google CEO Sundar Pichai unveils Googles new and improved burger emoji

Android P Is Now in Beta (But Still Nameless)

While Android P’s name is still shrouded in mystery, Google I/O 2018 did bring us the first beta of Android P, plus a closer look at some of its key features:

  • Adaptive battery. Battery life is a concern for all mobile users, so Android P is introducing a new feature that will optimize battery usage for the individual user. Based on a person’s habits, the adaptive battery will place running apps into groups ranging from “active” to “rare,” where each group has different restrictions. If your app is optimized for Doze, App Standby, and Background Limits, then Adaptive Battery should work out of the box.
  • App Actions. This new feature uses machine learning to analyse the user’s context and recent actions, and then presents your app to the user at the moment when they need it the most. App Actions will make your app visible to users across multiple Google and Android surfaces, such as the Google Search app, the Play Store, Google Assistant, and the Launcher, plus a variety of Assistant-enabled devices, including speakers and smart displays. To take advantage of this feature, you’ll need to register your app to handle one or more common intents.
  • Slices. These are customisable UI templates that will allow users to engage with your app outside of the full-screen experience, across Android and Google surfaces, such as the Google Assistant. You can create slices that include a range of dynamic content, including text, images, videos, live data, scrolling content, deep links, and even interactive controls such as toggles and sliders. Although slices are a new feature for Android P, they will eventually be available all the way back to Android KitKat, thanks to project Jetpack (which we’ll be looking at later in this article).

The first beta of Android P is now available for Sony Xperia XZ2, Xiaomi Mi Mix 2S, Nokia 7 Plus, Oppo R15 Pro, Vivo X21, OnePlus 6, Essential PH‑1, Pixel, and Pixel 2. To check whether your device is eligible for this beta, head over to the Android Beta Program website.

More Kotlin Extensions

One of the biggest moments at last year’s keynote came when Director of Product Management, Stephanie Cuthbertson, announced that Kotlin would become an officially supported language for Android development, so we were always going to see more Kotlin-related news at Google I/O 2018.

Kotlin KTX is one interesting new Kotlin project that got some attention during this year’s I/O. This new project is a collection of modules consisting of extensions that optimize the Android platform for Kotlin. Using these extensions, you can make lots of minor improvements to your code. For example, if you wanted to edit SharedPreferences using vanilla Kotlin, then your code might look something like this:

With the help of the KTX’s androidx.core:core-ktx module, you can now write code that looks more like this:

Android KTX is currently in preview, so you should expect some breaking changes before it reaches its first stable release. However, if you want to experiment with this early version, then the following modules are available today:

  • androidx.core:core-ktx
  • androidx.fragment:fragment-ktx
  • androidx.palette:palette-ktx
  • androidx.sqlite:sqlite-ktx
  • androidx.collection:collection-ktx
  • androidx.lifecycle:lifecycle-viewmodel-ktx
  • androidx.lifecycle:lifecycle-reactivestreams-ktx
  • android.arch.navigation:navigation-common-ktx
  • android.arch.navigation:navigation-fragment-ktx
  • android.arch.navigation:navigation-runtime-ktx
  • android.arch.navigation:navigation-testing-ktx
  • android.arch.navigation:navigation-ui-ktx
  • android.arch.work:work-runtime-ktx

To start working with Android KTX, you’ll need to add a dependency for each module that you want to use. For example:

Android Jetpack

Android Jetpack is a new set of libraries, tools and architectural guidance that aims to eliminate boilerplate code by automatically managing activities such as background tasks, navigation, and lifecycle management.

Jetpack is divided into four categories:

  • Foundation. This includes components for core system capabilities, such as App Compat and Android KTX.
  • UI. This is the category for UI-focused components, such as Fragment and Layout, but also components that extend beyond smartphones, including Auto, TV, and Wear OS by Google.
  • Architecture. This is where you’ll find modules to help you manage the UI component lifecycle and handle data persistence, including Data Binding, LifeCycles, LiveData, Room, and ViewModel.
  • Behaviour. This category contains modules such as Permissions, Notifications, and the newly announced Slices.

The easiest way to get started with Jetpack is to download Android Studio 3.2 or higher and then create a project using the Activity & Fragment + ViewModel template, which is designed to help you incorporate Jetpack into your app.

A New Build of Android Studio 3.2 Canary

No Google I/O would be complete without some Android Studio news! This year, we got a new preview of Android 3.2, which introduced the following features:

A New Navigation Editor

Your app’s navigation is crucial to delivering a good user experience. For the best results, you should carefully design your navigation so users can complete each task in as few screens as possible.

To help you create a navigational structure that feels intuitive and effortless, Jetpack includes a Navigation Architecture Component, and Android Studio 3.2 is supporting this component with a new graphical navigation editor.

The navigation editor lets you visualise and perfect your app’s navigational structure, although the downside is that you can’t just use it out of the box: you’ll need to set up the Navigation Architecture Component and create a Navigation graph XML resource file, before you can access this editor.

Goodbye Support Library, Hello AndroidX

Android’s Support Library is invaluable, but due to the way it’s evolved over the years, it isn’t exactly intuitive, especially for newcomers. For example, the Support Library includes many components and packages named v7, even though API 14 is the minimum that most of these libraries support.

To help clear up this confusion, Google is refactoring the Support Library into a new AndroidX library that will feature simplified package names and Maven groupIds and artifactIds that better reflect the library’s contents. For more information about the mappings between old and new classes, check out the AndroidX refactoring map.

Android Studio 3.2 supports this migration with a new refactoring feature, which you can access by Control-clicking your project and selecting Refactor > Refactor to AndroidX. This will update your code, resources, and Gradle configuration to reference the Maven artifacts and refactored classes.

According to the Google blog, they plan to continue updating the android.support-packaged libraries throughout the P Preview timeframe, to give the community plenty of time to migrate to AndroidX.

Reduce Your APK Size With Android App Bundle

Since the Android Marketplace launched in March 2012, average app size has quintupled, and there’s evidence to suggest that for every 6 MB increase in APK size, you can expect to see a 1% decrease in installation rates.

To help you get your APK size under control, Android Studio 3.2 introduces the concept of Android App Bundles. Under this new model, you build a single artifact that includes all the code, assets, and libraries that your app needs for every device, but the actual APK generation is performed by Google Play’s Dynamic Delivery service.

This new service generates APKs that are optimized for each specific device configuration, so the user gets a smaller download containing only the code and resources that are required by their particular device, and you don’t have to worry about building, signing, uploading and managing multiple APKs.

If you already organize your app’s code and resources according to best practices, then creating an App Bundle in Android Studio 3.2 is fairly straightforward:

  • Choose Build > Build Bundle(s) / APK(s) from the Android Studio toolbar.
  • Select Build Bundle(s).
Select Build  Build Bundles  APKs  Build Bundles from the Android Studio toolbar

This generates an app bundle and places it in your project-name/module-name/build/outputs/bundle/ directory.

To generate a signed app bundle that you can upload to the Google Play console:

  • Select Build > Generate Signed Bundle/APK from the Android Studio toolbar.
  • Select Android App Bundle and then click Next.
  • In the Module dropdown menu, select your app’s base module.
  • Complete the rest of the signing dialogue, as normal, and Android Studio will generate your signed bundle.

When you upload your App Bundle, the Play Console automatically generates split APKs and multi-APKs for all the device configurations that your application supports. If you’re curious, then you can see exactly what artifacts it’s created, using the new App Bundle Explorer:

  • Sign into the Google Play Console.
  • Select your application.
  • In the left-hand menu, select Release management > App releases > Manage.
  • Select the bundle that you want to explore.
  • Click Open in bundle explorer.

You can also add dynamic feature modules to your App Bundle, which contain features and assets that the user won’t require at install time but may need to download at a later date. Eventually, Google also plans to add instant-enable support to the App Bundle, which will allow users to launch your app’s module from a link, without installation, in a manner that sounds very reminiscent of Android Instant Apps.

Populate Your Layouts With Sample Data

When your layout includes lots of runtime data, it can be difficult to visualise how your app will eventually look. Now, whenever you add a View to your layout, you’ll have the option to populate it with a range of sample data.

To see this feature in action:

  • Open Android Studio’s Design tab.
  • Drag a RecyclerView into your app’s layout.
  • Make sure your RecyclerView is selected.
  • In the Attributes panel, find the RecyclerView / listitem section and give the corresponding More button a click (where the cursor is positioned in the following screenshot).
Populate your layouts with a range of sample data

This launches a window where you can choose from a variety of sample data.

Android Profiler Gets an Energy Profiler

The Android Profiler has also been updated with lots of new features, most notably an Energy Profiler that displays a graph of your app’s estimated energy usage.

Android Studio 32 includes a new Energy Profiler

New Lint Checks for Java/Kotlin Interoperability

To make sure your Java code plays nicely with your Kotlin code, Android Studio 3.2 introduces new Lint checks that enforce the best practices described in the Kotlin Interop Guide.

To enable these checks:

  • Choose Android Studio > Preferences from the Android Studio toolbar.
  • Select Editor from the left-hand menu.
  • Select Inspections.
  • Expand the Kotlin section, followed by the Java interop issues section.
  • Select the inspections that you want to enable.

Why Won’t Android Studio Detect My Device?

At some point, we’ve all experienced the pain of connecting our Android smartphone or tablet to our development machine, only for Android Studio to refuse to recognise its existence. Android Studio 3.2 introduces a Connection Assistant that can help you troubleshoot these frustrating connection issues.

To launch the Assistant, select Tools > Connection Assistant from the Android Studio toolbar, and then follow the onscreen instructions.

Actions for the Assistant

If you’ve built Actions for the Assistant, then Google I/O saw the launch of several new and expanded features that can help you get more out of your Actions.

Customise Actions With Your Own Branding

It’s now possible to create a custom theme for your Actions. For example, you could change an Action’s background image and typeface to complement your app’s branding.

To create themed Actions:

  • Head over to the Actions console (which has also undergone a redesign).
  • Open the project where you want to implement your custom theme.
  • In the left-hand menu, select Theme customization.
Create custom themes in Googles Actions console

This takes you to a screen where you can make the following customisations:

  • Background colour. A colour that’s applied to the background of your Action cards. Wherever possible you should use a light colour, as this makes the card’s content easier to read.
  • Primary colour. A colour that’s applied to header text, such as card titles, and UI components such as buttons. It’s recommended that you use a dark colour, as these provide the greatest contrast with the card’s background.
  • Typography. A font family that’s applied to your card’s primary text, such as titles.  
  • Shape. Give your Action cards angled or curved corners.
  • Background image. Upload an image to use as your Action card’s background. You’ll need to provide separate images for the device’s landscape and portrait modes.

Once you’re happy with your changes, click Save. You can then see your theme in action, by selecting Simulator from the left-hand menu.

Show the Assistant What Your Actions Can Do!

Google is in the process of mapping all the different ways that people can ask for things to a set of built-in intents. These intents are an easy way of letting the Assistant know that your Action can fulfil specific categories of user requests, such as getting a credit score or playing a game. In this way, you can quickly and easily expand the range of phrases that trigger your Actions, without going to the effort of defining those terms explicitly.

A developer preview of the first set of built-in intents is already available, with Google planning to roll out “hundreds of built-in intents in the coming months.”

You can integrate these built-in intents using the Dialogflow Console or the Actions SDK, depending on how you implemented your Actions.

Using Dialogflow

  • Head over to the Dialogflow Console.
  • Select your agent from the left-hand menu.
  • Find Intents in the left-hand menu, and then select its accompanying + icon.
  • Click to expand the Events section.
  • Select Add Event.
  • Select the intent that you want to add.
Open the Dialogflows Events dropdown and choose from a range of built-in intents
  • Scroll back to the top of the screen, give your intent a name, and then click Save.

Using the Actions SDK

If you’re using the Actions SDK, then you’ll need to specify the mapping between each built-in intent and the Actions in your Action package, which is a JSON file that you create using the gactions CLI.

For example, here we’re updating the Action package to support the GET_CREDIT_SCORE built-in intent:

Drive Traffic to Your Actions With Deep Links

You can now generate Action Links, to provide quick and easy access to your app’s Actions. When the user interacts with one of your Action Links on their smartphone or Smart Display, they’ll be taken directly to their Assistant where they can interact with the associated Action. If they interact with one of your Action Links on their Desktop, then they’ll be prompted to select the Assistant-enabled device where they want to access your Action.

To see an example of deep linking, check out this Action Link from the meditation and mindfulness app, Headspace.

To generate an Action Link:

  • Head over to the Actions Console.
  • Open the project where you want to create your Action Link.
  • In the left-hand menu, select Actions.
  • Select the Action that you want to generate a link for.
  • Scroll down to the Links section, and click to expand.
  • Drag the Would you like to enable a URL for this Action? slider, so it’s set to On
  • Give your link a title.
  • Scroll to the top of the page, and then click Save.
  • Find the URL in the Links section, and then click Copy URL.

You can now use this URL in any location that supports a hyperlink, such as websites, blogs, Facebook, Twitter, YouTube comment sections, and more.

Become Part of Your Users’ Everyday Routines

The most effective way to drive people to your app is to become part of their daily routines. Google Assistant already allows users to execute multiple Actions at once, as part of pre-set routines, but now Google is launching a developer preview of Routine Suggestions.

Once this feature becomes publicly available, you’ll be able to prompt users to add your own Actions to their routines.

Although this feature isn’t ready to be rolled out just yet, you can add Routine Suggestions support to your Actions, ready for when this feature does graduate out of developer preview.

  • Head over to the Actions on Google console.
  • Select your project.
  • In the left-hand menu, select Actions.
  • Select the Action where you want to add Routine Suggestions support.
  • Scroll to the User engagement section, and then click to expand.
  • Push the Would you like to let users add this Action to Google Assistant Routines? slider, so it’s set to On.
  • Enter a Content title.
  • Scroll back to the top of the screen, and then click Save.

A New Release of the Cross-Platform Flutter Toolkit

If your mobile app is going to reach the widest possible audience, then you’ll need to develop for other platforms besides Android! This has long presented developers with a conundrum: do you build the same app multiple times, or compromise with a cross-platform solution that doesn’t quite deliver the native experience that mobile users have come to expect? 

At Google I/O 2017, Google announced Flutter, a UI toolkit that promised to help you write your code once and provide a native experience for both iOS and Android, with widgets that are styled according to Cupertino (iOS) and Material Design (Android) guidelines.

At this year’s event, Google launched the third beta release of Flutter, with new features such as:

  • Dart 2 is enabled by default.
  • Localisation support, including support for right-to-left languages and mirrored controls.
  • More options for building accessible apps, with support for screen readers, large text, and contrast capabilities.

To get started with Flutter, you’ll need to set up Git, if you haven’t already. Once you’ve installed Git, you can get your hands on Flutter by running the following command from a Terminal or Command Prompt window:

You can use Flutter with any text editor, but if you install the Flutter and Dart plugins then you can create Flutter apps using Android Studio:

  • Launch Android Studio and select Android Studio > Preferences… from the toolbar.
  • Select Plugins from the left-hand menu.
  • Give the Browse repositories… button a click.
  • Search for Flutter, and then click the green Install button.  
  • When Android Studio prompts you to install Dart, click Yes.
  • Restart Android Studio.

You now have access to a selection of Flutter templates, so the easiest way to get a feel for this toolkit is to create a project using one of these templates:

  • Select New > New Flutter Project…
  • Select the Flutter application template, and then click Next.
  • Complete the project setup, as normal.

To run this app:

  • Open the Flutter Device Selection dropdown.
  • Select your Android Virtual Device (AVD) or physical Android device from the list.
  • Select Run > main.dart from the Android Studio toolbar.

This creates a simple app that tracks how many times you’ve tapped a Floating Action Button.

Use the Flutter application template to create a simple Dart-based app

To take a look at the code powering this app, open your project's flutter_app/java/main.dart file.

Let Google Assistant Book Your Next Hair Appointment

While this technically isn’t something you can add to your apps or start experimenting with today, Google Duplex was one of the most intriguing announcements made during the opening keynote, so it definitely deserves a mention.

While many businesses have an online presence, there are still times when you’ll need to pick up the phone and contact a business directly, especially when you’re dealing with smaller, local businesses.

During the opening keynote, Sundar Pichai announced that Google is testing a new feature that aims to automate tasks that’d typically require you to pick up the phone, such as reserving a table at your favourite restaurant or booking a haircut.

Using this new feature, you’ll just need to specify the date and time when you want to book your appointment, and Google Assistant will then call the business on your behalf. Powered by a new technology called Google Duplex, the Assistant will be able to understand complex sentences and fast speech, and will respond naturally in a telephone conversation, so the person on the other end of the line can talk to Google Assistant as though it were another human being, rather than a computerised voice!

Once Google Assistant has booked your appointment, it’ll even add a reminder to your calendar, so you don’t forget about your haircut or dinner reservations.

Currently, Duplex is restricted to scheduling certain types of appointments, but several clips were played during the Google I/O keynote, and the results are already pretty impressive. You can hear these clips for yourself, over at the Google AI blog.

Behind the scenes, Duplex is a recurrent neural network (RNN), built using the TensorFlow Extended (TFX) machine learning platform and trained using a range of anonymised phone conversation data. The computerised voice varies its intonation based on the context, thanks to a combination of the text-to-speech (TTS) engine and a synthesis TTS engine, using Tacotron and WaveNet—plus the addition of some “hmmm”s and “uh”s and pauses, calculated to help the conversation sound more natural.

As well as being convenient for the user, this technology can help small businesses that rely on bookings but don’t have an online booking system, while also reducing no-shows by reminding customers about their appointments. Duplex also has huge potential to help hearing-impaired users, or people who don’t speak the local language, by completing tasks that would be challenging for them to perform unassisted.

Conclusion

In this article, we covered some of the most noteworthy developer-focused announcements at Google I/O 2018, but there’s plenty more we haven’t touched on! If you want to catch up on all the Google-related news (and you have a few hundred hours to spare) then you can watch all the Google I/O 2018 sessions on YouTube.

Introducing Fuse for Cross-Platform App Development

$
0
0

There's no shortage of tools when it comes to developing apps that work cross-platform. It originally started with PhoneGap, which then became Cordova. Then came the hybrid frameworks with near-native performance, like React Native and NativeScript. And more recently came Google's Flutter. 

My point is that there are a lot of those frameworks out there. You'll believe me if you just do a quick Google search of "cross-platform mobile development frameworks". If you're just beginning to develop mobile apps, it can be paralyzing. That's why it's important to get to know your options.

So today I'll be introducing you to Fuse, yet another platform for developing mobile apps that work cross-platform.

In this article, I'll be aiming to answer the following questions:

  • What is Fuse?
  • What are its pros and cons?
  • How does it work?
  • How does it compare to more popular alternatives such as React Native?

What Is Fuse?

Fuse is a platform for developing cross-platform apps with UX Markup and JavaScript. It's in the same category as React Native and NativeScript, but its main selling point is in the provision of tools that enable developers and designers collaborate in real time.

Fuse uses UX Markup, an XML-based language which provides the building blocks for the UI. It also allows you to specify how the different components would behave when users interact with them, thus the name "UX".

Another important thing to understand when you're getting started with Fuse is that it's not a browser-based platform like Cordova. So even though it allows you to use JavaScript code, not all JavaScript features that are available in a browser environment work. 

Fuse provides a decent collection of polyfills which allow you to do things like performing AJAX requests or setting an interval for executing a piece of code. Other than that, you're limited to the core JavaScript features.

Pros

  • Cross-platform: enables you to build apps that run on both Android and iOS devices.
  • Native performance: UX Markup is compiled to native code, which is why the performance is comparable to native (if not the same). The different effects and animations are OpenGL-accelerated, which makes for a top-notch user experience.
  • Declarative code: animations, effects, and transitions are declared via UX Markup. So things like scaling a button when it's clicked are managed purely via the UX Markup. This lets you focus your JavaScript code on things like making requests to APIs, performing calculations, and writing business logic.
  • Developer- and designer-friendly: Fuse uses technologies that web developers know and love: JavaScript for processing tasks and an XML-like language for the UX. The UX Markup they use for building the UI is very simple, which makes it easy to use, even for designers.
  • Good documentation: the different features and APIs are well documented. They also have a collection of examples, though it mostly showcases their UX. 
  • Extendable: Fuse uses a language called Uno to extend native functionality. This means that you can implement custom functionality yourself if you need native functionality that isn't exposed via Fuse's JavaScript APIs.

Cons

  • Young community: compared to React Native, Fuse's community is still young, and it's not really that active. They have a Slack channel and a forum. They also have a page for community packages, but when you look at the GitHub repos, there's not really much activity. There's also a lack of blog posts and tutorials about Fuse.
  • No support for existing JavaScript frameworks: Fuse only supports vanilla JavaScript. So if you're coming from Vue, React, or Angular and you want to use your skills on the Fuse platform, sadly that isn't possible.
  • No Linux support: You can't develop apps with Fuse if you're not on either Windows or macOS. 
  • No NPM support and package system: you can't use NPM to install and use existing JavaScript libraries. Though there are a few JavaScript libraries that are known to work, a platform isn't really complete without a package system that allows developers to install existing libraries which implement a specific functionality! 
  • No Native ES6 support: Fuse only supports ECMAScript 5.1 for writing JavaScript code. However, you can use a transpiler such as Babel to transpile your ES6 code to ES5.

How Does Fuse Work?

Under the hood, Fuse translates the UX Markup into native C++ code via the Uno compiler. Uno is the C#-like language which was used to write all of Fuse's core classes. So the UX Markup that you've written, together with the Fuse framework, is compiled to C++. After that, the native platform tools (Android Studio or Xcode) take that C++ code and compile the native app.

As for the JavaScript code, it's interpreted by a JavaScript VM at runtime. This means that the UI and the business logic are independent of each other. 

How Does Fuse Compare to React Native?

No introductory article about a new platform would be complete without comparing it to an existing platform. One platform which is comparable to Fuse is React Native. So we'll be comparing those two platforms based on the following criteria:

  • platform features
  • performance
  • code
  • extendability

Note that I'll only be comparing the free features of Fuse because React Native is a free platform.

Platform Features

Both Fuse and React Native come with the following features:

  • Hot reloading: changes to the code are automatically reflected in the app preview. However, if you compare how fast the UI updates happen, Fuse is clearly the winner. Their hot reload is almost instant.
  • JavaScript APIs for using native functionality: both Fuse and React Native allow you to access native device functionality such as the camera, geolocation, and push notifications through a JavaScript API. However, if you compare the documentation, it's clear that React Native has more APIs available.

Here are the features that are only available to Fuse:

  • Previewing on multiple devices: this lets the developers and designers preview the app on multiple devices with different form factors. The only requirement is that the development machine should be on the same wireless network as the devices. This is very useful because they'll immediately see if something doesn't look nice on a specific viewport.
  • Desktop preview: this allows the apps to be previewed on the desktop. Note that this will have very little impact on the performance of your computer. This is because it's not actually a device emulator. The desktop preview also lets you preview the app on multiple viewports. 
  • Preview App: if you want a quick way to preview your app, a client app for Android and iOS is also available. This lets you scan a QR code, which then opens the app on the device. You can do this for as many devices as you want. Changes to the source code are automatically reflected on every single one of these devices. 
Fuse App Preview

The only downside of the preview app, as opposed to the custom preview (the default way of previewing apps on a device), is that custom Uno code and third-party packages won't work. Geolocation, push notifications, and local notifications also won't work. You're better off using the custom preview in those cases. 

Performance

Fuse's performance is comparable to native because the UX Markup is compiled to native UI for the specific platform. And because all of the animations, effects, and transitions are defined in the markup itself, it already knows what to do when, for example, a button is pressed. As mentioned earlier, JavaScript runs on a separate thread, and it won't affect the UI performance at all. On top of that, Fuse uses OpenGL ES, which provides hardware-accelerated graphics performance. This means that different animations and effects can be used at the same time with no considerable effect on the UI performance. This makes Fuse a very suitable platform for developing mobile games.

On the other hand, React Native uses a bridge module for each platform. This module acts as a connection between the JavaScript APIs (including the UI components) and native functionality so they can communicate with each other. This makes React Native less performant than Fuse because of the communication cost between the native components and React Native's corresponding UI components. 

Code

Both Fuse and React Native offer a markup language as a building block for the UI. However, just by comparing the docs of Fuse and React Native, you can see that React Native has more components which represent their native counterparts.

Fuse's UX Markup allows you to describe the animations of a component whenever a user interacts with it. For example, here's how you might create a button which becomes three times as big as its original size while it's being pressed. Fuse takes care of how long the transition will be if you don't specify it:

On the other hand, React Native relies on JavaScript for almost everything. In the code below, the TextInput component relies on text to be initialized in the state. It then updates it every time the text inputted by the user changes: 

Here's how the default text for a text field is supplied:

Between the two, the way Fuse separates business logic from managing the UI is favorable in terms of collaboration between a developer and designer. UX Markup is simple enough for the designer to understand, so they can work on it while the developer handles the business logic. 

Extendability

Fuse allows you to use the same language that they use for all of their core classes as a way to extend native functionality. However, this does require you to have knowledge of how to use the native APIs in Android and iOS. From Fuse's Uno, you can use foreign code to implement native functionality. Currently, Uno only supports Objective-C for iOS and Java for Android. The resulting class is then exposed so that you can call it from JavaScript.

Similarly, React Native has a corresponding bridge module for both iOS and Android. This bridge module serves as the bridge between native functionality and JavaScript. Just like Fuse, this requires you to have a working knowledge of Objective-C or Java.

Both platforms also allow you to extend native UI components for each of your target platforms. So what if, for example, you want to implement a corresponding UI component for the native tooltip control on Android? You can do that on both Fuse and React Native.

Is Fuse Worth It?

If you ask my opinion, I'd say it depends on your specific use case. Fuse is definitely production-ready. Its main advantage is its performance and how fast you can go from an idea to a working prototype. Apps created with Fuse are highly performant, and it also makes collaboration between developers and designers really easy.

Its main disadvantage is its community. Fuse is clearly committed to open source with their release of the libraries which make Fuse work under the hood. However, they're still a small company (when compared to Facebook, at least). This means that they have to make money in one way or another. That's why they have professional paid plans which are more geared towards teams and the enterprise. So one can assume that most of their efforts will be put towards developing these paid tools. This leaves the open-source effort a second-class citizen. 

If you're working for a company that develops apps on a daily basis, then Fuse is a good option. But if you're an independent developer like me, we're mostly stuck with using the free plan. It's good enough for most use cases, but if you need custom native functionality, then you'll have to implement it yourself.

At the end of the day, it all depends on your use case. If you see your app not needing to work with a whole bunch of services, tools, and native APIs, then go for Fuse. Otherwise, don't. Not unless you have a lot of time to spare in developing custom native modules!

Conclusion

You should now have a good understanding of what Fuse is, how it works, its pros and cons, and if it's worth trying out as an alternative to more popular mobile development frameworks. In the second part of this series, we'll take a look at how to develop an app with Fuse.

Introduction to Machine Learning in Python

$
0
0

Machine learning is the act of giving computers the ability to learn without explicitly programming them. This is done by giving data to computers and having them transform the data into decision models which are then used for future predictions.

In this tutorial, we will talk about machine learning and some of the fundamental concepts that are required in order to get started with machine learning. We will also devise a few Python examples to predict certain elements or events.

Introduction to Machine Learning

Machine learning is a type of technology that aims to learn from experience. For example, as a human, you can learn how to play chess simply by observing other people playing chess. In the same way, computers are programmed by providing them with data from which they learn and are then able to predict future elements or conditions.

Let's say, for instance, that you want to write a program that can tell whether a certain type of fruit is an orange or a lemon. You might find it easy to write such a program and it will give the required results, but you might also find that the program doesn't work effectively for large datasets. This is where machine learning comes into play.

There are various steps involved in machine learning:

  1. collection of data
  2. filtering of data
  3. analysis of data
  4. algorithm training
  5. testing of the algorithm
  6. using the algorithm for future predictions

Machine learning uses different kinds of algorithms to find patterns, and these algorithms are classified into two groups:

  • supervised learning
  • unsupervised learning

Supervised Learning

Supervised learning is the science of training a computer to recognize elements by giving it sample data. The computer then learns from it and is able to predict future datasets based on the learned data.

For example, you can train a computer to filter out spam messages based on past information.

Supervised learning has been used in many applications, e.g. Facebook, to search images based on a certain description. You can now search images on Facebook with words that describe the contents of the photo. Since the social networking site already has a database of captioned images, it is able to search and match the description to features from photos with some degree of accuracy.

There are only two steps involved in supervised learning:

  • training
  • testing

Some of the supervised learning algorithms include:

  • decision trees
  • support vector machines
  • naive Bayes
  • k-nearest neighbor
  • linear regression

Example

We are going to write a simple program to demonstrate how supervised learning works using the Sklearn library and the Python language. Sklearn is a machine learning library for the Python programming language with a range of features such as multiple analysis, regression, and clustering algorithms.

Sklearn also interoperates well with the NumPy and SciPy libraries.

Install Sklearn

The Sklearn installation guide offers a very simple way of installing it for multiple platforms. It requires several dependencies:

  • Python (>= 2.7 or >= 3.3),
  • NumPy (>=1.82)
  • SciPy (>=0.13.3)

If you already have these dependencies, you can install Sklearn as simply as:

An easier way is to simply install Anaconda. This takes care of all the dependencies so you don't have to worry about installing them one by one.

To test if Sklearn is running properly, simply import it from a Python interpreter as follows:

If no error occurs, then you are good to go.

Now that we are done with the installation, let's get back to our problem. We want to able to differentiate between different animals. So we will design an algorithm that can tell specifically whether a given animal is either a horse or a chicken.

We first need to collect some sample data from each type of animal. Some sample data is shown in the table below.

Height (inches)Weight (kg)
Temperature (Celsius)
Label
7
0.6
40Chicken (0)
7
0.641
Chicken (0)
37
0.837
Horse (1)
37
0.838
Horse (1)

The sample data we have obtained gives some of the common features of the two animals and data from two of the animals. The larger the sample data, the more accurate and less biased the results will be.

With this type of data, we can code an algorithm and train it to recognize an animal based on the trained values and classify it either as a horse or a chicken. Now we will go ahead and write the algorithm that will get the job done.

First, import the tree module from Sklearn.

Define the features you want to use to classify the animals.

Define the output each classifier will give. A chicken will be represented by 0, while a horse will be represented by 1.

We then define the classifier which will be based on a decision tree.

Feed or fit your data to the classifier.

The complete code for the algorithm is shown below.

We can now predict a given set of data. Here's how to predict an animal with a height of 7 inches, a weight of 0.6 kg, and a temperature of 41:

Here's how to predict an animal with a height of 38 inches, a weight of 600 kg, and a temperature of 37.5:

As you can see above, you have trained the algorithm to learn all the features and names of the animals, and the knowledge of this data is used for testing new animals.

Unsupervised Learning

Unsupervised learning is when you train your machine with only a set of inputs. The machine will then be able to find a relationship between the input data and any other you might want to predict. Unlike in supervised learning, where you present a machine with some data to train on, unsupervised learning is meant to make the computer find patterns or relationships between different datasets.

Unsupervised learning can be further subdivided into:

  • clustering
  • association

Clustering: Clustering means grouping data inherently. For example, you can classify the shopping habits of consumers and use it for advertising by targeting the consumers based on their purchases and shopping habits.

Association: Association is where you identify rules that describe large sets of your data. This type of learning can be applicable in associating books based on author or category, whether motivational, fictional, or educational books.

Some of the popular unsupervised learning algorithms include:

  • k-means clustering
  • hierarchical clustering

Unsupervised learning will be an important technology in the near future. This is due to the fact that there is a lot of unfiltered data which has not yet been digitized.

Conclusion

I hope this tutorial has helped you get started with machine learning. This is just an introduction—machine learning has a lot to cover, and this is just a fraction of what machine learning can do.

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

Your decision to use either a supervised or unsupervised machine learning algorithm will depend on various factors, such as the structure and size of the data.

Machine learning can be applied in almost all areas of our lives, e.g. in fraud prevention, personalizing news feed in social media sites to fit users' preferences, email and malware filtering, weather predictions, and even in the e-commerce sector to predict consumer shopping habits.

How to Prepare Your Site for WordPress Gutenberg

$
0
0

Gutenberg is coming to WordPress soon. Is your website ready? While we still don't know exactly what form it will take, this new content system will be added to WordPress core in the future. Let's take a look at the potential impacts this could have on your site, and ways that you can determine, and fix, problem areas ahead of time.

What Is Gutenberg?

Gutenberg is a WordPress project that aims to give users more flexibility in the design of their content. Essentially, the project aims to replace the current editor, which performs mostly as a word processor, with a more visual and structured interface. Currently, Gutenberg is a plugin, and it grants users the ability to modify their content similarly to how Visual Composer or other drag-and-drop editors do—albeit in a simplified and highly intuitive way.

If you would like to  learn more about what Gutenberg is specifically, take a look at my earlier post "What Is WordPress Gutenberg?"

The Pieces of Your Site

Gutenberg is a massive undertaking and will likely touch a large number of endpoints within your website. These are the three areas we'll be scouring for issues:

  • Your Theme: Gutenberg comes with its own set of styles for content. Is your theme compatible? What will it look like with Gutenberg active?

  • Your Plugins: It's possible that Gutenberg might interact with your other plugins in unexpected ways. We'll look at what those might be, and what to do about any issues that arise.

  • Your Content: Gutenberg will affect how your content itself is displayed. We'll examine how that might change what your pages look like, and go over some potential fixes if you're having problems.

Setting Up a Testing Area

Before we get started, it's a good idea to set up a testing area where you can experiment with Gutenberg without breaking your live site. Ideally, you should set up your own testing area or create a local copy of your site. For more on how to perform either of those tasks, see the following tutorial:

If neither of these is possible, you can do the testing directly on your site. Note that this can be risky, however, as we'll be activating and deactivating a number of pieces of your site. If you are doing the testing live, please make sure to create a backup of your site before beginning.

Once you know where you'll be testing, head to the plugins directory and find Gutenberg. Once it's installed and activated, read on.

Put Your Theme Through Its Paces

Now that you have Gutenberg installed, let's take a look at the first section of your site that might be affected: its theme. If there are already major problems at this point, such as database errors or problems with the WordPress admin, skip down to the What to Do When There Are Too Many Issues section.

Since Gutenberg interacts mainly with the content of the site, we only need to test a narrow set of things—luckily for us.

The first is that Gutenberg comes with its own style sheet and set of styles. Check each of the different page types and templates used on your site to make sure that they still appear appropriately. The main focus here is going to be elements within the main content area of your pages—especially content and image blocks. If you see any issues, it's likely that Gutenberg's styles are taking precedence over your site's.

To correct this, you'll need to identify where the problem is coming from. Typically, it will be a CSS selector focused on an HTML element, or it could be a priority of Gutenberg styles over your own classes. Whatever the case may be, try to identify where the error is occurring. Next, determine why the Gutenberg styles are overriding yours, and correct your code to allow it to take precedence.

Try to make any corrections within your own theme (or better yet, in a child theme or specified area for CSS in your theme), rather than altering Gutenberg. If you alter any of the files in Gutenberg directly, it's likely to be overwritten when the plugin is updated.

In a similar fashion, you'll want to give your admin area a once-over for any styling issues. Theme options and other custom-implemented sections generated by your theme appear to be the biggest culprits so far. Once you've identified styling issues in these areas, you can typically correct them by changing or creating a child theme and adjusting the CSS there.

Do Your Plugins Work?

After your theme is squared away, next up are your site's plugins. Specifically, keep an eye on any plugins that provide shortcodes that you use in your content (e.g. Gravity Forms), plugins that affect the appearance of your content (e.g. accessibility plugins that affect text size), and plugins that directly insert elements into your page (such as Advanced Custom Fields).

Looking at Shortcodes

To audit this area, first gather a list of any shortcodes that you may be using, along with what pages they exist on. With your list in hand, visit each of these pages to see if they are performing as intended. If you encounter any styling issues, then it’s likely that you're experiencing the same problem as above and need to readjust your styles.

However, if you're getting the dreaded rendered shortcode—that is to say that your page is displaying the [shortcode] instead of doing what it should—there is another solution. In this case, you can look at the block where the shortcode is and confirm that it’s not considered text (looking for and removing unwanted tags around the shortcode). If the problem still persists, moving the shortcode to a more appropriate block type should get everything back up and running.

Content Appearance

This issue arises from the same problem we've covered previously: style overrides. Identify the elements that are being affected and correct the CSS.

Element Creation

The final area that we'll be looking at for conflicting issues concerns element creation.  Any plugin that inserts HTML elements into a page without using shortcodes is suspect here—for example, when PHP pulls in custom fields from the Advanced Custom Fields plugin.

The most common slip-up with element creation revolves around blocks being mismatched. Since Gutenberg provides its own styles, there is a chance that if your elements are created inside an unintended block, they may render incorrectly. The fix for this is making sure your code adds elements to the block where you want them to be.

Is Your Content Appearing as Necessary?

This is not quite as urgent as the other problems we've discussed, but there might be some complications with how your content is rendered. Most of these problems will be from minor styling changes or how blocks are organized. To correct this, you'll have to play around with the block system until you get your page how you want it.

What to Do When There Are Too Many Issues

Did you run into a problem that you couldn't solve with the suggestions in this article? Don't panic! There’s still some time before Gutenberg hits WordPress Core.

First, record what the error is and what steps led to the error. The more information that you can gather, the better. Pass all of this information along to the Gutenberg team. With luck, they'll be able to determine the issue and fix it in a future release.

If you were working on a staging site, then at this point, that's all you can do for now. Continue to check the release notes to see if your problem is solved, or possibly work on solving it yourself.

If you were working on your live site, deactivating Gutenberg should put everything back to normal. If not, then now is the time to revert to that backup you made!

Good Luck on Your Install!

Gutenberg aims to be a massive change to the WordPress environment, one that looks to change content for the better. Before it hits the main branch, make sure to check that your site will function with the new changes. If you have problems other than what's listed here, better solutions, or corrections for anything in this article, please leave a comment below!

15 Best Android App Templates of 2018

$
0
0

Android app templates have been gaining in popularity over the past few years, and that’s no wonder. They’re a huge time saver for experienced developers, helping them to cut through the slog of creating an app from scratch and focus their talents instead on the unique and customised parts of creating a new app.

App templates are also an indispensable learning tool for novice developers who want to improve their coding skills by studying the building blocks of an app while building their own.

We've combed through the thousands of Android app templates available at CodeCanyon to find the 15 best available.

The templates we’ve chosen reflect the most popular Android app categories. Almost all are made with Android Studio, use Google Material Design, support AdMob, give users the option of removing banners and interstitial ads, and come with step-by-step instructions and/or video tutorials on how to configure the templates from scratch.  

1. Universal Android App

Hands down one of the best and most popular Android app templates is Universal Android App. This awesome app lets users create just about any app they want by pulling in unlimited content from blogs, timelines, feeds, channels, playlists, webpages, etc., and easily combining them into one customisable app.

Universal Android App

The template supports the most popular web content sources, like WordPress, YouTube, Facebook, RSS, etc.

User valvze says:

“From the minute of buying this product, I have had nothing but fun. It was an absolute joy creating a personalized app from this template and would definitely recommend this to anybody trying to learn programming. The app is built with easy to figure code and the design elements are fantastic as well. Customer service was quick to response to each of my queries. Would recommend.”

2. The City

Cities are complex spaces, and any app that helps locals and visitors alike navigate them is bound to be a hit. The City is a great app template for developers who want to create an app for their city featuring the most interesting sights, the best restaurants, cafés, bars, shops, and more.

The City

All the app data is stored in a local SQLite database, so the app works in offline mode. And the template has some great features like MapView to show place location, a featured category for recommended places, the ability to filter searches, a save history of searches, and much more.

Customers say: 

“The code is very well structured and clean, the documentation is excellent.”

3. Material Design UI 

Material Design UI is a cool and stylish Android UI template with five gorgeous themes that can be used to make any app project you’re working on more aesthetically appealing. The template themes target social, travel, media, and shopping apps, and there is a universal theme that can be used with a wider variety of apps. The template uses hundreds of UI elements that can be recombined endlessly to create a beautiful and unique looking app. 

Material Design UI

User gayuh says:

“The template contains many UI styles that are very useful when developing new UI for an Android app. Documentation is minimal, but design and code quality are fairly good, and customizability and flexibility are very good."

4. Dating App

Finding love in the 21st century often involves the Internet, and the appropriately named template Dating App is just what you need if you want to try your hand at creating your own online dating app.

Dating App

Built with Android Studio, the template's notable features include a beautiful gallery and user profiles. Users have the ability to comment, like, reply and send gifts, see potential dates that are nearby, make in-app purchases, send real-time direct messages with photos, and of course they can block other users.

Users say of the app: 

“My app has been updated to Google Play Store and is running fine” and “Very good documentation, easy to setup, perfect code quality, outstanding design.”

5. Universal Android WebView App

There seem to be no end of amazing content-rich websites on the internet, and though most of them are responsive and show well on mobile phones and tablets, some clients will want to convert their site into beautiful apps that allow their visitors to access key features easily and seamlessly.

Universal Android WebView App

Universal Android WebView App allows developers to do just that. It is compatible with WordPress and other web frameworks, is highly customisable and packed with features, and it supports HTML5, CSS3, JavaScript, jQuery, Bootstrap, and other web technologies.

Users say Universal Android WebView App is a:

“great template”, with “fast support and excellent documentation”.

6. Store Finder

When you’re out and about and you need to find the closest store to you for a particular item, having a store finder app on your mobile app is a godsend. This kind of indispensability has made the Store Finder app template popular among developers.

Store Finder

Made with Android Studio and material design, the app features a long list of must-have features like email and SMS integration, user ratings and reviews, Google directions, and social media logins. Users also have the ability to draw in the map, use map pins, share to Facebook and Twitter, and more.

Customer Seolio says: 

“The app design and code quality is second to none.”

7. Android News App

Android News App template is the go-to template for those looking to create a mobile news app for Android devices. Users can view the latest news in different categories, save articles as favourites, get notified about the latest articles, and more. It comes with an easy-to-use admin dashboard for modifying the news categories and other details.

Android News App

User jadeofheavens says:

“5 Stars: not just for the customer support but definitely for the code quality, features and documentation. A person like me who knows nothing about Android Studio made an app within half hour.”

8. Your Videos Channel

If you are a YouTuber, videographer or developer with clients who are videographers, Your Videos Channel app template may appeal to you because it essentially allows you to create an app dedicated to showing off your videos or a video collection of your choosing. The app, which has YouTube integration, uses PHP MySQL for the admin side and can manage unlimited categories and video uploads.

Your Videos Channel

User androbogor says:

“Outstanding experience! Good seller. Best support!”

9. My Social Network

Built in Android Studio, My Social Network template allows you to create your own personal social network app where you can publish posts, read the posts of friends, have a personal conversation with friends in real time, and more.

My Social Network

User Joespace says: 

"Very good app, well coded and well documented. It's easy to install if you follow the steps."

10. FlappyBot

Games are without a doubt one of the most popular app categories on Android devices, and the FlappyBot game app template is one of our most popular games. It's written in Java with Eclipse, and a narrated video tutorial is included for a quick start. 

The player touches the screen to move the flappy bird up, and the aim is to keep it alive as long as possible. The game saves the top ten high scores on the user’s device, and users can share their scores on Facebook.

FlappyBot

The template allows developers to edit the game by adding more obstacle columns, changing bird speeds or delays, etc.  

User Neogoapp says: 

“Good documentation and tutorial”.

11. Quizix

Keeping with the entertainment category, Quizix is a fabulous Android quiz app template that only came on the market at the beginning of 2018, but is already one of our best rated app templates. The template uses maths, text and/or photo questions, and has space for two to four answer options. 

Developers simply add their categories, sub-categories and questions in the back end, and the app formulates the quiz. Quizix uses the latest features of the Android platform and is AdMob Banner and Interstitials ready.

Quizix

User Alnoah says:

“I usually don't give ratings but decided to give so because I am fully satisfied with this product. Quality code, great backend and amazing job! I truly recommend this."

12. Your Radio App

Hands down the best radio app template to be found at CodeCanyon, Your Radio App is perfect for developers who want to create their own mobile Internet radio-streaming app. With a powerful admin panel, the app can manage unlimited radio stations and categories and supports many formats.

Your Radio App

User Save2011usa says:

“Excellent Radio app and excellent support! Thanks!”

13. Cookbook Recipe App

Create your own recipe application with the Cookbook Recipe App template. This native Android app template gives experienced and novice developers alike an easy way to make their own recipe app, as it doesn’t require programming skills and the code is easy to configure and customise.

Cookbook Recipe App

The app has many great built-in features like a drawer menu with categories, shopping list, favourites, a powerful search, Google Analytics, various animations and effects, and more.

Cookbook Recipe App stores recipes in a local SQLite database so users can run the app without an Internet connection.

User HiimNaru7o says:

“Great customer support. I had some bugs and they helped me to resolve them. Very cool guy. Highly recommended!”

14. HD Wallpaper

If you’ve been searching for the perfect template to create a great wallpaper app, look no further. The HD Wallpaper app template allows developers to create an app which delivers gorgeous wallpapers and backgrounds to the user’s Android device. 

The app features multiple galleries of high-resolution images, easy tap, swipe and scroll functions, and offline caching of wallpapers.

HD Wallpaper

User saidogame says:

“I like this code. It is a very good one and the support helps you and answers your questions. In my case I had a good support via Skype. I recommend purchasing this code and other codes from this developer.”

15. xMusic

xMusic will appeal to Android developers who are looking for a template to help them create an online-offline music player app. This app plays millions of free songs from SoundCloud via the SoundCloud API, but can switch to music from the user’s own library if they prefer. 

xMusic

Some of the great features the template offers are a powerful Equalizer with many preset music styles, support for sleep mode and a number of playlists, a powerful search, and much more.

User dajin says:

“Clean code, flexibility, customizability, design quality! Great! Awesome!”

Conclusion

These 15 best Android app templates of 2018 are just a small selection of hundreds of Android app templates we have available at CodeCanyon, so if none of them quite fits your needs, there are plenty of other great options to choose from.

And if you want to improve your skills building Android apps and templates, then check out some of the ever-so-useful Android tutorials we have on offer.

How to Make a Real-Time Sports Application Using Node.js

$
0
0
Final product image
What You'll Be Creating

In today's article I'm going to demonstrate how to make a web application that will display live game scores from the NHL. The scores will update automatically as the games progress.

This is a very exciting article for me, as it allows me the chance to bring two of my favorite passions together: development and sports.

The technologies that will be used to create the application are:

  1. Node.js
  2. Socket.io
  3. MySportsFeed.com

If you don't have Node.js installed, visit their download page now and set it up before continuing.

What Is Socket.io?

Socket.io is a technology that connects a client to a server. In this example, the client is a web browser and the server is the Node.js application. The server can have multiple clients connected to it at any given time.

Once the connection has been established, the server can send messages to all of the clients or an individual client. In return, the client can send a message to the server, allowing for bi-directional real-time communication.

Before Socket.io, web applications would commonly use AJAX, and both the client and server would poll each other looking for events. For example, every 10 seconds an AJAX call would occur to see if there were any messages to handle.

Polling for messages caused a significant amount of overhead on both the client and server as it would be constantly looking for messages when there were none.

With Socket.io, messages are received instantaneously, without needing to look for messages, reducing the overhead.

Sample Socket.io Application

Before we consume the real-time sports data, let's create an example application to demonstrate how Socket.io works.

To begin, I am going to create a new Node.js application. In a console window, I am going to navigate to C:\GitHub\NodeJS, create a new folder for my application, and create a new application:

I used all the default settings.

Because we are making a web application, I'm going use an NPM package called Express to simplify the setup. In a command prompt, install it as follows: npm install express --save

And of course we will need to install the Socket.io package: npm install socket.io --save

Let's begin by creating the web server. Create a new file called index.js and place the following code within it to create the web server using Express:

If you are not familiar with Express, the above code example includes the Express library and creates a new HTTP server. In this example, the HTTP server is listening on port 3000, e.g. http://localhost:3000. A route is created at the root of the site "/". The result of the route returns an HTML file: index.html.

Before we create the index.html file, let's finish the server by setting up Socket.io. Append the following to your index.js file to create the Socket server:

Similar to Express, the code begins by importing the Socket.io library. This is stored in a variable called io. Next, using the io variable, an event handler is created with the on function. The event being listened for is connection. This event is called each time a client connects to the server.

Let's now create our very basic client. Create a new file called index.html and place the following code within:

The HTML above loads the Socket.io client JavaScript and initializes a connection to the server. To see the example, start your Node application: node index.js

Then, in your browser, navigate to http://localhost:3000. Nothing will appear on the page; however, if you look at the console where the Node application is running, two messages are logged:

  1. HTTP server started on port 3000
  2. Client connection received

Now that we have a successful socket connection, let's put it to use. Let's begin by sending a message from the server to the client. Then, when the client receives the message, it can send a response back to the server.

Let's look at the abbreviated index.js file:

The previous io.on function has been updated to include a few new lines of code. The first, socket.emit, sends the message to the client. The sendToClient is the name of the event. By naming events, you can send different types of messages so the client can interpret them differently. The second addition is the socket.on, which also contains an event name: receivedFromClient. This creates a function that accepts data from the client. In this case, the data is logged to the console window.

That completes the server-side amendments; it can now send and receive data from any connected clients.

Let's complete this example by updating the client to receive the sendToClient event. When it receives the event, it can respond with the receivedFromClient event back to the server.

This is accomplished in the JavaScript portion of the HTML, so in the index.html file, I have updated the JavaScript as follows:

Using the instantiated socket variable, we have very similar logic on the server with a socket.on function. For the client, it is listening to the sendToClient event. As soon as the client is connected, the server sends this message. When the client receives it, it is logged to the console in the browser. The client then uses the same socket.emit that the server used to send the original event. In this instance, the client sends back the receivedFromClient event to the server. When the server receives the message, it is logged to the console window.

Try it out for yourself. First, in a console, run your Node application: node index.js. Then load http://localhost:3000 in your browser.

Check the web browser console and you should see the following JSON data logged: {hello: "world"}

Then, in the command prompt where the Node application is running, you should see the following:

Both the client and server can use the JSON data received to perform specific tasks. We will learn more about that once we connect to the real-time sports data.

Sports Data

Now that we have mastered how to send and receive data to and from the client and server, this can be leveraged to provide real-time updates. I chose to use sports data, although the same theory is not limited to sports. Before I began this project, I researched different sports data. The one I settled on, because they offer free developer accounts, was MySportsFeeds (I am not affiliated with them in any way). To access the real-time data, I signed up for an account and then made a small donation. Donations start at $1 to have data updated every 10 minutes. This will be good for the example.

Once your account is set up, you can proceed to setting up access to their API. To assist with this, I am going to use their NPM package: npm install mysportsfeeds-node --save

After the package has been installed, API calls can be made as follows:

In the example above, be sure to replace the call to the authenticate function with your username and password.

The following code executes an API call to the get the NHL scoreboard for today. The fordate variable is what specifies today. I've also set force to true so that a response is always returned, even when the data has not changed.

With the current setup, the results of the API call get written to a text file. In the final example, this will be changed; however, for demonstration purposes, the results file can be reviewed in a text editor to understand the contents of the response. The results contain a scoreboard object. This object contains an array called gameScore. This object stores the result of each game. Each object contains a child object called game. This object provides the information about who is playing.

Outside of the game object, there are a handful of variables that provide the current state of the game. The data changes based on the state of the game. For example, when the game hasn't started, there are only a few variables that tell us the game is not in progress and has not started.

When the game is in progress, additional data is provided about the score, what period the game is in, and how much time is remaining. We will see this in action when we get to the HTML to show the game in the next section.

Real-Time Updates

We have all the pieces to the puzzle, so it is now time to put the puzzle together to reveal the final picture. Currently, MySportsFeeds has limited support for pushing data to us, so we will have to poll the data from them. Luckily, we know the data only changes once every 10 minutes, so we don't need to add overhead by polling for changes too frequently. Once we poll the data from them, we can push those updates from the server to all clients connected.

To perform the polling, I will use the JavaScript setInterval function to call the API (in my case) every 10 minutes to look for updates. When the data is received, an event is sent to all of the connected clients. When the clients receive the event, the game scores will be updated with JavaScript in the web browser.

MySportsFeeds will also be called when the Node application first starts up. This data will be used for any clients who connect before the first 10-minute interval. This is stored in a global variable. This same global variable is updated as part of the interval polling. This will ensure that when any new clients connect after the polling, they will have the latest data.

To assist with some code cleanliness in the main index.js file, I have created a new file called data.js. This file will contain a function that is exported (available in the index.js file) that performs the previous call to the MySportsFeeds API. Here are the full contents of that file:

A getData function is exported and returns the result of the call, which in this case is a Promise that will be resolved in the main application.

Now let's look at the final contents of the index.js file:

The first seven lines of code above instantiate the required libraries and the global latestData variable. The final list of libraries used are: Express, Http Server created with Express, Socket.io, and the aforementioned data.js file just created.

With the necessities taken care of, the application populates the latestData for clients who will connect when the server is first started:

The next few lines set up a route for the root page of the website (http://localhost:3000/) and start the HTTP server to listen on port 3000.

Next, the Socket.io is set up to look for connections. When a new connection is received, the server emits an event called data with the contents of the latestData variable.

And finally, the final chunk of code creates the polling interval. When the interval occurs, thelatestData variable is updated with the results of the API call. This data then emits the same data event to all clients.

You may notice that when the client connects and an event is emitted, it is emitting the event with the socket variable. This approach will send the event to that connected client only. Inside the interval, the global io is used to emit the event. This will send the event to all clients.

That completes the server. Let's work on the client front-end. In an earlier example, I created a basic index.html file that set up the client connection that would log events from the server and send one back. I am going to extend that file to contain the completed example.

Because the server is sending us a JSON object, I am going to use jQuery and leverage a jQuery extension called JsRender. This is a templating library. It will allow me to create a template with HTML that will be used to display the contents of each NHL game in an easy-to-use, consistent manner. In a moment, you will see the power of this library. The final code is over 40 lines of code, so I am going to break it down into smaller chunks, and then display the full HTML together at the end.

This first part creates the template that will be used to show the game data:

The template is defined using a script tag. It contains the id of the template and a special script type called text/x-jsrender. The template defines a container div for each game that contains a class game to apply some basic styling. Inside this div, the templating begins.

In the next div, the away and home team are displayed. This is done by concatenating the city and team name together from the game object from the MySportsFeed data.

{{:game.awayTeam.City}} is how I define an object that will be replaced with a physical value when the template is rendered. This syntax is defined by the JsRender library.

Once the teams are displayed, the next chunk of code does some conditional logic. When the game isunPlayed, a string will be outputted that the game will start at {{:game.time}}.

When the game is not completed, the current score is displayed: Current Score: {{:awayScore}} - {{:homeScore}}. And finally, some tricky little logic to identify what period the hockey game is in or if it is in intermission.

If the variable currentIntermission is provided in the results, then I use a function I defined called ordinal_suffix_of, which will convert the period number to read: 1st (2nd, 3rd, etc.) Intermission.

When it is not in intermission, I look for the currentPeriod value. This also uses the ordinal_suffix_of to show that the game is in the 1st (2nd, 3rd, etc.) period.

Beneath this, another function I defined called time_left is used to convert the number of seconds remaining into the number of minutes and seconds remaining in the period. For example: 10:12.

The final part of the code displays the final score because we know the game has completed.

Here is an example of what it looks like when there is a mix of finished games, in progress games, and games that have not started yet (I'm not a very good designer, so it looks as you would expect when a developer makes their own User Interface).

An example of finished games

Next up is a chunk of JavaScript that creates the socket, the helper functions ordinal_suffix_of and time_left, and a variable that references the jQuery template created.

The final piece of code is the code to receive the socket event and render the template:

I have a placeholder div with the id of data. The result of the template rendering (tmpl.render) writes the HTML to this container. What is really neat is that the JsRender library can accept an array of data, in this case data.scoreboard.gameScore, that iterates through each element in the array and creates one game per element.

Here is the final HTML and JavaScript all together:

Start the Node application and browse to http://localhost:3000 to see the results for yourself!

Every X minutes, the server will send an event to the client. The client will redraw the game elements with the updated data. So when you leave the site open and periodically look at it, you will see the game data refresh when games are currently in progress.

Conclusion

The final product uses Socket.io to create a server that clients connect to. The server fetches data and sends it to the client. When the client receives the data, it can seamlessly update the display. This reduces load on the server because the client only performs work when it receives an event from the server.

Sockets are not limited to one direction; the client can also send messages to the server. When the server receives the message, it can perform some processing.

Chat applications would commonly work this way. The server would receive a message from the client and then broadcast to all connected clients to show that someone has sent a new message.

Hopefully you enjoyed this article as I had a blast creating this real-time sports application for one of my favorite sports!


Introduction to Popmotion: Tween

$
0
0

Popmotion is a functional JavaScript animation library. Compared to other libraries like GreenSock or Anime.js, Popmotion is low-level and unopinionated.

It packs a ton of features, like spring physics and pointer tracking, into a very small filesize (11.5kb).

It allows developers to write their own features using simple functions, rather than waiting for the library author to add them.

It also means it's just as easy to animate 3D objects, charts or React components as it is to animate DOM or SVG elements.

This flexibility can make the initial learning curve steeper than for other libraries. So, in this tutorial series, we'll learn the basics of Popmotion's powerful animations. We'll start with the workhorse of the animation world, the tween.

Install

Popmotion supports a variety of installation methods. In production, I recommend installing via npm, as this allows you to import only the bits you need, saving space even further.

However, for this tutorial, you can follow along with this CodePen, which has been set up with the latest version of Popmotion.

Tween

For those unfamiliar, a tween transitions between one number and another over a predetermined length of time. If you've used a CSS transition, Popmotion's tween function works exactly the same.

We can import tween like so:

By default, tween animates between 0 and 1 over a duration of 300 milliseconds. If you open your console, you can test this yourself:

But we don't want to animate the console—we want to animate the ball. For this, Popmotion includes another function, styler.

Note: In this first example, we defined both the update and complete functions. But if you provide start with only a single function, it will automatically assign it to update.

Styler

styler is used to create get/set interfaces for HTML and SVG styles optimised for use with animations (from any library!).

In the above example, tween is outputting a number, so we could of course set the ball's opacity like this (try it):

However, styler has the following benefits:

  • Batches renders to prevent layout thrashing.
  • Renders, at most, once per frame.
  • Allows transform props to be set individually, allowing the independent animation of props like scale and translateX.
  • Unifies the CSS and SVG transform coordinate models.
  • Understands default value types, so you can set translateX (for instance) without appending 'px'.

You're also not limited to using it inside an animation. You could manually set an element's style while others are animating, and the change will be automatically scheduled and batched along with the others.

So let's import it:

Create the ball styler:

Now we can use ballStyler to set and animate any of the ball's properties. ballStyler.set is flexible. It can set a single property:

Or multiple properties:

We want to animate opacity for now, so let's change our animation:

set can also be curried. By providing it just a property name, it will return a setter function for that prop. So we can neaten the above by writing:

So far, we've only animated the ball using the default tween properties. Let's take a look at how versatile a tween can be.

Tween Props

tween accepts one optional argument, an object of tween properties. Let's take a look at some of the more commonly used props:

from/to

tween can be between any two states. We define these with from and to.

Let's animate translateX by rewriting 'opacity' to 'x'. Then, pass from and to props:

Your ball now moves from left to right by 300px.

However, I said that a tween can be between two states, not just numbers. If we provide from and to objects of numbers and/or colors, we can animate multiple properties at once.

Try this:

This is an easy way to animate multiple props simultaneously.

Duration

duration is defined in milliseconds. By default, a tween will take 300ms, but if we set duration to 1000, it'll take a second:

Easing

Easing functions are used in tweening to change the rate of movement throughout the animation.

In real life, objects don't start or stop at their target velocity. Depending on the object, they gradually speed up, or gradually slow down, or both.

An easing function simply works by taking the tween's progress, defined as a number between 0 and 1, and returning a new one.

You don't need to know how to make these functions because Popmotion provides a bunch for you.

Import them:

By default, ease is set to easing.easeOut. When a function eases out, it means it starts fast and ends slow.

This was chosen as default because it's my belief that most animation in user interfaces should initiate as a result of a user's action. By starting fast and ending slow, the user will feel as if they imparted their energy, via their tap or click, directly into the interface. It feels snappy, alive, and responsive.

For many animations away from the user's input, or on their own, it can feel a little less jarring to use an animation that eases in, like easing.easeInOut or easing.anticipate, which does a playful tug before animating.

Finally, there's the easing.cubicBezier function, which creates a new easing function based on an easing curve, just like CSS transitions. This provides a massive degree of control and flexibility over your motion.

Try applying some of these to your animation while playing around with duration to see how it affects the feel and character of it.

Repeating

Animations can be repeated in three different ways: loopyoyo, and flip.

Loop starts the animation from the start. Yoyo mirrors the tween by running it backwards. And flip runs it backwards and flips the easing function.

One of these can be set per tween, and each is set as a number that denotes the number of times to repeat the animation. To repeat forever, simply pass Infinity:

Playback 

When a tween is started, it returns playback controls that we can use to control that animation.

In the above example, controls will have access to all of these playback methods, like stoppause, and resume:

We can use these playback controls to pause and then seek through the tween:

With this, we can create a scrubbable animation! In a later tutorial, we'll explore how to use Popmotion's pointer function to create a scrub bar, but for now you can scrub one tween with a second tween, to see this in action:

Keyframes

For simple, a-to-b transitions, tween is excellent. For more complicated sequences of tweens, Popmotion provides another function called keyframes.

Let's import it now:

keyframes tweens through alinear series of states. We provide these states to its values property:

Like tween, we can also define these states as objects. So to move the ball around in a square, we can write:

By default, keyframes will allocate each of these tweens an equal share of the overall duration.

By providing a times array, we can mark each of these states with a number between 0 and 10 represents the start of the animation, and 1 represents the end:

This way, we can adjust the length of the animation without having to remark each individual segment.

It also allows each animation to be given an individual easing with the easings property:

Because keyframes is just a tween, we can adjust its overall playback with all the same properties like ease and loop, and control it with all the same methods that we learned earlier.

Conclusion

The tween and keyframes functions allow you to create both simple and complex animations.

styler brings its own benefits, like usage outside of animations, standardisation of CSS and SVG transform models, and render batching for high animation performance.

In this tutorial, we've covered just a couple of the animations that Popmotion offers. In the next installment, we're going to explore pointer tracking and velocity-based animations like physics and spring.

Velocity-based animations can be used to create natural-feeling UIs that react realistically to a user's input. See you there!

20 Best WPBakery Page Builder Addons & Extensions of 2018

$
0
0

With over a million users worldwide, the popular drag-and-drop page builder, WPBakery Page Builder (formerly Visual Composer), has inspired a legion of developers to create loads of cool and useful addons and extensions that increase its functions and provide virtually unlimited possibilities when it comes to creating the WordPress site of your dreams. Here’re a list of the 20 best of these addons and extensions for 2018 to be found at CodeCanyon.

Some offer a huge range of features within one powerful extension, while others provide just one specialised and targeted function. Some have been on the market for a while and have earned a reputation as the go-to plugins for users of WPBakery Page Builder, while others are newer to the market but have the potential to carve out their own unique following. Either way, you’re bound to find a plugin here that will answer your prayers… some of them, anyway.

1. Ultimate Addons

It’s no surprise that Ultimate Addons is one of the highest rated and best selling addons for WPBakery Page Builder. With 20 updates since its inception, this is an addon that works consistently to stay ahead of the competition and deliver a product that meets the needs of a wide range of designers.

Ultimate Addons

Notable features:

  • parallax and video backgrounds
  • video tutorials
  • over 40 unique elements
  • 15 demo pages for inspiration
  • and more

A perennial favourite, Ultimate Addons ticks a lot of boxes as a reliable WPBakery Page Builder Addon.

2. Massive Addons

Massive Addons has been gaining quite a following over the past two years. This all-in-one extension is packed with features that will make even the most demanding web designer happy. The latest version 2.0 has incorporated a ton of user suggested improvements. Most notably it has integrated a feature called container presets which allow users to preset entire rows or columns.

Notable features:

  • over 70 customisable shortcodes and addons
  • 31 page templates
  • supports WooCommerce
  • over 15 training videos
  • and more

Massive Addons is exactly what you need if you’re looking for a WPBakery Page Builder extension that covers a huge range of functionality.

3. Calendarize it!

Calendarize it! is a feature-rich calendar for your WordPress site that can be used as a standalone plug in or an addon for WPBakery Page Builder.

Calendarize it

Notable features:

  • events countdown
  • events year view
  • payment options
  • social share panel
  • and more

User deezeeweb says of Calendarize it!:

“I really love the plugin itself - beautiful, thoughtful design and UI. The add-ons handle just about any additional needs we could have, plus they offer a lot of free features. Support seals the deal - quick to respond and helpful. And aside from that, well documented with quality coding.”

4. Composium

One of the top sellers at CodeCanyon, Composium is packed with a dizzying amount of features including a Google Font Manager with more than 810 fonts, over 70 CSS3 animations, and the option to use any WPBakery Page Builder element in a sidebar. In addition, when you download this extension, you also get a built-in downtime/maintenance manager for your site, which allows you to create a custom maintenance page.

Composium

Notable features:

  • over 150 different elements
  • Icon and Google Font Managers
  • custom premium Lightbox
  • template and widget builder
  • and more

With its record of consistent updates and the addition of new features to an already great product, Composium is bound to remain a crowd favourite for years to come.

5. Kaswara

Kaswara entered the market in January last year with a few addons and extensions, quickly gaining a lot of attention with its modern and stylish designs. Now it has expanded its offerings to 45 elements and over 550 shortcode options and has become a powerful contender in the WPBakery Page Builder addons and extensions market. 

Kaswara

Notable features:

  • contact form designer
  • shortcode manager
  • replica section
  • Icon and Google font managers
  • and more

User laughingsteam says of Kaswara:

“Tons of features and add-ons! Truly the one package you need to fulfill whatever you want! Support is super good as well. Had an issue with a bug, and wanted HTML Code inside Hotspot images, and they made that possible, which is super cool!”

6Super Bundle

Last year, Video & Parallax Backgrounds made our list of the top 20 Best WPBakery Page Builder Addons and Extensions. This year it’s still our favourite addon for adding video backgrounds as well as image parallax scrolling effects to your WordPress site, and you can still buy it as a standalone. But if you’re looking for a few other great effects as well, Video & Parallax Backgrounds now comes bundled with over 20 other fabulous addons from the same developer in the Super Bundle collection.

Super Bundle

Notable features:

  • hover animation
  • animated text effects
  • carousel
  • background gradient
  • and more

User gpf1973 says of Super Bundle:

“Really nice set of useful plugins. Works across my site (Carbon theme) without any problems. Good work.”

7Sortable Grid and Taxonomy Filter

If you’re looking for an interesting way to display your posts or products, then the Sortable Grid and Taxonomy Filter may be the answer for you. This addon is packed with features that allow you to display your products, posts or other types of content in a selection of grid layouts.

Sortable Grid and Taxonomy Filter

Notable features:

  • fully customisable
  • five different grid layouts
  • CSS3 animations to animate your grid items
  • custom taxonomy filter—you can enable filter posts from a determined category
  • and more

Sortable Grid & Taxonomy Filter is a great addon to bring some variety to the way you sort and display content like posts, products, and more. 

8All In One Addons

An oldie but goodie, All In One Addons combines 64 different functions in one powerful tool that extends WPBakery Page Builder wonderfully.

All In One Addons

Notable features:

  • carousel and gallery
  • to-do list and price table
  • draggable timeline
  • iHover with 35 transitions
  • and more

User JordanHobbs says of All in One Addons:

“Customer service and quality of features have me buzzing about this plugin. We have been through multiple "Addon" packages with VC/WPBakery and this one fills a lot of gaps!"

9Team Showcase

Team Showcase for WPBakery Page Builder is another specialised addon for WPBakery Page Builder that enables you to add a team or staff member section anywhere on your website in different layouts.

Team Showcase

Notable features:

  • ten predefined responsive themes
  • four different display options
  • ability to create custom links for each team member
  • animated in and out slider
  • and more

Though designed specifically for showcasing team members, Team Showcase can also be repurposed to display testimonials or other image and text content.

10. Image Hotspot with Tooltip

The Image Hotspot with Tooltip comes bundled with another bestselling CodeCanyon addon, All In One Addons, but for those who don’t own that plugin, this standalone enables you to add a hotspot icon with a popup tooltip to any image on your site.

Image Hotspot with Tooltip

Notable features:

  • the tooltip feature supports text, images, video, and other kinds of content
  • hotspot icon’s position easily customisable
  • hotspot icons come in a variety of colours
  • and more

Image Hotspot with Tooltip may not be for everyone but will be of great value to photographers and e-commerce or educational sites.

11VCKit 

VCKit is another relative newcomer to the WPBakery Page Builder addons and extensions market. This feature-rich collection of addons offer over 45 beautifully designed elements and highly customised features and is fast becoming a major player at CodeCanyon. 

VCKit

Notable features:

  • five pre-designed demo homepage templates
  • over 45 animation effects
  • 30 gorgeous effects
  • one-click installation
  • and more

User by CSWCSW says of VCKit:

“Five stars for design quality,  features availability and customer service! Certainly an awesome and powerful kit to have in my toolbox. Has a total of 42 great effects, each with a video tutorial. Any questions, ThemeLego is prompt and friendly. Any problems, ThemeLego offers helpful tips, advice, etc. You won't be disappointed!”

12. Testimonials Showcase

Testimonials Showcase is designed specifically to help you display and manage your testimonials. It comes with several themes, colour schemes, and customisable options that will allow you to integrate the addon into your site seamlessly.

Testimonials Showcase

Notable features:

  • ten responsive themes
  • grid or slider display
  • submission form that allows customers to write and submit their testimonials
  • ability to filter testimonials
  • and more

Testimonials Showcase will have a broad appeal to businesses that need an elegant and easy solution to collecting and displaying customer feedback.

13. WP Post Modules

WP Post Modules is ideal for creating online magazine layouts, newspaper blocks, creative portfolio showcases, and regular blog feeds using a drag-and-drop interface.

WP Post Modules

Notable features:

  • 7 display styles
  • 20 pre-built home page layouts
  • grid and list module
  • 100% responsive design, optimised for retina display
  • and more

User HELKE says of WP Post Modules:

“The design, features, flexibility, customisability and customer support are really amazing. Very dedicated author. I'm really happy and hope that this piece of software continues to develop and stays up-to-date for as long as possible.”

14. Modal Popup Box

Modal Popup Box comes bundled with CodeCanyon’s top-selling Ultimate Addons but can also be bought as a standalone for those who are just looking for a popup feature. The addon allows you to add popups for a wide variety of purposes: opt-ins for email subscription, shortcodes, images, videos, contact forms, or social media widgets.

 Modal Popup Box

Notable features:

  • ability to create popups of various content, including images and video
  • MailChimp supported
  • shortcode support
  • and more

Modal Popup Box is the easy solution for adding various types of popups and opt-ins to your website.

15. Templatera

Created by the authors of the WPBakery Page Builder, Templatera is a WordPress template manager that allows users to create, manage and set access to templates based on user roles or content type.

Templatera

Notable features:

  • easy content reuse across templates
  • edit content across templates from one central place
  • import/export templates in XML format
  • and more

User viablethought says of Templatera:

“This is such a great plugin to use for larger sites that have the same designed elements that exist on many pages (e.g. custom sidebars or call to actions). This allows you to update everything from a template rather then going to each page individually. This is a "must have" tool for those using WordPress for client projects. Such a time saver!”

16. Smart One Page

Smart One Page is a great plugin for users looking for a quick, easy, no-hassle way to create a landing page or a single-page website.

Smart One

Notable features:

  • supports Google Fonts and Font Awesome Icons and Image Icons
  • smart sticky navigation
  • supports fullscreen scrolling 
  • unlimited colour selection
  • and more

A five star rated addon, Smart One Page is the only WPBakery Page Builder addon you need to create a beautiful single-page website or landing page.

17. Fast Gallery

Fast Gallery allows you to build a variety of photo galleries and insert them into your WordPress site. With its large selection of gallery types, layouts, and animation effects, the addon is an indispensable tool for image-rich sites.

Fast Gallery

Notable features:

  • eight types of galleries
  • nine different layouts
  • animations with over 200 effects
  • video tutorial available
  • and more

User TimJamesNSW says of Fast Gallery:

“The best responsive gallery plugin for Wordpress. Customer support was immediate and had a solution very fast. Would highly recommend this product for it's quality and flexibility.”

18. Cost Calculator

If you’re looking for a WPBakery Page Builder addon that will enable you to create price estimates that give clients an idea of the costs involved in your service or product, Cost Calculator might be the perfect plugin for you. Cost Calculator allows you to easily create quote or price estimation forms for your WordPress site.

Cost Calculator

Notable features:

  • dropdown menus with images icons
  • numeric slider
  • on/off switcher
  • reCAPTCHA
  • and more

Cost Calculator also includes PayPal integration and Contact Form 7 support.

19. WooCommerce Page Builder

Design a stylish and individual WooCommerce store with the popular WooCommerce Page Builder, which comes with a full set of easy-to-use WooCommerce shortcodes.

WooCommerce Page Builder

Notable features:

  • single product, category, cart and checkout page builders
  • easy installation
  • easy configuration
  • online documentation
  • and more

User Ovisz says of WooCommerce Page Builder:

“Very good plugin that gives you freedom with WooCommerce to display products how you want without any coding knowledge. Customer support is amazing I have to say, my theme and WooCommerce Page Builder plugin had some compatibility issues and I couldn't fix it, so I contacted support and they created custom product template that I wanted without any problems and very fast.”

20. Vera

Vera is a multimedia addon for WPBakery Page Builder that enables you to add video, audio and radio players, multimedia carousels, countdown timers and more to your WordPress site.

Vera

Notable features:

  • video, audio and radio players
  • logos showcase pro
  • multimedia carousel
  • multimedia playlist slider
  • and more

One of the great things about purchasing Vera is that users continually receive bonuses that extend the functionality of the plugin.

Conclusion

These 20 WPBakery Page Builder addons and extensions are just scratch the surface of products available at CodeCanyon. So if none of them catch your fancy, there are plenty of other great options there to hold your interest.

And if you want to improve your skills building WordPress sites, head on over to the site and check out the ever so useful free WordPress tutorials we have on offer.

New Course: Connect to a Database With Laravel's Eloquent ORM

$
0
0
Final product image
What You'll Be Creating

In our new course, Connect to a Database With Laravel's Eloquent ORM, you'll learn all about Eloquent, which makes it easy to connect to relational data in a database and work with it using object-oriented models in your Laravel app. It is simple to set up, easy to use, and packs a lot of power.

What You’ll Learn

In this course, Envato Tuts+ instructor Jeremy McPeak will teach you how to use Eloquent, Laravel's object-relational mapper (ORM). 

Connect to a Database With Laravel's Eloquent ORM screenshot

Follow along as Jeremy builds the data back-end for a simple guitar database app. You'll learn how to create data tables with migrations, how to create data models, and how to use Eloquent for querying and mutating data.

Watch the Introduction

 

Take the Course

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 580,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

Creating Your First App With Fuse

$
0
0

Now that you've learned the basic concepts of Fuse, it's time to put things into practice and build an app. In this tutorial, you'll learn how to develop an app using the Fuse framework. Specifically, you're going to learn the following:

  • How to code using UX Markup.
  • How to use the Observable, Timer, and Geolocation APIs.
  • How to preview an app using desktop preview and custom preview.

If you need a refresher on Fuse, check out my previous post in this series: Introducing Fuse for Cross-Platform App Development.

Prerequisites

To start working with Fuse, go to the downloads page and sign up for an account. You can also log in to an existing account if you have one. 

Fuse is available for both Windows and macOS. Download and install the correct installer for your platform. On the downloads page, they also point out the Fuse plugins available for various text editors. Install the one for your text editor. The Fuse plugins include code completion, goto definition, and viewing of logs generated from the app, all of which makes developing apps more convenient.

We'll also cover how to preview the app using custom preview. This requires Android Studio or Xcode to be installed on your computer.  

A basic understanding of web technologies such as HTML, CSS, and JavaScript is helpful but not required.

What You'll Be Creating

You'll be creating a stopwatch app which also measures the distance covered. The distance is measured using geolocation. The user can also create laps, and the individual distance and time for each lap will be displayed on the screen.

Here's what the app will look like:

Final Output HIIT Stopwatch

You can view the complete source code in the tutorial GitHub repo.

Creating a New Fuse Project

Once you have installed Fuse Studio, you should now be able to create a new Fuse project. Just open Fuse Studio and click on the New Fuse Project button. Enter the name of the project, and click Create:

Create a new Fuse project

This will create a new folder in the selected directory. Open that folder and open the MainView.ux file. By default, it will only have the <App> markup. Update it to include a <Text>, and then save the file:

The preview should now be updated with the text you specified:

Hello world output

That's the main development workflow in Fuse. Just save the changes to any of the files in the project directory, and they will automatically get reflected in the desktop preview. 

You can also see the logs in the bottom panel. You can trigger your own by using console.log(), like in the browser. The only difference is that you have to JSON.stringify() objects in order to see their value, since the console.log() implementation in Fuse can only output strings. 

UX Markup

Now we're ready to build the app. Open the MainView.ux file and remove the <Text> element from earlier. That way, we can start with a blank slate:

Including Fonts

Just like in an HTML document, the standard is to include the assets—things like fonts, stylesheets, and scripts—before the actual markup of the page. So add the following inside the <App> element:

This imports the font specified in the File attribute and gives it the name Thin. Note that this doesn't make it the default font for the whole page. If you want to use this font, you have to use its name (Thin) on the specific text you want to apply it to. 

You can download the font from the tutorial GitHub repo. After that, create an assets/fonts/robot folder inside the root project directory and put the .ttf file in it.

If you want to use another font, you can download it from dafont.com. That's where I downloaded the font for this app.

Next, we want to use icons inside the app. Fuse doesn't really have built-in elements and icon sets which allow you to do that. What it offers is a way to include existing icon fonts in your app. Since icon fonts are essentially fonts, we can use the same method for including fonts:

You can download the icon font from the GitHub repo or download it directly from fontawesome.com. Note that not all icons on fontawesome are free, so it's best to check the actual icon page before using it. If you see a "pro" label next to the icon, then you can't simply use it in your project without paying. 

Including JavaScript

Next, we need to include the JavaScript file for this page. We can do that using the <JavaScript> element:

Don't forget to create the scripts/MainView.js file at the root of the project directory. 

Creating New Components

To maximize code reuse, Fuse allows us to create custom components from existing ones. In the code below, we're using a <Panel> to create a custom button. Think of it like a div which acts as a container for other elements. In this case, we're using it as a reusable component for creating a button. 

Fuse comes with many elements. There are elements for laying out content such as the <Panel>, elements for showing user controls, pages and navigation, scripting and data, and primitives for building the UI. Each one has its own set of properties, allowing you to modify the data, presentation, and behavior.

To create a reusable component, add a ux:Class property to a presentation element that you'd like to use as a base. In this case, we're using a <Panel> as the base. You can then add some default styling. This is similar to how styling is done in CSS. Margin adds space outside of the container. Here we've only specified a single value, so this margin is applied on all sides of the panel. Color adds a background color to the element:

Inside the <Panel>, we want to show the button text. We want to make this into a reusable component, so we need a way to pass in properties for when we use this component later on. This allows us to achieve different results by only changing the properties. 

Inside the <Panel>, use the data type of the value you want to pass in as the name of the element, and then add the name of the property using ux:Property. You can then show the value supplied to the property by using {ReadProperty PropertyName}, where PropertyName is the value you supplied to ux:Property. This will allow you to supply a Text property whenever you're using the <ToggleBtn> component.

Next, we want to offer the user some sort of feedback while the button is being pressed. We can do that via triggers and animators. Triggers are basically the event listeners—in this case, <WhilePressed>. And animators are the animations or effects you want to perform while the trigger is active. The code below will make the button 10% bigger than its original size and change its color. Duration and DurationBack allow you to specify how long it takes for the animation to reach its peak and reach its end.

Next, we create the <IconBtn> component. As the name suggests, this is a button which only shows an icon as its content. This works the same way as the previous component, though there are a few new things we've done here. 

First is the ux:Name property. This allows us to give a name to a specific element so we can refer to it later. In this case, we're using it to change its Color property while the button is being pressed. 

We've also used a conditional element called <WhileTrue>. This allows us to disable the <WhilePressed> trigger when the value for is_running is a falsy one. We'll supply the value for this variable once we get to the JavaScript part. For now, know that this variable indicates whether the timer is currently running or not.

Main Content

We can now proceed with the main content. First, we wrap everything in a <StackPanel>. As the name suggests, this allows us to "stack" its children either vertically or horizontally. By default, it uses vertical orientation so we don't need to explicitly specify it: 

In the code above, we used four values for the Margin. Unlike CSS, the value distribution is left, top, right, bottom. If only two values are specified, it's left-right, top-bottom. You can use the selection tool in Fuse Studio to visualize the margins applied.

Next, we add a background image for the page. This accepts the file path to the background image you want to use. A StretchMode of Fill makes the background stretch itself to fill the entire screen:

You can download the background image I've used from the tutorial GitHub repo. Or you can find similar patterns on the Toptal website

Next, show the name of the app. Below it is the time-elapsed text field. This text needs to be updated frequently, so we need to turn it into a variable which can be updated via JavaScript. To output some text initialized in this page's JavaScript file, you need to wrap the variable name in curly braces. Later on, you'll see how the value for this variable is supplied from the JavaScript file:

Next, we use the <IconBtn> component that we created earlier—not unlike in a web environment where we use the ID of the font. In Fuse, you have to use the Unicode assigned to the icon font you want to use. You also need to use &#x as a prefix. When this button is pressed (called Clicked), the addLap() function declared in the JavaScript file is executed:

In Font Awesome, you can find the unicode of the icon font on its own page.

Right below the button for adding a new lap is some text which indicates that the button above is for adding new laps:

Next, show the button for starting and stopping the timer. This also executes a function which we will declare later:

Next, we need to output the laps added by the user. This includes the lap number, distance covered, and time spent. The <Each> element allows us to iterate through a collection of objects and display the individual properties for each object:

In the code above, we're using the <DockPanel> to wrap the contents for each item. This type of panel allows us to "dock" its children on different sides (top, left, right, and bottom) of the available space. By default, this positions its children directly on top of each other. To evenly space them out, you need to add the Alignment property. 

JavaScript Code

Now we're ready to add the JavaScript code. In Fuse, JavaScript is mainly used for the business logic and working with the device's native functionality. Effects, transitions, and animations for interacting with the UI are already handled by the UX Markup.

Start by importing all the APIs that we need. This includes Observable, which is mainly used for assigning variables in the UI. These variables can then be updated using JavaScript. Timer is the equivalent of the setTimeout and setInterval functions in the web version of JavaScript. GeoLocation allows us to get the user's current location:

Next, we initialize all the observable values that we'll be using. These are the variables that you have seen in the UX markup earlier. The values for these variables are updated throughout the lifetime of the app, so we make them an observable variable. This effectively allows us to update the contents of the UI whenever any of these values change:

After that, we can now set the initial values for the toggle button and timer text:

That's how you change the value of an observable variable. Since these are not inside any function, this should update the UI immediately when the app is launched.

Set the initial values for the timer, lap time, and location for each lap:

The toggle() function is used for starting and stopping the timer. When the timer is currently stopped and the user taps on the toggle button, that's the only time we reset the values for the timer and laps. This is because we want the user to see these values even after they stopped the timer. 

After that, get the user's current location and push it on the locations array. This allows us to compare it to the next location later, once the user adds a lap. Then, create a timer which executes every 10 milliseconds. We increment both the overall time and the lap_time for every execution. Then update the UI with the formatted value using the formatTimer() function:

When the user stops the timer, we delete it using the delete() method in the timer. This requires the timer_id that was returned when the timer was created:

Next is the function for formatting the timer. This works by converting the milliseconds into seconds and into minutes. We already know that this function is executed every 10 milliseconds. And the time is incremented by 1 every time it executes. So to get the milliseconds, we simply multiply the time by 10. From there, we just calculate the seconds and minutes based on the equivalent value for each unit of measurement:

Every time the user taps on the refresh button, the addLap() function is executed. This adds a new entry on top of the laps observable: 

Here's the function for getting the distance covered in meters. This uses the Haversine formula:

Don't forget to export all the observable values:

Geolocation Package

To keep things lightweight, Fuse doesn't really include all the packages that it supports by default. For things like geolocation and local notifications, you need to tell Fuse to include them when building the app. Open StopWatch.unoproj at the root of your project directory and include Fuse.GeoLocation under the Packages array:

This should instruct Fuse to include the Geolocation package whenever building the app for custom preview or for generating an installer. 

Setting Up for Custom Preview 

Before you can run the app on your iOS device, you need to add a bundle identifier to the app first. Open the StopWatch.unoproj file and add the following under iOS. This will be the unique identification for the app when it's submitted to the app store:

Next, on Xcode, log in with your Apple developer account. If you don't already have one, you can go to the Apple developer website and create one. It's actually free to develop and test apps on your iOS device. However, there are some limitations if you're not part of the developer program.

Once your account is created, go to Xcode preferences and add your Apple account. Then click on Manage Certificates and add a new certificate for iOS development. This certificate is used to ensure that the app is from a known source.

Once that's done, you should now be able to run the app on your device. Click on Preview > Preview on iOS in Fuse Studio and wait for it to launch Xcode. Once Xcode is open, select your device and click the play button. This will build the app and install it on your device. If there's a build error, it's most likely that the preview bundle identifier is not unique:

change the bundle ID

Changing the Bundle Identifier to something unique should solve the issue. Once the error under the signing section disappears, click on the play button again to rebuild the app. This should install the app on your device. 

However, you won't be able to open the app until you approve it. You can do that on your iOS device by going to Settings General Device Management and selecting the email associated with your Apple Developer account. Approve it, and that should unlock the app.

For Android, you should be able to preview the app without any additional steps.

Conclusion

That's it! In this tutorial, you've learned the basics of creating an app using the Fuse framework. Specifically, you've created a stopwatch app. By creating this app, you've learned how to work with Fuse's UX Markup and a few of Fuse's JavaScript APIs. You also learned how to use Fuse Studio to preview the app on your computer and your phone while developing it.

What Are the WordPress PHP Coding Standards?

$
0
0

What are the WordPress PHP coding standards? In this video from my course, Learn PHP for WordPress, you'll learn all about the coding standards and why they're important.

The WordPress PHP Coding Standards

 

What Are the WordPress PHP Coding Standards?

You can find the full WordPress PHP coding standards in the official WordPress handbook.

WordPress PHP coding standards

They're essentially a set of best practices on how to use PHP in WordPress. We'll go through some examples of what that means in practice in the rest of this tutorial.

As you can see, there are standards not only for PHP but also for accessibility and for the other languages that you'd use within WordPress. 

Why Are the PHP Coding Standards Important?

Why is it important that we all adhere to these standards? 

Well, there are two reasons. One of them is about quality of code, and the other is about consistency. 

So firstly, quality is important because it means that everybody coding in WordPress is creating code that will work, that will do its job, and that will be written in an up-to-date and high-quality fashion.

The second, which is about consistency, is equally important. It's very likely that you're going to be working with other people's code from time to time. For example, if you're creating a child theme, you might have to copy some of the code from the parent theme. And if you're creating a plugin, that plugin could be a fork of an existing third-party plugin that you're copying and adding extra functionality to. It's really important that the way you code is consistent with the way that everybody else who codes PHP for WordPress writes code themselves. 

Examples of PHP Coding Standards for WordPress

So let's take a look at some of the PHP coding standards. And I'm going to show you examples of these in some of the files in my theme.

Naming Conventions and Cases

Let's start with naming conventions and cases. When you're thinking about naming conventions, there are four things to think about:

  1. the functions within your theme or your plugin
  2. the files and the way that you name those
  3. any classes that you write
  4. any variables that you create

So let's start with functions. Here's the functions.php file in my theme as an example. 

the functionsphp file in my theme

You can see that I've got a function that I've defined called rachelmcc_register_widgets. That's all written in lower case, and I'm using underscores between the words, which is how you should always write a function in WordPress.

As you'll also see, I've used a prefix. That's to ensure that this function doesn't clash with any other functions that might be provided by my theme or by another plugin. So if I wrote a function that was just called register_widgets and one of my plugins also had a function called register_widgets, the two of them could clash. You might find that one of them overrides the other or that the plugin doesn't work. 

So instead, I'm using a unique function that's relevant to my theme. My theme is called rachelmccollin, so my functions have rachelmcc as a prefix. And it's also important to use underscores for your functions and not to use hyphens.

You do use hyphens in two places. Firstly, you use hyphens when you're defining CSS classes. So you can see that within my widgets, I'm defining CSS classes for my h3 element and also for the id of that widget area. And here, you use hyphens.

The other place that you use hyphens is in your file names. So this is front-page.php. 

the front-pagephp file

You should always use hyphens in your file names within your themes and your plugins; don't use underscores. So here there is a call using locate_template. And loop-frontpage.php is a file, a template part that I'm calling, and you can see that that's got a hyphen and not an underscore. 

On the other hand, my post type ID, which is a custom post type I've registered, uses an underscore: rmcc_blurb

Now you also might need to think about variables within your theme. Let's look at loop-frontpage.php:

loop-frontpagephp file

Within this particular file, which is the one I was calling from that previous file, I've defined some variables, one called count and one called title. And you can see that I'm using lower case for both of those. 

The other place where you need to think about underscores and capitalization is when you're using a class. Let's go back to front-page.php:

the  front-pagephp file

And you can see here, I'm using the WP_Query class. So a class has a capital letter after the underscore, as well as at the beginning. So that's where you use capitalization when you're defining a class. It helps people working with your code instantly identify that it's a class and not a function.

Using Single and Double Quotes

Now let's have a look at how you would use single and double quotes in PHP for WordPress. 

You can use either single quotes or double quotes, depending on which works best for the specific code that you're working with.

The reason that double quotes can sometimes be more helpful is that they make it easier to work with special characters. Here's an example:

how to use single and double quotes in WordPress

Say you were writing a search template file, search.php. And within that, if nothing was found, you would put a paragraph that says, "I'm sorry, your search didn't find anything. Why don't you try again?"

I've put that within double quotes because the text contains apostrophes. Let me show you how that would work if we did it in single quotes. 

Example of single and double quotes

You need to put a backslash before the apostrophes in order for them to be output correctly within the HTML—otherwise, it'll give you errors. Now I don't know about you, but I'd rather just type it normally within double quotes than do all this within single quotes.

The other thing you need to remember is that if you need to put quotes within quotes, you either put single quotes within double quotes, or vice versa. It doesn't matter which way around, but you can't put single quotes within single quotes or double quotes within double quotes.

So here's an example going back to my functions.php file. 

Example of single and double quotes in PHP

Within here I've got single quotes for the value of before_widget, and then within that, I've got double quotes for the ID and the class of that. I couldn't use double quotes here and then put double quotes inside it, so that's why I'm using single quotes there, because it's better to use double quotes with your CSS. 

Indentation

Now, let's look at indentation. And let's continue looking at the functions.php file, which is quite a good example because I've indented a number of lines of code within it. 

You can see that the function name is on the left, and then within that the register_sidebar function is indented at one level. And the contents of that are indented again. 

So each time you're putting content within braces or curly braces, everything inside that should be indented. And also for indentation, you should use line breaks. 

So let's take a look at another file where there are single lines as well as double lines. 

Line breaks with a block of PHP

So here you can see I've got an if statement that's got two lines of code within it. So I've put a line break above and below those two lines of code.

If there was only one line of code within that, I wouldn't have to put those line spaces in—I would just put that straight inside my braces. 

Using spacing like this helps make it clear where your blocks of code are. And you can see also that indentation has been used. So there are multiple layers of indentation. 

The other thing you need to bear in mind is where you open and close your PHP tag and whether that is on the same line as your code or a different line. And that also depends on whether you're coding a block of code or a single line.

Where you've got a block of code, you put your opening tag on one line and your closing tag on another line. That helps to make it obvious that it's a block of PHP and that everything within those tags is PHP.

The other thing you have to make sure you do is use a full opening PHP tag. So don't just use a question mark, as you might have done in some other systems that use PHP, because in WordPress you have to use the full PHP tag. 

If I wrote some PHP that was just on one line, I would put the PHP opening and closing tags on the same line.

PHP opening and closing tags on the same line

You can see that we've got some PHP that's all in one line, and then after that I've got HTML. So the opening and closing tags go on the same line as my code. 

Conclusion

That's an introduction to some of the elements of the WordPress PHP coding standards, and I've shown you some examples of them in my files and changed some as I've gone along to show you how things are done correctly. 

If you want to know more about the coding standards, there's documentation on the WordPress website. And you can also check out this Envato Tuts+ series, which goes into all of the elements of the coding standards in detail.

Watch the Full Course

In the full course, Learn PHP for WordPress, you'll learn all about PHP, the programming language that WordPress is built in.  

I'll give you an overview of what PHP is and how it's used for WordPress themes and plugins, with examples. You'll go on to learn how to create a PHP file and use it to output HTML. Then you'll learn to use functions, loops and if statements for coding custom WordPress themes and plugins.

You can take this 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 580,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

Introduction to Popmotion: Pointers and Physics

$
0
0

Welcome back to the Introduction to Popmotion tutorial series. In part 1, we discovered how to use tweens and keyframes to make precise, time-scheduled animations.

In Part 2, we're going to look at pointer tracking and velocity-based animations.

Pointer tracking allows us to create scrollable product shelves, custom value sliders, or drag-and-drop interfaces.

Velocity-based animations are different to a time-based animation like tween in that the primary property that affects how the animation behaves is velocity. The animation itself might take any amount of time.

We'll look at the three velocity-based animations in Popmotion, springdecay, and physics. We'll use the velocity of the pointer tracking animation to start these animations, and that'll demonstrate how velocity-based animations can create engaging and playful UIs in a way that time-based animations simply can't.

First, open this CodePen to play along.

Pointer Tracking

Popmotion provides the pointer function to track and output the coordinates of either a mouse or single touch pointer.

Let's import this along with styler, which will allow us to set the position of the ball.

For this example, we want to drag the ball. Let's add an event that will output the pointer's position to the ball:

We'll also want some code to stop tracking when we release the ball:

If you try and drag the ball now, there's an obvious problem. The ball jumps away when we touch it! Not a great user experience.

This is because, by default, pointer outputs the pointer's position relative to the page.

To output the pointer's position relative to another point, in this case the ball's x/y transform, we can simply pass that position to pointer like this:

Now you've made the ball, in very few lines of code, draggable! However, when the user releases the ball, it stops dead.

This isn't satisfying: Imagine a scrollable carousel of products that a user can drag to scroll. If it just stopped dead instead of momentum scrolling, it'd be less pleasurable to use.

It'd be harder, too, because the overall physical effort needed to scroll the carousel would be higher.

To enable animations like this, we first need to know the velocity of the object being thrown.

Track Velocity

Popmotion provides a function that can help us track velocity. It's called value. Let's import that:

To speak technically for a moment, all of Popmotion's animations are known as actions. Actions are reactive streams of values that can be started and stopped.

A value is, conversely, a reaction. It can't be stopped or started. It just passively responds when its update method is called. It can keep track of values and can be used to query their velocity.

So, after we define ballStyler, let's define a new value for ballXY:

Whenever ballXY updates, we want to update ballStyler. We can pass a second argument to value, a function that will run whenever ballXY updates:

Now we can rewrite our pointer to update ballXY instead of ballStyler.set:

Now, at any pointer, we can call ballXY.getVelocity() and we'll receive the velocities of both x and y, ready to plug into our velocity-based animations.

Velocity-Based Animations

spring

The first velocity-based animation to introduce is spring. It's based on the same equations that govern Apple's CASpringAnimation, the spring animation behind all that iOS springy playfulness.

Import:

Now, amend stopTracking so that instead of stopping the pointerTracker animation, it starts a spring animation like this:

We provide it with the ball's current position, its velocity, and a target, and the simulation is run. It changes depending on how the user has thrown the ball.

The cool thing about springs is they're expressive. By adjusting the massstiffness and damping properties, you can end up with radically different spring-feels.

For instance, if you only change the stiffness above to 1000, you can create a motion that feels like high-energy snapping. Then, by changing mass to 20, you create motion that looks almost like gravity.

There's a combination that will feel right and satisfying for your users, and appropriate to your brand, under almost any circumstance. By playing with different spring-feels, you can communicate different feelings, like a strict out-of-bounds snap or a softer affirmative bounce.

decay

The decay animation, as the name suggests, decays the provided velocity so that the animation gradually slows to a complete stop.

This can be used to create the momentum scrolling effect found on smartphones, like this:

Import the decay function:

And replace the stopTracking function with the following:

decay automatically calculates a new target based on the provided from and velocity props.

It's possible to adjust the feel of the deceleration by messing with the props outlined in the docs linked above but, unlike spring and physicsdecay is designed to work out of the box. 

physics

Finally, we have the physics animation. This is Popmotion's Swiss Army knife of velocity-based animations. With it, you can simulate:

  • constant velocity
  • acceleration
  • springs
  • friction

spring and decay offer super-precise motion and a wider variety of "feels". Soon, they'll both also be scrubbable.

But both are immutable. Once you've started either, their properties are set in stone. Perfect for when we want to start an animation based on the initial from/velocity state, but not so good if we want ongoing interaction.

physics, instead, is an integrated simulation closer to that of a video game. It works by, once per frame, taking the current state and then modifying it based on the current properties at that point in time.

This allows it to be mutable, which means we can change those properties, which then changes the outcome of the simulation.

To demonstrate this, let's make a twist on classic pointer smoothing, with elastic smoothing.

Import physics:

This time, we're going to change the startTracking function. Instead of changing ballXY with pointer, we'll use physics:

Here, we're setting from and velocity as normal. friction and springStrength both adjust the properties of the spring.

restSpeed: false overrides the default behaviour of the animation stopping when motion stops. We want to stop it manually in stopTracking.

On its own, this animation won't do anything because we set to, the spring's target, to the same as from. So let's reimplement the pointer tracking this time to change the spring target of physics. On the last line of startTracking, add:

Here, we're using a similar pointer animation as before. Except this time, we're using it to change the target of another animation. In doing so, we create this elasticated pointer tracking:

Conclusion

Velocity-based animations paired with pointer tracking can create engaging and playful interfaces.

spring can be used to create a wide-variety of spring-feels, while decay is specifically tailored for momentum scroll animations. physics is more limited than either in terms of configurability, but also provides the opportunity to change the simulation in progress, opening new interaction possibilities.

In the next and final part of this introductory series on Popmotion, we're going to take everything we've learned in the first two parts and use them along with some light functional composition to create a scrubbable animation, along with a scrubber to do the scrubbing with!

WordPress Gutenberg Block API: Creating Custom Blocks

$
0
0

The new WordPress editor (codenamed Gutenberg) is due for release in version 5.0. Now is the perfect time to get to grips with it before it lands in WordPress core. In this series, I'm showing you how to work with the Block API and create your very own content blocks which you can use to build out your posts and pages.

In the previous post, we saw how to use the create-guten-block toolkit to create a plugin containing a sample block ready for us to work with. We can easily extend this as required, but it's a good idea to know how to create a block from scratch to fully understand all aspects of Gutenberg block development.

In this post we'll create a second block in our my-custom-block plugin to display a random image from the PlaceIMG web service. You'll also be able to customize the block by selecting the image category from a drop-down select control.

But first we'll learn how block scripts and styles are enqueued before moving on to the all-important registerBlockType() function, which is fundamental to creating blocks in Gutenberg.

Enqueueing Block Scripts and Styles

To add the JavaScript and CSS required by our blocks, we can use two new WordPress hooks provided by Gutenberg:

  • enqueue_block_editor_assets
  • enqueue_block_assets

These are only available if the Gutenberg plugin is active, and they work in a similar way to standard WordPress hooks for enqueueing scripts. However, they are intended specifically for working with Gutenberg blocks.

The enqueue_block_editor_assets hook adds scripts and styles to the admin editor only. This makes it ideal for enqueueing JavaScript to register blocks and CSS to style user interface elements for block settings.

For block output, though, you'll want your blocks to render the same in the editor as they do on the front end most of the time. Using enqueue_block_assets makes this easy as styles are automatically added to both the editor and front end. You can also use this hook to load JavaScript if required.

But you might be wondering how to enqueue scripts and styles only on the front end. There isn't a WordPress hook to allow you to do this directly, but you can get around this by adding a conditional statement inside the enqueue_block_assets hook callback function.

To actually enqueue scripts and styles using these two new hooks, you can use the standard wp_enqueue_style() and wp_enqueue_scripts() functions as you normally would.

However, you need to make sure that you're using the correct script dependencies. For enqueueing scripts on the editor, you can use the following dependencies:

  • scripts: array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-components' )
  • styles: array( 'wp-edit-blocks' )

And when enqueueing styles for both the editor and front end, you can use this dependency:

  • array( 'wp-blocks' )

One thing worth mentioning here is that the actual files enqueued by our my-custom-block plugin are the compiled versions of JavaScript and CSS and not the files containing the JSX and Sass source code.

This is just something to bear in mind when manually enqueueing files. If you try to enqueue raw source code that includes React, ES6+, or Sass then you'll encounter numerous errors.

This is why it's useful to use a toolkit such as create-guten-block as it processes and enqueues scripts for you automatically!

Registering Gutenberg Blocks

To create a new block, we need to register it with Gutenberg by calling registerBlockType() and passing in the block name plus a configuration object. This object has quite a few properties that require proper explanation.

Firstly, though, let's take a look at the block name. This is the first parameter and is a string made up of two parts, a namespace and the block name itself, separated by a forward slash character.

For example:

If you're registering several blocks in a plugin then you can use the same namespace to organize all your blocks. The namespace must be unique to your plugin, though, which helps prevent naming conflicts. This can happen if a block with the same name has already been registered via another plugin.

The second registerBlockType() parameter is a settings object and requires a number of properties to be specified:

  • title (string): displayed in the editor as the searchable block label
  • description (optional string): describes the purpose of a block
  • icon (optional Dashicon or JSX element): icon associated with a block
  • category (string): where the block appears in the Add blocks dialog
  • keywords (optional array): up to three keywords used in block searches
  • attributes (optional object): handles the dynamic block data
  • edit (function): a function that returns markup to be rendered in the editor
  • save (function): a function that returns markup to be rendered on the front end
  • useOnce (optional boolean): restrict block from being added more than once
  • supports (optional object): defines block-supported features

Assuming we're using JSX for block development, here's what an example registerBlockType() call could look like for a very simple block:

Notice how we didn't include an entry for the description, attributes, useOnce, and supports properties? Any fields that are optional (and not relevant to your block) can be safely omitted. For example, as this block didn't involve any dynamic data, we don't need to worry about specifying any attributes.

Let's now cover the registerBlockType() configuration object properties in more detail one by one.

Title and Description

When inserting or searching for a block in the editor, the title will be displayed in the list of available blocks.

It's also displayed in the block inspector window, along with the block description if defined. If the block inspector isn't currently visible then you can use the gear icon in the top right corner of the Gutenberg editor to toggle visibility.

Block title and description

Both the title and description fields should ideally be wrapped in i18n functions to allow translation into other languages.

Category

There are five block categories currently available:

  • common
  • formatting
  • layout
  • widgets
  • embed

These determine the category section where your block is listed inside the Add block window.

Block categories

The Blocks tab contains Common Blocks, Formatting, Layout Elements, and Widgets categories, while the Embeds category has its own tab.

Categories are currently fixed in Gutenberg, but this could be subject to change in the future. This would be useful, for instance, if you were developing multiple blocks in a single plugin and you wanted them all to be listed under a common category so users could locate them more easily.

Icon

By default, your block is assigned the shield Dashicon, but you can override this by specifying a custom Dashicon in the icon field.

Dashicons

Each Dashicon is prefixed with dashicons- followed by a unique string. For example, the gear icon has the name dashicons-admin-generic. To use this as a block icon, just remove the dashicons- prefix for it to be recognised, e.g. icon: 'admin-generic'.

However, you aren't just limited to using Dashicons as the icon property. The function also accepts a JSX element, which means you can use any image or SVG element as your block icon. 

Just make sure to keep the icon size consistent with other block icons, which is 20 x 20 pixels by default.

Keywords

Choose up to three translatable keywords to help make your block stand out when users search for a block. It's best to choose keywords that closely relate to the functionality of your block for best results.

You could even declare your company and/or plugin name as keywords so that if you have multiple blocks, users can start typing your company name and all your blocks will appear in search results.

Although adding keywords is entirely optional, it's a great way to make it easier for users to find your blocks.

Attributes

Attributes help with managing dynamic data in a block. This property is optional as you don't need it for very simple blocks that output static content.

However, if your block deals with data that could change (such as the contents of an editable text area) or you need to store block settings, then using attributes is the way to go. 

Attributes work by storing dynamic block data either in the post content saved to the database or in post meta. In this tutorial we'll only be using attributes that store data along with the post content.

To retrieve attribute data stored in post content, we need to specify where it's located in the markup. We can do this by specifying a CSS selector that points to the attribute data.

For example, if our block contained an anchor tag, we can use its title field as our attribute as follows:

Here, the attribute name is linktitle, which is an arbitrary string and can be anything you like.

For example, we could use this attribute to store the link title <a title="some title"> that's been entered via a textbox in block settings. Doing so suddenly makes the title field dynamic and allows you to change its value in the editor.

When the post is saved, the attribute value is inserted into the links title field. Similarly, when the editor is loaded, the value of the title tag is retrieved from the content and inserted into the linktitle attribute.

There are more ways you can use source to determine how block content is stored or retrieved via attributes. For instance, you can use the 'text' source to extract the inner text from a paragraph element.

You can also use the children source to extract all child nodes of an element into an array and store it in an attribute.

This selects the element with class .parent and stores all child nodes in the editablecontent attribute.

If you don't specify a source then the attribute value is saved in HTML comments as part of the post markup when saved to the database. These comments are stripped out before the post is rendered on the front end.

We'll be seeing a specific example of this type of attribute when we get into implementing our random image block later in this tutorial.

Attributes can take a little getting used to, so don't worry if you don't fully understand them first time around. I'd recommend taking a look at the attributes section of the Gutenberg handbook for more details and examples.

Edit

The edit function controls how your block appears inside the editor interface. Dynamic data is passed to each block as props, including any custom attributes that have been defined.

It's common practice to add className={ props.className } to the main block element to output a CSS class specific to your block. WordPress doesn't add this for you inside the editor, so it has to be added manually for each block if you want to include it.

Using props.className is standard practice and is recommended as it provides a way to tailor CSS styles for each individual block. The format of the generated CSS class is .wp-block-{namespace}-{name}. As you can see, this is based on the block namespace/name and makes it ideal to be used as a unique block identifier.

The edit function requires you to return valid markup via the render() method, which is then used to render your block inside the editor.

Save

Similar to the edit function, save displays a visual representation of your block but on the front end. It also receives dynamic block data (if defined) via props.

One main difference is that props.className isn't available inside save, but this isn't a problem because it's inserted automatically by Gutenberg.

Supports

The supports property accepts an object of boolean values to determine whether your block supports certain core features.

The available object properties you can set are as follows.

  • anchor (default false): allows you to link directly to a specific block
  • customClassName (true): adds a field in the block inspector to define a custom className for the block 
  • className (true): adds a className to the block root element based on the block name
  • html (true): allows the block markup to be edited directly

The useOnce Property

This is a useful property that allows you to restrict a block from being added more than once to a page. An example of this is the core More block, which can't be added to a page if already present.

useOnce property

As you can see, once the More block has been added, the block icon is grayed out and can't be selected. The useOnce property is set to false by default.

Let's Get Creative!

It's time now to use the knowledge we've gained so far to implement a solid working example of a block that does something more interesting than simply output static content.

We'll be building a block to output a random image obtained via an external request to the PlaceIMG website, which returns a random image. Furthermore, you'll be able to select the category of image returned via a select drop-down control.

Our random image block

For convenience, we'll add our new block to the same my-custom-block plugin, rather than creating a brand new plugin. The code for the default block is located inside the /src/block folder, so add another folder inside /src called random-image and add three new files:

  • index.js: registers our new block
  • editor.scss: for editor styles
  • style.scss: styles for the editor and front end

Alternatively, you could copy the /src/block folder and rename it if you don't want to type everything out by hand. Make sure, though, to rename block.js to index.js inside the new block folder.

We're using index.js for the main block filename as this allows us to simplify the import statement inside blocks.js. Instead of having to include the path and full filename of the block, we can just specify the path to the block folder, and import will automatically look for an index.js file.

Open up /src/blocks.js and add a reference to our new block at the top of the file, directly underneath the existing import statement.

Inside /src/random-image/index.js, add the following code to kick-start our new block.

This sets up the framework of our block and is pretty similar to the boilerplate block code generated by the create-guten-block toolkit.

We start by importing the editor and front-end style sheets, and then we'll extract some commonly used functions from wp.i18n and wp.blocks into local variables.

Inside registerBlockType(), values have been entered for the title, icon, category, and keywords properties, while the edit and save functions currently just output static content.

Add the random image block to a new page to see the output generated so far.

Bare bones block output

Make sure you're still watching files for changes so any block source code (JSX, ES6+, Sass, etc.) is transpiled into valid JavaScript and CSS. If you aren't currently watching files for changes, then open a command line window inside the my-custom-block plugin root folder and enter npm start.

You might be wondering why we didn't have to add any PHP code to enqueue additional block scripts. The block scripts for the my-custom-block block are enqueued via init.php, but we don't need to enqueue scripts specifically for our new block as this is taken care of for us by create-guten-block.

As long as we import our main block file into src/blocks.js (as we did above) then we don't need to do any additional work. All JSX, ES6+, and Sass code will automatically be compiled into the following files:

  • dist/blocks.style.build.css: styles for editor and front end
  • dist/blocks.build.js: JavaScript for editor only
  • dist/blocks.editor.build.css: styles for editor only

These files contain the JavaScript and CSS for all blocks, so only one set of files needs to be enqueued, regardless of the number of blocks created!

We're now ready to add a bit of interactivity to our block, and we can do this by first adding an attribute to store the image category.

This creates an attribute called category, which stores a string with a default value of 'nature'. We didn't specify a location in the markup to store and retrieve the attribute value, so special HTML comments will be used instead. This is the default behavior if you omit an attribute source.

We need some way of changing the image category, which we can do via a select drop-down control. Update the edit function to the following:

Here is what it will look like:

Adding a block select drop down control

This is quite different from the previous static edit function, so let's run through the changes.

First we've added a select drop-down control with several choices matching the image categories available on the PlaceIMG site.

PlaceIMG image categories

When the drop-down value changes, the setCategory function is called, which finds the currently selected category and then in turn calls the setAttributes function. This is a core Gutenberg function and updates an attribute value correctly. It's recommended that you only update an attribute using this function.

Now, whenever a new category is selected, the attribute value updates and is passed back into the edit function, which updates the output message.

Image category updated

We have to complete one last step to get the random image to display. We need to create a simple component that will take in the current category and output an <img> tag with a random image obtained from the PlaceIMG site.

The request we need to make to PlaceIMG is of the form: https://placeimg.com/[width]/[height]/[category]

We'll keep the width and height fixed for now, so we only have to add the current category onto the end of the request URL. For example, if the category was 'nature' then the full request URL would be: https://placeimg.com/320/220/nature.

Add a RandomImage component above registerBlockType():

To use it, just add it inside the edit function and remove the static output message. While we're at it, do the same for the save function.

The full index.js file should now look like this:

Finally (for now), add the following styles to editor.scss to add a colored border around the image.

You'll also need some styles in style.css.

Whenever the page is refreshed in the editor or on the front end, a new random image will be displayed. 

Finished editor view
Final front end view

If you're seeing the same image displayed over and over, you can do a hard refresh to prevent the image being served from your browser cache.

Conclusion

In this tutorial we've covered quite a lot of ground. If you've made it all the way through then give yourself a well-deserved pat on the back! Gutenberg block development can be a lot of fun, but it's definitely challenging to grasp every concept on first exposure.

Along the way, we've learned how to enqueue block scripts and styles and covered the registerBlockType() function in depth.

We followed this up by putting theory into practice and creating a custom block from scratch to display a random image from a specific category using the PlaceIMG web service.

In the next and last part of this tutorial series, we'll add more features to our random image block via the settings panel in the block inspector.

If you've been following along with this tutorial and just want to experiment with the code without typing everything in, you'll be able to download the final my-custom-block plugin in the next tutorial.


Code an Image Gallery Android App With Picasso

$
0
0
Final product image
What You'll Be Creating

Picasso is a popular open-source Android library for loading both local and remote images. Learn how to easily use it for handling your image loading needs. 

1. What Is Picasso?

Picasso (name inspired by the famous French artist Pablo Picasso) is a very popular open-source Android library for loading images in your Android app. According to the official docs, it states:

...Picasso allows for hassle-free image loading in your application—often in one line of code!

Note that Picasso uses OkHttp (a network library from the same developer) under the hood to load the images over the internet. 

2. So Why Use Picasso?

Now you have learned what Picasso is all about, the next question you might ask is why use it?

Developing your own media loading and display functionality in Java or Kotlin can be a real pain: you have to take care of caching, decoding, managing network connections, threading, exception handling, and more. Picasso is an easy to use, well planned, well documented, and thoroughly tested library that can save you a lot of precious time—and save you some headaches. 

Here are many of the common pitfalls of loading images on Android that are dealt with for you by Picasso, according to the official docs:

  • handling ImageView recycling and download cancellation in an adapter
  • complex image transformations with minimal memory use
  • automatic memory and disk caching

Adding images to your app can make your Android app come alive. So in this tutorial, we'll learn about Picasso 2 by building a simple image gallery app. It will load the images via the internet and display them as thumbnails in a RecyclerView, and when a user clicks on an image, it will open a detail activity containing the larger image. 

A sample project (in Kotlin) for this tutorial can be found on our GitHub repo so you can easily follow along.

Good artists copy, great artists steal. — Pablo Picasso

3. Prerequisites

To be able to follow this tutorial, you'll need:

Fire up Android Studio and create a new project (you can name it PicassoDemo) with an empty activity called MainActivity. Make sure to also check the Include Kotlin support check box.

Android Studios Add an Activity to Mobile dialog

4. Declare Dependencies

After creating a new project, specify the following dependencies in your build.gradle. At the time of writing, the latest version of Picasso is 2.71828

Or with Maven:

Make sure you sync your project after adding Picasso and the RecyclerView v7 artifacts.

5. Add Internet Permission

Because Picasso is going to perform a network request to load images via the internet, we need to include the permission INTERNET in our AndroidManifest.xml

So go do that now!

Note that this is only required if you're going to load images from the internet. This is not required if you are only loading images locally on the device. 

6. Create the Layout

We'll start by creating our RecyclerView inside the activity_main.xml layout file. 

Creating the Custom Item Layout

Next, let's create the XML layout (item_image.xml) that will be used for each item (ImageView) within the RecyclerView

Now that we have created the layouts needed for our simple gallery app, the next step is to create the RecyclerView adapter for populating data. Before we do that, though, let's create our simple data model. 

7. Create a Data Model

We are going to define a simple data model for our RecyclerView. This model implements Parcelable for high-performance transport of data from one component to another in Android. In our case, data will be transported from SunsetGalleryActivity to SunsetPhotoActivity

Note that this model SunsetPhoto has only a single field called url (for demo purposes), but you can have more if you want. This class implements Parcelable, which means we have to override some methods. 

We can make use of Android Studio IDEA to generate these methods for us, but the downside to this is maintenance. How? Anytime we add any new fields to this class, we might forget to explicitly update the constructor and writeToParcel methods, which can lead to some bugs if we don't update the methods.  

Now, to circumvent updating or writing these boilerplate methods, Kotlin 1.1.14 introduced the @Parcelize annotation. This annotation will help us generate the writeToParcel, writeFromParcel, and describeContents methods automatically under the hood for us. 

Now, our code SunsetPhoto class is just two lines! Awesome! 

Remember to add the following code to your app module build.gradle:

In addition, I included a companion object (or static method in Java) getSunsetPhotos() in the SunsetPhoto model class that will simply return an ArrayList of SunsetPhoto when called.

8. Create the Adapter

We'll create an adapter to populate our RecyclerView with data. We'll also implement a click listener to open the detail activity—SunsetPhotoActivity—passing it an instance of SunsetPhoto as an intent extra. The detail activity will show a close-up of the image. We'll create it in a later section.

Notice that we used the apply extension function to put an object as extra to the intent. As a reminder, the apply function returns the object passed to it as an argument (i.e. the receiver object). 

9. Loading Images From a URL

We're going to need Picasso to do its job in this section—not to paint us a work of art, but to fetch images from the internet and display them. We'll display these images individually in their respective ImageViews inside our RecyclerView onBindViewHolder() method as the user scrolls the app. 

Step by step, here's what the calls to Picasso are doing:

The get() Method

This returns the global Picasso instance (singleton instance) initialized with the following default configurations: 

  • LRU memory cache of 15% the available application RAM.
  • Disk cache of 2% storage space up to 50MB but no less than 5MB. Note: this is only available on API 14+.
  • Three download threads for disk and network access.

Note that if these settings do not meet the requirements of your application, you're free to construct your own Picasso instance with full control of these configurations by using Picasso.Builder

Finally, you call the build() method to return you a Picasso instance with your own configurations. 

It's recommended you do this in your Application.onCreate and then set it as the singleton instance with Picasso.setSingletonInstance in that method—to make sure that the Picasso instance is the global one.

The load() Method 

load(String path) starts an image request using the specified path. This path can be a remote URL, file resource, content resource, or Android resource.

  • placeholder(int placeholderResId): a local placeholder resource id or drawable to be used while the image is being loaded and then displayed. It serves as a good user experience to display a placeholder image while the image is downloading.  

Note that Picasso first checks if the image requested is in the memory cache, and if it is, it displays the image from there (we'll discuss caching in Picasso more in a later section).

Other Methods

  • error(int errorResId): a drawable to be used if the requested image could not be loaded—probably because the website is down. 
  • noFade(): Picasso always fades in the image to be displayed into the ImageView. If you don't want this fade-in animation, simply call the noFade() method. 
  • into(ImageView imageView): the target image view into which the image will be placed.

Image Resizing and Transformation

If the server you are requesting the image from doesn't give you the image you need in the required size, you can easily resize that image using resize(int targetWidth, int targetHeight). Calling this method resizes the image and then displays it on the ImageView. Note that the dimensions are in pixels (px), not dp. 

You can pass in an Android dimension resource for both the width and height using the method resizeDimen(int targetWidthResId, int targetHeightResId). This method will convert the dimension size to raw pixels and then call resize() under the hood—passing the converted sizes (in pixels) as arguments. 

Note that these resize methods won't respect aspect ratio. In other words, your image aspect ratio can be distorted. 

Fortunately, Picasso gives us some useful methods to solve this issue: 

  • centerCrop(): scales the image uniformly (maintaining the image's aspect ratio) so that the image fills up the given area, with as much of the image showing as possible. If needed, the image will be cropped horizontally or vertically to fit. Calling this method crops an image inside of the bounds specified by resize().
  • centerInside(): scales the image so that both dimensions are equal to or less than the requested bounds. This will center an image inside of the bounds specified by resize()
  • onlyScaleDown(): only resize an image if the original image size is bigger than the target size specified by resize().
  • fit(): attempt to resize the image to fit exactly into the target ImageView's bounds.

Image Rotation

Picasso has an easy API to rotate an image and then display that image. The rotate(float degrees) method rotates the image by the specified degrees.

In the example above, this would rotate the image by 90 degrees. The rotate(float degrees, float pivotX, float pivotY) method rotates the image by the specified degrees around a pivot point.

Here we are going to rotate the image by 30 degrees around the pivot point 200, 100 pixels. 

Transformation

Apart from just manipulating an image by rotating it, Picasso also gives us the option to apply a custom transformation to an image before displaying it.  

You simply create a class that implements the Picasso Transformation interface. You then have to override two methods: 

  • Bitmap transform(Bitmap source): this transforms the source bitmap into a new bitmap. 
  • String key(): returns a unique key for the transformation, used for caching purposes.

After you're done creating your custom transformation, you simply execute it by invoking transform(Transformation transformation) on your Picasso instance. Note that you can also pass a list of Transformation to transform()

Here, I applied a circle crop transformation to the image from the Picasso Transformations open-source Android library. This library has many transformations you can apply to an image with Picasso—including transformations for blurring or grey-scaling an image. Go check it out if you want to apply some cool transformations to your images.  

10. Initializing the Adapter

Here, we simply create our RecyclerView with GridLayoutManager as the layout manager, initialize our adapter, and bind it to the RecyclerView

11. Creating the Detail Activity

Create a new activity and name it SunsetPhotoActivity. We get the SunsetPhoto extra and load the image—inside onStart()—with Picasso as we did before. 

The Detail Layout

Here's a layout to display the detail activity. It just displays an ImageView that will show the full-resolution version of the loaded image. 

12. Caching Mechanism in Picasso

If you observe carefully, you'll notice that when you revisit an image that was previously loaded, it loads even faster than before. What made it faster? It's Picasso's caching mechanism, that's what.

Here is what's going on under the hood. After an image has been loaded once from the internet, Picasso will cache it both in memory and on disk, saving repeated network requests and permitting faster retrieval of the image. When that image is needed again, Picasso will first check if the image is available in memory, and if it's there, it will return it immediately. If that image is not in memory, Picasso will check the disk next, and if it's there, it returns it. If it's not there, Picasso will finally do a network request for that image and display it. 

In summary, here's what goes on (under the hood) for an image request: memory -> disk -> network. 

Depending on your application, though, you might want to avoid caching—for example, if the images being displayed are likely to change often and not be reloaded.

So How Do You Disable Caching? 

You can avoid memory caching by calling memoryPolicy(MemoryPolicy.NO_CACHE). This will simply skip the memory cache lookup when processing an image request. 

Note that there is another enum: MemoryPolicy.NO_STORE. This is useful if you are very certain that you will only request an image once. Applying this will also not store the image in the memory cache—thereby not forcing out other bitmaps from the memory cache. 

But be very aware that the image will still be cached on the disk—to prevent that also, you use networkPolicy(@NonNull NetworkPolicy policy, @NonNull NetworkPolicy... additional), which takes one or more of the following enum values:

  • NetworkPolicy.NO_CACHE: skips checking the disk cache and forces loading through the network.
  • NetworkPolicy.NO_STORE: skips storing the result into the disk cache.
  • NetworkPolicy.OFFLINE: forces the request through the disk cache only, skipping the network.

To avoid both memory and disk caching altogether, just call both methods one after the other:

13. Request Listeners

In Picasso, you can implement a listener or callback to monitor the status of the request you made as the image loads. Only one of these methods will be called if you implement the Target interface on a request. 

  • void onBitmapFailed(e: Exception?, errorDrawable: Drawable?): triggered whenever the image could not be successfully loaded. Here, we can access the exception that was thrown. 
  • void onBitmapLoaded(Bitmap bitmap, LoadedFrom from): fired whenever an image has been successfully loaded. Here, we get the Bitmap to show the user. 
  • void onPrepareLoad(Drawable placeHolderDrawable): invoked right before your request is submitted. 

Here you could also show and then hide a progress dialog if you had one. 

There is another callback listener you can implement if you want, called Callback. This interface has just two methods: onSuccess() and onError(Exception e). The former is called when the image request load was successful, and the later is called when there is an error in processing the request. 

Going back to our image gallery app (inside SunsetPhotoActivity), let's modify the display a little by using a Callback object that will set the bitmap to the ImageView and also change the background colour of the layout by extracting the dark and vibrant colour of our image using the Android Palette API

So include the palette artifact in your app module's build.gradle:

Let's now implement the Callback interface in our Picasso request. 

14. Testing the App

Finally, you can run the app! Click on a thumbnail to get a full-sized version of the image.

Final app result

15. Prioritizing Requests

When you want to load different images at the same time on the same screen, you have the option to order which one is more important than the other. In other words, you can load important images first. 

You simply call priority() on your Picasso request instance and pass in any of the enums: Priority.LOW, Priority.NORMAL, or Priority.HIGH

16. Tagging Requests

By tagging your Picasso requests, you can resume, pause, or cancel requests which are associated with specific tags. Depending on your use case, you can tag your requests with a string or objects that should define the scope of the request as a Context, an Activity, or a Fragment. You can easily tag a Picasso request by calling tag(@NonNull Object tag) on one. Pass it an instance of Object which serves as the tag. 

Here are the following operations you can perform on tagged Picasso requests:

  • pauseTag(Object tag): pause all requests associated with the given tag. 
  • resumeTag(Object tag): resume paused requests with the given tag.
  • cancelTag(Object tag): cancel any existing requests with the given tag.

Though tagging your requests gives you some control over your requests, you should be very careful when using tags because of the potential for memory leaks. Here's what the official documentation says:

Picasso will keep a reference to the tag for as long as this tag is paused and/or has active requests. Look out for potential leaks.

Loading From the File System

It's straightforward to load images locally in your app.

Conclusion

Nice job! In this tutorial, you've built a complete image gallery app with Picasso, and along the way you've learned how the library works and how you can integrate it into your own project. 

You've also learned how to display both local and remote images, tagging requests, prioritizing requests, and how to apply image transformations like resizing. Not only that, but you've seen how easy it is to enable and disable caching, error handling, and custom request listeners. 

To learn more about Picasso, you can refer to its official documentation. To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!

Introduction to Popmotion: Custom Animation Scrubber

$
0
0

In the first part of the Popmotion introductory series, we learned how to use time-based animations like tween and keyframes. We also learned how to use those animations on the DOM, using the performant styler.

In part two, we learned how to use pointer tracking and record velocity. We then used that to power the velocity-based animations springdecay, and physics.

In this final part, we're going to be creating a scrubber widget, and we're going to use it to scrub a keyframes animation. We'll make the widget itself from a combination of pointer tracking as well as spring and decay to give it a more visceral feel than run-of-the-mill scrubbers.

Try it for yourself:

Getting Started

Markup

First, fork this CodePen for the HTML template. As before, because this is an intermediate tutorial, I won't go through everything.

The main twist of note is that the handle on the scrubber is made up of two div elements: .handle and .handle-hit-area.

.handle is the round blue visual indicator of where the scrubber handle is. We've wrapped it in an invisible hit area element to make grabbing the element easier for touchscreen users.

Import Functions

At the top of your JS panel, import everything we're going to use in this tutorial:

Select Elements

We're going to need three elements in this tutorial. We'll animate the .box, drag and animate the .handle-hit-area, and measure the .range.

Let's also create stylers for the elements we're going to animate:

Keyframes Animation

For our scrubbable animation, we're going to make the .box move from left to right with keyframes. However, we could just as easily scrub a tween or timeline animation using the same method outlined later in this tutorial.

Your animation will now be playing. But we don't want that! Let's pause it for now:

Dragging the x-axis

It's time to use pointer to drag our scrubber handle. In the previous tutorial, we used both x and y properties, but with a scrubber we only need x.

We prefer to keep our code reusable, and tracking a single pointer axis is quite a common use case. So let's create a new function called, imaginatively, pointerX.

It will work exactly like pointer except it'll take just a single number as its argument and output just a single number (x):

Here, you can see we're using a method of pointer called pipepipe is available on all the Popmotion actions we've seen so far, including keyframes.

pipe accepts multiple functions. When the action is started, all output will be passed through each of these functions in turn, before the update function provided to start fires.

In this case, our function is simply:

All it is doing is taking the { x, y } object usually output by pointer and returning just the x axis.

Event Listeners

We need to know if the user has started pressing the handle before we start tracking with our new pointerX function.

In the last tutorial we used the traditional addEventListener function. This time, we're going to use another Popmotion function called listenlisten also provides a pipe method, as well as access to all action methods, but we're not going to use that here.

listen allows us to add event listeners to multiple events with a single function, similar to jQuery. So we can condense the previous four event listeners to two:

Move the Handle

We'll be needing the handle's x velocity later on, so let's make it a value, which as we learned in the last tutorial allows us to query velocity. On the line after we define handleStyler, add:

Now we can add our startDrag and stopDrag functions:

Right now, the handle can be scrubbed beyond the boundaries of the slider, but we'll come back to this later.

Scrubbing

Now we have a visually functional scrubber, but we're not scrubbing the actual animation.

Every value has a subscribe method. This allows us to attach multiple subscribers to fire when the value changes. We want to seek the keyframes animation whenever handleX updates.

First, measure the slider. On the line after we define range, add:

keyframes.seek accepts a progress value as expressed from 0 to 1, whereas our handleX is set with pixel values from 0 to rangeWidth.

We can convert from the pixel measurement to a 0 to 1 range by dividing the current pixel measurement by rangeWidth. On the line after boxAnimation.pause(), add this subscribe method:

Now, if you play with the scrubber, the animation will scrub successfully!

The Extra Mile

Spring Boundaries

The scrubber can still be pulled outside the boundaries of the full range. To solve this, we could simply use a clamp function to ensure we don't output values outside of 0, rangeWidth.

Instead, we're going to go the extra step and attach springs to the end of our slider. When a user pulls the handle beyond the permitted range, it will tug back towards it. If the user releases the handle while it's outside the range, we can use a spring animation to snap it back.

We'll make this process a single function that we can provide to the pointerXpipe method. By creating a single, reusable function, we can reuse this piece of code with any Popmotion animation, with configurable ranges and spring strengths.

First, let's apply a spring to the left-most limit. We'll use two transformersconditional and linearSpring.

conditional takes two functions, an assertion and a transformer. The assertion receives the provided value and returns either true or false. If it returns true, the second function will be provided the value to transform and return.

In this case, the assertion is saying, "If the provided value is smaller than min, pass this value through the linearSpring transformer." The linearSpring is a simple spring function that, unlike the physics or spring animations, has no concept of time. Provide it a strength and a target, and it will create a function that "attracts" any given value towards the target with the defined strength.

Replace our startDrag function with this:

We're now passing the pointer's x offset through our springRange function, so if you drag the handle past the left-most side, you'll notice it tugs back.

Applying the same to the right-most side is a matter of composing a second conditional with the first using the stand-alone pipe function:

Another benefit of composing a function like springRange is that it becomes very testable. The function it returns is, like all transformers, a pure function that takes a single value. You can test this function to see if it passes through values that lie within min and max unaltered, and if it applies springs to values that lie without.

If you let go of the handle while it lies outside the range, it should now spring back to within range. For that, we'll need to adjust the stopDrag function to fire a spring animation:

Our snapHandleToEnd function looks like this:

You can see that to is set either as 0 or rangeWidth depending on which side of the slider the handle currently sits. By playing with damping and stiffness, you can play with a range of different spring-feels.

Momentum Scrolling

A nice touch on iOS scrubber that I always appreciated was that if you threw the handle, it would gradually slow down rather than come to a dead stop. We can replicate that easily using the decay animation.

In stopDrag, replace handleX.stop() with momentumScroll(x).

Then, on the line after the snapHandleToEnd function, add a new function called momentumScroll:

Now, if you throw the handle, it will come to a gradual stop. It will also animate outside the range of the slider. We can stop this by passing the clamp transformer to the decay.pipe method:

Conclusion

Using a combination of different Popmotion functions, we can create a scrubber that has a bit more life and playfulness than the usual.

By using pipe, we compose simple pure functions into more complex behaviours while leaving the composite pieces testable and reusable.

Next Steps

How about trying these challenges:

  • Make the momentum scroll end with a bounce if the handle hits either end of the scrubber.
  • Make the handle animate to any point on the scrubber when a user clicks on another part of the range bar.
  • Add full play controls, like a play/pause button. Update the scrubber handle position as the animation progresses.

A Beginner's Guide to Regular Expressions in JavaScript

$
0
0

Everyone working with JavaScript will have to deal with strings at one point or other. Sometimes, you will just have to store a string inside another variable and then pass it over. Other times, you will have to inspect it and see if it contains a particular substring.

However, things are not always this easy. There will be times when you will not be looking for a particular substring but a set of substrings which follow a certain pattern.

Let's say you have to replace all occurrences of "Apples" in a string with "apples". You could simply use theMainString.replace("Apples", "apples"). Nice and easy.

Now let's say you have to replace "appLes" with "apples" as well. Similarly, "appLES" should become "apples" too. Basically, all case variations of "Apple" need to be changed to "apple". Passing simple strings as an argument will no longer be practical or efficient in such cases.

This is where regular expressions come in—you could simply use the case-insensitive flag i and be done with it. With the flag in place, it doesn't matter if the original string contained "Apples", "APPles", "ApPlEs", or "Apples". Every instance of the word will be replaced with "apples".

Just like the case-insensitive flag, regular expressions offer a lot of other features which will be covered in this tutorial.

Using Regular Expressions in JavaScript

You have to use a slightly different syntax to indicate a regular expression inside different String methods. Unlike a simple string, which is enclosed in quotes, a regular expression consists of a pattern enclosed between slashes. Any flags that you use in a regular expression will be appended after the second slash.

Going back to the previous example, here is what the replace() method would look like with a regular expression and a simple string.

As you can see, the regular expression worked in both cases. We will now learn more about flags and special characters that make up the pattern inside a regular expression.

Backslash in Regular Expressions

You can turn normal characters into special characters by adding a backslash before them. Similarly, you can turn special characters into normal characters by adding a backslash before them.

For example, d is not a special character. However, \d is used to match a digit character in a string. Similarly, D is not a special character either, but \D is used to match non-digit characters in a string.

Digit characters include 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. When you use \d inside a regular expression, it will match any of these nine characters. When you use \D inside a regular expression, it will match all the non-digit characters.

The following example should make things clear.

You should note that only the first matched character is replaced in the third case. You can also use flags to replace all the matches. We will learn about such flags later.

Just like \d and \D, there are other special character sequences as well.

  1. You can use \w to match any "word" character in a string. Here, word character refers to A-Z, a-z, 0-9, and _. So, basically, it will match all digits, all lowercase and uppercase alphabets, and the underscore.
  2. You can use \W to match any non-word character in a string. It will match characters like %, $, #, ₹, etc.
  3. You can use \s to match a single white space character, which includes space, tab, form feed, and line feed. Similarly, you can use \S to match all other characters besides white space.
  4. You can also look for a specific white space character using \f, \n, \r, \t, and \v, which stand for form feed, line feed, carriage return, horizontal tab, and vertical tab.

Sometimes, you will face situations where you need to replace a word with its substitute, but only if it is notpart of a larger word. For example, consider the following sentence:

"A lot of pineapple images were posted on the app".

In this case, we want to replace the word "app" with "board". However, using a simple regular expression pattern will turn "apple" into "boardle", and the final sentence would become:

"A lot of pineboardle images were posted on the app".

In such cases, you can use another special character sequence: \b. This checks for word boundaries. A word boundary is formed by use of any non-word characters like space, "$", "%", "#", etc. Watch out, though—it also includes accented characters like "ü".

Similarly, you can use\B to match a non-word boundary. For example, you could use \B to only match "app" when it is within another word, like "pineapple".

Matching a Pattern "n" Number of Times

You can use ^ to tell JavaScript to only look at the beginning of the string for a match. Similarly, you can use $ to only look at the end of the string for a match.

You can use *to match the preceding expression 0 or more times. For example, /Ap*/ will match A, Ap, App, Appp, and so on.

In a similar manner, you can use + to match the preceding expression 1 or more times. For example, /Ap+/ will match Ap, App, Appp, and so on. The expression will not match the single A this time.

Sometimes, you only want to match a specific number of occurrences of a given pattern. In such cases, you should use the {n} character sequence, where n is a number. For instance, /Ap{2}/ will match App but not Ap. It will also match the first two 'p's in Appp and leave the third one untouched.

You can use {n,} to match at least 'n' occurrences of a given expression. This means that /Ap{2,}/ will match App but not Ap. It will also match all the 'p's in Apppp and replace them with your replacement string.

You can also use {n,m} to specify a minimum and maximum number and limit the number of times the given expression should be matched. For example, /Ap{2,4}/ will match App, Appp, and Apppp. It will also match the first four 'p's in Apppppp and leave the rest of them untouched.

Using Parentheses to Remember Matches

So far, we have only replaced patterns with a constant string. For example, in the previous section, the replacement we used was always "Add". Sometimes, you will have to look for a pattern match inside the given string and then replace it with a part of the pattern.

Let's say you have to find a word with five or more letters in a string and then add an "s" at the end of the word. In such cases, you will not be able to use a constant string value as a replacement as the final value depends on the matching pattern itself.

This was a simple example, but you can use the same technique to keep more than one matching pattern in memory. The number of sub-patterns in the full match will be determined by the number of parentheses used.

Inside the replacement string, the first sub-match will be identified using $1, the second sub-match will be identified using $2, and so on. Here is another example to further clarify the usage of parentheses.

Using Flags With Regular Expressions

As I mentioned in the introduction, one more important feature of regular expressions is the use of special flags to modify how a search is performed. The flags are optional, but you can use them to do things like making a search global or case-insensitive.

These are the four commonly used flags to change how JavaScript searches or replaces a string.

  • g: This flag will perform a global search instead of stopping after the first match.
  • i: This flag will perform a search without checking for an exact case match. For instance, Apple, aPPLe, and apPLE are all treated the same during case-insensitive searches.
  • m: This flag will perform a multi-line search.
  • y: This flag will look for a match in the index indicated by the lastIndex property.

Here are some examples of regular expressions used with flags:

Final Thoughts

The purpose of this tutorial was to introduce you to regular expressions in JavaScript and their importance. We began with the basics and then covered backslash and other special characters. We also learned how to check for a repeating pattern in a string and how to remember partial matches in a pattern in order to use them later.

Finally, we learned about commonly used flags which make regular expressions even more powerful. You can learn more about regular expressions in this article on MDN.

If there is anything that you would like me to clarify in this tutorial, feel free to let me know in the comments.

8 Best Backup Software for Mac in 2018 (Free + Paid)

$
0
0

Your Mac probably contains hundreds of important documents and thousands of sentimental photos. If you don’t have a backup, a single careless moment could lose them all forever. A spill from a cup of coffee, a fall onto a concrete floor, or an opportunistic thief are all enough for your data to be gone for good. Trust me, you want to back up everything.

In this article I'll discuss the different types of Mac backup software available, explain the features necessary for the best backup software solutions for Macs, and list eight of the best Mac backup software choices.

Different Types of Backup Software for Macs

When it comes to backing up your Mac, there are several different kinds of backups: 

  1. Cloud Storage like Dropbox or Google Drive is a great first line of defence. With their basic versioning systems, they also stop you accidentally deleting a file and make sure you can’t lose your only copy in a single mishap. 
  2. A local backup—like Time Machine—is perfect for quickly restoring large files and giving you a bit of added security. However, a local backup is still vulnerable to things like fire, flooding, and theft. If your house burns down with your Mac inside, your backup drive isn’t likely to survive either.
  3. A bootable clone is like a local backup but, instead of just storing a copy of your files, it stores a copy of your whole operating system. This means that if the hard drive in your computer fails, you can boot directly from your backup hard drive. 
  4. A cloud back up service like Backblaze stores all your files offsite. This means they’re safe from the kind of things that can take out a local backup. The problem is that restoring a large number of files from an online offsite backup is very time consuming. It can also take a bit of time before your files upload which means that if you accidentally delete a file you recently created, it might not be available. Cloud backups are a brilliant, bulletproof option, but they aren’t great as your only option.

There’s a saying when it comes to digital backups (and emergency supplies): one is none and two is one. The different backup options aren’t competing, instead you should build a system that uses a few different ones. To give you an idea of what this looks like, let’s take my current backup setup.

Every important file and everything I’m currently working on—like this article—is saved in Dropbox. Instead of using a Documents folder, I've got everything automatically moved into an Inbox in Dropbox. The only exception to this is large numbers of photos. This means that whatever happens to my Mac, the stuff I’m working on at the moment is safe. I could spill my coffee all over it, but at least this article would be safe. 

About once a week, I connect an external hard drive to my Mac for an hour or two. Time Machine automatically backs everything up to the drive. This just means I’ve got a local copy of every file whatever happens. 

I also have Backblaze running in the background. It’s constantly backing up my files to Backblaze’s servers. If the worst comes to the worst and every piece of tech I own is destroyed, at least my files are safe. I hope I never have to use it, but it’s very comforting to know it’s there.

At the moment, I don’t use a clone backup, however, when I was regularly using my Hackintosh, I had one. It was great to be able to roll back my Hackintosh to a stable system at any time. I always took a new clone before I updated anything or made major changes to how it ran.

What We’re Looking For in a Mac Backup Software Solution

A good backup app needs to do one thing really well: back up your files. You can’t be left thinking something is backed up when it really isn’t. We’re going to look at some great back up apps in each of the four categories above: local backups, clone backups, cloud backups, and cloud storage. 

Each app we’ll look at is one of the best in its class. Most of them are apps that people on the Tuts+ team rely on to protect our own data. I’ve personally relied on five of them at various different stages and confidently recommend them all. 

Since we’re really looking at four different kinds of apps, there’s no one feature set we want. We aren’t going to ding Time Machine for not backing up to an offsite server. Instead, for inclusion, each app had to have what we felt were the most important features for that kind of backup app. For example, a local backup should really have some kind of versioning, a clone needs to be easily bootable, and so on.

Best Backup Software for Macs

Now that we've discussed what to look for in Mac backup software, let’s look at the apps. Here are my picks for the best Mac backup software for 2018:

1. Time Machine

Time Machine is built into macOS and it should be your first go to as Mac backup software. Since it’s entirely free and dead simple to use (plug in hard drive, wait), there’s really no excuse for not having a Time Machine backup in addition to whatever other backup plan you have. 

Time Machine isn’t perfect—no local backup is—so we would recommend you use at least one other solution as well. 

2. Backblaze 

backblaze

Backblaze is my favorite cloud backup solution. For $5/month for each computer you want to back up, you can keep all your files totally safe. All your important data gets uploaded to Backblaze’s secure servers.

If you’re concerned about Backblaze slowing down your network, you can set an upload limit, schedule backups for when you’re asleep, or just let auto throttling do its thing. 

If the worst comes to the worst and you need to restore some files, you can easily download them from Backblaze’s website. They also keep versions of each file for 30 days if you ever need to recover an early version. If you’re trying to restore an entire computer worth of data, you can order a 128GB USB key or 4TB hard drive with your data on it instead of waiting for it all to download.

3. Carbonite 

carbonite

Carbonite offers much the same service as Backblaze. For an annual fee, an unlimited amount of data on a single computer is backed up to their servers. At any time, you can log in and restore single files or everything. 

Carbonite, however, comes with a couple of caveats. For example, video files are only backed up automatically if you’re prepared to sign up for the $111.99/year Plus plan. Similarly, if you want your data couriered to you, you’ll need to be on the $149.99/year Prime plan; Backblaze, on the other hand, charges a fee only if you choose to use a physical delivery, rather than having it built into the plan. 

4. SuperDuper! 

superduper

SuperDuper! is one of the best disk cloning apps for Mac. While there's a paid version available for $27.95, the free version has all the features most people need. 

You can use SuperDuper! as a regular backup app that copies files and folders to another hard drive, but it’s real strength is creating bootable clones. As discussed above, they make it a lot easier to get up and running again if your Mac’s hard drive fails. 

The paid version of SuperDuper! adds a few useful features. One neat one is Smart Update which can update your existing clone backups; this means that SuperDuper! doesn’t have to create a totally new backup each time. You can also schedule backups to run. 

5. Carbon Copy Cloner 

carboncopycloner

Carbon Copy Cloner, like SuperDuper!, can create bootable backups and regular backups. The big difference is that the interface is a bit nicer and it’s easier for you to fully customise what files get backed up. If you want a separate back up of a few important files and folders in addition to a bootable clone, Carbon Copy Cloner is the way to go.

The downside is that there’s only a 30-day free trial. Carbon Copy Cloner is definitely worth the nearly forty dollars, but only if you’re going to use the extra features. If not, stick with SuperDuper!

6. Dropbox 

dropbox

Dropbox isn’t traditional backup software for a Mac and shouldn’t be treated as such. However, it’s a great place to keep the files you’re working on as soon as you create them. 

With the exception of a cloud backup service, it’s unlikely your files will get backed up right away. This means that there is a window between whenever you start to work on something and when you back it up where something could happen. If, however, you save that file straight to your Dropbox folder, then you know it’s secure until a more permanent backup solution also has it stored.

You get 2GB of space on Dropbox for free which really isn’t very much at all. For $9.99 a month, however, you get a terabyte which is more than enough for most people’s needs.

7. Google One 

google one

Google One—Google’s recently rebranded Drive—is essentially the exact same service as Dropbox. It’s not the best traditional backup (although it does now offer some backup features) but it’s a great service for keeping your files accessible and a lot more secure than if they’re just sitting on your computer.

The big difference with Google One is the pricing and storage tiers. You get 15GB free, 100GB for $1.99/month, 200GB for $2.99/month, 2TB for $9.99/month, and it goes up from there. If you’re comfortable getting deep into Google’s ecosystem, it’s a better priced option than Dropbox. 

8. Acronis True Image 2018 

acronis

Acronis True Image is pretty much, an all in one backup solution. You can back files up to local hard drives, network attached storage devices, and Acronis’ own cloud backup service. 

For $49.99 you get the app, however, to back up to the cloud, you'll need to either subscribe to the Advanced plan for $49.99/year or the Premium plan for $99.99/year. Both also come with some extra features like social media backup and phone support. 

If you’re looking for one app that takes care of everything, then Acronis true image is a good bet. You can have it take care of your local backups as well as your cloud backups. 

Wrapping Up

Backing up your files is incredibly important if you don’t want to lose them. Lots of people—myself included—have been caught out by a faulty hard drive in the past. As I mentioned at the top of this article, a single local backup really isn’t a strong solution. It'll protect you against some things, but not against stuff like fire or theft. Ideally, you should have two or three independent backups. All the backup software for Macs on this list will help you do it.

Augmented Reality With ARKit: Feature Points and Horizontal Plane Detection

$
0
0

By now, you may have used an augmented reality app on your iPhone, with virtual objects that appear lifelike and blend in well with the features of the environment. In this series, you'll learn how to implement this in your own iOS app with ambient light detection and horizontal plane detection to improve your augmented reality application. This tutorial will focus on showing horizontal planes and feature points in ARKit.

Often, when using augmented reality, you want to place your virtual object on a flat surface such as a table, a desk, or even the ground. In order to do this accurately, it's important that you are able to detect these objects before you begin. After your plane is detected, the object will use a series of dots to anchor your virtual object to it, and the object will remain there, even as you move your device around.

For this tutorial, you'll need some basic knowledge of Swift, Xcode, and ARKit. If you haven't used ARKit in the past, you may find it helpful to read my previous tutorial, which is specifically aimed at helping beginners make their first augmented reality application:

Getting Started

Xcode Version

Before we begin, make sure you have the latest version of Xcode installed on your Mac. This is very important because ARKit will only be available on Xcode 9 or newer. You can check your version by opening Xcode and going to Xcode > About Xcode in the upper toolbar. 

If your version of Xcode is older than Xcode 9, you can go to the Mac App Store and update it for free. If you don't already have Xcode, you can also download and install it for free.

Sample Project

New Project

After you've made sure you have the right version of Xcode, you'll need to make a new Xcode project. 

Go ahead and open Xcode and click Create a new Xcode project.

Figure 1 Create an Xcode Project

You may be used to making a Single View Application, but for this tutorial, you will need to choose an Augmented Reality App. Then click Next.

Figure 2 Select Augmented Reality Template

Gaming Frameworks

You can name your project anything you like, but I will be naming mine Plane Detection. You will also notice that there is an option at the bottom where you can select from SceneKit, SpriteKit, and Metal. 

These are all Apple's gaming frameworks, and for the purpose of the tutorial, we will be using SceneKit because we'll be using 3D objects. 

Go ahead and select SceneKit if it isn't already selected. Your screen should look something like this:

Figure 3 Name your Project

Preparing to Test

Connecting an iPhone

Since the Xcode Simulator doesn't have a camera, you'll need to plug in your iPhone. Unfortunately, if you don't have an iPhone, you'll need to borrow one to be able to follow along with this tutorial (and for any other camera-related apps). If you already have an iPhone connected to Xcode, you can skip ahead to the next step.

A nifty new feature in Xcode 9 is that you can wirelessly debug your app on a device, so let's take the time to set that up now:

In the top menu bar, choose Window > Devices and Simulators. In the window that appears, make sure that Devices is selected at the top.

Now, plug in your device using a lightning cable. This should make your device appear in the left pane of the Devices and Simulators window. Simply click your device, and check the Connect via Network box.

Figure 4 Devices and Simulators

You will now be able to wirelessly debug on this iPhone for all future apps.

Complete Setup

Now your setup is complete. You should have a working ARKit app, and you can test it on the iPhone that you just connected. In the upper left of Xcode, next to the Run and Stop buttons, select your device from the simulator dropdown. I've selected Vardhan's iPhone, but you need to select your specific device.

Now you're done creating your starter project, and you should see a virtual spaceship appear in your world once you click Run. Here's what it should look like:

Figure 5 Run the Sample App

In Theory

Before we actually begin programming this app, it's important to understand how ARKit actually detects these planes. In this tutorial, we'll explore two main concepts: feature points and horizontal planes. In short, augmented reality on your iPhone works with a process called Visual Inertial Odometry (VIO), which takes the data from your cameras and internal sensors to gain a 3D understanding of a scene.

Feature Point

So, what exactly is a feature point? Every image, naturally, would have its own unique features. For example, in a flower, there would be unique shapes, or on a carpet, there may be distinctive textures.

These points represent notable features detected in the camera image. Their positions in 3D world coordinate space are extrapolated as part of the image analysis that ARKit performs in order to accurately track the device's position, orientation, and movement. Taken together, these points loosely correlate to the contours of real-world objects in view of the camera. — Apple

As Apple's documentation explains, feature points help your device (and ARKit) get a sense of the depth and "realism" of your world, making augmented reality much more accurate. These are also used to help give your virtual objects a place to anchor on, helping them get a sense of where to remain in case you move your device around.

Horizontal Planes

Similar to feature points, horizontal planes help your app get a sense of its surroundings. Not surprisingly, feature points and horizontal planes are very closely coupled in that these planes couldn't be detected without feature points. 

Using your iPhone's built-in sensors, including the camera (of course) and a combination of these feature points, ARKit can detect various planes in your scene. These calculations and estimations are done every frame, and multiple planes can be detected at once.

When you run a world-tracking AR session whose planeDetection option is enabled, the session automatically adds to its list of anchors an ARPlaneAnchor object for each flat surface ARKit detects with the back-facing camera. Each plane anchor provides information about the estimated position and shape of the surface. — Apple

In Code

Great! You've now got yourself a working ARKit app. Your goal for this app is to be able to detect a horizontal plane and visualize it with feature points (virtual dots which are placed on scenes in ARKit).

Starter Code

You now have a solid understanding of what feature points and horizontal planes are, and you're now ready to start programming them into an app. If you want more background on feature points and horizontal planes, I would recommend reading Apple's Documentation.

Preparing Your Project

If you open your ViewController.swift file, you'll notice that Apple has some starter code already set up for you (which renders a spaceship). We won't be covering what everything means in this tutorial, but if you'd like to have a line-by-line explanation, feel free to check out my other tutorial on ARKit.

Since a lot of the code is boilerplate code, we'll keep it, but as for the spaceship, let's get it out of the way by removing the code which handles its placement. In your ViewController.swift file, within your viewDidLoad() method, remove the following lines of code:

Feature Points

Enabling Debugging Options

Your Xcode project is now ready to start working on. Our first step is to add visible feature points. It's likely that you won't be making them visible for production apps, but it's a wonderful feature for debugging augmented reality apps.

This step is pretty simple, and it can be done in one line. In your viewDidLoad() method, add the following line of code:

This code configures debug options using an array of options. You can enable other features by adding them to this array, but for now, we just need to display our feature points. Here's what it should look like when you run your app:

Figure 6 Feature Points

As you can see, all the detected feature points are visible. If you don't see them, try moving your iPhone around, and you should see yellow dots appear. Part of the reason why they don't appear immediately is that ARKit is still detecting the scene.

Configuration

Now, we're ready for plane detection. If you take a look at your viewWillAppear() method, you'll see the following two lines of code. Let's take a moment to learn what they mean as they will be relevant for plane detection:

Here, an instance of the ARWorldTrackingConfiguration class is made. This class is responsible for device positioning. After that, we run the configuration on our current sceneView session. If you're interested in learning more about this, you can visit Apple's Documentation about it. For now, though, you're ready to continue to the next step.

Now, let's enable plane detection on our ARWorldTrackingConfiguration. Below the line which creates the configuration, you'll need to insert the following line:

Excellent! Now, horizontal plane detection is enabled, but we can't see it because it's happening under the hood, meaning that the iPhone knows where the plane is, but we can't see what it thinks.

Plane Detection

Checking for Anchors

Before we can start visualizing our detected planes, we'll need to find out when and where the planes are being detected. This can be easily done with a delegate method which is provided to us by Apple.

Start off by declaring a method for the ARSCNViewDelegate, and as you'll see, the ViewController class already conforms to this delegate in the starter code. Paste the following delegate method into your ViewController class:

This is called when new ARAnchors are added with a corresponding node, which, in this case, would be our horizontal planes.

Tells the delegate that a SceneKit node corresponding to a new AR anchor has been added to the scene.—Apple

Plane Geometry

For most apps, though, you would want the user to be able to tell where your app thinks it spots horizontal planes, so we'll be learning how to actually display these planes to the user using the node and the anchor provided in the delegate method we called earlier.

Our first question is: is the ARAnchor really a plane, or is it something we don't want? We can check this using type-casting and optional binding. Put this line of code into your delegate method:

You may have noticed that the anchor parameter has the type ARAnchor. If we want to know whether this anchor is a plane, we can attempt to type-cast it as an ARPlaneAnchor. If that succeeds, we know that a plane has been detected.

Inside the optional binding statement, let's add code to create an SCNPlane with the dimensions of the anchor we received from the delegate method. Write out the following two lines of code:

The first line here creates a two-dimensional SCNPlane which takes two parameters in its constructor: a width and a height. You'll see that we pass in anchor.extent.x and anchor.extent.z, which, as their names suggest, represent the width and the height of the detected planes. You'll notice that we've omitted the y-value of the anchor, and that's because the planes we're detecting are two-dimensional, and the x and z axes run across planes that we're identifying.

The next line of code applies a translucent red hue to these detected planes, and you can see through these planes because the alpha value is set to 0.5. Of course, you can use any colors or appearances you wish, as long as you'll be able to see them.

Creating the Node

We're not done yet; we still need to create the node to add to our view. Though our plane is a two-dimensional object, we still need to represent it in 3D with an x, y, and z coordinate. These coordinates will be relative to the parent node of the detected plane anchor and not the sceneView. Enter the following lines of code:

We're first creating a SCNNode with the plane geometry we created in the previous step. This is being done by passing in the geometry as a parameter of SCNNode's constructor.

Next, we're positioning the plane node directly in the center of the plane anchor using a SCNVector3 representation of x, y, and z coordinates in the three-dimensional plane. 

Also, in the next line, you'll see that the x value of our eulerAngles is being set to -π/2. The property eulerAngles represents the pitch, yaw, and roll of the SCNNode. According to Apple's documentation, the x value represents the pitch (or rotation about the x-axis), and we want ours to be flat against the plane (not sticking upright).

Last, the newly created node is added as a child node of the detected plane node to make it visible to the user at the same location.

Conclusion

Great job! You should now be able to see horizontal planes (and, of course, the feature points) when you run your application on your iPhone. If you don't, make sure you move your phone around slowly for it to scan the surface, and try increasing the alpha of the color we set earlier. Here's what mine looks like:

Figure 7 Horizontal Planes and Feature Points

You now know how to detect flat surfaces such as tables or desks and display them to the user as horizontal planes. In addition to this, you've been able to see how ARKit views the world with feature points. While you're here, be sure to check out some of our other ARKit courses and tutorials here on Envato Tuts+!


Viewing all 4704 articles
Browse latest View live