Friday, February 5, 2016

Getting Started with React: Building a Hello World Demo

This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.

React is quickly becoming the most popular JavaScript library for building user interface (UI) components for HTML/CSS/JS applications. Among a crowded field of frameworks and libraries, it stands out as a simple and efficient approach to building complex, composable UIs that efficiently update the DOM. React was born out of Facebook’s desire to have better UI components for its Facebook and Instagram web applications.
[author_more]
This post serves as an introduction to a series of blog posts on how to build components with React. The post will explore the assets needed to create React components, examples and explanations of some of the core functionality, as well as comparisons to other JavaScript UI solutions. Additionally, JSX combined with Babel will demonstrate React’s extended syntax, JSX, to simplify the code needed to build HTML and React Component declaratively. React is also cross-browser compatible, and works great in Microsoft Edge.

Hello World

To get started with React.js, let's setup a Hello World demonstration with CodePen. To view the demonstration, and edit the code, please click on the graphic link in the upper left hand corner “Edit on CodePen”.

See the Pen React.js Hello World Demo by SitePoint (@SitePoint) on CodePen.

To setup this CodePen, click on “Settings” in the header, then on “JavaScript”, and you will see, two external JavaScript files were included: React and React-DOM. Both files are referenced from Facebook, and their URLs are:

React: http://ift.tt/1MCOfVV

React-DOM: http://ift.tt/213YRqA

The first React JavaScript file contains the React library, while the second library React-DOM, contains code to use React with the DOM of a web browser.

Hello World demo

Screenshots are from Visual Studio Code

To create React Components, use the createClass function of the React object. The createClass function expects an object configuring the component to be passed in. The createClass function is a helper function for creating new components which inherit from React.Component. If you are using using ES2015 natively in the browser or through a transpiler such as Babel, then it's possible to inherit directly from React.Component using the new class and extends keywords. To use Babel in CodePen, click on “Settings”, then “JavaScript”, and select it from the “JavaScript Preprocessor” drop down list.

See the Pen React.js Hello World ES2015 Demo by SitePoint (@SitePoint) on CodePen.

Regardless of the approach to creating the class structure for the component, the result is the same.

The only required property for a component is the render property, which points to a function object which is used to actually render the DOM of the component. The implementation of the render function introduces a new function, createElement, that is provided by the React object. The createElement function is used to create new DOM elements with React. The function expects up to three parameters.

The first parameter is the name of the HTML element or React Component to create. HTML elements should be a lowercase string containing only the name of the element without the angle brackets and no attributes. Examples of acceptable HTML element arguments include “h1”, “p”, etc. In addition to HTML element names, React Component objects can be passed in. For React Components, the object itself, not a string name of the object, is passed in.

The second parameter is an object of the properties to pass in. For HTML elements, these properties correspond to the attributes of the HTML element. For React Components, these properties correspond to stateless (state will be covered in a future blog post) data for use when rendering the component.

Finally, the third parameter represents the child elements of the element being created. In the “Hello World” example, the child content of the h1 element is the content “Hello World!” In addition to textual content, element objects can be passed in.

See the Pen React.js Child Content Demo by SitePoint (@SitePoint) on CodePen.

Or by using an array, multiple child elements can be passed in as well.

See the Pen React.js Child Content List Demo by SitePoint (@SitePoint) on CodePen.

To utilize the React Components in a web page, the ReactDOM object’s render function is used. It expects an element object, and a root element to which the DOM of the element object will be appended. In the code demonstration, the createElement function is used to create an instance of the HelloWorld component, while document.querySelector is used to select the main element to which the instantiated and rendered HelloWorld component is appended. Once appended, the component appears in the web page, and the React demonstration is complete.

Continue reading %Getting Started with React: Building a Hello World Demo%


by Eric Green via SitePoint

Multi-Device Scrolling Menu

Multi-Device Scrolling Menu is a simple responsive horizontal menu ready for any device.


by via jQuery-Plugins.net RSS Feed

Angular 2 Components and Providers: Classes, Factories & Values

This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.

This is the fourth part in the Angular 2 series. You can read part three here.

In a previous article, we looked at how to get data into and out of components using the @Input and @Output annotations. In this article, we’ll look at another fundamental aspect of Angular 2 components – their ability to use “providers.” You may have seen “providers” in a list of properties you can use to configure components and you might have realized that it allows you to define a set of injectable objects that will be available to the component. That’s nice, but it of course begs the question, “what is a provider?”

Answering that question involves a bit and gets us into a discussion of Angular 2’s Dependency Injection (DI) system. We may specifically cover DI in a future blog post, but it is well covered in a series of articles by Pascal Precht beginning with: http://ift.tt/1PR80KU. We’ll assume you are familiar with DI and Angular 2’s DI’s system in general as covered in Pascal’s article, but in brief the DI system is responsible for:

  • Registering a class, function or value. These items, in the context of dependency injection, are called “providers” because they result in something. For example, a class is used to provide or result in an instance – see below for more details on provider types.
  • Resolving dependencies between providers – for example, if one provider requires another provider.
  • Making the provider’s result available in code when we ask for it. This process of making the provider result available to a block of code is called “injecting it.” The code that injects the provider results is, logically enough, called an “injector.”
  • Maintaining a hierarchy of injectors so that if a component asks for a provider result from a provider not available in its injector, DI searches up the hierarchy of injectors.

In the previous article, we included a diagram showing that components form a hierarchy beginning with a root component. Let’s add to that diagram to include the injectors and the resources (providers) they register:

Component hierarchy with injectors and resources
Figure 1: Each component has its own injector that registers providers. Injectors create child injectors and a request for a provider starts with the local injector and searches up the injector hierarchy.
[author_more]
We can see from the above that while components form a downwards directed graph, their associated injectors have a two-way relationship: parent injectors create children (downwards) and when a provider is requested, Angular 2 searches the parent injector (upwards) if it can’t find the requested provider in the component’s own injector. This means that a provider with the same identifier at a lower level will shadow (hide) the same-named provider at a higher level.

What are Providers?

So, what are these “providers” that the injectors are registering at each level? Actually, it is simple: a provider is a resource or JavaScript “thing” that Angular uses to provide (result in, generate) something we want to use:

  • A class provider generates/provides an instance of the class.
  • A factory provider generates/provides whatever returns when you run a specified function.
  • A value provider doesn’t need to take an action to provide the result like the previous two, it just returns its value.

Unfortunately, the term “provider” is sometimes used to mean both the class, function or value and the thing that results from the provider – a class instance, the function’s return value or the returned value.

Let’s see how we can add a provider to a component by creating a class provider using MyClass, a simple class that will generate the instance we want to use in our application.

A simple class with four properties

Code screenshots are from Visual Studio Code

Figure 2: A simple class with four properties.

Okay, that’s the class; now let’s instruct Angular to use it to register a class provider so we can ask the dependency injection system to give us an instance to use in our code. We’ll create a component, ProvDemo_01.ts that will serve as the root component for our application. We load this component and kick-off our application in the bootstrap.ts:

Our application’s bootstrap.ts file that instantiates the root component

Figure 3: Our application’s bootstrap.ts file that instantiates the root component.

If the above doesn’t make sense, then take a look at our earlier post that walks through building a simple Angular 2 application. Our root component is called ProvDemo and the repository contains several numbers versions of it. You can change the version that is displayed by updating the line that imports ProvDemo above. Our first version of the root component looks like:

CompDemo with MyClass imported

Figure 4: CompDemo with MyClass imported, added to the providers array and used as a Type in the constructor arguments.

Adding the MyClass provider to this component is straightforward:

  • Import MyClass
  • Add it to the @Component providers property
  • Add an argument of type “MyClass” to the constructor

Under the covers, when Angular instantiates the component, the DI system creates an injector for the component which registers the MyClass provider. Angular then sees the MyClass type specified in the constructor’s argument list and looks up the newly registered MyClass provider and uses it to generate an instance which it assigns to “myClass” (initial small “m”).

The process of looking up the MyClass provider and generating an instance to assign to “myClass” is all Angular. It takes advantage of the TypeScript syntax to know what type to search for but Angular’s injector does the work of looking up and returning the MyClass instance.

Given the above, you might conclude that Angular takes the list of classes in the “providers” array and creates a simple registry used to retrieve the class. But, there is a slight twist to make things more flexible. A key reason why a “twist” is needed is to help us write unit tests for our components that have providers we don’t want to use in the testing environment. In the case of MyClass, there isn’t much reason not to use the real thing but if MyClass made a call to a server to retrieve data, we might not want to or be able to do that in the test environment. To get around this, we need to be able to substitute within ProvDemo a mock MyClass that doesn’t make the server call.

How do we make the substitution? Do we go through all our code and change every MyClass reference to MyClassMock? That’s not efficient and is a poor pattern for writing tests.

We need to swap out the provider implementation without changing our ProvDemo component code. To make this possible, when Angular registers a provider it sets up a map to associate a key (called a “token”) with the actual provider. In our example above, the token and the provider are the same thing: MyClass. Adding MyClass to the providers property in the @Component decorator is shorthand for:

providers: [ provide(MyClass, {useClass: MyClass} ]

which says “register a provider using ‘MyClass’ as the token (key) to find the provider and set the provider to MyClass so when we request the provider, the dependency injection system returns a MyClass instance.” Most of us are used to thinking of keys as being either numbers or strings. But in this case the token (key) is the class itself. We could have also registered the provider using a string for the token as follows:

providers: [ provide(“aStringNameForMyClass”, {useClass: MyClass} ]

So, how does this help us with testing? It means in the test environment we can override the provider registration, effectively doing:

provide(MyClass, {useClass: MyClassMock})

This associates the token (key) MyClass with the class provider MyClassMock. When our code asked the DI system to inject MyClass in testing, we get an instance of MyClassMock which can fake the data call. The net effect is that all our code remains the same and we don’t have to worry about whether the unit test will make a call to a server that might not exist in the test environment.

Continue reading %Angular 2 Components and Providers: Classes, Factories & Values%


by David Aden via SitePoint

5 Tips for Designers New to WordPress

WordPress design opens huge possibilities for both designers and developers. What’s more, you can bet this isn’t just a passing fashion. WordPress is really great and it’s definitely here to stay.

If you haven’t jumped on the WordPress wagon by now, you’ve certainly missed a lot. Don’t worry, it’s never too late to join. If you are a designer – a web designer, or even a graphic one, and you are considering switching to WordPress, here is some advice to help you.

1. Decide If You Can Handle PHP Code

I don’t know if this is true for most designers, but I get the feeling the biggest hurdle they face when they become WordPress designers is code. I don’t remember this being a problem for me back in the day when I first got my hands dirty with WordPress design, but I’d had some coding experience with Java and C before I became interested in WordPress design, so to me PHP wasn’t a monster. Maybe because of this, it’s hard for me to understand how a designer, especially a web designer, who must be familiar with code like HTML and CSS can freak out at the sight of PHP code.

However, I know many designers, some of whom are way better designers than me, who simply can’t deal with this horrible PHP monster. For instance, this article explains why for some (graphic) designers WordPree code (and WordPress itself) is way too much.

Continue reading %5 Tips for Designers New to WordPress%


by Ada Ivanoff via SitePoint

Validating Data With JSON-Schema, Part 2

In the first part of this tutorial, you learned how to create quite advanced schemas using all available validation keywords. Many real-world examples of JSON data are more complex than our user example. An attempt to put all the requirements to such data in one file may lead to very a large schema that may also have a lot of duplication.

Structuring Your Schemas

The JSON-schema standard allows you to break schemas into multiple parts. Let’s look at the example of the data for the news site navigation:

The navigation structure above is somewhat similar to the one you can see on the website http://dailymail.co.uk. You can see a more complete example in the GitHub repository.

The data structure is complex and recursive, but the schemas describing this data are quite simple:

navigation.json:

page.json:

defs.json:

Have a look at the schemas above and the navigation data they describe (that is valid according to the schema navigation.json). The main thing to notice is that the schema navigation.json references the schema page.json that in its turn references the first one.

JavaScript code to validate the user record against the schema could be:

All the code samples are available in the GitHub Repository.

Ajv, the validator used in the example, is the fastest JSON-Schema validator for JavaScript. I created it, so I am going to use it in this tutorial. We will look at how it compares with other validators in the end so you can choose the right one for you.

Tasks

See part 1 of the tutorial for instructions on how to install the repository with the tasks and to test your answers.

References Between Schemas With the “$ref” Keyword

The JSON-Schema standard allows you to reuse the repeated parts of schemas using references with the “$ref” keyword. As you can see from the navigation example, you can reference the schema that is located:

  • in another file: use the schema URI that is defined in its “id” property
  • in any part of another file: append the JSON pointer to the schema reference
  • in any part of the current schema: append the JSON pointer to “#”

You can also refer to the whole current schema using “$ref” equal to “#”—it allows you to create recursive schemas referring to themselves.

So in our example, the schema in navigation.json refers to:

  • the schema page.json
  • definitions in the schema defs.json
  • the definition positiveIntOrNull in the same schema

The schema in page.json refers:

  • back to the schema navigation.json
  • also to definitions in the file defs.json

The standard requires that the “$ref” should be the only property in the object, so if you want to apply a referenced schema in addition to another schema, you have to use the “allOf” keyword.

Task 1

Refactor the user schema from part 1 of the tutorial using references. Separate the schema in two files: user.json and connection.json.

Put your schemas in the files part2/task1/user.json and part2/task1/connection.json and run node part2/task1/validate to check if your schemas are correct.

JSON-Pointer

JSON-pointer is a standard defining the paths to the parts of JSON files. The standard is described in RFC6901.

This path consists of segments (that can be any string) connected with the “/” character. If the segment contains characters “~” or “/”, they should be replaced with “~0” and “~1”. Each segment means the property or the index in the JSON data.

If you look at the navigation example, the “$ref” that defines the color property is “defs.json#/definitions/color”, where “defs.json#” is the schema URI and “/definitions/color” is the JSON pointer. It points to the property color inside property definitions.

The convention is to put all the parts of the schema that are used in refs inside the definitions property of the schema (as you can see in the example). Although the JSON-schema standard reserves the definitions keyword for this purpose, it is not required to put your subschemas there. JSON-pointer allows you to refer to any part of the JSON file.

When JSON pointers are used in URIs, all the characters that are invalid in URIs should be escaped (in JavaScript the global function encodeURIComponent can be used).

JSON-pointers can be used not only in JSON-schemas. They can be used to represent the path in JSON data to any property or item. You can use the library json-pointer to access objects with JSON-pointers.

Task 2

The JSON file below describes the folders and files structure (folder names start with “/”):

What are the JSON pointers that point to:

  • the size of the “Word” application,
  • the size of the “my_story~.rtf” document,
  • the name of the second application that can open the “my_story~.rtf” document?

Put your answers in part2/task2/json_pointers.json and run node part2/task2/validate to check them.

Schema IDs

Schemas usually have a top-level “id” property that has the schema URI. When “$ref” is used in a schema, its value is treated as a URI that is resolved relatively to the schema “id”.

The resolution works in the same way as the browser resolves URIs that are not absolute—they are resolved relatively to the schema URI that is in its “id” property. If “$ref” is a filename, it replaces the filename in the “id”. In the navigation example, the navigation schema id is "http://ift.tt/1PXOI5X", so when reference "page.json#" is resolved, the full URI of the page schema becomes "http://ift.tt/1K30kIC" (that is the “id” of the page.json schema).

If the “$ref” of the page schema were a path, e.g. "/page.json", then it would have been resolved as "http://ift.tt/1K30kII". And "/folder/page.json" would have been resolved as "http://ift.tt/1PXOGeq".

If “$ref” starts from the “#” character, it is treated as a hash fragment and is appended to the path in the “id” (replacing the hash fragment in it). In the navigation example, the reference "defs.json#/definitions/color" is resolved as "http://ift.tt/1K30iAB" where "http://ift.tt/1PXOGem" is the ID of the definitions schema and "/definitions/color" is treated as a JSON pointer inside it.

If “$ref” were a full URI with a different domain name, in the same way links work in the browser, it would have been resolved as the same full URI.

Internal Schema IDs

The JSON-schema standard allows you to use “id” inside the schema to identify these subschemas and also to change the base URI relative to which inner references will be resolved—it’s called “changing resolution scope”. That is probably one of the most confusing parts of the standard, and that’s why it is not very commonly used.

I would not recommend over-using internal IDs, with one exception below, for two reasons:

  • Very few validators consistently follow the standard and correctly resolve references when internal IDs are used (Ajv fully follows the standard here).
  • Schemas become more difficult to understand.

We will still look into how it works because you may encounter schemas that use internal IDs and there are cases when using them helps with structuring your schemas.

Firstly, let’s look at our navigation example. Most of the references are in the definitions object and that makes references quite long. There is a way to shorten them by adding IDs to the definitions. This is the updated defs.json schema:

Now instead of references "defs.json#/definitions/positiveInteger" and "defs.json#/definitions/color" that are used in navigation and page schemas, you can use shorter references: "defs.json#positiveInteger" and "defs.json#color". That’s a very common usage of internal IDs as it allows you to make your references shorter and more readable. Please note that while this simple case will be handled correctly by most JSON-schema validators, some of them may not support it.

Let’s look at a more complex example with IDs. Here’s the sample JSON schema:

In very few lines, it became very confusing. Have a look at the example and try to figure out which property should be a string and which one an integer.

The schema defines an object with properties bar, baz and bax. Property bar should be an object that is valid according to the subschema, which requires that its property foo is valid according to the "bar" reference. Because the subschema has its own “id”, the full URI for the reference will be "http://ift.tt/1PXOIml", so it should be an integer.

Now look at the properties baz and bax. The references for them are written in a different way, but they point to the same reference "http://ift.tt/1PXOIml" and they both should be integers. Although the property baz points directly to the schema { "$ref": "#bar" }, it should still be resolved relative to the ID of the subschema because it is inside it. So the object below is valid according to this schema:

Many JSON schema validators will not handle it correctly, and that’s why IDs that change the resolution scope should be used with caution.

Task 3

Solving this puzzle will help you better understand how references and changing resolution scope work. Your schema is:

Create an object that is valid according to this schema.

Put your answer in part2/task3/valid_data.json and run node part2/task3/validate to check it.

Loading Referenced Schemas

Until now we were looking at different schemas referring to each other without paying attention to how they are loaded to the validator.

One approach is to have all connected schemas preloaded like we had in the navigation example above. But there are situations when it is either not practical or impossible—for example, if the schema you need to use is supplied by another application, or if you don’t know in advance all the possible schemas that may be needed.

In such cases, the validator could load referenced schemas at the time when the data is validated. But that would make the validation process slow. Ajv allows you to compile a schema into a validating function asynchronously loading the missing referenced schemas in the process. The validation itself would still be synchronous and fast.

For example, if navigation schemas were available to download from the URIs in their IDs, the code to validate the data against the navigation schema could be this:

The code defines the validateNavigation function that loads the schema and compiles the validation function when it is called the first time and always returns the validation result via the callback. There are various ways to improve it, from preloading and compiling the schema separately, before it is used the first time, to accounting for the fact that the function can be called multiple times before it has managed caching the schema (ajv.compileAsync already ensures that the schema is always requested only once).

Now we will look at the new keywords that are proposed for version 5 of the JSON-schema standard.

JSON-Schema Version 5 Proposals

Although these proposals haven’t been finalised as a standard draft, they can be used today—the Ajv validator implements them. They substantially expand what you can validate using JSON-schema, so it’s worth using them.

To use all these keywords with Ajv, you need to use the option v5: true.

Keywords “constant” and “contains”

These keywords are added for convenience.

The “constant” keyword requires that the data is equal to the value of the keyword. Without this keyword, it could have been achieved with the “enum” keyword with one item in the array of elements.

This schema requires that the data is equal to 1:

The “contains” keyword requires that some array element matches the schema in this keyword. This keyword applies to arrays only; any other data type will be valid according to it. It is a bit more difficult to express this requirement using only keywords from version 4, but it is possible.

This schema requires that if the data is an array then at least one of its items is integer:

It is equivalent to this one:

For this schema to be valid, either data should not be an array or it should not have all its items non-integers (i.e. some item should be integer).

Please note that both the “contains” keyword and the equivalent schema above would fail if the data were an empty array.

Keyword “patternGroups”

This keyword is proposed as a replacement for “patternProperties”. It allows you to limit the number of properties matching the pattern that should exist in the object. Ajv supports both “patternGroups” and “patternProperties” in v5 mode because the first one is much more verbose, and if you don’t want to limit the number of properties you may prefer using the second one.

For example the schema:

is equivalent to this schema:

They both require that the object has only properties with keys consisting only of lowercase letters with values of type string and with keys consisting only of numbers with values of type number. They don’t require any number of such properties, nor do they limit the maximum number. That’s what you can do with “patternGroups”:

The schema above has additional requirements: there should be at least one property matching each pattern and no more than three properties whose keys contain only letters.

You can’t achieve the same with “patternProperties”.

Keywords for Limiting Formatted Values “formatMaximum” / “formatMaximum”

These keywords together with “exclusiveFormatMaximum” / “exclusiveFormatMinimum” allow you to set limits for time, date and potentially other string values that have format required with the “format” keyword.

This schema requires that data is a date and it’s greater than or equal to January 1, 2016:

Ajv supports comparing formatted data for the formats “date”, “time” and “date-time”, and you can define custom formats that would support limits with the “formatMaximum” / “formatMaximum” keywords.

Keyword “switch”

While all the previous keywords were either allowing you to better express what was possible without them or slightly extending the possibilities, they didn’t change the declarative and static nature of the schema. This keyword allows you to make the validation dynamic and data-dependent. It contains multiple if-then cases.

It is easier to explain with an example:

The schema above sequentially validates the data against the subschemas in “if” keywords until one of them passes validation. When that happens, it validates the schema in the “then” keyword in the same object—that will be the result of the validation of the whole schema. If the value of “then” is false, the validation immediately fails.

In this way, the schema above requires that the value is:

  • either greater than or equal to 50 and is a multiple of 5
  • or between 10 and 49 and a multiple of 2
  • or between 5 and 9

This particular set of requirements can be expressed without a switch keyword, but there are more complex cases when it is not possible.

Task 4

Create the schema equivalent to the last example above without using a switch keyword.

Put your answer in part2/task4/no_switch_schema.json and run node part2/task4/validate to check it.

The “switch” keyword cases can also contain the “continue” keyword with a boolean value. If this value is true, the validation will continue after a successful “if” schema match with successful “then” schema validation. That is similar to a fall-through to the next case in a JavaScript switch statement, although in JavaScript fall-through is a default behaviour and the “switch” keyword requires an explicit “continue” instruction. This is another simple example with a “continue” instruction:

If the first “if” condition is satisfied and the “then” requirement is met, the validation will continue to check the second condition.

“$data” Reference

The “$data” keyword even further extends what is possible with JSON-schema and makes validation more dynamic and data-dependent. It allows you to put values from some data properties, items or keys into certain schema keywords.

For example, this schema defines an object with two properties where if both are defined, “larger” should be larger than or equal to “smaller”—the value in “smaller” is used as a minimum for “larger”:

Ajv implements the “$data” reference for most keywords whose values are not schemas. It fails validation if the “$data” reference points to an incorrect type and succeeds if it points to the undefined value (or if the path doesn’t exist in the object).

So what is the string value in the “$data” reference? It looks similar to JSON-pointer but it is not exactly it. It is a relative JSON-pointer that is defined by this standard draft.

It consists of an integer number that defines how many times the lookup should traverse up the object (1 in the example above means a direct parent) followed by “#” or JSON pointer.

If the number is followed by “#” then the value JSON-pointer resolves to will be the name of the property or the index of the item the object has. In this way, “0#” in place of “1/smaller” would resolve to the string “larger”, and “1#” would be invalid as the whole data is not a member of any object or array. This schema:

is equivalent to this one:

because { “$data”: “0#” } is replaced with the property name.

If the number in the pointer is followed by JSON-pointer, then this JSON-pointer is resolved starting from the parent object this number refers to. You can see how it works in the first “smaller” / “larger” example.

Let’s look again at our navigation example. One of the requirements you can see in the data is that the page_id property in the page object is always equal to the parent_id property in the contained navigation object. We can express this requirement in the page.json schema using the “$data” reference:

The “switch” keyword added to the page schema requires that if the page object has the navigation property then the value of the page_id property should be the same as the value of the parent_id property in the navigation object. The same can be achieved without the “switch” keyword, but it is less expressive and contains duplication:

Task 5

Examples of relative JSON-pointers can be helpful.

Using v5 keywords, define the schema for the object with two required properties list and order. List should be an array that has up to five numbers. All items should be numbers and they should be ordered in ascending or descending order, as determined by the property order that can be "asc" or "desc".

For example, this is a valid object:

and this is invalid:

Put your answer in part2/task5/schema.json and run node part2/task5/validate to check it.

How would you create a schema with the same conditions but for a list of unlimited size?

Defining New Validation Keywords

We’ve looked at the new keywords that are proposed for version 5 of the JSON-schema standard. You can use them today, but sometimes you may want more. If you’ve done task 5, you probably have noticed that some requirements are difficult to express with JSON-schema.

Some validators, including Ajv, allow you to define custom keywords. Custom keywords:

  • allow you to create validation scenarios that cannot be expressed using JSON-Schema
  • simplify your schemas
  • help you to bring a bigger part of the validation logic to your schemas
  • make your schemas more expressive, less verbose and closer to your application domain

One of the developers who uses Ajv wrote on GitHub:

“ajv with custom keywords has helped us a lot with business logic validation in our backend. We consolidated a whole bunch of controller-level validations into JSON-Schema with custom keywords. The net effect is far far better than writing individual validation code.”

The concerns you have to be aware of when extending the JSON-schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas.

The best approach here is to define a new meta-schema that will be the extension of draft 4 meta-schema or “v5 proposals” meta-schema that will include both the validation of your additional keywords and their description. Then your schemas that use these custom keywords will have to set the $schema property to the URI of the new meta-schema.

Now that you’ve been warned, we’ll dive in and define a couple of custom keywords using Ajv.

Ajv provides four ways to define custom keywords that you can see in the documentation. We will look at two of them:

  • using a function that compiles your schema to a validation function
  • using a macro-function that takes your schema and returns another schema (with or without custom keywords)

Let’s start with the simple example of a range keyword. A range is simply a combination of minimum and maximum keywords, but if you have to define many ranges in your schema, especially if they have exclusive boundaries, it may easily become boring.

That’s how the schema should look:

where exclusive range is optional, of course. The code to define this keyword is below:

And that’s it! After this code you can use the range keyword in your schemas:

The object passed to addKeyword is a keyword definition. It optionally contains the type (or types as an array) the keyword applies to. The compile function is called with parameters schema and parentSchema and should return another function that validates the data. That makes it almost as efficient as native keywords, because the schema is analysed during its compilation, but there is the cost of an extra function call during validation.

Ajv allows you to avoid this overhead with keywords that return the code (as a string) that will be made part of the validation function, but it is quite complex so we won’t look at it here. The simpler way is to use macro keywords—you will have to define a function that takes the schema and returns another schema.

Below is the implementation of the range keyword with a macro function:

You can see that the function simply returns the new schema that is equivalent to the range keyword that uses keywords maximum and minimum.

Let’s also see how we can create a meta-schema that will include the range keyword. We’ll use draft 4 meta-schema as our starting point:

If you want to use “$data” references with the range keyword, you will have to extend “v5 proposals” meta-schema that is included in Ajv (see the link above) so that these references can be the values of range and exclusiveRange. And while our first implementation will not support “$data” references, the second one with a macro-function will support them.

Now that you have a meta-schema, you need to add it to Ajv and use it in schemas using the range keyword:

The code above would have thrown an exception if the invalid values were passed to range or exclusiveRange.

Task 6

Assume that you have defined the keyword jsonPointers that applies the schemas to the deep properties defined by the JSON pointers that point to data starting from the current one. This keyword is useful with the switch keyword as it allows you to define requirements for deep properties and items. For example, this schema using the jsonPointers keyword:

is equivalent to:

Assume that you also have defined the keyword requiredJsonPointers that works similar to required but with JSON-pointers instead of properties.

If you like, you can define these keywords yourself too, or you can see how they are defined in the file part2/task6/json_pointers.js.

Your task is: using keywords jsonPointers and requiredJsonPointers, define the keyword select that is similar to the JavaScript switch statement and has the syntax below (otherwise and fallthrough are optional):

This syntax allows values of any type. Please note that fallthrough is different from continue in the switch keyword. fallthrough applies the schema from the next case to the data without checking that the selector is equal to the value from the next case (as it is most likely not equal).

Put your answers in part2/task6/select_keyword.js and part2/task6/v5-meta-with-select.json and run node part2/task6/validate to check them.

Bonus 1: Improve your implementation to also support this syntax:

It can be used if all values are different strings and there is no fallthrough.

Bonus 2: extend the “v5 proposals” meta-schema to include this keyword.

Other Usages of JSON-Schemas

In addition to validating data, JSON-schemas can be used to:

  • generate UI
  • generate data
  • modify data

You can look at the libraries that generate UI and data if you are interested. We won’t explore it as it is out of the scope of this tutorial.

We will look at using JSON-schema to modify the data while it is being validated.

Filtering Data

One of the common tasks while validating the data is removing the additional properties from the data. This allows you to sanitize the data before passing it to the processing logic without failing the schema validation:

Without the option removeAdditional, the validation would have failed, as there is an additional property bar that is not allowed by the schema. With this option, validation passes and the property is removed from the object.

When the removeAdditional option value is true, additional properties are removed only if the additionalProperties keyword is false. Ajv also allows you to remove all additional properties, regardless of the additionalProperties keyword, or additional properties that fail validation (if the additionalProperties keyword is the schema). Please look at the Ajv documentation for more information.

Assigning Defaults to Properties and Items

The JSON-schema standard defines the keyword “default” that contains a value that the data should have if it is not defined in the validated data. Ajv allows you to assign such defaults in the process of validation:

Without the option useDefaults, the validation would have failed, as there is no required property bar in the validated object. With this option, the validation passes and the property with the default value is added to the object.

Coercing Data Types

“type” is one of the most commonly used keywords in JSON-schemas. When you are validating user inputs, all your data properties you get from forms are usually strings. Ajv allows you to coerce the data to the types specified in the schema, both to pass the validation and to use the correctly typed data afterwards:

Comparing JavaScript JSON-Schema Validators

There are more than ten actively supported JavaScript validators available. Which one should you use?

You can see the benchmarks of performance and of how different validators pass the tests suite from the JSON-schema standard in the project json-schema-benchmark.

There are also distinctive features that some validators have that can make them the most suitable for your project. I will compare some of them below.

is-my-json-valid and jsen

These two validators are very fast and have very simple interfaces. They both compile schemas to JavaScript functions, as Ajv does.

Their disadvantage is that they both have limited support of remote references.

schemasaurus

This is one-of-a-kind library where JSON-schema validation is almost a side effect.

It is built as a generic and easily extensible JSON-schema processor/iterator that you can use to build all sorts of tools that use JSON-schema: UI generators, templates, etc.

It already has relatively fast JSON-schema validator included.

It doesn’t support remote references at all, though.

themis

The slowest in the group of fast validators, it has a comprehensive set of features, with a limited support of remote references.

Where it really shines is its implementation of the default keyword. While the majority of validators have limited support of this keyword (Ajv is not an exception), Themis has a very complex logic of applying defaults with rollbacks inside compound keywords such as anyOf.

z-schema

Performance-wise, this very mature validator is on the border between fast and slow validators. It was probably one of the fastest before the new breed of compiled validators appeared (all of the above and Ajv).

It passes almost all the tests from the JSON-schema test suite for validators, and it has quite thorough implementation of remote references.

It has a large set of options allowing you to tweak the default behaviour of many JSON-schema keywords (e.g., not accept empty arrays as arrays or empty sets of strings) and to impose additional requirements on JSON schemas (e.g., require the minLength keyword for strings).

I think that in most cases, both modifying schema behaviours and including requests to other services in JSON-schema are the wrong things to do. But there are cases when the ability to do so simplifies a lot.

tv4

This is one of the oldest (and slowest) validators supporting version 4 of the standard. As such it is often a default choice for many projects.

If you are using it, it is very important to understand how it reports errors and missing references and to configure it correctly, otherwise you will be getting many false positives (i.e., the validation passes with invalid data or unresolved remote references).

Formats are not included by default, but they are available as a separate library.

Ajv

I wrote Ajv because all the existing validators were either fast or compliant with the standard (especially with regards to supporting remote references) but not both. Ajv filled that gap.

At the moment it is the only validator that:

  • passes all the tests and fully supports remote references
  • supports validation keywords proposed for version 5 of the standard and $data references
  • supports asynchronous validation of custom formats and keywords

It has options to modify the validation process and to modify validated data (filtering, assigning defaults and coercing types—see the examples above).

Which Validator to Use?

I think the best approach is to try several and to choose the one that works best for you.

I wrote json-schema-consolidate, which supplies a collection of adapters that unify the interfaces of 12 JSON-schema validators. Using this tool you can spend less time switching between validators. I recommend removing it once you have decided which validator to use, as keeping it would negatively affect performance.

This is it! I hope this tutorial was useful. You have learned about:

  • structuring your schemas
  • using references and IDs
  • using validation keywords and $data reference from version 5 proposals
  • loading remote schemas asynchronously
  • defining custom keywords
  • modifying data in the process of validation
  • advantages and disadvantages of different JSON-schema validators

Thanks for reading!


by Evgeny Poberezkin via Envato Tuts+ Code

How to Install WordPress: The Server Software

For some, signing up for a blog on WordPress.com is the easiest process for setting up a blog, but if you're looking to download a copy of the WordPress software and install it on a your local machine (that is, your laptop or desktop), then there are some other prerequisites.

Throughout this series, we've covered how to do things like Install a WordPress Theme and How to Install a WordPress Plugin, but we haven't actually covered how to install WordPress itself.

But it only makes sense to cover that, right? I mean, how many of you are interested in getting deeper into WordPress development, but aren't even sure where to start with regard to getting WordPress set up on your computer?

Regardless of whether you're on Mac OS X, Windows, or Linux, there are a few pieces of software that need to be installed. Furthermore, it's important to know what each piece of software does.

In this article, we're going to cover each of the three main pieces of software that need to be installed, and then we'll cover the various ways they can be set up on your operating system.

If you're an advanced user, then you're likely familiar with everything that's going to be covered in this tutorial. Alternatively, if you're a beginner who is looking to get started with installing WordPress with the ultimate goal of designing themes and/or building plugins, then the following information is tailored specifically for you.

Understanding the Software

Before looking into how to get a web server set up on your machine, it's important to understand all of the pieces that fit together to make up what's considered the web server.

That is, we need to take a look at:

  1. the web server
  2. the database
  3. the programming language

I know: It's already kind of confusing because we're talking about setting up a web server, but part of a web server is the web server? 

Bear with me.

When you set up a machine to host a website, you're actually setting up what's known as a hosting environment, though people don't typically refer to it as that whenever they are talking to one another. 

To that end, it's completely normal to ask someone what their hosting environment is, but you're much more likely to hear someone ask you, "What's your web server setup?" 

I mention this not to be pedantic, but to make sure that you're prepared to hear the terminology used in multiple ways when talking with peers at WordCamps, at meet-ups, or online.

The Web Server

There are a number of different web servers available. I can't possibly cover all of them here, though we have articles covering a variety of them. This includes software such as Nginx, Apache, and more.

Obviously, there are a variety of choices when it comes to web servers; however, using Apache is normally the most common place that WordPress developers will start. Only those who are more experienced with WordPress or with hosting in general will be comfortable starting with other servers.

So what is Apache, exactly? According to the project's web site:

The Apache HTTP Server Project is an effort to develop and maintain an open-source HTTP server for modern operating systems including UNIX and Windows NT. The goal of this project is to provide a secure, efficient and extensible server that provides HTTP services in sync with the current HTTP standards.

Easy enough to follow, I suppose. What if we wanted a simpler definition? Wikipedia provides:

The Apache HTTP Server, colloquially called Apache, is the world's most used web server software.

And there you have it. That's one reason so many people start off with using Apache.

Of course, this still doesn't answer the question of what the web server actually is. An entire tutorial, or even a series of tutorials, could be written in order to describe it. But that's not the purpose of what we're covering here.

Instead, think of it this way:

  1. A request from the user's browser comes across the Internet to the computer on which your web site is hosted.
  2. Apache intercepts the requests, parses out information, and determines what files and other assets need to be bundled together to respond to the request.
  3. The response is then returned to the computer that requested the information and sent across the Internet.
  4. The web page renders in the user's web browser.

Nothing too complicated at this level, right? And for the purposes of this tutorial and this series, that works.

The Database

So what's this talk about a database? If a web server can route information from one computer to another, what's a database and why do we need it?

Think of it this way: If you're hosting a site that has to retrieve a few pages and a few images, then retrieving the files themselves is fine.

But what if a given page is made up of components found in multiple files, requires data that's spread across the file system, and images that are stored all over the directories that make up the website?

At this point, it gets a bit more complicated, and you need a way to efficiently manage all of the data being sent to and retrieved from the website. This is where a database comes into the picture. From Wikipedia:

A database is an organized collection of data. It is the collection of schemas, tables, queries, reports, views and other objects. The data is typically organized to model aspects of reality in a way that supports processes requiring information, such as modelling the availability of rooms in hotels in a way that supports finding a hotel with vacancies.

To be clear, the topic of databases can go on for quite some time. There are multiple courses at the university level that focus specifically on databases. But we're not worried about that for the purposes of this tutorial.

Additionally, there are a wide variety of database types. For the purposes of WordPress, we're going to be working with a relational database system known as MySQL.

The world's most popular open source database.

Once again, it's one of the most popular database systems—just like Apache—and so many people who start off working with WordPress will start off working with MySQL.

To be clear, other database systems can be used with WordPress, but it takes more work to get it all set up, so that's something for an advanced tutorial or series of tutorials.

The Programming Language

Finally, it's important to note that WordPress is actually made up of four programming languages. In no particular order, these languages are:

  1. CSS
  2. JavaScript
  3. HTML
  4. PHP

CSS, JavaScript, and HTML can all be rendered via the browser without any special software. But PHP? That's something completely different.

First, PHP stands for "hypertext preprocessor". I know, it's a weird acronym, isn't it? It's what's called a recursive acronym. Anyway, the point is that PHP is actually a server-side programming language. This means that's it's a language that runs on the same machine as the website runs on (versus the machine on which you view the website).

It gives the author access to the file system, the database, and it allows them to write a lot of functionality that other languages like CSS, JavaScript, and HTML simply do not offer.

With that said, what is PHP? From Wikipedia:

PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. Originally created by Rasmus Lerdorf in 1994, the PHP reference implementation is now produced by The PHP Group.

In short, this language is what allows all of the pieces of WordPress to work together so they are able to produce all of the functionality you're used to seeing. This includes everything from the installation to the dashboard, the administration area, themes, plugins, and the public-facing side of the site.

To say there's a lot to learn would be an understatement. But we all start somewhere, and that's exactly what the purpose of this tutorial is all about.

All-In-One Installers

I know: Just to get WordPress up and running, that's a lot of information. It may even cause you to question if it's worth pursuing it at all. But trust me (and hundreds and thousands of others) when we say it is!

The good news is that you don't have to manually set up, configure, and connect all of the various components to get a web server running on your machine. Granted, there's something to be said for doing this. If nothing else, you'll learn a lot. 

But if you have a solid understanding of everything that's been covered thus far in the tutorial, then you're in a good position to use one of the many all-in-one installers that are available for a variety of operating systems.

These software packages are designed to set up Apache, MySQL, and PHP for you so that, as soon as the installation is completed, you can start working on your web-based project. And considering WordPress is a web-based application, they make the perfect solution to install in order to get up and running with WordPress in no time.

Providing a tutorial on every single package that's available would be an exercise in writing pages and pages of tutorials. Below, you'll find a summary of the most popular applications as well as a link to where you can download them and their instructions.

  • XAMPP. XAMPP is an all-in-one installer for Windows, OS X, and Linux. It makes it incredibly easy to set up the web server, database, and programming language necessary to get a basic hosting environment working on your machine. It has an easy-to-use interface and can be further configured via the configuration files bundled with the application.
  • MAMP. MAMP is similar to XAMPP in that it's yet another way to get a hosting environment set up, but it's specifically designed for OS X. There are two versions: a free version and a premium version. Though the free version works just fine, it will be up to you and your needs to decide if you want to use the premium version. Secondly, this is what we'll be using in the next article in this tutorial to walk through installing WordPress.
  • WAMP. If you're looking for a Windows-only solution, then WAMP is your best choice. It's just like the aforementioned projects, but it's dedicated solely to Windows. It makes setting up the environment a cinch, and makes it easy to administer the environment from your local machine as easily as possible.

To be clear, there are other ways to get something like this set up. Other tools include things like VVV and DesktopServer; however, both of these are outside of the scope of what this tutorial offers. If you're just starting out or aren't familiar with the concepts discussed thus far, I recommend avoiding those tools until much later in your WordPress career.

I recommend checking each out for yourself, determining which suits your needs best, and then going from there.

Conclusion

From here, you have everything that you need to know in order lay the foundation of what you need to install WordPress. If you opt to configure all of the components on your own, great; otherwise, pick the all-in-one installer that works best for you, install it, and set it up.

In the next article, we'll take a look at everything that's needed to get WordPress installed and ready to go on your computer. This will make it easy to test out WordPress before actually deploying it to a web server as well as experiment with themes, plugins, and other development-related tasks.

In the meantime, don't hesitate to take a look at the other posts in this series, and leave any questions on the tutorial pages as necessary, all in order to prepare for the upcoming final tutorial.

Please don't hesitate to leave any questions or comments in the feed below, and I'll aim to respond to each of them as time permits.

For those who are interested in the rest of what I've written about development in the context of WordPress, you can see all of my courses and tutorials on my profile page, and you can follow me on my blog and/or Twitter at @tommcfarlin where I talk about software development in WordPress.


by Tom McFarlin via Envato Tuts+ Code

Building a Pong Clone in Unity: UI and Gameplay

In Part 1 of this tutorial – the Retro Revolution: Building a Pong Clone in Unity – we created a Pong clone with basic artificial intelligence (AI) and almost no user interface (UI).

In this tutorial, we’ll build upon our previously created clone and update it so that it will look identical to classic Pong, have basic UI, and have improved gameplay.

Pong

Let’s jump right in, but first, please either go through the original tutorial, or just download the resulting project from GitHub if you’d like to follow along. (You can also view the working demo. Or, if you prefer, play the improved game, which is the result of this article.

Styling the Game

Classic Pong is traditionally black and white, so we must get rid of the colored elements in our Pong.

This also means we need to import new sprites into the Unity project (by dragging them into the Sprites folder in the Assets pane). If you’re following along, feel free to use these examples from the demo code.

After importing the new sprites into Unity, we should select both sprites in the Assets pane and change their pixels per unit to 64. We must also hit Apply for the changes to take effect.

Now that we have our images, we can start updating our Pong Clone. First, we should change the color of the Main Camera’s background to black. This can be done by clicking on the color bar next to the word Background in the Main Camera’s inspector pane. Next, we need to change the color of the paddles. We should select the Player game object in the hierarchy pane and drag the white square sprite into the Sprite attribute’s value in the Sprite Renderer element. Now we should do the same for the Enemy game object.

In order to create the nice middle bar in Pong (see below), we need to create an empty game object (right-click in hierarchy -> create empty) and name it MiddleBar. The Middle Bar game object should have an X of 0 and a Y of 0, so that it’s located in the center of the screen. We can now drag the white square sprite onto the Middle Bar game object to make white squares that are children of the Middle Bar Game object. All of the children’s X scales should be low so that they look like skinny, white sticks.

Middle Bar Example

Finally, we need to change the ball’s sprite so that instead of a grey circle it will be a white circle. If we go to the the ball prefab (located in the Prefabs folder), we can select it and change its sprite as we did with the Player and Enemy, except using the white circle sprite.

Continue reading %Building a Pong Clone in Unity: UI and Gameplay%


by Vincent Quarles via SitePoint