Brands show support for Black Lives Matter

Original Source: http://feedproxy.google.com/~r/CreativeBloq/~3/AMfFq1eEBxI/brands-black-lives-matter

As anti-racism protests continue across the world in the wake of the death of George Floyd, several brands have spoken out to show support for the Black Lives Matter movement over the last few days.

Many brands are delivering strong statements right now (and it will be interesting to see if they are followed by tangible action). In a minimal, text-based ad, Nike inverted its famous 'Just do it' slogan, urging its followers: 'For once, don't do it. Don't turn your back on racism." Sportswear brand Adidas even put its rivalry with Nike aside to share the message (below). 

Elsewhere, Twitter changed its profile picture to a black version of its logo, as well as opting for a plain-black header photo (below). This echoes the #blackouttuesday movement sweeping across Instagram today, in which countless users have posted a plain-black square in support of Black Lives Matter.

Ice cream brand Ben and Jerry's took to Twitter two days after George Floyd's death, sharing a four year-old news post covering the unrest in Ferguson after the death of Michael Brown, in which the brand expressed its support for the Black Lives Matter movement. 

While it's important for brands to show solidarity, it can be a challenge to avoid looking opportunistic or even tone-deaf – past actions matter, too. Less warmly received was L'Oreal Paris's effort, which saw it proclaim: "Speaking out is worth it". British model and activist Munroe Bergdorf was quick to condemn the post (below), having been dropped from a campaign by the brand after speaking out on racism in 2017.

A global audience is quick to speak out when they judge that a brand is failing to deliver an authentic message, as we saw with McDonald's social distancing logo this March. We have seen before that it can be a challenging tone to strike – take a look at these other examples of big brands trying to be woke and failing – while others get it right.

Read more:

Pop culture creatures become scientific drawings (and we want them all)Lego's comical guide to working from home will brighten your dayCartoons for key workers are a heartwarming delight

28 Chrome Extensions for Better Productivity

Original Source: https://www.hongkiat.com/blog/productivity-chrome-extensions/

There are a number of productivity apps for mobiles and a lot of productivity tools for PCs. But did you know that there are some really amazing Chrome extensions that can take your productivity to…

Visit hongkiat.com for full content.

30 Cool Street Art Around The World

Original Source: https://www.hongkiat.com/blog/cool-street-art/

Art has been changing its appeal to the man on the street. You no longer have to visit museums and art galleries to get a taste of contemporary art. You can easily find wall paintings, graffiti and…

Visit hongkiat.com for full content.

UI Interactions & Animations Roundup #7

Original Source: http://feedproxy.google.com/~r/tympanus/~3/Y0n9HyYXXJw/

A couple of weeks have past and a fresh collection of inspirational UI shots is waiting for you! This time the roundup comes with lots of sophistication in movements and more subtle distortion effects on images and typographic elements. Animated 3D objects give a touch of drama to interfaces; you’ll also see some of those.

Please enjoy this special collection and hopefully it will get your creative juices flowing!

M. Editorial Website Animation

by Zhenya Rynzhuk

Hestia

by Hrvoje Grubisic

The Secret Project — 001

by Aristide Benoist

Format Ikea planner inner page interaction

by Taras Migulko

Otherworldly the Blob in Action

by Efi Kabak

Furniture Ecommerce Website

by tubik

Nº1

by Slava Kornilov

Millie N. Portfolio — Website

by Bastien Allard

Francesco Interactions

by Matthew Hall

GlobeKit Website Refresh – FAQs Transition

by Nainoa Shizuru

Real Estate Landing Page

by Adam Roller

MIX

by Slava Kornilov

M. Editorial Website Loading Animation

by Zhenya Rynzhuk

Havana – Animation

by Tran Mau Tri Tam

Fashion Magazine

by Zinat Farahani

2º Reading

by Dimest

Folio No.01

by Ruslan Siiz

MOBIUS RIING C4D ANIMATION

by 秦能补拙的大表哥

New digs at FishermenLabs.com!

by Fishermen Labs

Reject 001 – A Landing Page

by Quintin Lodge

The post UI Interactions & Animations Roundup #7 appeared first on Codrops.

React Error Handling And Reporting With Error Boundary And Sentry

Original Source: https://www.smashingmagazine.com/2020/06/react-error-handling-reporting-error-boundary-sentry/

React Error Handling And Reporting With Error Boundary And Sentry

React Error Handling And Reporting With Error Boundary And Sentry

Chidi Orji

2020-06-01T12:00:00+00:00
2020-06-01T15:38:02+00:00

In this article, we’ll look at error boundaries in React. We’ll learn what they are and how to use them to deliver a better user experience, even when something breaks in our app. We’ll also learn how to integrate with Sentry for realtime error monitoring.

This tutorial is aimed at React developers of every level who wants to start using error boundaries in their react apps.

The only prerequisite is that you have some familiarity with React class components.

I will be using Yarn as my package manager for this project. You’ll find installation instructions for your specific operating system over here.

What Is An Error Boundary And Why Do We Need It?

A picture, they say, is worth a thousand words. For that reason, I’d like to talk about error boundaries using — you guessed it — pictures.

The illustration below shows the component tree of a simple React app. It has a header, a sidebar on the left, and the main component, all of which is wrapped by a root <App /> component.

An example react component tree

Component tree. (Large preview)

On rendering these components, we arrive at something that looks like the picture below.

Rendered view of previous component tree

App render. (Large preview)

In an ideal world, we would expect to see the app rendered this way every single time. But, unfortunately, we live in a non-ideal world. Problems, (bugs), can surface in the frontend, backend, developer’s end, and a thousand other ends. The problem could happen in either of our three components above. When this happens, our beautifully crafted app comes crashing down like a house of cards.

React encourages thinking in terms of components. Composing multiple smaller components is better than having a single giant component. Working this way helps us think about our app in simple units. But aside from that won’t it be nice if we could contain any errors that might happen in any of the components? Why should a failure in a single component bring down the whole house?

In the early days of React, this was very much the case. And worse, sometimes you couldn’t even figure out what the problem was. The React repository on Github has some of such notable errors here, here, and here.

React 16 came to the rescue with the concept of an “error boundary”. The idea is simple. Erect a fence around a component to keep any fire in that component from getting out.

The illustration below shows a component tree with an <ErrorBoundary /> component wrapping the <Main /> component. Note that we could certainly wrap the other components in an error boundary if we wanted. We could even wrap the <App /> component in an error boundary.

Component tree with error boundary: An example React component tree with an error boundary component.

Component tree with error boundary. (Large preview)

The red outline in the below illustration represents the error boundary when the app is rendered.

Rendered view of previous component tree, with error boundary

App rendered with error boundary. (Large preview)

As we discussed earlier, this red line keeps any errors that occur in the <Main /> component from spilling out and crashing both the <Header /> and <LeftSideBar /> components. This is why we need an error boundary.

Now that we have a conceptual understanding of an error boundary, let’s now get into the technical aspects.

What Makes A Component An Error Boundary?

As we can see from our component tree, the error boundary itself is a React component. According to the docs,

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch().

There are two things to note here. Firstly, only a class component can be used as an error boundary. Even if you’re writing all your components as function, you still have to make use of a class component if you want to have an error boundary. Secondly, it must define either (or both) of static getDerivedStateFromError() or componentDidCatch(). Which one(s) you define depends on what you want to accomplish with your error boundary.

Functions Of An Error Boundary

An error boundary isn’t some dumb wall whose sole purpose in life is to keep a fire in. Error boundaries do actual work. For starters, they catch javascript errors. They can also log those errors, and display a fallback UI. Let’s go over each of these functions one after the other.

Catch JavaScript Errors

When an error is thrown inside a component, the error boundary is the first line of defense. In our last illustration, if an error occurs while rendering the <Main /> component, the error boundary catches this error and prevents it from spreading outwards.

Logs Those Errors

This is entirely optional. You could catch the error without logging it. It is up to you. You can do whatever you want with the errors thrown. Log them, save them, send them somewhere, show them to your users (you really don’t want to do this). It’s up to you.

But to get access to the errors you have to define the componentDidCatch() lifecycle method.

Render A Fallback UI

This, like logging the errors, is entirely optional. But imagine you had some important guests, and the power supply was to go out. I’m sure you don’t want your guests groping in the dark, so you invent a technology to light up the candles instantaneously. Magical, hmm. Well, your users are important guests, and you want to afford them the best experience in all situations.
You can render a fallback UI with static getDerivedStateFromError() after an error has been thrown.

It is important to note that error boundaries do not catch errors for the following situations:

Errors inside event handlers.
Errors in asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks).
Errors that happen when you’re doing some server-side rendering.
Errors are thrown in the error boundary itself (rather than its children). You could have another error boundary catch this error, though.

Working With Error Boundaries

Let’s now dive into our code editor. To follow along, you need to clone the repo.
After cloning the repo, check out the 01-initial-setup branch. Once that is done, run the following commands to start the app.

# install project dependencies
yarn install

# start the server
yarn start

When started, the app renders to what we have in the picture below.

The starter app running in the browser

Browser view of starter app. (Large preview)

The app currently has a header and two columns. Clicking on Get images in the left column makes an API call to the URL https://picsum.photos/v2/list?page=0&limit=2 and displays two pictures. On the right column, we have some description texts and two buttons.

When we click the Replace string with object button, we’ll replace the text {"function":"I live to crash"}, which has been stringified, with the plain JavaScript object. This will trigger an error as React does not render plain JavaScript objects. This will cause the whole page to crash and go blank. We’ll have to refresh the page to get back our view.

Try it for yourself.

Now refresh the page and click the Invoke event handler button. You’ll see an error screen popup, with a little X at the top right corner. Clicking on it removes the error screen and shows you the rendered page, without any need to refresh. In this case, React still knows what to display even though an error is thrown in the event handler. In a production environment, this error screen won’t show up at all and the page will remain intact. You can only see that something has gone wrong if you look in the developer console.

A screen to alert us that an error has occurred in an event handler.

Event handler error alert. (Large preview)

Note: To run the app in production mode requires that you install serve globally. After installing the server, build the app, and start it with the below command.

# build the app for production
yarn build

# serve the app from the build folder
serve -s build

Having seen how React handles two types of errors, (rendering error, and event handler error), let’s now write an error boundary component.

Create a new ErrorBoundary.js file inside the /src folder and let’s build the error boundary component piece by piece.

import React, { Component } from ‘react’;
import PropTypes from ‘prop-types’;

export default class ErrorBoundary extends Component {
state = {
error: ”,
errorInfo: ”,
hasError: false,
};
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
// eslint-disable-next-line no-console
console.log({ error, errorInfo });
this.setState({ errorInfo });
}
render() {
// next code block goes here
}
}
ErrorBoundary.propTypes = {
children: PropTypes.oneOfType([ PropTypes.object, PropTypes.array ]).isRequired,
};

We define both of the two lifecycle methods that make a component an error boundary. Whenever an error occurs inside the error boundary’s child component, both of our lifecycle methods are activated.

static getDerivedStateFromError() receives the error and updates the state variables, error and hasError.
componentDidCatch() receives the error, which represents the error that was thrown and errorInfo which is an object with a componentStack key containing information about which component threw the error. Here we logged the error and also update the state with the errorInfo. It’s totally up to you what you want to do with these two.

Then in the render method, we return this.props.children, which represents whatever component that this error boundary encloses.

Let’s add the final piece of code. Copy the following code and paste it inside the render() method.

const { hasError, errorInfo } = this.state;
if (hasError) {
return (
<div className=”card my-5″>
<div className=”card-header”>
<p>
There was an error in loading this page.{‘ ‘}
<span
style={{ cursor: ‘pointer’, color: ‘#0077FF’ }}
onClick={() => {
window.location.reload();
}}
>
Reload this page
</span>{‘ ‘}
</p>
</div>
<div className=”card-body”>
<details className=”error-details”>
<summary>Click for error details</summary>
{errorInfo && errorInfo.componentStack.toString()}
</details>
</div>
</div>
);
}

In the render() method, we check if hasError is true. If it is, then we render the <div className="card my-5"></div> div, which is our fallback UI. Here, we’re showing information about the error and an option to reload the page. However, in a production environment, it is not advised to show the error to the user. Some other message would be fine.

Let’s now make use of our ErrorBoundary component. Open up App.js, import ErrorBoundary and render ColumnRight inside it.

# import the error boundary
import ErrorBoundary from ‘./ErrorBoundary’;

# wrap the right column with the error boundary
<ErrorBoundary>
<ColumnRight />
</ErrorBoundary>

Now click on Replace string with object. This time, the right column crashes and the fallback UI is displayed. We’re showing a detailed report about where the error happened. We also see the error log in the developer console.

A view of an error boundary showing a fallback UI.

View of error boundary in action. (Large preview)

We can see that everything else remains in place. Click on Get images to confirm that it still works as expected.

At this point, I want to mention that with error boundaries, you can go as granular as you want. This means that you can use as many as necessary. You could even have multiple error boundaries in a single component.

With our current use of Error Boundary, clicking Replace string with object crashes the whole right column. Let’s see how we can improve on this.

Open up src/columns/ColumnRight.js, import ErrorBoundary and render the second <p> block inside it. This is the paragraph that crashes the <ColumnRight /> component.

# import the component
import ErrorBoundary from ‘../ErrorBoundary’;

# render the erring paragraph inside it.
<ErrorBoundary>
<p>
Clicking this button will replace the stringified object,{‘ ‘}
<code>{text}</code>, with the original object. This will result in a
rendering error.
</p>
</ErrorBoundary>

Now click on Replace string with object.

View of app with an improvement on the use of our error boundary.

Improved error boundary usage. (Large preview)

This time, we still have most of the page intact. Only the second paragraph is replaced with our fallback UI.

Click around to make sure everything else is working.

If you’d like to check out my code at this point you should check out the 02-create-eb branch.

In case you’re wondering if this whole error boundary thing is cool, let me show you what I captured on Github a few days ago. Look at the red outline.

A view of an error message on Github, with something that looks like an error boundary.

Error screen on Github. (Large preview)

I’m not certain about what is happening here, but it sure looks like an error boundary.

Error boundaries are cool, but we don’t want errors in the first place. So, we need to monitor errors as they occur so we can get a better idea of how to fix them. In this section, we’ll learn how Sentry can help us in that regard.

Integrating With Sentry

As I opened the Sentry homepage while writing this line, I was greeted by this message.

Software errors are inevitable. Chaos is not.
Sentry provides self-hosted and cloud-based error monitoring that helps all software teams discover, triage, and prioritize errors in real-time.

Sentry is a commercial error reporting service. There are many other companies that provide similar services. My choice of Sentry for this article is because it has a free developer plan that lets me log up to 5,000 events per month across all my projects (pricing docs). An event is a crash report (also known as an exception or error). For this tutorial, we will be making use of the free developer plan.

You can integrate Sentry with a lot of web frameworks. Let’s go over the steps to integrate it into our React project.

Visit the Sentry website and create an account or login if you already have one.
Click on Projects in the left navigation. Then, click on Create Project to start a new project.
Under Choose a platform, select React.
Under Set your default alert settings check Alert me on every new issue.
Give your project a name and click Create project. This will create the project and redirect you to the configuration page.

Let’s install the Sentry browser SDK.

# install Sentry
yarn add @sentry/browser

On the configuration page, copy the browser SDK initialization code and paste it into your index.js file.

import * as Sentry from ‘@Sentry/browser’;

# Initialize with Data Source Name (dsn)
Sentry.init({ dsn: ‘dsn-string’ });

And that is enough for Sentry to start sending error alerts. It says in the docs,

Note: On its own, @Sentry/browser will report any uncaught exceptions triggered from your application.

Click on Got it! Take me to the issue stream to proceed to the issues dashboard. Now return to your app in the browser and click on the red buttons to throw some error. You should get email alerts for each error (Sometimes the emails are delayed). Refresh your issues dashboard to see the errors.

Sentry issues dashboard showing list of error events.

Sentry issues dashboard. (Large preview)

The Sentry dashboard provides a lot of information about the error it receives. You can see information such as a graph of the frequency of occurrence of each error event type. You can also assign each error to a team member. There’s a ton of information. Do take some time to explore them to see what is useful to you.

You can click on each issue to see more detailed information about the error event.

Now let’s use Sentry to report errors that are caught by our error boundary. Open ErrorBoundary.js and update the following pieces of code.

# import Sentry
import * as Sentry from ‘@sentry/browser’

# add eventId to state
state = {
error: ”,
eventId: ”, // add this to state
errorInfo: ”,
hasError: false,
};

# update componentDidCatch
componentDidCatch(error, errorInfo) {
// eslint-disable-next-line no-console
console.log({ error, errorInfo });
Sentry.withScope((scope) => {
scope.setExtras(errorInfo);
const eventId = Sentry.captureException(error);
this.setState({ eventId, errorInfo });
});
}

With this setup, Sentry sends all errors captured by our error boundary to our issue dashboard using the Sentry.captureException method.

Sentry also gives us a tool to collect user feedback. Let’s add the feedback button as part of our fallback UI inside our error boundary.

Open ErrorBoundary.js and add the feedback button just after the div with a className of card-body. You could place this button anywhere you like.

<div className=”card-body”>

</div>

# add the Sentry button
<button
className=”bg-primary text-light”
onClick={() =>
Sentry.showReportDialog({ eventId: this.state.eventId })
}
>
Report feedback
</button>

Now, whenever our fallback UI is rendered, the Report feedback button is displayed. Clicking on this button opens a dialog that the user can fill to provide us with feedback.

Sentry dialog with feedback form

Sentry feedback form. (Large preview)

Go ahead and trigger an error, then, fill and submit the feedback form. Now go to your Sentry dashboard and click on User Feedback in the left navigation. You should see your reported feedback.

Sentry feedback showing list of user feedbacks.

Sentry feedback dashboard. (Large preview)

Currently, we get alerts for every error, even those that happen during development. This tends to clog our issue stream. Let’s only report errors that happen in production.

On the left navigation click on Settings. Underneath the ORGANIZATION menu, click on Projects. In that list, click on your error boundary project. From Project Settings on the lefthand side, click on Inbound Filters. Look for Filter out events coming from localhost and enable it. This is just one of the numerous configurations that are available in Sentry. I encourage you to have a look around to see what might be useful for your project.

If you’d like to take a look at my code, the corresponding branch in my repo is 03-integrate-sentry.

Conclusion

If you haven’t been using error boundaries in your React app, you should immediately add one at the top level of your app. Also, I encourage you to integrate an error reporting service into your project. We’ve seen how easy it is to get started with Sentry for free.

The finished version of the app is hosted on Netlify.

Related Resources

React, Sentry
Error Boundaries
Error Boundaries In React

Smashing Editorial
(ks, ra, yk, il)

Forget the Apple iPhone 12, everyone's talking about the iPhone 13

Original Source: http://feedproxy.google.com/~r/CreativeBloq/~3/08juDo1rnz4/iphone-13-rumours

While the iPhone 12 is still yet to be released, some seem to have forgotten about it already as new leaks today speculate what the iPhone 13 could look like. It might be over a year away from release, but the iPhone 13 is set to feature one camera to rule them all. By which, we mean four. 

According to a regular Apple-leaker by the name of, er, Fudge, the iPhone 13 could contain the first four-camera setup in an iPhone. It could also feature a LiDAR scanner (currently only found in the 2020 iPad Pro), making it a portable AR powerhouse – great for choosing your next sofa.

The iPhone has been a permanent fixture in our round up of the best camera phones, with the 12 looking likely to bump the 11 off the top spot any time now. But if these iPhone 13 camera leaks are anything to go by, its younger sibling won'tlast long in poll position. 

Browse iPhones at Apple.com

But, as we mentioned already, the iPhone 12 isn't even out yet, so let's step back for a second. The iPhone 12 rumours suggest significantly improved cameras over the current iPhone 11, including enhanced autofocus and zoom. It will, however, allegedly contain a mere three cameras. Not only could the iPhone 13 contain a feature a whole extra lens, but two of its cameras could rock massive 64MB sensors. Fudge also shared a rough layout for the device:

While it'll come as no surprise to anybody that the iPhone 13 will feature a better camera than the iPhone 12, it could open up huge possibilities for creatives and photographers on the move. With its countless photo editing apps, the iPhone is already a superb device for photographers, but could the iPhone 13 become the first to rival your DSLR? Time will tell, but our best camera guide is safe from smartphones for now.

Fudge reminds us that, as with all leaks, these should be taken with a huge pinch of salt. But with the rate that smartphone photography has advanced over the last few years, it's easy to get carried away by what the next few years could bring. 

While this is all very exciting, the iPhone 11 Pro's camera is still seriously impressive. If you want the best iPhone camera available right now, check out the best deals below.

Keep reading:

Your Fujifilm camera is now an ultra-HD webcam for video callsYou can now get retro iPhone app icons – and you'll want them all right nowYou won't believe what Apple's next MacBook might look like

How To Create Better Angular Templates With Pug

Original Source: https://www.smashingmagazine.com/2020/05/angular-templates-pug/

How To Create Better Angular Templates With Pug

How To Create Better Angular Templates With Pug

Zara Cooper

2020-05-28T11:00:00+00:00
2020-05-28T17:08:35+00:00

As a developer, I appreciate how Angular apps are structured and the many options the Angular CLI makes available to configure them. Components provide an amazing means to structure views, facilitate code reusability, interpolation, data binding, and other business logic for views.

Angular CLI supports multiple built-in CSS preprocessor options for component styling like Sass/SCSS, LESS, and Stylus. However, when it comes to templates, only two options are available: HTML and SVG. This is in spite of many more efficient options such as Pug, Slim, HAML among others being in existence.

In this article, I’ll cover how you — as an Angular developer — can use Pug to write better templates more efficiently. You’ll learn how to install Pug in your Angular apps and transition existing apps that use HTML to use Pug.

Managing Image Breakpoints

A built-in Angular feature called BreakPoint Observer gives us a powerful interface for dealing with responsive images. Read more about a service that allows us to serve, transform and manage images in the cloud. Learn more →

Pug (formerly known as Jade) is a template engine. This means it’s a tool that generates documents from templates that integrate some specified data. In this case, Pug is used to write templates that are compiled into functions that take in data and render HTML documents.

In addition to providing a more streamlined way to write templates, it offers a number of valuable features that go beyond just template writing like mixins that facilitate code reusability, enable embedding of JavaScript code, provide iterators, conditionals, and so on.

Although HTML is universally used by many and works adequately in templates, it is not DRY and can get pretty difficult to read, write, and maintain especially with larger component templates. That’s where Pug comes in. With Pug, your templates become simpler to write and read and you can extend the functionality of your template as an added bonus. In the rest of this article, I’ll walk you through how to use Pug in your Angular component templates.

Why You Should Use Pug

HTML is fundamentally repetitive. For most elements you have to have an opening and closing tag which is not DRY. Not only do you have to write more with HTML, but you also have to read more. With Pug, there are no opening and closing angle brackets and no closing tags. You are therefore writing and reading a lot less code.

For example, here’s an HTML table:

<table>
<thead>
<tr>
<th>Country</th>
<th>Capital</th>
<th>Population</th>
<th>Currency</th>
</tr>
</thead>
<tbody>
<tr>
<td>Canada</td>
<td>Ottawa</td>
<td>37.59 million</td>
<td>Canadian Dollar</td>
</tr>
<tr>
<td>South Africa</td>
<td>Cape Town, Pretoria, Bloemfontein</td>
<td>57.78 million</td>
<td>South African Rand</td>
</tr>
<tr>
<td>United Kingdom</td>
<td>London</td>
<td>66.65 million</td>
<td>Pound Sterling</td>
</tr>
</tbody>
</table>

This is how that same table looks like in Pug:

table
thead
tr
th Country
th Capital(s)
th Population
th Currency
tbody
tr
td Canada
td Ottawa
td 37.59 million
td Canadian Dollar
tr
td South Africa
td Cape Town, Pretoria, Bloemfontein
td 57.78 million
td South African Rand
tr
td United Kingdom
td London
td 66.65 million
td Pound Sterling

Comparing the two versions of the table, Pug looks a lot cleaner than HTML and has better code readability. Although negligible in this small example, you write seven fewer lines in the Pug table than in the HTML table. As you create more templates over time for a project, you end up cumulatively writing less code with Pug.

Beyond the functionality provided by the Angular template language, Pug extends what you can achieve in your templates. With features (such as mixins, text and attribute interpolation, conditionals, iterators, and so on), you can use Pug to solve problems more simply in contrast to writing whole separate components or import dependencies and set up directives to fulfill a requirement.

Some Features Of Pug

Pug offers a wide range of features but what features you can use depends on how you integrate Pug into your project. Here are a few features you might find useful.

Adding external Pug files to a template using include.

Let’s say, for example, that you’d like to have a more succinct template but do not feel the need to create additional components. You can take out sections from a template and put them in partial templates then include them back into the original template.

For example, in this home page component, the ‘About’ and ‘Services’ section are in external files and are included in the home page component.

//- home.component.pug
h1 Leone and Sons
h2 Photography Studio

include partials/about.partial.pug
include partials/services.partial.pug

//- about.partial.pug
h2 About our business
p Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

//- services.partial.pug
h2 Services we offer
P Our services include:
ul
li Headshots
li Corporate Event Photography

HTML render of included partial templates example

HTML render of included partial templates example (Large preview)

Reusing code blocks using mixins.

For example, let’s say you wanted to reuse a code block to create some buttons. You’d reuse that block of code using a mixin.

mixin menu-button(text, action)
button.btn.btn-sm.m-1(‘(click)’=action)&attributes(attributes)= text

+menu-button(‘Save’, ‘saveItem()’)(class=”btn-outline-success”)
+menu-button(‘Update’, ‘updateItem()’)(class=”btn-outline-primary”)
+menu-button(‘Delete’, ‘deleteItem()’)(class=”btn-outline-danger”)

HTML render of menu buttons mixin example

HTML render of menu buttons mixin example (Large preview)

Conditionals make it easy to display code blocks and comments based on whether a condition is met or not.

– var day = (new Date()).getDay()

if day == 0
p We’re closed on Sundays
else if day == 6
p We’re open from 9AM to 1PM
else
p We’re open from 9AM to 5PM

HTML render of conditionals example

HTML render of conditionals example (Large preview)

Iterators such as each and while provide iteration functionality.

ul
each item in [‘Eggs’, ‘Milk’, ‘Cheese’]
li= item

ul
while n < 5
li= n++ + ' bottles of milk on the wall'

HTML renders of iterators example

(Large preview)

HTML renders of iterators example

HTML renders of iterators example (Large preview)

Inline JavaScript can be written in Pug templates as demonstrated in the examples above.
Interpolation is possible and extends to tags and attributes.

– var name = ‘Charles’
p Hi! I’m #{name}.

p I’m a #[strong web developer].

a(href=’https://about.me/${name}’) Get to Know Me

HTML render of interpolation example

HTML render of interpolation example (Large preview)

Filters enable the use of other languages in Pug templates.

For example, you can use Markdown in your Pug templates after installing a JSTransformer Markdown module.

:markdown-it
# Charles the Web Developer
![Image of Charles](https://charles.com/profile.png)

## About
Charles has been a web developer for 20 years at **Charles and Co Consulting.**

HTML render of filter example

HTML render of filter example (Large preview)

These are just a few features offered by Pug. You can find a more expansive list of features in Pug’s documentation.

How To Use Pug In An Angular App

For both new and pre-existing apps using Angular CLI 6 and above, you will need to install ng-cli-pug-loader. It’s an Angular CLI loader for Pug templates.

For New Components And Projects

Install ng-cli-pug-loader.

ng add ng-cli-pug-loader

Generate your component according to your preferences.

For example, let’s say we’re generating a home page component:

ng g c home –style css -m app

Change the HTML file extension, .html to a Pug extension, .pug. Since the initial generated file contains HTML, you may choose to delete its contents and start anew with Pug instead. However, HTML can still function in Pug templates so you can leave it as is.
Change the extension of the template to .pug in the component decorator.

@Component({
selector: ‘app-component’,
templateUrl: ‘./home.component.pug’,
styles: [‘./home.component.css’]
})

For Existing Components And Projects

Install ng-cli-pug-loader.

ng add ng-cli-pug-loader

Install the html2pug CLI tool. This tool will help you convert your HTML templates to Pug.

npm install -g html2pug

To convert a HTML file to Pug, run:

html2pug -f -c [Pug file path]

Since we’re working with HTML templates and not complete HTML files, we need to pass the -f to indicate to html2pug that it should not wrap the templates it generates in html and body tags. The -c flag lets html2pug know that attributes of elements should be separated with commas during conversion. I will cover why this is important below.
Change the extension of the template to .pug in the component decorator as described in the For New Components and Projects section.
Run the server to check that there are no problems with how the Pug template is rendered.

If there are problems, use the HTML template as a reference to figure out what could have caused the problem. This could sometimes be an indenting issue or an unquoted attribute, although rare. Once you are satisfied with how the Pug template is rendered, delete the HTML file.

Things To Consider When Migrating From HTML To Pug Templates

You won’t be able to use inline Pug templates with ng-cli-pug-loader. This only renders Pug files and does not render inline templates defined in component decorators. So all existing templates need to be external files. If you have any inline HTML templates, create external HTML files for them and convert them to Pug using html2pug.

Once converted, you may need to fix templates that use binding and attribute directives. ng-cli-pug-loader requires that bound attribute names in Angular be enclosed in single or double quotes or separated by commas. The easiest way to go about this would be to use the -c flag with html2pug. However, this only fixes the issues with elements that have multiple attributes. For elements with single attributes just use quotes.

A lot of the setup described here can be automated using a task runner or a script or a custom Angular schematic for large scale conversions if you choose to create one. If you have a few templates and would like to do an incremental conversion, it would be better to just convert one file at a time.

Angular Template Language Syntax In Pug Templates

For the most part, Angular template language syntax remains unchanged in a Pug template, however, when it comes to binding and some directives (as described above), you need to use quotes and commas since (), [], and [()] interfere with the compilation of Pug templates. Here are a few examples:

//- [src], an attribute binding and [style.border], a style binding are separated using a comma. Use this approach when you have multiple attributes for the element, where one or more is using binding.
img([src]=’itemImageUrl’, [style.border]=’imageBorder’)

//- (click), an event binding needs to be enclosed in either single or double quotes. Use this approach for elements with just one attribute.
button(‘(click)’=’onSave($event)’) Save

Attribute directives like ngClass, ngStyle, and ngModel must be put in quotes. Structural directives like *ngIf, *ngFor, *ngSwitchCase, and *ngSwitchDefault also need to be put in quotes or used with commas. Template reference variables ( e.g. #var ) do not interfere with Pug template compilation and hence do not need quotes or commas. Template expressions surrounded in {{ }} remain unaffected.

Drawbacks And Trade-offs Of Using Pug In Angular Templates

Even though Pug is convenient and improves workflows, there are some drawbacks to using it and some trade-offs that need to be considered when using ng-cli-pug-loader.

Files cannot be included in templates using include unless they end in .partial.pug or .include.pug or are called mixins.pug. In addition to this, template inheritance does not work with ng-cli-pug-loader and as a result, using blocks, prepending, and appending Pug code is not possible despite this being a useful Pug feature.

Pug files have to be created manually as Angular CLI only generates components with HTML templates. You will need to delete the generated HTML file and create a Pug file or just change the HTML file extension, then change the templateUrl in the component decorator. Although this can be automated using a script, a schematic, or a Task Runner, you have to implement the solution.

In larger pre-existing Angular projects, switching from HTML templates to Pug ones involves a lot of work and complexity in some cases. Making the switch will lead to a lot of breaking code that needs to be fixed file by file or automatically using a custom tool. Bindings and some Angular directives in elements need to be quoted or separated with commas.

Developers unfamiliar with Pug have to learn the syntax first before incorporating it into a project. Pug is not just HTML without angle brackets and closing tags and involves a learning curve.

When writing Pug and using its features in Angular templates ng-cli-pug-loader does not give Pug templates access to the component’s properties. As a result, these properties cannot be used as variables, in conditionals, in iterators, and in inline code. Angular directives and template expressions also do not have access to Pug variables. For example, with Pug variables:

//- app.component.pug
– var shoppingList = [‘Eggs’, ‘Milk’, ‘Flour’]

//- will work
ul
each item in shoppingList
li= item

//- will not work because shoppingList is a Pug variable
ul
li(*ngFor=”let item of shoppingList”) {{item}}

Here’s an example with a property of a component:

//- src/app/app.component.ts
export class AppComponent{
shoppingList = [‘Eggs’, ‘Milk’, ‘Flour’];
}

//- app.component.pug

//- will not work because shoppingList is a component property and not a Pug variable
ul
each item in shoppingList
li= item

//- will work because shoppingList is a property of the component
ul
li(*ngFor=”let item of shoppingList”) {{item}}

Lastly, index.html cannot be a Pug template. ng-cli-pug-loader does not support this.

Conclusion

Pug can be an amazing resource to use in Angular apps but it does require some investment to learn and integrate into a new or pre-existing project. If you’re up for the challenge, you can take a look at Pug’s documentation to learn more about its syntax and add it to your projects. Although ng-cli-pug-loader is a great tool, it can be lacking in some areas. To tailor how Pug will work in your project consider creating an Angular schematic that will meet your project’s requirements.

Smashing Editorial
(ra, yk, il)

Overhang.js – A jQuery Plugin for Dropdown Notification Messages

Original Source: https://www.hongkiat.com/blog/overhang-js/

How annoying are the default JS alert boxes? They feel like a relic from a primitive bygone era of web development. Nowadays, we can make unobtrusive notification messages that share the same…

Visit hongkiat.com for full content.

An Infinitely Scrollable Vertical Menu

Original Source: http://feedproxy.google.com/~r/tympanus/~3/TwP5evi-5Ng/

Note: from now on I’m planning to release simple “components” and explain their basic working principle in tiny articles. In this first one I’m going to look at the infinite looping scroll illusion.

A while back a came across a really nice menu on Madeleine Dalla’s incredible website that was infinitely scrollable. I wondered how that was achieved and after searching for existing solutions, I found this great demo by Vincent Orback on Codepen. It shows how to pull off that effect with sections on a page. I wanted to use his script to make it work for a menu.

The principle of how this works is not too complicated: there’s a bunch of menu items that we need to clone in order to make sure that we have enough items to create a scroll illusion. The illusion works like this: once we scroll and reach the cloned items, we reset the scroll position to 0. So, as soon as the same (visual) point is reached, we jump back to the beginning.

How many clones do we need? We need as many clones as items fit into the visible area. As an example, if 8 items fit into the height of the viewport, than we need to create 8 clones.

The amount of menu items is important when considering how much space they’ll take up on the screen (or scroll area). If your items don’t fill the screen fully, the illusion will break. So you need to make sure to have enough and to set a reasonable font size for the items to occupy enough space.

We let the menu be scrollable but we hide the scrollbar. The menu is covering the whole viewport and this is the element we scroll.

Tip: if you want to visualize the illusion, just make sure that the scrollbar is not hidden. You’ll see it jumping back to the top, once the “cloned” zone is reached. Just delete:

::-webkit-scrollbar {
display: none;
}

… and the line scrollbar-width: none; for Firefox.

Note that I use a fallback for mobile where I simply want to show the complete menu.

Hope you find this little component useful!

An Infinitely Scrollable Vertical Menu was written by Mary Lou and published on Codrops.

7 Reasons to Use Illustrations on Your Website (And Examples of How to Do It)

Original Source: http://feedproxy.google.com/~r/tympanus/~3/sweN9hGioJw/

When building a new website, one of the very first decisions you’ll need to make is: 

What kind of visual style do you want to use? 

Does the practical and realistic nature of photographs fit well with your brand? Or does it make more sense to turn to a more abstract and creative approach and use illustrations instead? 

If you decide that you want to take the illustrative approach, keep in mind that it comes in many different forms. As a result, a very different style and story can be depicted from illustrated website to illustrated website. 

This is something we’ve accounted for when creating our pre-built sites for BeTheme. We wanted to reflect a wide array of illustration styles so our customers not only get to see how diverse this visual style is, but also have a robust source of inspiration for their own designs. 

We’re not alone. There are many great websites out there that creatively use illustrations. And, today, we’re going to take a look at a number of them as we explore the seven reasons why you may want to use illustrations to style a website:

1. When a photograph can’t fully capture a complicated subject

If you’ve ever tried to find a photo for a brand and struggled to pick out something that accurately reflected who they were or what they did, it’s probably because the subject was too difficult to capture. 

That can mean any number of things. 

It could mean that the subject itself is too difficult to photograph. Copywriters are a good example of this. While they could get someone to photograph them while typing away on their computer, there’s nothing very exciting about that. A photograph would simply capture the mundane task of writing, which is what the client would be trying to avoid. 

If you take a look at the BeCopywriter 2 pre-built site, you’ll see that an illustrative style is a much better way to approach this: 

The design is striking. The words are powerful. And the illustrative touches add a unique touch to the overall look. 

There are other kinds of websites that would be better off with illustrations if their subjects are too complicated to capture. Take, for instance, a recycling services company like WeRecycle: 

While it’s possible to pick out images or take real-life photos of recycling, that doesn’t fully capture what this company does. Rather than focus on individual scraps of trash, illustrations enable companies like these to give website visitors the full scope of what they do. 

It’s a much more powerful image, to say the least. 

2. When a brand has a unique look that requires a unique approach

Every brand has its own style and personality. Without a unique edge, it would be hard for consumers to differentiate between similar solutions. 

That said, some companies have styles that are way out there, which means that some of the traditional rules of web design can get thrown out the window. 

One way we see this happening is when photographs and illustrations blend. This allows a brand with a surreal, edgy, imaginative, or whimsical look to leverage the traditional elements of design while shaking things up. 

For example, this is how the BeFoodTruck pre-built site handles it: 

The illustrations are a unique choice for a business in the food industry, which would instantly make this site a standout. That said, without real photos of food, it would be difficult to convince customers to dine in or out. 

That’s why the balance between the two styles works so well. 

Handwrytten is a website that uses a similar balance between real photos and eye-catching illustrations:

In this case, the illustrations are animated, which gives the homepage yet another unique twist. This concept alone is already quite innovative and now they have a site to match it.

3. When a company wants to stand out from photo-strewn sites

When it comes to certain industries, the expectation is that their websites will have a similar look to them. 

Take the travel and hospitality industries, for instance. Because they’re in the business of selling in-person experiences — or telling stories about them — you’d figure that photos are the only option for those websites. 

But if your website is trying to compete amongst an endless supply of lookalike companies, using illustrations may be the thing that sets them apart. 

Case in point, BeJourney 2: 

Although the site isn’t complete devoid of photos, the majority of it is designed with illustrations or illustrative touches. 

Bateau Mon Paris is a boat rental company in France that takes a similar approach: 

You can see the peekaboo photo poking out there, but, for the most part, this website’s main visual style is illustration. 

4. When a new company wants to leverage the style of a brand that consumers already trust

You see this quite often when brand new companies enter high-risk spaces. They design their branding and website to be reminiscent of a well-established company that customers already trust. 

That way, there’s an unconscious association in prospects’ minds between the two companies and it eases the concerns and doubts that often arise when working with a new company.

One such company’s website that became the standard for other software companies entering the space is Stripe: 

Stripe’s illustrative style (as well as its choice to use gradients) has been copied for years. And it’s been a good look to emulate. 

Our BePay 2 site takes the trust-building elements that we see in Stripe and puts a unique spin on them:

The site is designed using illustrations, including the mobile application images. The color blue is also prevalent, which is a color that’s symbolic of stability and trust. 

5. When a creator has an interesting story and work to share

Although you’ll find some design agencies and web developers who use photos of themselves and their teams on their websites, many times creative types use illustrations instead. 

One reason why they go this route is because it’s another way to flex their creative muscles and to show prospective clients what they can do. 

Another reason takes us back to point #1 in this post. Unless they have a large team and an interesting-looking studio they work from, photos aren’t going to be the most exciting way to capture what it is they do.  

The BeBand 5 pre-built site, for example, uses illustrations and animations to give its site an 80s-style look. 

Unless band members are in the habit of dressing up like rockers from the 80s, photos wouldn’t accurately capture the style of music the band plays. But this unique illustrative style certainly does and also proves useful in drawing attention over to their music. 

 Artist Polly Kole has taken a unique approach to building an illustrative website:

In addition to the dramatic and intriguing look of the site, it’s interactive too. It’s almost as though the site emulates the experience of going to look at art (maybe not the interacting part, but being able to walk around it).

6. When a company is selling a smart app or resource

Companies that sell “smart” tools to users commonly design their websites with illustrations instead of photographs. And it makes a lot of sense. 

For one, these companies aren’t really selling the product itself. While the experience inside an app or using a device matters, what they’re selling on a website is a solution to the users’ problems which often involves managing a lot of data. That’s not an easy thing to depict with photos. 

Another reason they use illustrations — or, more specifically, vector graphics — is because geometric styling is a good way to give a website a stable and logical feel. 

BeApp 6 uses data visualizations to really hammer home the strengths of the app: 

While designers could use screenshots from within their apps to do something similar, this approach enables them to highlight important elements within the product in an attractive way.

Swiggy Labs builds products that solve big problems for consumers: 

While the designer of the site could’ve chosen to display the actual products they’ve built, this is a much more interesting approach. When you drag the “Swiggy It” toggle to the right, the hero image comes to life with animations and messages that allude to what the company does.

7. When a brand’s target audience is children (or their parents)

This is another no-brainer use case for illustrations on the web. Considering how comfortable children are with cartoons, games, and apps, an illustrative style is much more relatable when trying to reach this audience — or even their parents. 

You might also argue that illustrations are presented in a manner that’s easier for kids to understand because of how much better illustrations are able to simplify a complex subject.

BeLanguage 3 is an interesting case because it’s a language learning website:

You might argue that illustrations are a universal language. You don’t need to understand English or Japanese or Italian in order to understand what is going on with a website or the company it represents when illustrations tell the story. 

Other kinds of organizations that serve children or their families can use illustrations to simplify language and strengthen their sales pitch as See Make Play does: 

The illustrations on this site give it a fun and youthful quality. In this particular part of the homepage, the illustrations are static images. However, elsewhere on the page, parents and their kids will encounter animated graphics that bring a lighthearted touch to this site. 

Will you use illustrations to style your website?

If you’re finding it difficult to use photography to tell your brand’s visual story or are thinking about pursuing something a little less conventional, illustration might be the solution. 

As you can see in the websites from BeTheme and others around the web, illustrated websites are in no short supply. And, yet, whenever you encounter one, they tend to have a unique look you can’t help but look away from. 

If you want to make your website really stand out, an illustrated website would be a fantastic style to experiment with.

7 Reasons to Use Illustrations on Your Website (And Examples of How to Do It) was written by Bogdan Sandu and published on Codrops.