Archiwum kategorii: CSS

Developing a design environment

Post pobrano z: Developing a design environment

Jules Forrest discusses some of the work that her team at Credit Karma has been up to when it comes to design systems. Jules writes:

…in most engineering organizations, you spend your whole first day setting up your development environment so you can actually ship code. It’s generally pretty tedious and no one likes doing it, but it’s this thing you do to contribute meaningful work to production. Which got me thinking, what would it look like to make it easier for designers to design for production?

That’s what Jules calls a “design environment” and she’s even written a whole bunch of documentation in Thread, Credit Karma’s design system, for designers on their team to get that design environment up and running. That’s stuff like fonts, Sketch plugins, and other useful assets:

These problems have certainly been tackled by other teams in the past but this is the first time I’ve heard the phrase “design environment” before and I sort of love the heck out of it. Oh, and this post reminds me of a piece by Jon Gold where he wrote about Painting with Code.

Direct Link to ArticlePermalink

The post Developing a design environment appeared first on CSS-Tricks.

What does the ‘h’ stand for in Vue’s render method?

Post pobrano z: What does the ‘h’ stand for in Vue’s render method?

If you’ve been working with Vue for a while, you may have come across this way of rendering your app — this is the default in the latest version of the CLI, in main.js:

new Vue({
 render: h => h(App)
}).$mount('#app')

Or, if you’re using a render function, possibly to take advantage of JSX:

Vue.component('jsx-example', {
  render (h) {
    return <div id="foo">bar</div>
  }
})

You may be wondering, what does that h do? What does it stand for? The h stands for hyperscript. It’s a riff of HTML, which means Hypertext Markup Language: since we’re dealing with a script, it’s become convention in virtual DOM implementations to use this substitution. This definition is also addressed in the documentation of other frameworks as well. Here it is, for example, in Cycle.js.

In this issue, Evan describes that:

Hyperscript itself stands for „script that generates HTML structures”

This is shortened to h because it’s easier to type. He also describes it a bit more in his Advanced Vue workshop on Frontend Masters.

Really, you can think of it as being short for createElement. Here would be the long form:

render: function (createElement) {
  return createElement(App);
}

If we replace that with an h, then we first arrive at:

render: function (h) {
  return h(App);
}

…which can then be shortened with the use of ES6 to:

render: h => h (App)

The Vue version takes up to three arguments:

render(h) {
  return h('div', {}, [...])
}
  1. The first is type of the element (here shown as div).
  2. The second is the data object. We nest some fields here, including: props, attrs, dom props, class and style.
  3. The third is an array of child nodes. We’ll then have nested calls and eventually return a tree of virtual DOM nodes.

There’s more in-depth information in the Vue Guide here.

The name hyperscript may potentially be confusing to some people, given the fact that hyperscript is actually the name of a library (what isn’t updated these days) and it actually has a small ecosystem. In this case, we’re not talking about that particular implementation.

Hope that clears things up for those who are curious!

The post What does the ‘h’ stand for in Vue’s render method? appeared first on CSS-Tricks.

Managing State in React With Unstated

Post pobrano z: Managing State in React With Unstated

As your application becomes more complex, the management of state can become tedious. A component’s state is meant to be self-contained, which makes sharing state across multiple components a headache. Redux is usually the go-to library to manage state in React, however, depending on how complex your application is, you might not need Redux.

Unstated is an alternative that provides you with the functionality to manage state across multiple components with a Container class and Provider and Subscribe components. Let’s see Unstated in action by creating a simple counter and then look at a more advanced to-do application.

Using Unstated to Create a Counter

The code for the counter we’re making is available on GitHub:

View Repo

You can add Unstated to your application with Yarn:

yarn add unstated

Container

The container extends Unstated’s Container class. It is to be used only for state management. This is where the initial state will be initialized and the call to setState() will happen.

import { Container } from 'unstated'

class CounterContainer extends Container {
  state = {
    count: 0
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 })
  }

  decrement = () => {
    this.setState({ count: this.state.count - 1 })
  }
}

export default CounterContainer

So far, we’ve defined the Container (CounterContainer), set its starting state for count at the number zero and defined methods for adding and subtracting to the component’s state in increments and decrements of one.

You might be wondering why we haven’t imported React at this point. There is no need to import it into the Container since we will not be rendering JSX at all.

Events emitters will be used in order to call setState() and cause the components to re-render. The components that will make use of this container will have to subscribe to it.

Subscribe

The Subscribe component is used to plug the state into the components that need it. From here, we will be able to call the increment and decrement methods, which will update the state of the application and cause the subscribed component to re-render with the correct count. These methods will be triggered by a couple of buttons that contain events listeners to add or subtract to the count, respectively.

import React from 'react'
import { Subscribe } from 'unstated'

import CounterContainer from './containers/counter'

const Counter = () => {
  return (
    <Subscribe to={[CounterContainer]}>
      {counterContainer => (
        <div>
          <div>
            // The current count value
            Count: { counterContainer.state.count }
          </div>
          // This button will add to the count
          <button onClick={counterContainer.increment}>Increment</button>
          // This button will subtract from the count
          <button onClick={counterContainer.decrement}>Decrement</button>
        </div>
      )}
    </Subscribe>
  )
}

export default Counter

The Subscribe component is given the CounterContainer in the form of an array to its to prop. This means that the Subscribe component can subscribe to more than one container, and all of the containers are passed to the to prop of the Subscribe component in an array.

The counterContainer is a function that receives an instance of each container the Subscribe component subscribes to.

With that, we can now access the state and the methods made available in the container.

Provider

We’ll make use of the Provider component to store the container instances and allow the children to subscribe to it.

import React, { Component } from 'react';
import { Provider } from 'unstated'

import Counter from './Counter'

class App extends Component {
  render() {
    return (
      <Provider>
        <Counter />
      </Provider>
    );
  }
}

export default App;

With this, the Counter component can make use of our counterContainer.

Unstated allows you to make use of all the functionality that React’s setState() provides. For example, if we want to increment the previous state by one three times with one click, we can pass a function to setState() like this:

incrementBy3 = () => {
  this.setState((prevState) => ({ count: prevState.count + 1 }))
  this.setState((prevState) => ({ count: prevState.count + 1 }))
  this.setState((prevState) => ({ count: prevState.count + 1 }))
}

The idea is that the setState() still works like it does, but this time with the ability to keep the state contained in a Container class. It becomes easy to spread the state to only the components that need it.

Let’s Make a To-Do Application!

This is a slightly more advanced use of Unstated. Two components will subscribe to the container, which will manage all of the state, and the methods for updating the state. Again, the code is available on Github:

View Repo

The container will look like this:

import { Container } from 'unstated'

class TodoContainer extends Container {
  state = {
    todos: [
      'Mess around with unstated',
      'Start dance class'
    ],
    todo: ''
  };

  handleDeleteTodo = (todo) => {
    this.setState({
      todos: this.state.todos.filter(c => c !== todo)
    })
  }
 
  handleInputChange = (event) => {
    const todo = event.target.value
    this.setState({ todo });
  };

  handleAddTodo = (event) => {
    event.preventDefault()
    this.setState(({todos}) => ({
      todos: todos.concat(this.state.todo)
    }))
    this.setState({ todo: '' });
  }

}

export default TodoContainer

The container has an initial todos state which is an array with two items in it. To add to-do items, we have a todo state set to an empty string.

We’re going to need a CreateTodo component that will subscribe to the container. Each time a value is entered, the onChange event will trigger then fire the handleInputChange() method we have in the container. Clicking the submit button will trigger handleAddTodo(). The handleDeleteTodo() method receives a to-do and filters out the to-do that matches the one passed to it.

import React from 'react'
import { Subscribe } from 'unstated'

import TodoContainer from './containers/todoContainer'

const CreateTodo = () => {
  return (
    <div>
      <Subscribe to={[TodoContainer]}>
        {todos =>
          <div>
            <form onSubmit={todos.handleAddTodo}>
              <input
                type="text"
                value={todos.state.todo}
                onChange={todos.handleInputChange}
              />
              <button>Submit</button>
            </form>
          </div>
        }
      </Subscribe>
    </div>
  );
}

export default CreateTodo

When a new to-do is added, the todos state made available in the container is updated. The list of todos is pulled from the container to the Todos component, by subscribing the component to the container.

import React from 'react';
import { Subscribe } from 'unstated';

import TodoContainer from './containers/todoContainer'

const Todos = () => (
  <ul>
    <Subscribe to={[TodoContainer]}>
      {todos =>
        todos.state.todos.map(todo => (
          <li key={todo}>
            {todo} <button onClick={() => todos.handleDeleteTodo(todo)}>X</button>
          </li>
        ))
      }
    </Subscribe>
  </ul>
);

export default Todos

This component loops through the array of to-dos available in the container and renders them in a list.

Finally, we need to wrap the components that subscribe to the container in a provider like we did in the case of the counter. We do this in our App.js file exactly like we did in the counter example:

import React, { Component } from 'react';
import { Provider } from 'unstated'

import CreateTodo from './CreateTodo'
import Todos from './Todos'

class App extends Component {
  render() {
    return (
      <Provider>
        <CreateTodo />
        <Todos />
      </Provider>
    );
  }
}

export default App;

Wrapping Up

There are different ways of managing state in React depending on the complexity of your application and Unstated is a handy library that can make it easier. It’s worth reiterating the point that Redux, while awesome, is not always the best tool for the job, even though we often grab for it in these types of cases. Hopefully you now feel like you have a new tool in your belt.

The post Managing State in React With Unstated appeared first on CSS-Tricks.

​Build a realtime polling web app with Next.js

Post pobrano z: ​Build a realtime polling web app with Next.js

(This is a sponsored post.)

Learn to build a webapp that accepts user votes, using Next.js and Chart.js. Users can vote for their favorite pet, and the results are displayed in realtime on a graph in their browser using Pusher Channels.

Direct Link to ArticlePermalink

The post ​Build a realtime polling web app with Next.js appeared first on CSS-Tricks.

Learning Gutenberg: Modern JavaScript Syntax

Post pobrano z: Learning Gutenberg: Modern JavaScript Syntax

One of the key changes that Gutenberg brings to the WordPress ecosystem is a heavy reliance on JavaScript. Helpfully, the WordPress team have really pushed their JavaScript framework into the present and future by leveraging the modern JavaScript stack, which is commonly referred to as ES6 in the community. It’s how we’ll refer to it as in this series too, to avoid confusion.

Let’s dig into this ES6 world a bit, as it’s ultimately going to help us understand how to structure and build a custom Gutenberg block.

Article Series:

  1. Series Introduction
  2. What is Gutenberg, Anyway?
  3. A Primer with create-guten-block
  4. Modern JavaScript Syntax (This Post)
  5. React 101 (Coming Soon!)
  6. Setting up a Custom webpack (Coming Soon!)
  7. A Custom „Card” Block (Coming Soon!)

What is ES6?

ES6 is short for “EcmaScript 6” which is the 6th edition of EcmaScript. It’s official name is ES2015, which you may have also seen around. EcmaScript has since gone through many iterations, but modern JavaScript is still often referred to as ES6. As you probably guessed, the iterations have continued ES2016, ES2017 and so-on. I actually asked a question on ShopTalk show about what we could name modern JavaScript, which I the conclusion was… ES6.

I’m going to run through some key features of ES6 that are useful in the context of Gutenberg.

Functions

Functions get a heck of an update with ES6. Two changes I want to focus on are Arrow Functions and Class Methods.

Inside a class you don’t actually need to write the word function anymore in ES6. This can be confusing, so check out this example:

class Foo { 
  // This is your 'bar' function
  bar() {
    return 'hello';
  }
}

You’d invoke bar() like this:

const fooInstance = new Foo();
const hi = fooInstance.bar();

This is commonplace in the land of modern JavaScript, so it’s good to clear it up.

Fun fact! ES6 Classes in JavaScript aren’t really “classes” in an object-oriented programming sense—under the hood, it’s the same old prototypical inheritance JavaScript has always had. Prior to ES6, the bar() method would be defined like so: Foo.prototype.bar = function() { ... }. React makes great use of ES6 classes, but it’s worth noting that ES6 classes are essentially syntactic sugar and hotly contested by some. If you’re interested in more details, checkout the MDN docs and this article on 2ality.

Right, let’s move on to arrow functions. 🚀

An arrow function gives us a compact syntax that is often used as a one-liner for expressions. It’s also used to maintain the value of this, as an arrow function won’t rebind this like setInterval or an event handler would usually do.

An example of an arrow function as an expression is as follows:

// Define an array of fruit objects
const fruit = [
  {
    name: 'Apple',
    color: 'red'
  },
  {
    name: 'Banana',
    color: 'yellow'
  },
  {
    name: 'Pear',
    color: 'green'
  }
];

// Select only red fruit from that collection
const redFruit = fruit.filter(fruitItem => fruitItem.color === 'red');

// Output should be something like Object { name: "Apple", color: "red" }
console.log(redFruit[0]);

As you can see above, because there was a single parameter and the function was being used as an expression, we can redact the brackets and parenthesis. This allows us to really compact our code and improve readability.

Let’s take a look at how we can use an arrow function as an event handler in our Foo class from before:

class Foo {
        
  // This is your 'bar' function
  bar() {
    let buttonInstance = document.querySelector('button');
    
    buttonInstance.addEventListener('click', evt => {
      console.log(this);
    });
  }
}

// Run the handler
const fooInstance = new Foo();
fooInstance.bar();

When the button is clicked, the output should be Foo { }, because this is the instance of Foo. If we were to replace that example with the following:

class Foo {
        
  // This is your 'bar' function
  bar() {
    let buttonInstance = document.querySelector('button');
    
    buttonInstance.addEventListener('click', function(evt) {
      console.log(this);
    });
  }
}

// Run the handler
const fooInstance = new Foo();
fooInstance.bar();

When the button is clicked, the output would be <button> because the function has bound this to be the <button> that was clicked.

You can read more about arrow functions with Wes Bos, who wrote an excellent article about them.

const, let, and var

You may have noticed that I’ve been using const and let in the above examples. These are also a part of ES6 and I’ll quickly explain what each one does.

If a value is absolutely constant and won’t change through re-assignment, or be re-declared, use a const. This would commonly be used when importing something or declaring non-changing properties such as a collection of DOM elements.

If you have a variable that you want to only be accessible in the block it was defined in, then use a let. This can be confusing to understand, so check out this little example:

function foo() {
  if (1 < 2) {
    let bar = 'always true';
    
    // Outputs: 'always true'
    console.log(bar);
  }
  
  // Outputs 'ReferenceError: bar is not defined'
  console.log(bar);
}

// Run the function so we can see our logs
foo();

This is a great way to keep control of your variables and make them disposable, in a sense.

Lastly, var is the same old friend we know and love so well. Unfortunately, between const and let, our friend is becoming more and more redundant as time goes on. Using var is totally acceptable though, so don’t be disheartened—you just won’t see it much in the rest of this tutorial!

Destructuring assignment

Destructuring allows you to extract object keys at the point where you assign them to your local variable. So, say you’ve got this object:

const foo = {
  people: [
    {
      name: 'Bar',
      age: 30
    },
    {
      name: 'Baz',
      age: 28
    }
  ],
  anotherKey: 'some stuff',
  heyAFunction() {
    return 'Watermelons are really refreshing in the summer' 
  }
};

Traditionally, you’d extract people with foo.people. With destructuring, you can do this:

let { people } = foo;

That pulls the people array out of the the foo object, so we can dump the foo. prefix and use it as it is: people. It also means that anotherKey and heyAFunction are ignored, because we don’t need them right now. This is great when you’re working with big complex objects where being able to selectively pick stuff out is really useful.

You can also make use of destructuring to break up an object into local variables to increase code readability. Let’s update the above snippet:

let { people } = foo;
let { heyAFunction } = foo;

Now we’ve got those two separate elements from the same object, while still ignoring anotherKey. If you ran console.log(people), it’d show itself an array and if you ran console.log(heyAFunction), you guessed it, it’d show itself as a function.

JSX

Most commonly found in React JS contexts: JSX is an XML-like extension to JavaScript that is designed to be compiled by preprocessors into normal JavaScript code. Essentially, it enables us to write HTML(ish) code within JavaScript, as long as we’re preprocessing it. It’s usually associated with a framework like React JS, but it’s also used for Gutenberg block development.

Let’s kick off with an example:

const hello = <h1 className="heading">Hello, Pal</h1>;

Pretty cool, huh? No templating system or escaping or concatenating required. As long as you return a single element, which can have many children, you’re all good. So let’s show something a touch more complex, with a React render function:

class MyComponent extends React.Component {
  /* Other parts redacted for brevity */
  
  render() {
    return (
      <article>
        <h2 className="heading">{ this.props.heading }</h2>
        <p className="lead">{ this.props.summary }</p>
      </article>
    );
  }
};

You can see above that we can drop expressions in wherever we want. This is also the case with element attributes, so we can have something like this:

<h2 className={ this.props.headingClass }> 
  { this.props.heading }
</h2> 

You might be thinking, “What are these random braces doing?”

The answer is that this is an expression, which you will see a ton of in JSX. Essentially, it’s a little inline execution of JavaScript that behaves very much like a PHP echo does.

You’ll also probably notice that it says className instead of class. Although it looks like HTML/XML, it’s still JavaScript, so reserved words naturally are avoided. Attributes are camel-cased too, so keep and eye out for that. Here’s a useful answer to why it’s like this.

JSX is really powerful as you’ll see while this series progresses. It’s a great tool in our stack and really useful to understand in general.

I like to think of JSX as made up-tag names that are actually just function calls. Pick out any of the made-up tags you see in Gutenberg, let’s use <InspectorControls /> for example, and do a „Find in Folder” for class InspectorControls and you’ll see something structured like Andy’s example here! If you don’t find it, then the JSX must be registered as functional component, and should turn up by searching for function InspectorControls.

Wrapping up

We’ve had a quick run through some of the useful features of ES6. There’s a ton more to learn, but I wanted to focus your attention on the stuff we’ll be using in this tutorial series. I’d strongly recommend your further your learning with Wes Bos’ courses, JavaScript 30 and ES6.io.

Next up, we’re going to build a mini React component!


Article Series:

  1. Series Introduction
  2. What is Gutenberg, Anyway?
  3. A Primer with create-guten-block
  4. Modern JavaScript Syntax (This Post)
  5. React 101 (Coming Soon!)
  6. Setting up a Custom webpack (Coming Soon!)
  7. A Custom „Card” Block (Coming Soon!)

The post Learning Gutenberg: Modern JavaScript Syntax appeared first on CSS-Tricks.

Just a Couple’a Fun Typography Links

Post pobrano z: Just a Couple’a Fun Typography Links

The post Just a Couple’a Fun Typography Links appeared first on CSS-Tricks.

Learning Gutenberg: A Primer with create-guten-block

Post pobrano z: Learning Gutenberg: A Primer with create-guten-block

Welcome back! We’ve just taken a look at what Gutenberg is and how it operates from the admin side. Gutenberg is certainly going to have a massive impact on the WordPress world. If you are just arriving here and have no idea what we’re talking about, I recommend at least skimming Part 1 to make sure you have the appropriate background.

Let’s create a custom block with a bit of help from a wonderful tool called create-guten-block. Onward!

Article Series:

  1. Series Introduction
  2. What is Gutenberg, Anyway?
  3. A Primer with create-guten-block (This Post)
  4. Modern JavaScript Syntax
  5. React 101 (Coming Soon!)
  6. Setting up a Custom webpack (Coming Soon!)
  7. A Custom „Card” Block (Coming Soon!)

Blocks live in plugins

To create a Gutenberg block, you create a WordPress plugin. Anything that affects *content*, like a Gutenberg block certain will, needs to be a plugin so that it remains active even as you change themes. Something that is very theme-specific or just affects how your site looks can be part of the theme files or functions.php file in your theme. Read more about this distinction in our article about WordPress Functionality Plugins.

That said, the blocks in themes issue is a hot topic. The WordPress Theme Review Team is discussing whether or not to allow blocks in themes at all as part of themes. A post, “Getting Ready for Gutenberg”, on the Theme Review Team’s Make page posed this question, and was met with strong opinions from both sides. The general consensus, however, is that blocks are plugin territory.

WordPress.org is comprised of various teams, each with their own homepage at make.wordpress.org/team-name, channel in the WordPress Slack, and a weekly meeting. If you are interested in getting involved in WordPress or curious about how it operates, I highly recommend browsing through a list of the teams here, joining a Slack channel, and popping into a weekly meeting to see how it all happens.

In the far future, it’s possible that themes will consist of *just a stylesheet*, while all custom functionality and content structure come from blocks in plugins. I’m paraphrasing the words of Tammie Lister, Gutenberg’s design lead, on this episode of Shoptalk Show. Very much worth a listen!

Taking a setup shortcut… for now

What’s kept me from diving head first into modern JavaScript is the dang configuration. The transpiling, the bundling, the code splitting, the tree shaking… yeesh, I’m busy! I love learning new things, but there’s a limit to my patience and, apparently, configuring a build process for a small test project is my limit.

It’s this sentiment that led to the development of a tool called create-react-app, zero-configuration build setup for, you guessed it, creating React apps. It’s brilliant. Assuming you have a functioning node and npm installation, you can run a single command and you have a project ready for you to start coding in React. The transpiling, bundling, and tree shaking is set up for you.

But wait… can we use create-react-app for Gutenberg blocks? No, but the aforementioned create-guten-block, developed and beautifully documented by Ahmad Awais, does pretty much the same thing for us! That’s what we’ll be using for our block.

create-guten-block is not the only block generating tool at our disposal! You can scaffold a block using WP-CLI, but I have chosen not to because the default setup is for ES5 (for now) and does not give us what we need for our journey into modern JavaScript. That being said, I found it helpful to dig through the ES5 implementation of a block as a way to reinforce the core concepts, so maybe give it a go after you finish here!

Yes, this is a shortcut. We are choosing to avoid understanding the core concepts of a technology by using a tool. We’ll have to learn these concepts someday. But for now, I’m totally fine bypassing this configuration step. My philosophy about using tools such as this: use them, but do so with the understanding that it *probably* won’t save you time or effort in the long run.

It’s worth noting that, like create-react-app, create-guten-block allows you to npm eject your configuration. This means exposing all of the settings the tool has created for us and making them available for customization. Note, however, that this is irreversible; if you eject and then make a mistake, you’re on your own to fix it! Like I said, you’ll have to learn it someday 🙂

Step 1: Install create-guten-block

We will first install create-guten-block globally, like so:

npm install -g create-guten-block

In theory this should work no problem, but that’s not realistic. create-guten-block requires a minimum of Node version 8 and npm 5.3, so if you haven’t updated either of them for a while, that’s one possible error (and here’s one possible solution).

I always start by pasting my console error into a search engine and removing line numbers and file names to keep my query general. In the interest of improving this tutorial, however, I am curious to hear about what went wrong so feel free to post your issue in the comments as well.

Step 2: Create that guten-block

It’s time! Let’s do it! You know what? I’m not going to tell you how because Ahmad’s documentation is so good and there’s no sense in replicating it.

Go here and follow Ahmad’s instructions to create that guten-block in your command line.

A screenshot of the integrated terminal showing the build process has started
You should see something like this when running the command, create-guten-block test, where “test” is the name of my block.

Step 3: Activate the plugin

Go to your Plugins screen, activate your new block plugin — it should be called something like test-block — CGB Gutenberg Block Plugin where „test-block” is what you named your block when creating it.

Screenshot of the Plugins screen of the WordPress admin showing the create-guten-block plugin is active

Step 4: That’s it! Let’s use our custom block!

So easy! Now, go to the editor view of a post or page, locate your block, and insert it.

Animated GIF showing the selection and insertion of the default block from create-guten-block

Although I named my block “test”, searching “test” in the block selector yielded the wrong result as you can see in the gif above. The default name of the block is instead “CGB Block” — we will change this very soon!

Text editor setup (optional)

I’ve found it very helpful to have a specific text editor setup for developing blocks. I use Visual Studio Code for my text editor, but I’m sure you can figure out something similar with whatever editor is your preference.

Here are the key ingredients:

  1. Easy access to the command line to keep an eye on build errors (there will be build errors)
  2. A copy of the Gutenberg source from GitHub for code reference (download or clone it here)
  3. Easy access to both your plugin’s directory and Gutenberg’s source directory from #2
A screenshot of the VS Code text editor, showing the integrated terminal and sidebar of folders
​​My VS Code setup for Gutenberg development. Notice the integrated terminal and multiple source directories on the right.

In VS Code, I accomplish this using the following features:

  1. The integrated terminal — open with Command + ~ on Mac, or from the menu bar with View > Integrated Terminal
  2. A Workspace containing folders for both your plugin and Gutenberg’s source from GitHub. You can doing this by opening your plugin directory in VS Code, then choosing File > Add Folder to Workspace and selecting the Gutenberg directory you downloaded from the GitHub repo. You can then save the Workspace for easy access with File > Save Workspace As (I called mine “Blocks” in the image above).

This part is optional, and you don’t have to use VS Code. The important thing is having ready access to the command line, your plugin’s source, and the Gutenberg plugin’s source for reference. You can totally reference the source on GitHub if you like, but I enjoy having the files in the same environment for side-by-side comparison and easy searching with Find In Folder.

We are using Gutenberg from the plugin repository for the actual functionality, but that instance only includes the compiled files. We want to reference the source files, so we need to use the codebase directly from GitHub. If you’d like to access updates before they are released in the plugin, you can clone the repository. It would be totally possible to build and work from the GitHub version, but for simplicity’s sake, we are using the plugin version in this tutorial.

Once you are ready to go, make sure you are cd’d into your block’s plugin folder and run npm start. You should see a satisfying message indicating the process has started:

A screenshot of the integrated terminal showing the build process has started
After running npm start in our plugin folder, we are officially “Watching for changes…” (and we didn’t have to touch any config! Cheaters…)

I’m using Wes Bos’s theme for Cobalt 2 in VS Code as well as the same theme for ZSH in my Terminal and iTerm. This makes absolutely no difference in how the technology works, but it does make a difference, on a personal level, to customize your workspace and make it feel like your own (or Wes Bos’, in my case).

What’s what

Now that we are in code mode, let’s take a look at the files we’ll be working with. I’ll borrow this from the create-guten-block Readme for reference:

└── test-block
  ├── plugin.php
  ├── package.json
  ├── README.md
  |
  ├── dist
  |  ├── blocks.build.js
  |  ├── blocks.editor.build.css
  |  └── blocks.style.build.css
  |
  └── src
     ├── block
     |  ├── block.js
     |  ├── editor.scss
     |  └── style.scss
     |
     ├── blocks.js
     ├── common.scss
     └── init.php

For the purposes of this tutorial, we are only concerned with what is inside the src directory. We will not touch anything in dist (those are compiled files), plugin.php, or any stragglers such as package.json, package-lock.json, or.eslintignore.

plugin.php officially alerts WordPress of our plugin’s existence. It requires src/init.php, which is where we’ll write any PHP we need for our block(s). In general, we won’t write anything in plugin.php — out of the box, the only code it contains are the comments to register our plugin.

Let’s drill into src:

└── src
   ├── block
   |  ├── block.js
   |  ├── editor.scss
   |  └── style.scss
   |
   ├── blocks.js
   ├── common.scss
   └── init.php

The block directory contains files for single, individual block. This includes:

  • block/block.js — All the JavaScript for the individual block.
  • block/editor.scss — Sass partial for styles specific to the editor view,
  • block/style.scss — Sass partial for styles specific to the front-end view, i.e. what you see when you view your page/post.

Now, open up src/blocks.js:

A screenshot of the contents of blocks.js showing a single line importing the file blocks/block.js

I think of src/blocks.js as a table of contents for blocks, similar to the role of an index.scss or main.scss in a Sass project structure. If we wanted to include two blocks in our plugin — let’s say this was a suite of custom blocks — we could, in theory, duplicate the block directory, rename it, and add something like this to src/blocks.js:

import 'new-block/block.js';>

Then, whatever create-guten-block has prepared for us behind the scenes would know to include our new block’s block.js in the main script file compiled into dist (now is a good time to take a peek into dist, if you haven’t already).

Not too bad so far, right? We still haven’t really gotten to any JavaScript…

A challenge!

Okay, now it’s time for a challenge! Open up src/block/block.js and take a couple of minutes to read through the author, Ahmad’s, excellent comments.

Then, see if you can figure out how to*:

  1. Change the name of your block, that is, the one that shows in the block selector
  2. Change the icon of your block (❤ Dashicons)
  3. Change the text that displays on the front end i.e. when you “View Post”
  4. Change the text that displays on the back end i.e. editor view
  5. Give the front end view a border radius of 30px
  6. Give the editor view a gradient background
  7. Make the text in first paragraph tag editable

* You should be able to work through (almost!) all of these in about 10 minutes. 😉


How was that?

What problems did you run into? Did you get tired of reloading the editor? Did you see the “This block appears to have been modified externally” message more often than you’d like? I sure did, but such is life with new technology — there’s a lot to be desired in the developer experience, but this isn’t a priority for the team at present and will come in the later stages of Gutenberg’s planned development.

Most importantly, did you get #7?

If you did, then you should be writing this tutorial! That one was a gotcha. I hope you felt at least a little confused and curious because that’s how we learn! We’ll get to that in Part 3.

Now that we have our bearings, let’s dig deeper into this notion of a block.

Skeleton of a block

Here is block.js with the comments stripped out — what we might call the skeleton of a static block:

// Stripped down version of src/block/block.js

// PART 1: Import dependencies
import './style.scss';
import './editor.scss';

// PART 2: Setup references to external functions
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;

// PART 3: Register the block!
registerBlockType( 'cgb/block-test', {
  
  // Part 3.1: Block settings
  title: __( 'test - CGB Block' ),
  icon: 'shield',
  category: 'common',
  keywords: [
    __( 'test &mdash; CGB Block' ),
    __( 'CGB Example' ),
    __( 'create-guten-block' ),
  ],
  
  // PART 3.2: Markup in editor
  edit: function( props ) {
    return (
      <div>You’ll see this in the editor</div>
    );
  },
  
  // PART 3.3: Markup saved to database
  save: function( props ) {
    return (
      <div>This is saved to the database and returned with the_content();</div>
    );
  },
} );

Let’s do a side-by-side comparison with another static block, the “Separator” block from the default blocks included in Gutenberg. That file is is located in gutenberg/blocks/library/separator/index.js. If you have the folder open in either VS Code or Sublime, you can use the shortcut Command + Option + 2 on a Mac, or View > Split Editor to get the files side-by-side.

If you are following the text editor setup outlined previously, you should have something like this:

Side-by-side block.js files in VS Code — one side the block.js from create-guten-block, the other from the separator block in the Gutenberg library

In this image, I copy/pasted the above stripped-down version of the block into an empty file to compare it without the comments. That’s optional!

What similarities do you notice? What differences? Open up a few of the other block directories inside gutenberg-master/library/, and take a peek into their files, comparing them to our block skeleton. Spend a few minutes reading the code and see if you can spot some patterns.

Here are a few patterns I noticed:

  1. There are curly braces in variable declarations and function arguments all over the place.
  2. Markup appears inside of return statements and often contains made-up tag names (you might recognize these as React components).
  3. All blocks seem to have a settings object containing entires for title, icon , category, etc. In the library blocks, they appear in an export const settings = ... object, whereas in our plugin block, they are part of an argument for registerBlockType.
  4. All blocks have functions for edit and save as part of the settings object.
    • The syntax for the functions is slightly different than our block’s editand save functions:
      • edit( { className } ) { ... } in separator/index.js
      • edit: function(props) { ... } in our block.js
    • The library blocks appear to reference attributes and instead of props
  5. All blocks in the library contain an index.js. Some contain a block.js or other files that appear to contain a definition for a class extending a Component, e.g. class LatestPostsBlock extends Component { ....

What did you find? Feel free to contribute in the comments (but don’t stop reading here!).

A somewhat brief and relevant tangent

You probably noticed a statement importing @wordpress/i18n in every index.js and block.js file in the library, as well as a reference to wp.i18n in our plugin’s block.js. i18n stands for internationalization just like a11y stands for accessibility. Internationalization refers to the practice of developing your application to be easily translated to other languages. Since we want to prepare all static text in our blocks for translation, we assign wp.i18n to an alias of __for brevity, very much like we use the $ as an alias for good ‘ol jQuery. Read more about i18n for WordPress here

It’s also worth mentioning where that wp in wp.i18n is coming from and why it’s referenced as @wordpress/i18n in the Gutenberg source. wp is a global object — global meaning a variable available everywhere — containing all of WordPress’ publicly available JavaScript API methods. To demonstrate this, open up the console while on a page within the WordPress admin. Type wp and hit Enter. You should see something like this:

Animated GIF showing the response object when wp is typed into the console

So, anytime we reference something within that wp object, all we are doing is accessing some functionality the WordPress JavaScript API provides us. @wordpress/i18n in the Gutenberg source is doing the same thing, but its importing the functions from an npm module rather than the global object. The functions in the wp global have been intentionally exposed to the public API by the WordPress core developers for use in themes and plugins.

If you are anything like my internal critic, you might be thinking, “Whatever, Lara, I don’t care about those details. Just tell me how to make a cool block with all the JavaScript already!” To which I would reply:

There are so many moving parts and new concepts in this environment that, I’ve found, the more code I take for granted, the more frustrating and time-consuming the process becomes. Approach every line of code with curiosity! If you don’t know what it does, do a Find in Folder in the Gutenberg source and see if you can find a trail to follow. For me, at least, this has been a much more enjoyable way to approach unfamiliar code than trying to build something haphazardly with copy and paste.

And with that, let’s wrap up Part 2!

Homework

What? Homework? Heck yes, there is homework! In Part 3, Andy 🍉 will dive into modern JavaScript goodies: React, JSX, and ES6 syntax. Although our series is written for those relatively new to JavaScript, it is helpful to learn the code and the concepts from many different angles and resources.

In an effort to introduce some concepts early on, here is an outline for some “Homework” prior to Part 3:

1. Spend some time (1-2 hours) on a React tutorial, or until you can explain in your own words:

  • The render method in React
  • JSX and that those made-up tag names map to JavaScript functions
  • Why React uses className instead of class

Recommended resources:

I’d also recommend reading React State from the Ground Up here on CSS-Tricks, by Kingsley Silas, because it specifically dives into state in React. If you are brand new to React, this will be a lot to digest, but I think it’s worth getting it into your brain ASAP even if it doesn’t make sense quite yet.


2. Understand ES6 Destructuring and find a few examples of it in both the Gutenberg source and our plugin (that won’t be hard).

Recommended resources:


3. Be comfortable with conditional or ternary operators.

In a sentence, ternary operators are shorthand for if...else statements. You’ll see these all over the Gutenberg source — find some simple examples that provide a fallback for a string’s value, as well as more robust uses like in blocks/library/paragraph/index.js, for example.

Recommended resources:

  • The MDN article is very good.
  • Also look into the not not operator — here is a Stack Overflow post about it.
  • Not to get too far down this rabbit hole, but if you are extra ambitious, do some research about type coercion in JavaScript. This article on FreeCodeCamp and this chapter from You Don’t Know JS by Kyle Simpson are solid starting points.

Okay! Thank you so much for reading, and see you in Part 3 for React, JSX, and other goodies.

Comments

Was there any part of this tutorial that didn’t make sense? Did you get lost anywhere? We’d love to keep making this better, so please let us know if any part of this was hard to follow or if any information is incorrect or out of date.

Thank you, again, and good luck!


Article Series:

  1. Series Introduction
  2. What is Gutenberg, Anyway?
  3. A Primer with create-guten-block (This Post)
  4. Modern JavaScript Syntax
  5. React 101 (Coming Soon!)
  6. Setting up a Custom webpack (Coming Soon!)
  7. A Custom „Card” Block (Coming Soon!)

The post Learning Gutenberg: A Primer with create-guten-block appeared first on CSS-Tricks.

​Build live comments with sentiment analysis using Nest.js

Post pobrano z: ​Build live comments with sentiment analysis using Nest.js

(This is a sponsored post.)

Interestingly, one of the most important areas of a blog post is the comment section. This plays an important role in the success of a post or an article, as it allows proper interaction and participation from readers. This makes it inevitable for every platform with a direct comments system to handle it in realtime.

In this post, we’ll build an application with a live comment feature. This will happen in realtime as we will tap into the infrastructure made available by Pusher Channels. We will also use the sentiment analysis to measure whether comments are positive or negative, and display this information on an admin panel.

Direct Link to ArticlePermalink

The post ​Build live comments with sentiment analysis using Nest.js appeared first on CSS-Tricks.

The backdrop-filter CSS property

Post pobrano z: The backdrop-filter CSS property

I had never heard of the backdrop-filter property until yesterday, but after a couple of hours messing around with it I’m positive that it’s nothing more than magic. This is because it adds filters (like changing the hue, contrast or blur) of the background of an element without changing the text or other elements inside.

Take this example where I’ve replicated the iOS notification style: see how the background of each of these boxes are blurred but the text isn’t?

That’s only a single line of CSS to create that faded background effect, just like this:

.notification {
  backdrop-filter: blur(3px);
}

Now it’s worth noting that browser support for this CSS property isn’t particularly well supported just yet (see below). But we’ve been trying to do this sort of filtering stuff for a really long time and so it’s great to see that progress is being made here. Chris wrote about the “frosted-glass” technique in 2014 and way back then you had to use a bunch of weird hacks and extra images to replicate the effect. Now we can write a lot less code to get the same effect!

We also get to pick from a lot more filters than just that frosted glass style. The following demo showcases all of the backdrop-filter values and how they change the background:

Each of these boxes are just separate divs where I’ve applied a different backdrop-filter to each. And that’s it! I sort of can’t believe how simple this is, actually.

Of course you can chain them together like so:

.element {
  backdrop-filter: blur(5px) contrast(.8);
} 

And this could make all sorts of elaborate and complex designs, especially if you start combining them together with animations.

But wait, why do we even need this property? Well, after reading up a little it seems that the go-to default example is a modal of some description. That’s what Guillermo Esteves was experimenting with back in 2015:

See the Pen PwRPZa by Guillermo Esteves (@gesteves) on CodePen.

I reckon we can do something much weirder and more beautiful if we put our minds to it.

A note about browser support

The backdrop-filter property is not well supported at the time of this writing. And even in Safari where it is supported, you’ll still need to prefix it. There’s no support for Firefox at all. But, really, do websites need to look exactly the same in every browser?

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
No No No No 17 9*

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
9.0-9.2* No No No No No

Further reading

The post The backdrop-filter CSS property appeared first on CSS-Tricks.

A Strategy Guide To CSS Custom Properties

Post pobrano z: A Strategy Guide To CSS Custom Properties

CSS preprocessor variables and CSS custom properties (often referred to as „CSS variables”) can do some of the same things, but are not the same.

Practical advice from Mike Riethmuller:

If it is alright to use static variables inside components, when should we use custom properties? Converting existing preprocessor variables to custom properties usually makes little sense. After all, the reason for custom properties is completely different. Custom properties make sense when we have CSS properties that change relative to a condition in the DOM — especially a dynamic condition such as :focus, :hover, media queries or with JavaScript.

Direct Link to ArticlePermalink

The post A Strategy Guide To CSS Custom Properties appeared first on CSS-Tricks.