Tag Archiv: php

15 Interesting JavaScript and CSS Libraries for October 2016

interesting-libraries-october-2016

Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a handpicked collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.

Below is October’s list, packed with awesome free libraries including vanilla JS plug-ins, React components, an icon font, and much more! Enjoy :)


Leaflet

Leaflet

Leaflet is one of the most popular open-source solutions for creating interactive maps. It offers everything you’d expect out of a map library – markers, layers, zooming, and many more basic and advanced features. The project recently got it’s official 1.0 release with many improvements to the API, accessibility and performance.


Reflexbox

Reflexbox

Flexbox grid system for React that allows developers to quickly build page layouts using a simple API of 3 React components – Grid, Flex, and Box. Since it utilizes the flexbox model, all grids with Reflexbox are responsive and can be easily adjusted via the various flexbox properties.


Lory

Lory

Lightweight no-dependencies JavaScript carousel with excellent gesture controls for touch-screen devices. The library provides lots of customization options for controlling the transition speed, frequency, animations, and other details. Excellent browser-support, a clean API, and lots of examples.


Granim

Granim

Tiny, very simple to use JavaScript library for creating beautiful gradient animations. Go to the examples page to see all the features Granim provides, including linear and radial animations, image masks, and interactive change of gradient colors.


React Native Elements

React Native Elements

A UI toolkit for React Native that combines a number of useful components into one package. It includes elements such as menus, various buttons, and form inputs, with new components coming in the future. Very well documented and easy to implement.


Reframe

Reframe

JavaScript plugin that makes unresposnive elements responsive. Reframe is especially useful for <iframe> and <video> element as it preserves their original aspect ratio. Like most modern libraries, this one doesn’t rely on jQuery but can work with $('selectors') if it is included in the page.


Progress Bar

Progress Bar

Awesome library for creating responsive animated progress bars. ProgressBar.js provides a number of built in shapes, and also allows developers to create their own paths using SVG. The progress bars can be further customized through a rich JS options object.


Headroom.js

Headroom.js

Headroom is a vanilla JavaScript library that allows you to easily set up event listeners for user scroll. You can bind different functions for when the scroll moves up or down, the bottom/top of the page is reached, and other events. One of the best available solutions for creating self-toggling headers.


SpinThatSh*t

SpinThatSh*t

Sass mixins for loading indicators with fluid CSS-only animations. The spinners are extremely easy to implement as they require just one HTML element per spinner. To customize the mixins themselves you can simply change the provided SCSS variables.


Navigo

Vanilla JavaScript library that utilizes the History API to make a robust routing system with proper history on single page apps. In browsers where the History API isn’t available, Navigo automatically falls back to a hash (#) based routing.


Wysiwyg.css

Wysiwyg.css

Pretty theme for documents that have been generated from HTML or Markdown. It styles all elements on the page, providing them with proper typography, colors and paddings, greatly improving readability. Implementing the theme is as easy as adding a single class to the root element. Customization is done through Sass.


Choreographer

Choreographer

This is a library for easier handling of complex CSS animations. Choreographer makes more manageable the transition of multiple properties at once, animations that start off after different delays, and syncing with user gestures such as scrolling.


Open color

Open color

Color pallette created especially for designing user interfaces. It contains 12 colors, each having 10 variations with different intensity. Open color is available in CSS, Sass, Less, and as a plug-in for Photoshop, Illustrator, and Sketch.


Fuse.js

Fuse.js

No dependencies JavaScript library that enables you to integrate fuzzy-search (approximate string matching) to your web app. Fuse is very powerful and has lots of options for you to tinker and play with to get the exact search functionality you need.


Ionicons

Ionicons

Ionicons is the icon font from the Ionic framework, but it can be freely used as a standalone library. The collection consists of over 500 premium-quality symbols and logos, all drawn in a modern and very appealing style. One of our favorite icon fonts at the moment.

Everything You Should Know About Progressive Web Apps

progressive-web-apps_1

Progressive Web Apps is a web application which takes advantage of modern browser features and can be added to your homescreen, behaving just like a native application.

In this tutorial we’re going to show you everything you need to know about PWAs, step by step, with practical examples and a demo app. To not start from scratch, we are going to use the selfie app we made recently, and make it progressive.


What is a Progressive Web App

In its core a progressive web app isn’t any different from a normal website – it’s made of HTML, CSS and JavaScript, and lives in the browser. What separates PWAs from regular websites is a list of 10 key concepts that need to be fulfilled. Here they are, taken directly from the Google Developers website.

  1. Safe – Served via HTTPS to prevent snooping and ensure content hasn’t been tampered with.
  2. Progressive – Work for every user, regardless of browser choice because they’re built with progressive enhancement as a core tenet.
  3. Responsive – Fit any form factor: desktop, mobile, tablet, or whatever is next.
  4. Connectivity-independent – Enhanced with service workers to work offline or on low quality networks.
  5. App-like – Feel like an app to the user with app-style interactions and navigation because they’re built on the app shell model.
  6. Fresh – Always up-to-date thanks to the service worker update process.
  7. Discoverable – Are identifiable as “applications” thanks to W3C manifests and service worker registration scope allowing search engines to find them.
  8. Re-engageable – Make re-engagement easy through features like push notifications.
  9. Installable – Allow users to “keep” apps they find most useful on their home screen without the hassle of an app store.
  10. Linkable – Easily share via URL and not require complex installation.

Following these guidelines will ensure that your app works well not only when viewed in the browser, but also when started separately via a home screen shortcut. You may find the wording Google has chosen rather confusing, but don’t worry, we will explain the rules one by one later in the tutorial.


What a Progressive Web App is NOT

The concept of PWAs shouldn’t be confused with:

All of the aforementioned technologies wrap HTML apps and package them into executable files, be it an .apk, .exe or anything else, which then have to be downloaded from the respective app store and installed on the user’s device.

PWAs don’t require installation and aren’t available (yet) in Google Play or the iTunes App store. To download a PWA you need to simply visit it’s website and then save it to the home screen as a shortcut. Developing and maintaining separate iOS and Android versions is no longer an issue, but browser support needs to be taken into consideration.


1_safe1. Safe

Most progressive web apps work with native APIs and service workers, technologies that deal with sensitive data and need to be handled with caution. That’s why every PWA has to be served through a HTTPS connection.

If you don’t have access to a server with a SSL certificate, the easiest way run projects in a secure environment is via GitHub Pages or a similar service. Any GitHub repository can be hosted directly over HTTPS, and both GitHub and GitHub Pages are free for public repos.

This is where we’ve chosen to host our demo: https://tutorialzine.github.io/pwa-photobooth/.

For simple testing on a local server, you can also try Ngrok. Its a tiny tool that allows you to tunnel any currently running localhost to a secure public URL. Ngrok is free and available for Windows, Mac, and Linux.


2_progressive

2. Progressive

Essentially, what this means is that PWAs should use web technologies that are widely supported and work equally well on as many browsers as possible. As we all know, in the world of web development this is close to impossible, but still there are things we can do to cover a larger user base.

For example, in our PhotoBooth app we use the getUserMedia() API for accessing the hardware camera on a device. Its support in different browsers is quite inconsistent – Safari doesn’t support it at all, the browsers that do support it need prefixes and differ in usage.

To ensure more people can actually use our app, we cover all the prefixes:

navigator.getMedia = ( 
    navigator.getUserMedia ||
    navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia ||
    navigator.msGetUserMedia
);

We also show an error if none of the prefixes work:

if (!navigator.getMedia) {
    displayErrorMessage("Your browser doesn't have support for the navigator.getUserMedia interface.");
}
else {
    // Use Camera API
}

Fallbacks and polyfills should be provided where possible. The same principles go for the CSS and HTML code.


3_responsive

3. Responsive

The app should look nice on all devices, no matter their screen size. Our app has a fairly simple UI so we’ve used only a couple of media queries to control font-size, paddings, margins, etc.

Don’t be afraid to use CSS libraries and frameworks such as Bootstrap, as they make it really easy to form grids, and deal with typography and general responsiveness.


4_offline

4. Connectivity independent

This is an important one. Using service workers allows your app to work even when there is no internet connection available.

Some apps can be cached only partially: UI is cached and available offline, dynamic content still needs access to a server.

Others, like our PhotoBooth demo, can be cached in their entirety. All of the source code and resources will be saved locally and the app will work offline and online exactly the same way. Here is the code that makes the magic happen:

This is an oversimplified usage of Service Workers, use with caution in commercial projects.

First we need to make a service worker JavaScript file, and define the logic behind it.

sw.js

// Install the service worker.
this.addEventListener('install', function(event) {
    event.waitUntil(
        caches.open('v1').then(function(cache) {
            // The cache will fail if any of these resources can't be saved.
            return cache.addAll([
                // Path is relative to the origin, not the app directory.
                '/pwa-photobooth/',
                '/pwa-photobooth/index.html',
                '/pwa-photobooth/assets/css/styles.css',
                '/pwa-photobooth/assets/fonts/MaterialIcons-Regular.woff2',
                '/pwa-photobooth/assets/js/script.js',
                '/pwa-photobooth/assets/icons/ic-face.png',
                '/pwa-photobooth/assets/icons/ic-face-large.png',
                '/pwa-photobooth/manifest.json'
            ])
            .then(function() {
                console.log('Success! App is available offline!');
            })
        })
    );
});


// Define what happens when a resource is requested.
// For our app we do a Cache-first approach.
self.addEventListener('fetch', function(event) {
    event.respondWith(
        // Try the cache.
        caches.match(event.request)
        .then(function(response) {
            // Fallback to network if resource not stored in cache.
            return response || fetch(event.request);
        })
    );
});

Then we need to link that service worker to our HTML.

index.html

<script>
// Register Service Worker.

if ('serviceWorker' in navigator) {
    // Path is relative to the origin, not project root.
    navigator.serviceWorker.register('/pwa-photobooth/sw.js')
    .then(function(reg) {
        console.log('Registration succeeded. Scope is ' + reg.scope);
    })
    .catch(function(error) {
        console.error('Registration failed with ' + error);
    });
}
</script>

Now all of the files in our project will be saved in the user’s browser. Any JavaScript variables and object should also be saved in the localStorage or IndexDB where possible.

Right now Service Workers are supported in Chrome, Firefox and Opera. Safari and Edge are also working towards adopting them, and we hope that in the future they will be available in every browser.


5_applike

5. App-like

When building PWAs, it’s recommended to follow a design concept called app-shell architecture. It sounds very complicated but essentially boils down to this: the app is separated into two major components: the shell and the content.

The shell contains all the static UI elements such as a header, menus, drawers, etc. When we cache an app, the shell should always be saved on the device, because we want it to be available at all times. That way when a user with no internet connection opens the app, they won’t see an empty screen or a running dinosaur – they will see the cached app interface and an appropriate error message.

Image Courtesy To developers.google.com

The content resides within the shell. It can also be cached but it isn’t necessary to do so as content is usually dynamic, changes frequently and can be different on every single page load.


6_fresh_

6. Fresh

Once cached, our PWA will always load from the local storage. However, if we change the service worker sw.js in any way, on the next page load the new version will be downloaded and installed.

this.addEventListener('install', function(event) {
    event.waitUntil(
        caches.open('v1.0.1').then(function(cache) {
            // ...
        })
    );
});

Using service worker updates we can re-download resources, delete old cache, or completely change the service worker logic. You can learn more about the SW Update process from this Google Developers article – here.


7_discoverable_

7. Discoverable

By adding a Web Manifest to our app we can provide various information about it and change the way it is displayed on people’s devices. It allows apps to be saved to the home screen with a custom icon, to be started in a separate browser window, and a lot of other cool stuff.

The Web Manifest takes the form of a simple JSON file:

manifest.json

{
  "name": "Progressive Web App: PhotoBooth",
  "short_name": "PhotoBooth",
  "description": "Simple Progressive Web App for taking selfies.",
  "icons": [{
      "src": "assets/icons/ic-face.png",
      "type": "image/png",
      "sizes": "72x72"
    }, {
      "src": "assets/icons/ic-face-large.png",
      "type": "image/png",
      "sizes": "144x144 256x256" 
    }],
  "start_url": "index.html",
  "display": "standalone",
  "background_color": "#fff",
  "theme_color": "#fff",
  "orientation": "portrait"
}

Most of the properties are self explanatory so we will cover only the more important ones. To see the full Web manifest format and all the available fields go here.

  • Shortname – This is the name our app will have when saved to the home screen.
  • Icons – Array of icons with different resolutions.
  • Display – Defines how the app will be opened. We’ve chosen standalone so when started our photo booth will appear in a full-screen window without any browser navigation or menus. It will also be seen as a separate app in multitasking.

To register the manifest we have to link it to our HTML:

<!-- Web Manifest -->
<link rel="manifest" href="manifest.json">

Safari doesn’t support the Web Manifest standard yet but we can define app-like behavior with this Apple-specific meta tag:

<!-- Meta tag for app-like behaviour in iOS -->
<meta name=”apple-mobile-web-app-capable” content=”yes”>

8_notifications

8. Re-engageable

Push notifications aren’t limited to native apps any more. Thanks to service workers and the Push API, web applications can also send messages to the Android notification bar. Not all apps will benefit from having this feature, but when used properly notifications can really help engage users.

This topic goes beyond the scope of our tutorial, as Push Notifications are quite complicated and deserve a full lesson on their own. If you still want to implement notifications to your web app, here are some of the best learning resources available:

  • Google Developers, Push Notifications: Timely, Relevant, and Precise – here.
  • Google Developers, Push Notifications on the Open Web – here.
  • MDN, Using the Push API – here.
  • Push.js, Library that provides a cleaner API for handling push notifications – here.

9_installable_

9. Installable

By default any website can be manually saved to the home screen using the Add to Home Screen button from the Chrome browser menu. However, it might be rather difficult to make users “install” our app this way, since most people don’t know about that feature at all.

Thankfully, there is a way for your app to prompt users to save it with a simple installation pop-up. To prevent developers from abusing these pop ups, there isn’t any way to programmatically show them. Instead, they will appear on their own when an app fulfills a series of requirements:

  1. There is a valid Web Manifest.
  2. There is a valid Service Worker installed.
  3. The app is served over HTTPS.

We have all of the above covered, so when a user visits our app’s website a couple of times, they will get this prompt:

Add To Homescreen Prompt

Add To Homescreen Prompt

The entire installation process of our app is in this simple prompt. The install happens instantly, and once saved the PhotoBooth will be available to launch from a home screen icon, behaving exactly like a native app.


10_linkable_

10. Linkable

Anyone with a web browser has access to PWA apps and they can be shared simply via their URL. No third party tools are required for finding or installing them.

If an app runs in standalone mode, it’s also advisable to add in-app share buttons, since the browser address bar and menus aren’t visible.


Conclusion

Our PWA is now complete. We can test how well it follows the PWA rules with an official Google-made tool called Lighthouse. It recreates possible scenarios and tests the app thoroughly. Here is what it tells us about the PhotoBooth:

Lighthouse Report

Lighthouse Report

We passed!

If you want to find more PWAs to play with, go to pwa.rocks. They offer a nice collection of games and useful tools, showcasing the great power of Progressive Web Apps.

30 Learning Resources For Mastering Angular 2

30-angular-resources

Angular 2 is a vast and complex framework with a never ending learning curve. To help you grasp more of its many features, we’ve curated a list of 30 free learning resources that cover it all – from the quickstart guide to specific details and best practices.


1_official

Let’s first quickly go over the available guides and tutorials on the official Angular website. There are a bunch of different resources there and we decided it’s a good idea to explain them.

QuickStart (TypeScript version)

Angular2 apps can be written in TypeScript, Dart, or good ol’ vanilla JavaScript. There are separate versions of the official docs for each language, but the TypeScript one is by far most detailed, as this is the recommended technology to use.

This will be the starting point for most beginners to Angular2. It includes setting up a work environment and running a basic Hello World app. Don’t be fooled by its name, you will need a good hour or two to finish this QuickStart.

QuickStart (Vanilla JavaScript version)

A much simpler version of the TypeScript QuickStart. Since it is written for vanilla JavaScript this tutorial doesn’t require a complex work environment and setup, so it goes straight to the framework itself and some of it’s main concepts.

Tour of Heroes

Tour of heroes is a much more detailed tutorial than the QuickStart. It goes through the process of building a Single Page App, step by step, covering many of the must-know Angular2 features. There are TypeScript and Dart versions, but no vanilla JS.

Advanced Documentation

Here the Angular team offers over 15 standalone tutorials, each doing a very in-depth look into an important topic. You can learn about Angular animations, the lifecycle of components, the navigation router, and many other core features.

Cookbook

A collection of code snippets and quick solutions to common challenges. Here you can find a chart of the differences between Angular 1 and 2, a FAQ section on NgModules, and solutions for form validation among other helpful tips and guides.


2_tutorials

Now let’s look at some tutorials and articles written by the community. We’ve tried to include only publications that are fairly new, making them compatible with the changes in recent versions.

Upgrading Apps To Angular 2 Using ngUpgrade

A well-written article that covers everything you need to know about upgrading old Angular 1 apps to the new framework. In it you can see what Angular2 does better, which aspects of an app need the most radical changes, as well as practical code snippets to get the job done.

Router Introduction: Child Routes, Auxiliary Routes, Common Pitfalls

This tutorial focuses on the new 3.0 router component, and explains the whole process needed for configuring it correctly. The author has done a great job explaining what Single Page Apps are, how they work, and how to route them in a robust and secure way.

Ahead-of-Time Compilation

The new Angular2 compiler improves the performance of applications dramatically by taking full advantage of JavaScript Virtual Machines. In this blog post you can learn about Just-in-Time and Ahead-of-Time compilation, their pros and cons, and how to implement them.

Styling Angular 2 Components

A more beginner-oriented lesson looking at different techniques for adding CSS styles to components. It shows you how to use component inline styles, style urls, and template inline styles, and explains the advantages behind each one.

Web Workers In Angular 2

Web workers are great for doing asynchronous tasks that don’t block the UI JavaScript, something very important for Single Page Apps. Here you can learn how to run Angular apps or components as web workers, allowing them to function in the background, independent from the main app thread.

Angular Router: Declarative Lazy Loading

Angular apps tend to get really big, and at some point the source files become too large to be loaded at once. Lazy loading allows us to speed up application load time by splitting it into multiple bundles, and loading them on demand.

Dependency Injection In Angular 2

A deep dive into the greatly improved Angular2 dependency injection system and the different approaches behind the old and new DI. This article also has a second part, that further explains the host-child relationship and the visibility of dependencies.

How does Angular 2 Change Detection Really Work ?

The Angular2 change detection mechanism is much more transparent and easier to reason about than its equivalent in Angular 1. However, there are still situations where you need to know exactly whats going on under hood.

Building an Angular 2 Application for Production

Angular is a very powerful and complex framework, and it’s not surprising that it’s footprint is also quite large. In this blog post you can learn various techniques, such as Tree-shaking and minification, that will drastically reduce the size of your final app.

Taking Advantage Of Observables In Angular 2

Observables in Angular 2 can be used for handling asynch code as an alternative to Promises. They are a vast and complex topic, but this two-part tutorial does a great job of introducing them and showcasing their many use cases.

Communication Between Components & Components Design

An interesting take on design patterns for building Angular components. The article goes through the components of a YouTube music player app and the relationships between them, with lots of code examples and explanations.

Optimizing NgUpgrade Bundle Sizes

NgUpgrade is meant to bridge the gap between Angular 1 and 2 by allowing code from both frameworks to co-exist in the same app. This can greatly increase the size as both versions need to be included. You can learn how to reduce that extra footprint in this quick tip.

Three Ways to Test Angular 2 Components

In this article you will learn three different techniques that you can use to thoroughly test Angular 2 components. They are isolated testing, shallow testing, and integration testing. All three have their strengths and weaknesses and are best applied in certain scenarios.

Protecting Routes Using Guards

Protecting routes is a very common task when building applications, as we want to prevent our users from accessing areas that they’re not allowed to access. Angular 2’s router provides a feature called Guards that tries to solve exactly that problem.

Debugging Angular 2 Applications

This guide gives a comprehensive overview of the various ways you can debug an Angular 2 applications using tools such as the Chrome DevTools, Angular Augury, simple JSON pipe filters, and the console itself.


3_videos

Since we know many developers prefer interactive lessons, here are a couple of places where you can find excellent code walkthroughs and general Angular talks.

Egghead.io

Egghead.io is one of the most popular and recommended sources for learning Angular. Although many of the lessons are for pro members only, there are still lots and lots of awesome free lessons you can watch.

Adventures in Angular

Adventures in Angular is a weekly podcast dedicated to the Angular framework. The panel cover a wide array of topics and it’s probably the best place to get Angular news. The archive contains over 110 episodes, each at least 30 minutes long.

Angular 2 from Scratch

Awesome one-hour-long course covering most of the basics. Although its beginner-oriented there are lots of things everyone can learn from this video in therms of project management and workflow.

Ajden Towfeek

A YouTube channel with lots of screencasts on web development and programming, with a focus on Angular 2 and its ecosystem of related technologies, tools, and languages.

Angular University

Another YouTube channel with a large collection of Angular tutorials, courses, code examples, and quick-tips.


Last but not least, here are some resources that didn’t fit any of the above categories, but can still be essential learning tools for any Angular developer.

Rangle’s Angular 2 Training Book

The only completely free book on Angular 2 that we could find. It covers the most important Angular 2 topics, from getting started with the basic toolchain, to writing applications in a scalable and maintainable manner. You can read it in the web browser or download it as an eBook (PDF, Mobi, ePub).

TypeScript in 30 Minutes

Although you can technically write Angular 2 in vanilla JavaScript or Dart, TypeScript provides by far the best experience with the framework. Using this tutorial you can get started with the language and learn most of it’s important features.

Style Guide

The offical style guide for the framework. Contains a ton of syntax and formatting recommendations, as well as general best practices. It’s very detailed and long, but knowing Angular’s enterprise nature, you’ll probably need to go through it at some point.

Built With Angular 2

Learn from other people’s experiences with the framework by checking out this large collection of open-source applications and experiments, all developed in Angular 2.

Angular 2 Final Q&A

An interview and Q&A with the creators of the framework, right after the release of Angular 2 Final. A great place to hear more about the project and its upcoming features straight from the horses mouth.

Freebie: 5 Beautiful Bootstrap Headers

5-freebie-beautiful-headers

In this post we present to you a collection of five templates for headers and navigation bars. We’ve created them using Bootstrap 3, following all the best practices for working with the framework. The templates are ready to use and easy to incorporate in any existing design.

The Headers

To help you save time, we’ve created five different designs, that you can choose from. They are simple, fully responsive and work great on mobile devices.

Blue Header

Blue Header

Our headers can be used as part of an existing design, or can be customized easily if you have experience with Bootstrap. For some of the templates, we’ve used fonts from Google Fonts, the built-in Glyphicons set, and images from Pexels.com.

Header Nightsky

Header Nightsky

How to use

To use any of the templates from the demo, follow these simple steps:

  1. Grab the zip archive from the Download button near the top of the page and extract it.
  2. Open the .html file for the template you want, copy the code inside and paste it in your project.
  3. The styles are located in separate CSS files for each design. You can find them in the /assets/css/ folder.

Free for Commercial Use

You have all rights to customize and use these templates. They are 100% free and can be implemented in both personal and commercial projects, no attribution required (our license page). Enjoy!

15 Interesting JavaScript and CSS Libraries for September 2016

interesting-libraries-august-2016

Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a handpicked collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.

The list for September 2016 contains a wide variety of different libraries including an excellent drag-and-drop file uploader, a CSS reset, a CSS minifier, background animations, and much more!


Dropzone

Dropzone

Very polished JavaScript library that can turn any HTML element into a drag and drop zone for file uploads. Features include thumbnail previews for image uploads, multiple files at once, a progress tracker, support for large files, and many others. Highly customizable, no dependencies.


ReactMdl

React-MDL

Google’s Material Design Lite (MDL) is one of the most beautiful CSS frameworks available. Combine that with Facebooks’s hugely successful React JavaScript library and the result is React-MDL, a library that offers a huge collection of React components styled in material design fashion.


Postmate

Postmate

Postmate is a wrapper of the Window.postMessage() method, allowing pages to speak to iFrames inside them. The library provides a simple promise-based API with which developers can securely access various data about the iFrame and emit events to it from the parent page.


Particles

Particles

A very lightweight and easy to use library for creating animated backgrounds. It consists of a single 2kb .js file and only one method – Particles.init({options});, taking an object with a fair amount of customizations. There are two animations available: single particles, or connected particles forming beautiful constellations.


Recharts

Recharts

Charts library built on top of React and D3. Graphs can be created via a simple XML-like syntax, with many of the important options set directly as attributes. The library also offers a rich examples catalog with more than 50 ready-to-use components, including various Line, Bar, Pie and other types of charts.


Shephard

Shepherd

Shepherd let’s you take users on a tour of your website or app. With a simple step-based API, you can move the focus successively from one section to another. The HTML element you want to emphasize on is highlight and a text bubble pops up with a title, description and dialog buttons.


Waud

Waud

Did you know that apart from the HTML <audio>> interface there is also a complex JavaScript Web Audio API, offering a ton of advanced sound manipulations. Waud works as a 2-in-1 solution, allowing you to access the JavaScrtip API where it’s available, and the HTML API as a fallback.


Grade

Grade

Grade.js takes the two most dominant colors in an image and uses them to create elegant gradients. This effect can be used to make cool image frames or set a matching background to your entire page. The library is very small and has no dependencies whatsoever.


Rainyday

Rainyday

Add calming rain animations to your web pages using this small JavaScript library. Under the hood, Rainyday uses a HTML <canvas> element and it’s API to draw a realistic glass-like surface with random raindrops trickling down.


CSSnano

Instead of simply removing whitespace when minifying style sheets, CSSnano also does several other optimizations such as merging properties into their shorthand equivalents, removing comments, shortening color values, and many many more. CSSnano is compatible with a number of platforms, including Node.js, grunt, gulp, webpack, and the Atom text editor.


Multirange

Multirange

JavaScript and CSS library for creating input sliders with two handles, allowing users to pick intervals ranging between two numbers (e.g price between 100$ and 500$). On browsers where this behavior cannot be achieved, the library automatically goes back to using two separate sliders.


Minireset

Minireset

Minireset is a very simple CSS reset library that normalizes only the most important CSS properties without any extra sugar. It resets font-sizes, margins and paddings, sets box-sizing to border-box on all elements, and a few other useful defaults. Since it’s so small, you can easily modify this library if you need to change some of the values.


Cesium

Cesium

WebGL based JavaScript library for creating high-resolution 3D globes and 2D maps. It supports different map providers, weather simulations, and a ton of other complex features. Their Demos page has a big collection of community projects showcasing what Cesium is capable of, including a 3D map of all the building in New York and projects by NASA.


In view

In-view

Library that tracks elements on the page and reacts when they are about to leave or enter the viewport. The library has no external dependencies and is really easy to use with a simple callback syntax:

inView('.someSelector')
    .on('enter', doSomething)
    .on('exit', el => {
        el.style.opacity = 0.5;
    });

Papa Parse

Papa Parse

Papa Parse is a powerful client-side CSV parser. It is full of awesome features like conversion to JSON, support for strings, local files or URls, an asynchronous mode, a quick mode, and much more. This library has no dependencies and can work equally well with vanilla JavaScript or jQuery.

20 Protips For Writing Modern CSS

20-protips-for-writing-modern-css

In this post we want to share with you a collection of 20 useful conventions and best practices that are recommend by the CSS community. Some are tailored more towards beginners, and some are a bit advanced, but we hope everyone will find a cool trick they didn’t know about. Enjoy!


1. Beware of Margin Collapse

Unlike most other properties, vertical margins collapse when they meet. What this means is that when the bottom margin of one element touches the top margin of another, only the bigger of the two survives. Here is a simple example:

(Play with our code editor on Tutorialzine.com)

Instead of 70px between the red and blue square we have only 40px, the margin of the blue square isn’t taken into consideration at all. There are ways to battle this behavior, but it’s better to just work with it and use margins only going in one direction, preferably margin-bottom.


2. Use Flexbox For Layouts

The flexbox model exists for a reason. Floats and inline-blocks work, but they are all essentially tools for styling documents, not websites. Flexbox on the other hand is specifically designed to make it easy to create any layout exactly the way it was envisioned.

The set of properties that come with the flexbox model give developers lots of flexibility (no pun intended), and once you get used to them, doing any responsive layout is a piece of cake. Browser support nowadays is almost perfect, so there shouldn’t be anything stopping you from going full flexbox.

.container {
    display: flex;
    /* Don't forget to add prefixes for Safari */
    display: -webkit-flex;
}

We’ve featured a number of tips and trick with flexbox before on Tutorialzine. You can check them out here: 5 Flexbox Techniques You Need to Know About.


3. Do a CSS Reset

Although the situation has greatly improved over the years, there is still plenty of variation in the way different browsers behave. The best way to resolve this issue is to apply a CSS reset that sets universal default values for all elements, allowing you to start working on a clean style sheet that will yield the same result everywhere.

There are libraries like normalize.css, minireset, and ress that do this very well, correcting all imaginable browser inconsistencies. If you don’t want to use a library, you can do a very basic CSS reset yourself with these styles:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

This may seem a bit harsh, but nullifying margins and paddings actually makes laying out elements much easier as there are no default spaces between them to take into account. The box-sizing: border-box; property is another good default, which we will talk about more in our next tip.


4. Border-box for All

Most beginners don’t know about the box-sizing property but it’s actually quite important. The best way to understand what it does is to look at it’s two possible values:

  • content-box (default) – When we set a width/hight to an element, that’s just the size for it’s content. All paddings and borders are on top of that. E.g. a <div> has a width of 100 and padding of 10, our element will take up 120 pixels (100 + 2*10).
  • border-box – The padding and border are included in the width/height. A <div> with width: 100px; and box-sizing: border-box; will be 100 pixels wide no matter what paddings or borders are added.

Setting border-box to all elements makes it so much easier to style everything, since you don’t have to do math all the time.


5. Images as Background

When adding images to your design, especially if it’s going to be responsive, use a <div> tag with the background CSS property instead of <img> elements.

This may seem like more work for nothing, but it actually makes it much easier to style images properly, keeping their original size and aspect-ratio, thanks to background-sizebackground-position, and other properties.

(Play with our code editor on Tutorialzine.com)

A drawback of this technique is that the web accessibility of your page will take a slight hit, as images won’t be crawled properly by screen readers and search engines. This issue can be resolved by the awesome object-fit but it doesn’t have full browser support yet.


6. Better Table Borders

Tables in HTML are not fun. They are quirky, almost impossible to be made responsive, and overall difficult to style. For example, if you want to add simple borders to your table and its cells, you will most probably end up with this:

(Play with our code editor on Tutorialzine.com)

As you can see, there are quite a lot of repeating borders everywhere and it doesn’t look good. Here is a quick, hack-free way to remove all doubling borders: simply add border-collapse: collapse; to the table.

(Play with our code editor on Tutorialzine.com)

Much better!


7. Write Better Comments

CSS might not be a programming language but it’s code still needs to be documented. Some simple comments are all it takes to organize a style sheet and make it more accessible to your colleagues or your future self.

For larger sections of the CSS such as major components or media-queries, use a stylized comment and leave a couple of new lines after:

/*---------------
    #Header
---------------*/
header { }

header nav { }




/*---------------
    #Slideshow
---------------*/
.slideshow { }

Details in the design or less important components can be marked with a single-line comment.

/*   Footer Buttons   */
.footer button { }

.footer button:hover { }

Also, remember that CSS doesn’t have single line // comments, so when commenting something out you still need to use the /* */ syntax.

/*  Do  */
p {
    padding: 15px;
    /*border: 1px solid #222;*/
}

/*  Don't  */
p {
    padding: 15px;
    // border: 1px solid #222;  
}

8. Everyone Loves kebab-case

Class names and ids should be written with a hyphen (-) when they contain more then one word. CSS is case-insensitive so camelCase is not an option. A long time ago, underscores used to not be supported (they are now) which made dashes the default convention.

/*  Do     */
.footer-column-left { }

/*  Don't  */
.footerColumnLeft { }

.footer_column_left { }

When it comes to naming, you may also consider BEM, which follows a set of principles that add consistency and provide a component-based approach to development. You can read more about it in this excellent CSS-Tricks article.


9. Don’t Repeat Yourself

The values for most CSS properties are inherited from the element one level up in the DOM tree, hence the name Cascading Style Sheets. Let’s take the font property for example – it is almost always inherited from the parent, you don’t have to set it again separately for each and every element on the page.

Simply add the font styles that will be most prevalent in your design to the <html> or <body> element and let them trickle down. Here are some good defaults:

html {
    font: normal 16px/1.4 sans-serif;
}

Later on you can always change the styles for any given element. What we are saying is just to avoid repetition and use inheritance as much as possible.


10. CSS Animations with transform

Don’t animate elements by directly changing their width and height, or left/top/bottom/right. It’s preferred to use the transform() property as it provides smoother transitions and makes your intentions easier to understand when reading the code.

Here’s an example. We want to animate a ball and slide it out to the right. Instead of changing the value of left, it’s better to use translateX():

.ball {
    left: 50px;
    transition: 0.4s ease-out;
}

/* Not Cool*/
.ball.slide-out {
    left: 500px;
}

/* Cool*/
.ball.slide-out {
    transform: translateX(450px);
}

Transform, as well as all of its many functions (translate, rotate, scale, etc.) have almost universal browser compatibility and can be used freely.


11. Don’t DIY, Use A Library

The CSS community is enormous and there are constantly new libraries coming out. They serve all kinds of purposes, from tiny snippets to full-blown frameworks for building responsive apps. Most of them are open-source too.

Next time you are faced with a CSS problem, before you try to tackle it with all your might and hacks, check if there isn’t already a solution available on GitHub or CodePen.


12. Keep Selector Specificity Low

Not all CSS selectors are created equal. When novice developers write CSS they usually expect that selectors will always overwrite everything above them. However, this isn’t always the case, as we’ve illustrated in the following example:

(Play with our code editor on Tutorialzine.com)


We want to be able to add the .active class to any button and make it red. This won’t work here because our button has it’s background-color set with an ID selector, which has a higher selector specificity. The rule goes like this:

ID (#id) > Class (.class) > Type (e.g. header)

Specifity also stacks so a#button.active ranks higher than a#button. Using selectors with high specificity will cause you to constantly trump old selectors with even higher ones and eventually result in !important. This leads us into our next tip:


13. Don’t Use !important

Seriously, don’t. What is a quick fix now may end up causing lots of rewrites in the future. Instead, find why your CSS selector isn’t working and change it.

The only time when it’s acceptable to !important CSS rules is when you want to override inline styles from the HTML, which in itself is another bad practice to be avoided.


14. Caps Lock For Meaning, text-transform For Style

In the HTML, write upper case letters when you want to use them for their intended semantic meaning, like when you want to emphasize the importance of a word.

<h3>Employees MUST wear a helmet!</h3>

If you need to have some text in all caps for stylistic reasons, write the text normally in the HTML, and transform it to all-caps with CSS. It will look the same but your content will make more sense if taken out of context.

<div class="movie-poster">Star Wars: The Force Awakens</div>
.movie-poster {
    text-transform: uppercase;
}

The same goes for lowercasing and capitalizing strings – text-transform handles those just as well.


15. Em, Rem, and Pixel

There is a lot of debate whether people should use em, rem, or px values for setting the size of elements and text. Truth is, all three options are viable and have their pros and cons.

All developers and projects are different, so there can’t be any strict rules on when to use which. Here are, however, some tips and general good practices for each unit:

  • em – The value of 1 em is relative to the font-size of the direct parent. Often used in media-queries, em is great for responsiveness, but it can get really confusing tracing back the exchange rate of ems to pixels for each element (1.25em of 1.4em of 16px = ?).
  • rem – Relative to the font-size of the <html> element, rem makes it really easy to scale all headings and paragraphs on the page. Leaving the <html> with it’s default fontsize and setting everything else with rem is a great approach accessibility-wise.
  • px – Pixels give you the most precision but don’t offer any scaling when used in responsive designs. They are reliable, easy to understand, and present a good visual connection between value and actual result (15px is close, maybe just a pixel or two more).

Bottom line is, don’t be afraid to experiment, try them all and see what you like best. Sometimes em and rem can save you a lot of work, especially when building responsive pages.


16. Use a Preprocessor on Large Projects

You’ve heard about them – Sass, Less, PostCSS, Stylus. Preprocessors are the next step in the evolution of CSS. They provide features such as variables, CSS functions, selector nesting, and lots of other cool stuff, making CSS code easier to manage, especially in large projects.

For a quick example, here is a snippet of using CSS variables and functions directly in a style sheet with Sass:

$accent-color: #2196F3;

a {
    padding: 10px 15px;
    background-color: $accent-color;
}

a:hover {
    background-color: darken($accent-color,10%);
}

The only real drawback of preprocessors is that they need compiling to vanilla CSS, but if you are already using a build script in your project this shouldn’t be too much of a hassle.

To learn more about preprocessors, check out our tutorials on two of the most popular systems – Sass and Less.


17. Autoprefixers For Better Compatibility

Writing browser-specific prefixes is one of the most annoying things in CSS. They aren’t consistent, you never know exactly which ones you need, and if you do the actual process of placing them in your style sheet is a boring nightmare.

Thankfully, there are tools that automatically do that for you and will even let you decide which browsers you need supported:


18. Use Minified Code In Production

To improve the page load of your websites and apps you should always use minified resources. The minified version of your code will have all whitespace and repetitions removed, reducing the total file size. Of course, this process also makes style sheets completely unreadable so always keep a .min version for production and a regular version for development.

There are many different ways to minify CSS code:

Depending on your workflow, any of the above options can be used, but it’s recommended to automate the process in one way or another.


19. Caniuse Is Your Friend

The different web browsers still have lots of compatibility inconsistencies. Use canisue or a similar service to check if what you are using is widely supported, if it needs prefixes, or if it causes any bugs in a certain platform.

Just checking caniuse isn’t enough though. You also need to do tests (either manually or through a service) as sometimes layouts break for no obvious reasons. Knowing the preferred browsers of your userbase also helps a lot, since you can see where good support is most crucial.


20. Validate

Validating CSS might not be as important as validating HTML or JavaScript code, but running your code through a CSS Linter can still be very helpful. It will tell you if you’ve made any mistakes, warn you about bad practices, and give you general tips for improving the code.

Just like minfiers and autoprefixers, there are plenty of free validators available:

Quick Tip: Working with the JavaScript Battery API

working-with-js-battery-api

In this tutorial we’re going to show you how to use the JavaScript Battery API to improve the user experience for people in desperate need of a charger. We’ll look at the Battery API itself, as well as some techniques for getting the most out of every drop of the most precious of resources!

Monitoring Battery Life

The JavaScript Battery Status API talks to the device’s hardware and gives us accurate data about the system’s charging state. It can be accessed via the promise based navigator.getBattery() interface, or directly via the navigtator.battery object, although the second option is now deprecated and overall not recommended.

Some browsers lack support for the Battery API (you guessed it, they are Safari and IE), so a quick support check can go a long way in terms of debugging:

if(navigator.getBattery){
    // Battery API available.
    // Rest of code goes here.
}
else{
    // No battery API support.
    // Handle error accordingly.
}

Once we are sure that your user can access the API, grabbing the needed information is really easy:

navigator.getBattery()
    .then(function(batteryManager) {
        
        // Get current charge in percentages.
        var level = batteryManager.level * 100;

    })
    .catch(function(e) {
        console.error(e);
    });

The getBattery() method returns a promise and resolves with a BatteryManager object containing various information about the current status of the hardware:

  • batteryManager.level – The current charge, returns a float between 0 and 1.
  • batteryManager.charging – Is the device on power supply or not, returns true/false.
  • batteryManager.chargingTime – Remaining time in seconds till completely charged.
  • batteryManager.dischargingTime – Remaining time until battery is dead.

It also provides events that can be used to monitor changes in any of the above properties.

  • BatteryManager.onlevelchange
  • BatteryManager.onchargingchange
  • BatteryManager.onchargingtimechange
  • BatteryManager.ondischargingtimechange

Combining the raw data with the event listeners, we can easily set up a watcher for low battery levels:

navigator.getBattery()
    .then(function(battery) {    
        battery.onlevelchange = function() {

            if(battery.level<30 && !battery.charging) {
                powerSavingMode = true;
            }

        }
    });

Once we know how much juice is left in the device we can adapt the app and turn on a power saving mode if its needed.

Preserving energy

The biggest battery drainer of all components is the screen. This is especially true on smartphones and tablets where often CPUs are energy preserving, while the screens have super-ultra-full-QHD resolution with the brightness of two suns.

The first and foremost thing we can do to address this issue is limit the amount of light the screen is emitting. JavaScript doesn’t have the authority to control the brightness directly, but we can do so by changing the color pallet to a darker theme.

dark-theme

Dark colors need less energy to be displayed, with more than 50% reduction on AMOLED screens.

The next thing we can do is limit the amount and size of requests to external resources. The biggest drainers here are high-res images, advertisements, and large JavaScript libraries, as they need a lot of bandwidth to download.

Here we have two options – load an alternative, more optimized resource with a smaller footprint, or, fully remove the image/advert if it doesn’t portray any essential information. Any background images, videos or animations should be removed.

removed-ads

Removing non-essential elements from the page makes the vital content easier to reach when in a hurry.

The last battery-drainer we will talk about is JavaScript. We already mentioned that download large libraries and frameworks is bad enough, but the actual parsing and execution of JS block can also lead to unnecessary spending.

JavaScript animations that cause constant redrawing of elements on the screen, listening for notifications form the server, and multiple AJAX requests can all drain the battery just a tiny bit, but it quickly adds up. According to this study, the JavaScript code consumes ~7% of Yahoo’s total rendering energy, ~17% on Amazon, and more than 20% on YouTube.

App With Powersaving Mode

We have showcased some of the above concepts in a simple demo app. It consists of a static website which reacts to the amount of battery left. When it gets below 30% the app goes into PowerSaving and turns darker, stops all animations, and removes all ads.

For demonstration purposes our app works with a virtual battery to enable quick toggling between fully charged and almost dead. It does not contain much code for working with the Battery API itself.

Our Demo App

Our Demo App

You can get the full code for the demo from the Download button near the top of the article. It’s written in Vue.js for easier data monitoring and has lots of comments to guide you through all that is happening.

Further Reading

If you want to find out more about the Battery Status API or about ways your precious battery is running down the drain, check out these excellent resources:

Battery Status API on MDN – here
The BatteryManager interface on MDN – here
5 Ways to Improve Battery Life in Your App – here
Who Killed My Battery: Analyzing Mobile Browser Energy Consumption – here

15 Interesting JavaScript and CSS Libraries for August 2016

interesting-libraries-august-2016

Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a handpicked collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.

Our libraries for August 2016 follow modern conventions and have as little dependencies as possible, modular architectures, and simple APIs to ease the headaches caused by JavaScript fatigue.


Aquarelle

Library for creating magnificent watercolor effects. You can use Aqaurelle to add a fade-in animation to images and make them look as they are being painted on by smudged drops of paint. Built on top of the 3D canvas library Three.js.


SuperEmbed.js

SuperEmbed is a no-dependencies library that detects embeded videos on the page and makes them responsive without messing up their original aspect ratio. It works with many popular media sources including YouTube, Vimeo, Twitch, Vine, and many others.


Vuikit

A Vue.js implementation of the popular UIkit front-end framework. The developers behind Vuikit have recreated most of UIkit’s components and made them work naturally with Vue and it’s data driven logic so that you can now build responsive Vue.js apps with little to no effort.


Staticman

With Staticman you can add dynamic content to your static Jekyll websites. If your site is hosted on GibHub pages you can implement a comment section or any other user content form, which when submitted will push the data from the form as a file to your repository. Staticman also gives the option to push new content to a separate branch, so that it won’t show up on the website until the pull request is approved.


Choices.js

Library for creating better form fields. It offers many improvements over the default input elements like multiple entries per field, prettier select boxes, and linked form fields. Choices is written in vanilla JavaScript in it’s entirety so it’s very lightweight.


Flatpickr

You may have heard of Flatpickr as it is one of the most widely used date and time pickers available. We are including it in our list because it’s authors have recently announced version 2.0, introducing lots of new features like jQuery compatibility, improved performance, SVG icons, and more.


Uppy

JavaScript file uploader that can fetch files from services such as Dropbox and Instagram, as well as from a local hard drive. It has support for resumable uploads and is separated into opt-in modules to keep it lightweight. Uppy is still in the early stages of development but you can already tell it’s a very promising project.


Skippr

Skippr is a jQuery slideshow plugin, and from all the jQuery slideshow plugins that we’ve seen, this one is probably the easiest one to use. Installation is simple, the requried HTML markup is clean, and the jQuery method takes a straightforward options object.


Howler.js

Modern library for working with audio in the web. Howler is modular, dependency-free, and fully supported in all mainstream browsers. It provides developers with the entire set of tools and controls needed for implementing sound into a website or app.


Overhang.js

Overhang.js adds stylish and well-animated pop-up notifications on top of any DOM element of your choice. This tiny jQuery plugin offers a number of modal types that can be easily implemented as a replacement for the default alert, prompt and confirm dialogs.


Baffle.js

Baffle is a tiny JavaScript library for concealing text from the screen. The information you want to hide can be camouflaged with rectangular blocks, random symbols, or any other strings. The library provides all the methods you may ever need as well as some animation options.


Jets

Jets is a clever library that utilizes CSS selectors to do blazing fast searches. Instead of hiding non-matching search results one-by-one with individual attributes, Jets creates a single <style> tag on the parent container with a dynamic CSS selector that filters out elements based on their content.


Intercooler.js

Intercooler.js allows developers to quickly implement AJAX directly in the HTML. By adding a specific HTML attribute to your links and buttons you can enable them to send GET, POST, or other requests to a URL. The data returned from the server can also be accessed through HTML attributes.


SecLists

A gigantic collection of sample data for security assessments. The data comes in lists calssified in various types (usernames, passwords, URLs, etc.), with each type containing dozens of lists full of dummy entries or actual common passwords and usernames that people use (e.g. 500-worst-passwords.txt or top_1000_usa_malenames_english.txt).


Jumpsuit

Efficient React/Redux framework that brings together the best standards in JavaScript development and allows you to get a head start on your apps. Jumpsuit gives you a helpful CLI that simplifies setting up all the libraries and tasks needed for working with React.

Building Your First App With Vue.js

building-your-first-app-with-vuejs

Today we’re going to exercise our Vue.js skills by building a simple app for browsing reddit posts. We’re going to construct the whole thing from scratch to demonstrate just how easy it is to create user interfaces with a framework like Vue.

This tutorial requires you to have at least some basic knowledge of JavaScript and Vue.js. If you aren’t familiar with Vue.js at all, we advise you to go and check out our article 5 Practical Examples For Learning Vue.js, where we show many of the core concepts with practical code snippets.

The App

What we want from our application is simply to fetch the feed from a number of subbreddits and display them. Here is what the end result will look like:

vue-app

Our Vue.js App

We will have six separate subreddit feeds showing five posts each. The posts have links to the content and discussion on reddit, as well as some other details. For the sake of simplicity we have omitted features such as adding/removing subreddits and doing searches, but they can be easily added on top of the existing app.

Setting Up The Workspace

You can download the full source code for the reddit browser app from the Download button near the top of the article. Before we actually look at the code, let’s make sure that everything is setup properly. Here is an overview of the file structure:

Our project's folder

Our project’s folder

As you can see it’s quite basic: we just have one HTML file, one CSS file, a script.js containing our JavaScript code. We’ve also added local copies of the Vue.js and Vue-resource libraries, but you can use a CDN if you prefer.

Thankfully, Vue.js doesn’t require any special configuration, so it should work straight out of the box. To start the app we just have to create a global Vue instance:

new Vue({
    el: 'body'
});

The only thing left to do now is start a local web server to enable cross-origin AJAX requests to the reddit API. The easiest way to do this on OS X/Ubuntu is by running the following command from the project’s directory:

python -m SimpleHTTPServer 8080

If everything is done properly our project should be available at localhost:8080.

Creating Custom Components

Our app is going to need two reusable components – one for the Posts, and another for Subreddits. The two components will be in a Child-Parent relationship, meaning that the Subreddit component will have multiple Posts nested in it.

Components Structure

Components Hierarchy

Let’s start with the Subreddit component, and more specifically it’s JavaScript:

// Parent | Subreddit component containing a list of 'post' components. 
var subreddit = Vue.component('subreddit',{
    template: '#subreddit',
    props: ['name'],

    data: function () {
        return { posts: [] }
    },

    created: function(){
        this.$http.get("https://www.reddit.com/r/"+ this.name +"/top.json?limit=5")
        .then(function(resp){
            this.posts=resp.data.data.children;
        });
    }
});

Here we define the new component under the name subreddit. In props we provide an array with all the parameters our component can receive – in this case it is just the name of the subbreddit we want to browse. Now if we want to add a subreddit block to the HTML we will use this markup:

<subreddit name="food"></subreddit>

The data property defines what variables are needed for each instance of the component and their default values. We will start with an empty posts array, and populate it in the created method. When a <subreddit> tag is created, Vue will take its name property, make a call to the reddit API to fetch the top 5 posts from the subreddit with that name, and save them in this.posts. For the HTTP requests we’ve used the vue-resource library instead of jQuery, since it is way tinier and automatically binds the correct context for this.

After we’ve acquired everything we need in the model, Vue.js will automatically render our Subreddit components. The actual view that the user sees is defined in a template in index.html:

<template id="subreddit">

    <div class="subreddit">
        <h2>{{ name | uppercase }}</h2>

        <ul class="item-list">
            <li v-for="obj in posts">
                <post :item="obj"></post>
            </li>
        </ul>
    </div>

</template>

Personally, I like to wrap all the elements of a component in a div container. This makes them easier to style and also seems more semantic (to me at least). Inside that container we have a title (the uppercase filter comes built-in with Vue) and an unordered list iterating over the elements returned from the reddit API call.

If you look closely at the HTML, you’ll also notice we are using a <post> tag. This isn’t some new fancy HTML element – it’s our child component!

// Child | Componenet represiting a single post.
var post = Vue.component('post', {
    template: "#post",
    props: ['item']
});

Post components will expect a object called item containing all of the information about a single post on reddit – things like title, URLs, number of comments, etc. As we saw earlier, this is done in a v-for loop inside the Subreddit (parent) component:

<li v-for="obj in posts">
    <post :item="obj"></post>
</li>

The colon prefixing :item="obj" is very important. It tells Vue that we are proving a JavaScript object called obj (as opposed to the string "obj"), allowing us to pass the data from the v-for.

Now that we have all the needed properties for a post, we can display them. The template looks scary at first, but really isn’t:

<template id="post">

    <div class="post">
        <a   :href="item.data.url" :style="item.data.thumbnail | setAsBackground" 
             target="_blank" class="thumbnail"></a>

        <div class="details">
            <a :href="item.data.url" :title="item.data.title" target="_blank" class="title">
                {{ item.data.title | truncate}}
            </a>          
            
            <div class="action-buttons">
                <a href="http://reddit.com{{ item.data.permalink }}" title="Vote">
                    <i class="material-icons">thumbs_up_down</i>
                    {{item.data.score}}
                </a>

                <a href="http://reddit.com{{ item.data.permalink }}" title="Go to discussion">
                    <i class="material-icons">forum</i>
                    {{item.data.num_comments}}
                </a>
            </div>
        </div>
    </div>
    
</template>

The only thing worth mentioning here is the use of the setAsBackground and truncate filters. In contrast to the uppercase filter we used earlier, they don’t come bundled with Vue and we had to make them ourselves.

Creating Custom Filters

Defining filters is quite easy. The Vue.filter() method provides us with the incoming string data, which we can transform whatever way we want and then simply return.

The first filter we’ll need takes the preview image for a post and creates a CSS rule setting it as background. We use this to set the inline styles with less effort.

It takes one parameter: the URL for the image. If that’s not available a placeholder image is shown instead.

// Filter that takes an image url and creates a CSS style.
Vue.filter('setAsBackground', function(value) {
    if(value && value!='self' && value!='nsfw') {
        return 'background-image: url(' + value + ')';  
    }
    else {
        return 'background-image: url(assets/img/placeholder.png)';   
    }
});

Our other filter takes strings and truncates them if they are too long. This is applied to the post titles, which often are way too lengthy for the design we had in mind.

// Filter for cutting off strings that are too long.
Vue.filter('truncate', function(value) {
    var length = 60;

    if(value.length <= length) {
        return value;
    }
    else {
        return value.substring(0, length) + '...';            
    }
});

The Full Code

Below we’ve listed all of the files for the app, so that you can look through the full code and get a better idea how the whole thing works.

/*-----------------
    Components 
-----------------*/

// Parent | Subreddit component containing a list of 'post' components. 
var subreddit = Vue.component('subreddit',{
    template: '#subreddit',
    props: ['name'],

    data: function () {
        return { posts: [] }
    },

    created: function(){
        this.$http.get("https://www.reddit.com/r/"+ this.name +"/top.json?limit=3")
        .then(function(resp){
            this.posts=resp.data.data.children;
        });
    }
});


// Child | Componenet represiting a single post.
var post = Vue.component('post', {
    template: "#post",
    props: ['item']
});


/*-----------------
   Custom filters 
-----------------*/

// Filter for cutting off strings that are too long.
Vue.filter('truncate', function(value) {
    var length = 60;

    if(value.length <= length) {
        return value;
    }
    else {
        return value.substring(0, length) + '...';            
    }
});


// Filter that takes an image url and creates a CSS style.
Vue.filter('setAsBackground', function(value) {
    if(value && value!='self' && value!='nsfw') {
        return 'background-image: url(' + value + ')';  
    }
    else {
        return 'background-image: url(assets/img/placeholder.png)';   
    }
});


/*-----------------
   Initialize app 
-----------------*/

new Vue({
    el: 'body'
});
<!DOCTYPE html>
<html>
<head>
    <title>Your First App With Vue.js</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="assets/css/styles.css">
</head>
<body>
    <div class="container">
        <subreddit name="aww"></subreddit>
        <subreddit name="space"></subreddit>
        <subreddit name="gifs"></subreddit>
        <subreddit name="food"></subreddit>
        <subreddit name="comics"></subreddit>
        <subreddit name="sports"></subreddit>
    </div>


    <template id="subreddit">
        <div class="subreddit">
            <h2>{{ name | uppercase }}</h2>
            <ul class="item-list">
                <li v-for="obj in posts">
                    <post :item="obj"></post>
                </li>
            </ul>
        </div>
    </template>

    <template id="post">
        <div class="post">
            <a   :href="item.data.url" :style="item.data.thumbnail | setAsBackground" 
                 target="_blank" class="thumbnail"></a>
            <div class="details">
                <a :href="item.data.url" :title="item.data.title" target="_blank" class="title">
                    {{ item.data.title | truncate}}
                </a>          
                
                <div class="action-buttons">
                    <a href="http://reddit.com{{ item.data.permalink }}" title="Vote">
                        <i class="material-icons">thumbs_up_down</i>
                        {{item.data.score}}
                    </a>

                    <a href="http://reddit.com{{ item.data.permalink }}" title="Go to discussion">
                        <i class="material-icons">forum</i>
                        {{item.data.num_comments}}
                    </a>
                </div>
            </div>
        </div>       
    </template>

    <script src="assets/js/vue.js"></script>
    <script src="assets/js/vue-resource.min.js"></script>
    <script src="assets/js/script.js"></script>
</body>
</html>
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

a{
    text-decoration: none;
}

a:hover{
    text-decoration: underline;
}

html{
    font: normal 16px sans-serif;
    color: #333;
    background-color: #f9f9f9;
}

.container{
    padding: 27px 20px;
    margin: 30px auto 50px;
    max-width: 1250px;
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    background-color: #fff;
    box-shadow: 0 0 1px #ccc;
}

/* Subreddit component */

.subreddit{
    flex: 0 0 33%;
    min-width: 400px;
    padding: 20px 42px;
}

.subreddit h2{
    font-size: 18px;
    margin-bottom: 10px;
}

.subreddit .item-list{
    border-top: 1px solid #bec9d0;
    padding-top: 20px;
    list-style: none;
}

.subreddit .item-list li{
    margin-bottom: 17px;
}

/* Post component */

.post{
    display: flex;
}

.post .thumbnail{
    display: block;
    flex: 0 0 60px;
    height: 60px;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    margin-right: 10px;
    border-radius: 4px;
    margin-right: 12px;
}

.post .details{
    display: flex;
    flex-direction: column;
}

.post .details .title{
    font-size: 15px;
    margin-bottom: 3px;
    color: #04477b;
}

.post .details .title:visited{
    color: purple;
}

.post .details .action-buttons a{
    font-size: 11px;
    margin-right: 4px;
    display: inline-block;
    color: #666;
}

.post .details .action-buttons i{
    font-size: 10px;
    margin-right: 1px;
}

@media(max-width: 1250px){

    .container{
        justify-content: center;
        margin: 30px 30px 50px 30px;
    }
}

@media(max-width: 500px){

    .subreddit{
        min-width: 300px;
        padding: 20px 15px;
    }
}

Note that after creating our two components, the entire app interface comes down to:

<div class="container">
    <subreddit name="aww"></subreddit>
    <subreddit name="space"></subreddit>
    <subreddit name="gifs"></subreddit>
    <subreddit name="food"></subreddit>
    <subreddit name="comics"></subreddit>
    <subreddit name="sports"></subreddit>
</div>

The JavaScript file isn’t too large either and this is one of my favorite things about Vue. It does so much of the work for us that in the end we are left with a very clean and comprehensive piece of code.

Further Reading

The main focus of this tutorial was to show the process of building a simple Vue.js app. To keep it short we haven’t stopped to explain every tiny syntax peculiarity, but worry not! There are many awesome resources where you can learn the basics:

  • The official Vue.js starting guide and docs – here.
  • Excellent video series from Laracasts – here.
  • Our very own article: 5 Practical Examples For Learning Vue.js – here.

This concludes our Vue.js tutorial! We hope that you’ve had lots of fun with it and that you’ve learned a thing or two. If you have any suggestions or questions, feel free to leave a message in the comment section below :)

20 Awesome PHP Libraries For Summer 2016

20-php-libraries

Initially released in 1995, the PHP language is now of legal drinking age, but this doesn’t stop it from still being one of the most popular languages out there, and the first choice of many back-end developers.

The PHP community on GitHub is also one of the biggest and most active, with new awesome projects coming out constantly. Here are our picks for the 20 most useful and interesting open-source PHP libraries that you should check out – 2016 edition!


Monolog

With Monolog you can create advanced logging systems by sending your PHP logs to files, sockets, databases, inboxes or other web services. The library has over 50 handlers for various utilities and can be integrated into frameworks such as Laravel, Symfony2 and Slim.

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log
$log->warning('Foo');
$log->error('Bar');

PHPExcel

A set of PHP classes that allow developers to easily implement spreadsheet editing in their apps. The library can read and write spreadsheet documents in a number of popular formats including Excel (both .xls and .xlsx), OpenDocument (.ods), and CSV to name a few.

include 'PHPExcel/IOFactory.php';

$inputFileName = './sampleData/example1.xls';

echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory';
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);

$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);

PHP-ML

An interesting library for experimenting with Machine Learning, PHP-ML gives you an easy to use API for training your bot and making it do predictions based on input data. It offers a variety of different algorithms for pattern recognition and complex statistics calculations.

use Phpml\Classification\KNearestNeighbors;

$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
$labels = ['a', 'a', 'a', 'b', 'b', 'b'];

$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);

$classifier->predict([3, 2]);
// returns 'b' as the [3, 2] point is closer to the points in group b

Opauth

Library for enabling users to authenticate themselves via their account in social networks or other services. Of course all the big names are available: Google, Facebook, Twitter, Github, Instagram, LinkedIn. Opauth is supported by many PHP frameworks so it can be easily integrated in most PHP apps.

'Strategy' => array(  
    // Define strategies here.

    'Facebook' => array(
        'app_id' => 'YOUR APP ID',
        'app_secret' => 'YOUR APP SECRET'
    ),
);

Whoops

Whoops greatly improves the debugging experience in PHP by displaying a detailed error page when something breaks in an app. This error page gives us the full stack trace showing the specific files and snippets of code that caused the exception, all syntax-highlighted and colorful. The Laravel framework comes with Whoops built-in.

$whoops = new \Whoops\Run;
$whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
$whoops->register();
// That's it!

FastCache

Implementing this caching system in your PHP apps is guaranteed to make them load way quicker by reducing the amount of queries sent to the database. Instead of executing every DB query, FastCache sends only the unique ones, saves them as cache, and then serves them from there for each repetition. This way if you have the same query repeated 1000 times, it will be loaded from the DB one time, the rest 999 loads will be from cache.

use phpFastCache\CacheManager;

$config = array(
    "storage"   =>  "files",
    "path"      =>  "/your_cache_path/dir/",
);
CacheManager::setup($config);

// Try to get from Cache first with an Identity Keyword
$products = CacheManager::get("products");

// If not available get from DB and save in Cache.
if(is_null($products)) {
    $products = "DB SELECT QUERY";
    // Cache your $products for 600 seconds.
    CacheManager::set($cache_keyword, $products,600);
}

Guzzle

Guzzle is one of the best HTTP clients out there. It can handle almost any HTTP task that you throw at it: synchronous and asynchronous requests, HTTP cookies, streaming of large uploads and downloads. Working with Guzzle is really easy and the docs are well written with lots of examples and detailed explanations.

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
    'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'

// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});
$promise->wait();

Munee

Munee has lots of tricks up its sleeve: combining several CSS or JavaScript requests into one, image resizing, automatic compilation for Sass, Less and CoffeeScript files, as well as minification and Gzip compression. All of the previously mentioned processes are cached both server-side and client-side for optimal performance.

require 'vendor/autoload.php';
echo \Munee\Dispatcher::run(new \Munee\Request());
<!-- Combining two CSS files into one. -->
<link rel="stylesheet" href="/css/bootstrap.min.css, /css/demo.css">

<!-- Resizing image -->
<img src="/path/to/image.jpg?resize=width[100]height[100]exact[true]">

<!-- Files that need preprocessing are compiled automatically -->
<link rel="stylesheet" href="/css/demo.scss">

<!-- Minifying code -->
<script src="/js/script.js?minify=true"></script>

Twig

Templating engine with a very clean “mustache” syntax that makes markup shorter and easier to write. Twig offers everything you would expect from a modern templating library: variable escaping, loops, if/else blocks, as well as a secure sandbox mode for verifying template code.

// Template HTML

<p>Welcome {{ name }}!</p>


// Rendering

require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
    'cache' => '/path/to/compilation_cache',
));

echo $twig->render('index.html', array('name' => 'George'));

Goutte

Goutte is a Web Scraper that can crawl websites and extract HTML or XML data from them. It works by sending a request to a given URL and returning a Crawler object, which allows the developer to interact with the remote page in various ways.

use Goutte\Client;
$client = new Client();

// Go to the symfony.com website
$crawler = $client->request('GET', 'http://www.symfony.com/blog/');

// Click on the links
$link = $crawler->selectLink('Security Advisories')->link();
$crawler = $client->click($link);

// Extract data
$crawler->filter('h2 > a')->each(function ($node) {
    print $node->text()."\n";
});

Climate

Climate is a library for people who run PHP from the command line. It offers a collection of methods for talking to the terminal (both input and output), and also some beautifying functions for coloring and formatting. It can even draw and animate cool ASCII art.

$climate = new League\CLImate\CLImate;

// Output
$climate->out('This prints to the terminal.');

// Input
$input = $climate->input('How you doin?');
$response = $input->prompt();

// Formatting
$padding = $climate->padding(10);

$padding->label('Eggs')->result('$1.99');
$padding->label('Oatmeal')->result('$4.99');
// Eggs...... $1.99
// Oatmeal... $4.99

Alice

Built on top of Faker, Alice is a library that generates fake data objects for testing. To use it you first have to define the structure of your objects and what data you want in them. Then with a simple function call Alice will transform this template into an actual object with random values.

// Template in person.yml file
Person:
    person{1..10}:
        firstName: '<firstName()>'
        lastName: '<lastName()>'
        birthDate: '<date()>'
        email: '<email()>'


// Load dummy data into an object
$person = \Nelmio\Alice\Fixtures::load('/person.yml', $objectManager);

Ratchet

The Ratchet library adds support for the WebSockets interface in apps with a PHP backend. WebSockets enable two-way communication between the server and client side in real time. For this to work in PHP, Ratchet has to start a separate PHP process that stays always running and asynchronously sends and receives messages.

class MyChat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($from != $client) {
                $client->send($msg);
            }
        }
    }
}

// Run the server application through the WebSocket protocol on port 8080
$app = new Ratchet\App('localhost', 8080);
$app->route('/chat', new MyChat);
$app->run();

PHPMailer

No PHP library collection is complete without PHPMailer. This project is backed by a huge community and is implemented in popular systems such as WordPress and Drupal, making it the safest choice for sending emails in PHP. It has SMTP support, can do HTML-based emails, and much more.

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('steve@example.com');    

$mail->addAttachment('/var/tmp/file.tar.gz');        
$mail->isHTML(true);                                  

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

Hoa

Hoa isn’t actually a PHP library – it’s an entire set of PHP libraries, containing all kinds of useful web development utilities. Although not all are fully documented, there are 50+ libraries right now, with new ones constantly being added. It’s completely modular so you can select only the libraries you need without any clutter.

// Hoa Mail
$message            = new Hoa\Mail\Message();
$message['From']    = 'Gordon Freeman <gordon@freeman.hf>';
$message['To']      = 'Alyx Vance <alyx@vance.hf>';
$message['Subject'] = 'Hoa is awesome!';
$message->addContent(
    new Hoa\Mail\Content\Text('Check this out: http://hoa-project.net/!')
);
$message->send();

// Hoa Session
$user = new Hoa\Session\Session('user');

if ($user->isEmpty()) {
    echo 'first time', "\n";
    $user['foo'] = time();
} else {
    echo 'other times', "\n";
    var_dump($user['foo']);
}

CssToInlineStyles

Anyone who has tried creating HTML emails knows what a pain it is to inline all of the CSS rules. This small PHP Class does the whole job for you, saving you lots of time and nerves. Just write your styles in a regular .css file and the PHP library will use the selectors to assign them at the proper tags.

use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;

// create instance
$cssToInlineStyles = new CssToInlineStyles();

$html = file_get_contents(__DIR__ . '/examples/sumo/index.htm');
$css = file_get_contents(__DIR__ . '/examples/sumo/style.css');

// output
echo $cssToInlineStyles->convert(
    $html,
    $css
);

Stringy

Library for doing all kinds of string manipulations. It offers a ton of different methods for modifying text (reverse(), htmlEncode(), toAscii() etc.) or gather information about a string (isAlphanumeric(), getEncoding(), among others). A cool thing about Stringy is that it also works with special symbols like Greek or Nordic letters;

s('Camel-Case')->camelize(); // 'camelCase'

s('   Ο     συγγραφέας  ')->collapseWhitespace(); // 'Ο συγγραφέας'

s('foo & bar')->containsAll(['foo', 'bar']); // true

s('str contains foo')->containsAny(['foo', 'bar']); // true

s('fòôbàř')->endsWith('bàř', true); // true

s('fòôbàř')->getEncoding(); // 'UTF-8'

s('&amp;')->htmlDecode(); // '&'

Robo

Robo is a Gulp-like task runner, only for PHP. With it you can set up automations that improve your workflow and the time it takes to build a project after making changes. Robo can run tests, compile code from preprocessors, handle version control updates, and many other useful tasks.

// Doing a Git Commit with Robo
public function pharPublish()
{
    $this->pharBuild()->run();
    $this->_rename('robo.phar', 'robo-release.phar');
    return $this->collectionBuilder()
        ->taskGitStack()
            ->checkout('gh-pages')
        ->taskGitStack()
            ->add('robo.phar')
            ->commit('robo.phar published')
            ->push('origin', 'gh-pages')
            ->checkout('master')
            ->run();
}

PHP Humanizer

This library takes variables and transforms them into a more human-readable format using a set of methods. For example it can turn Roman numerals into numbers, truncate long strings, and calculate bytes to kB/MB/GB. Support for over 15 languages (the spoken kind, not programming ones).

use Coduo\PHPHumanizer\NumberHumanizer;

echo StringHumanizer::humanize('field_name'); // "Field Name"

echo NumberHumanizer::ordinalize(1); // "1st"
echo NumberHumanizer::ordinalize(23); // "23rd"

echo NumberHumanizer::toRoman(5); // "V"
echo NumberHumanizer::fromRoman("MMMCMXCIX"); // 3999

echo NumberHumanizer::binarySuffix(1024); // "1 kB"
echo NumberHumanizer::binarySuffix(1073741824 * 2); // "2 GB"

ColorExtractor

The last item on our list is this small library for extracting colors from images. It iterates all of the pixels in a given picture and returns a palette of the colors on it sorted by total area. Developers can then use this palette to get the most dominant colors and adapt the design according to them.

require 'vendor/autoload.php';

use League\ColorExtractor\Color;
use League\ColorExtractor\Palette;

$palette = Palette::fromFilename('./some/image.png');

$topFive = $palette->getMostUsedColors(5);
$colorCount = count($palette);
$blackCount = $palette->getColorCount(Color::fromHexToInt('#000000'));
Powered by Gewgley