Monthly Archiv: December, 2015

Creating Your First Desktop App With HTML, JS and Electron

creating-your-first-desktop-app-with-electron

Web applications become more and more powerful every year, but there is still room for desktop apps with full access to the hardware of your computer. Today you can create desktop apps using the already familiar HTML, JS and Node.js, then package it into an executable file and distribute it accordingly across Windows, OS X and Linux.

There are two popular open source projects which make this possible. These are NW.js, which we covered a few months ago, and the newer Electron, which we are going to use today (see the differences between them here). We are going to rewrite the older NW.js version to use Electron, so you can easily compare them.

Getting Started With Electron

Apps built with Electron are just web sites which are opened in an embedded Chromium web browser. In addition to the regular HTML5 APIs, these websites can use the full suite of Node.js modules and special Electron modules which give access to the operating system.

For the sake of this tutorial, we will be building a simple app that fetches the most recent Tutorialzine articles via our RSS feed and displays them in a cool looking carousel. All the files needed for the app to work are available in an archive which you can get from the Download button near the top of the page.

Extract its contents in a directory of your choice. Judging by the file structure, you would never guess this is a desktop application and not just a simple website.

Directory Structure

Directory Structure

We will take a closer look at the more interesting files and how it all works in a minute, but first, let’s take the app for a spin.

Running the App

Since an Electron app is just a fancy Node.js app, you will need to have npm installed. You can learn how to do it here, it’s pretty straightforward.

Once you’ve got that covered, open a new cmd or terminal in the directory with the extracted files and run this command:

npm install

This will create a node_modules folder containing all the Node.js dependencies required for the app to work. Everything should be good to go now, in the same terminal as before enter the following:

npm start

The app should open up in it’s own window. Notice it has a top menu bar and everything!

Electron App In Action

Electron App In Action

You’ve probably noticed that starting the app isn’t too user friendly. However, this is just the developer’s way of running an Electron app. When packaged for the public, the it will be installed like a normal program and opened like one, just by double clicking on its icon.

How it’s made

Here, we will talk about the most essential files in any electron app. Let’s start with package.json, which holds various information about the project, such as the version, npm dependencies and other important settings.

package.json

{
  "name": "electron-app",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "dependencies": {
    "pretty-bytes": "^2.0.1"
  },
  "devDependencies": {
    "electron-prebuilt": "^0.35.2"
  },
  "scripts": {
    "start": "electron main.js"
  },
  "author": "",
  "license": "ISC"
}

If you’ve worked with node.js before, you already know how this works. The most significant thing to note here is the scripts property, where we’ve defined the npm start command, allowing us to run the app like we did earlier. When we call it, we ask electron to run the main.js file. This JS file contains a short script that opens the app window, and defines some options and event handlers.

main.js

var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform != 'darwin') {
        app.quit();
    }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
    // Create the browser window.
    mainWindow = new BrowserWindow({width: 900, height: 600});

    // and load the index.html of the app.
    mainWindow.loadURL('file://' + __dirname + '/index.html');

    // Emitted when the window is closed.
    mainWindow.on('closed', function() {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
    });
});

Take a look at what we do in the ‘ready’ method. First we define a browser window and set it’s initial size. Then, we load the index.html file in it, which works similarly to opening a HTML file in your browser.

As you will see, the HTML file itself is nothing special – a container for the carousel and a paragraph were CPU and RAM stats are displayed.

index.html

<!DOCTYPE html>
<html>
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Tutorialzine Electron Experiment</title>

    <link rel="stylesheet" href="./css/jquery.flipster.min.css">
    <link rel="stylesheet" href="./css/styles.css">

</head>
<body>

<div class="flipster">
    <ul>
    </ul>
</div>

<p class="stats"></p>

<!-->In Electron, this is the correct way to include jQuery<-->
<script>window.$ = window.jQuery = require('./js/jquery.min.js');</script>
<script src="./js/jquery.flipster.min.js"></script>
<script src="./js/script.js"></script>
</body>
</html>

The HTML also links to the needed stylesheets, JS libraries and scripts. Notice that jQuery is included in a weird way. See this issue for more information about that.

Finally, here is the actual JavaScript for the app. In it we access Tutorialzine’s RSS feed, fetch recent articles and display them. If we try to do this in a browser environment, it won’t work, because the RSS feed is located on a different domain and fetching from it is forbidden. In Electron, however, this limitation doesn’t apply and we can simply get the needed information with an AJAX request.

$(function(){

    // Display some statistics about this computer, using node's os module.

    var os = require('os');
    var prettyBytes = require('pretty-bytes');

    $('.stats').append('Number of cpu cores: <span>' + os.cpus().length + '</span>');
    $('.stats').append('Free memory: <span>' + prettyBytes(os.freemem())+ '</span>');

    // Electron's UI library. We will need it for later.

    var shell = require('shell');


    // Fetch the recent posts on Tutorialzine.

    var ul = $('.flipster ul');

    // The same-origin security policy doesn't apply to electron, so we can
    // send ajax request to other sites. Let's fetch Tutorialzine's rss feed:

    $.get('http://feeds.feedburner.com/Tutorialzine', function(response){

        var rss = $(response);

        // Find all articles in the RSS feed:

        rss.find('item').each(function(){
            var item = $(this);

            var content = item.find('encoded').html().split('</a></div>')[0]+'</a></div>';
            var urlRegex = /(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&amp;:/~+#]*[w-@?^=%&amp;/~+#])?/g;

            // Fetch the first image of the article.
            var imageSource = content.match(urlRegex)[1];


            // Create a li item for every article, and append it to the unordered list.

            var li = $('<li><img /><a target="_blank"></a></li>');

            li.find('a')
                .attr('href', item.find('link').text())
                .text(item.find("title").text());

            li.find('img').attr('src', imageSource);

            li.appendTo(ul);

        });

        // Initialize the flipster plugin.

        $('.flipster').flipster({
            style: 'carousel'
        });

        // When an article is clicked, open the page in the system default browser.
        // Otherwise it would open it in the electron window which is not what we want.

        $('.flipster').on('click', 'a', function (e) {

            e.preventDefault();

            // Open URL with default browser.

            shell.openExternal(e.target.href);

        });

    });

});

A cool thing about the above code, is that in one file we simultaneously use:

  • JavaScript libraries – jQuery and jQuery Flipster to make the carousel.
  • Electron native modules – Shell which provides APIs for desktop related tasks, in our case opening a URL in the default web browser.
  • Node.js modules – OS for accessing system memory information, Pretty Bytes for formatting.

And with this our app is ready!

Packaging and Distribution

There is one other important thing to do to make your app ready for end users. You need to package it into an executable that can be started with a double click on users’ machines. Since Electron apps can work on multiple operating systems and every OS is different, there need to be separate distributions for Windows, for OS X and for Linux. Tools such as this npm module are a good place to start – Electron Packager.

Take into consideration that the packaging takes all your assets, all the required node.js modules, plus a minified WebKit browser and places them together in a single executable file. All these things sum up and the final result is an app that is roughly 50mb in size. This is quite a lot and isn’t practical for a simple app like our example here, but this becomes irrelevant when we work with big, complex applications.

Conclusion

The only major difference with NW.js that you will see in our example is that NW.js opens an HTML page directly, whereas Electron starts up by executing a JavaScript file and you create an application window through code. Electron’s way gives you more control, as you can easily build multi-window applications and organize the communication between them.

Overall Electron is an exciting way to build desktop web applications using web technologies. Here is what you should read next:

picStylizer (New)

Package:
picStylizer
Summary:
Generate sprite images and CSS from image files
Groups:
Files and Folders, Graphics, HTML, Printing, Utilities and Tools
Author:
Luciano Salvino
Description:
This class can generate sprite images and CSS from image files...

Read more at http://www.phpclasses.org/package/9497-PHP-Generate-sprite-images-and-CSS-from-image-files.html

PHP Ultimate Web Page Capture (New)

Package:
PHP Ultimate Web Page Capture
Summary:
Capture Web page as image using ScreenshotLayer
Groups:
Graphics, HTML, PHP 5, Web services
Author:
Dave Smith
Description:
This class can capture Web page as image using ScreenshotLayer API...

Read more at http://www.phpclasses.org/package/9530-PHP-Capture-Web-page-as-image-using-ScreenshotLayer.html

5 Tips for Making More Money as a Freelance Designer

When I started out, I made about $1,680 a month (after taxes). Now I make that in less than two days. It’s crazy when I think about it.

For a lot of us (myself included) it’s never about the money. But what I have inevitably realized is that money brings freedom. The freedom to choose the work we take on. The freedom to work on meaningful projects. The freedom to have time to do what we want.

As designers, I believe in improving not only the quality of our work, but also the value of our work.

Talking about money is always a touchy subject. But just to give you some background about where I’m coming from, and about my income as a freelance designer: I’ve made more than $140,000 working only seven months in a year. I enjoy some time off in between projects, and the freedom to do other things. However, bear in mind that I have been doing this for nine years, and with that comes experience and a honed set of skills.

Here are some tips that will surely boost your design work’s value. These tips are not things you can do overnight; you will need to put in some hard work in order to achieve your desired results. But if you take action, I’m sure you will eventually see positive results.

1. Be a Good Designer: Produce Great Work That Solves Problems

A strong body of work commands interest from prospective clients and increases your perceived value as a designer.

I am a strong believer in constantly working on my craft. Improving the quality of our work helps us get more projects, and also contributes to pushing our industry forward.

What aspects of your design work can you improve, and how?

Set a Goal

The first step is to have a good idea of what "good design" is. Think of all your favorite designers. Write down a list of the top five designers you admire. Done that? Good. Your goal is to close the gap between your work, and the work of the designers you hold in high regard. Follow their work, as well as the work of other designers that they like/favorite/save on social media platforms such as Behance, Dribbble, Pinterest, etc.

Now you have a benchmark for good design work.

Improve Your Visual Design Skills

The first and most obvious thing to work on is your visual design chops. The best way to improve in this area is to practice.

Spend one to two hours a day analyzing, deconstructing, and recreating the work of other designers. What would begin as an exercise of merely emulating and reproducing someone else’s work will eventually allow you to see and understand why certain designs work better than others.

Many great designers started this way. Haraldur Thorleifsson, a successful designer who has worked with companies such as Google, Microsoft, and Airbnb said in an interview:

When I was younger I liked to take things apart to figure out how they worked. I never did figure anything out, and I certainly couldn’t put anything back together, so this mostly meant that I had a lot of broken stuff.

I am by no means a natural designer or illustrator, so when I started designing I basically did the same thing. I would take screenshots of sites I liked and copy them, the digital equivalent of tracing from paper. This taught me a lot about spacing, typography, grids and how to create graphics from scratch.

Over time, as your visual library expands within your head, you will realize your own ideas.

To get better at design, the idea is really just to keep creating. When he was asked by a design student what to focus on to help grow one’s career, Mike Buzzard, a Design Manager in UX at Google, answered: Just keep making stuff.

Even if you’re a seasoned veteran — just keep creating, as there’s always room to improve. A seasoned chef still sharpens his knife. Join communities and find great mentors to learn from. Always make time to learn new skills that can make your work better.

Think Objectively

Visual chops are all well and good. But design is more than just the visual. It’s also about meeting the client’s goals, and thinking about your work as being a part of a system.

A lot of designers don’t want to think that their work sits in a marketing plan or a business strategy. But it does.

To be an effective designer, it’s essential to have a holistic view. You must see where your design work fits within the overall picture. To possess a holistic view means taking some time to learn about the other components of the system. Get into reading about business, marketing, copywriting, web performance, and other associated subjects.

While there may be art in what we do, we are not artists. We are designers. It’s the balance of form, function, and user/client objectives that makes your designs great.

2. Be a Great Communicator

At the end of the day, clients (whether they are creative directors, marketing managers, or business owners) are just people. People just like you and me.

When I used to work as a Creative Director, whenever we needed to hire designers, I would of course evaluate the design portfolios of the candidates as part of the decision-making process. But almost equally as important was looking at how well the candidates communicated. How did they come up with the context and rationale for their design solutions? Were they consistent with keeping the lines of communication open?

Being able to communicate well and eloquently helps you build trust with your clients. How well can you answer their questions? Try to be empathetic and put yourself in your client’s shoes. What do they need to know, and how can you best solve their problem?

Start by identifying your personal communication style and tone. I prefer to write clients using a conversational style of communication. It helps me weed out all the unnecessary jargon and allows us to engage on a more personable and "authentic" level. Also, people that are okay with this style of communication are usually from the types of organizations that I like working with.

Indirectly tied to communication is punctuality. Punctuality is super important. Honoring your promises and staying true to your word is important if you would like your clients to be able to trust what you say. If you’re going to say something is going to be done at a certain time, make sure you do it on time or (even better) earlier than the time you have committed to. Under-promise and over-deliver. Not vice versa. By nature, I’m not a super organized person, but through the years I’ve learned to always deliver no matter what.

3. Put Yourself Out There

No one is going to hire you if they don’t know about you.

I used to feel iffy about promoting myself. But I need to put myself and my work out there in order to attract prospective clients, as well as to be able to make connections and start conversations with like-minded designers. Dan Mall said it best: "Contribute to the conversations you want to be part of."

If you’re a freelancer, getting yourself exposure is almost as important as having great design work. Join online creative sites like Behance and Dribbble, and keep posting your work on them. Share your work and reach out to different communities. You can even share your journey by posting snippets of your design exercises, similar to what Paul Flavius Nechita did with his 100 Days UI project. (He was interviewed about the project on Dribbble.)

4. Work with Only Good Clients That Pay Well

As your designs become better, and as your reputation grows, you should be receiving more job leads.

Instead of taking on every single project that comes your way, it’s important to prioritize closing the clients that will pay you what you think your services are worth.

But how do you do that? By demonstrating the value of your work to prospective clients, and what it will mean to their business.

Read about value-based pricing in this article: How I Earned A Lot More on Projects by Changing My Pricing Strategy.

I have garnered clients via a "pull" methodology. This means prospective clients get in touch with me via different channels. I never reach out to potential clients. Getting projects using this "pull" methodology means that would-be clients already know about what kind of work I offer and what I’m about. Also, they will typically already know which markets I serve.

Identify what markets you serve and think about what your time and services are worth. Accept the projects that are within your criteria.

Good clients will refer you to other good clients. And I mean not just "good clients" in terms of pay, but also how easy and pleasant they are to work with. It’s because like-minded businesses and people tend to connect and engage with each other.

In the same token, less-than-stellar clients will probably refer you to other less-than-stellar clients. If you design sites for $100, you will be known as the $100 web designer, and you will in turn attract clients that believe websites should only cost a hundred dollars. If you do sites for $30,000, then you exist in that market. (And if you’re Huge, you exist in the $18 million market.)

5. Be Nice

Most people don’t like to work with designers who have huge egos.

The Golden Rule applies here: Treat others the way you would like to be treated. Good manners is a currency that goes a long way in the business world.

Related Content

How I Made Web Design Profitable by Not Doing Web Design

How to Fire Bad Clients

Web Designers Making Thousands of Dollars in Passive Income

Nguyen Le is an ex-Creative Director turned freelance designer/entrepreneur from Melbourne, Australia. He’s worked with brands such as Nintendo, Adidas, and Nissan. Visit his site, Verse, and get connected with him on Dribbble and Behance.

The post 5 Tips for Making More Money as a Freelance Designer appeared first on WebFX Blog.

Powered by Gewgley