Tag: Moving

Moving from Vanilla JavaScript to a Reusable Vue Component

I recently wrote an article explaining how you can create a countdown timer using HTML, CSS and JavaScript. Now, let’s look at how we can make that a reusable component by porting it into Vue using basic features that the framework provides.

Why do this at all? Well there are few reasons, but two stand out in particular:

  • Keeping UI in sync with the timer state: If you look at the code from the first post,  it all lives in the timerInterval function, most noticeably the state management. Each time it runs (every second) we need to manually find the proper element on our document — whether it’s the time label or the remaining time path or whatever — and change either its value or an attribute. Vue comes with an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying Vue instance’s data. That takes all the burden of finding and updating proper UI elements so we can rely purely on the component instance’s properties.
  • Having a highly reusable component: The original example works fine when only one timer is present on our document, but imagine that you want to add another one. Oops! We rely the element’s ID to perform our actions and using the same ID on multiple instances would prevent them from working independently. That means we would have to assign different IDs for each timer. If we create a Vue component, all it’s logic is encapsulated and connected to that specific instance of the component. We can easily create 10, 20, 1,000 timers on a single document without changing a single line in the component itself!

Here’s the same timer we created together in the last post, but in Vue.

Template and styles

From the Vue docs:

Vue uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying Vue instance’s data. All Vue.js templates are valid HTML that can be parsed by spec-compliant browsers and HTML parsers.

Let’s create our component by opening a new file called BaseTimer.vue. Here’s the basic structure we need for that:

// Our template markup will go here <template> // ... </template>  // Our functional scripts will go here <script> // ... </script>  // Our styling will go here <style> // ... </style>

In this step, we will concentrate on the <template> and <style> sections. Let’s move our timer template to the <template> section and all our CSS to <style> section. The markup mostly consists of SVG and we can use the exact same code we used from the first article.

<template>   // The wrapper for the timer   <div class="base-timer">      // This all comes from the first article     <svg class="base-timer__svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">       <g class="base-timer__circle">         <circle class="base-timer__path-elapsed" cx="50" cy="50" r="45"></circle>         <path           id="base-timer-path-remaining"           stroke-dasharray="283"           class="base-timer__path-remaining $  {remainingPathColor}"           d="             M 50, 50             m -45, 0             a 45,45 0 1,0 90,0             a 45,45 0 1,0 -90,0           "         ></path>       </g>     </svg>      // The label showing the remaining time     <span       id="base-timer-label"       class="base-timer__label"     >       $  {formatTime(timeLeft)}     </span>    </div> </template>  // "scoped" means these styles will not leak out to other elements on the page <style scoped> .base-timer {   position: relative;   width: 100px;   height: 100px; } </style>

Let’s have a look at the template we just copied to identify where we can use our framework. There are few parts that are responsible for making our timer count down the time and show the remaining time.

  • stroke-dasharray: A value passed to the SVG <path> element that is responsible for holding the remaining time.
  • remainingPathColor: A CSS class responsible for changing the color of the timer’s circular ring, giving is a way to visually indicate that time is running out.
  • formatTime(timeLeft): A value responsible for showing how much time is left inside the timer

We can control our timer by manipulating those values.

Constants and variables

OK, let’s go down to our <script> section and see what Vue gives us out of the box to make our life easier. One thing it lets us do is define our constants up front, which keeps them scoped to the component.

In the last post, we spent a little time tweaking the stroke-dasharray  value to make sure the animation of the timer’s top layer (the ring that animates and changes color as time progresses) is perfectly in line with its bottom layer (the gray ring that indicates past time). We also defined “thresholds” for when the top layer should change colors (orange at 10 remaining seconds and red at five seconds). We also created constants for those colors.

We can move all of those directly into the <script> section:

<script> // A value we had to play with a bit to get right const FULL_DASH_ARRAY = 283; // When the timer should change from green to orange const WARNING_THRESHOLD = 10; // When the timer should change from orange to red const ALERT_THRESHOLD = 5;  // The actual colors to use at the info, warning and alert threshholds const COLOR_CODES = {   info: {     color: "green"   },   warning: {     color: "orange",     threshold: WARNING_THRESHOLD   },   alert: {     color: "red",     threshold: ALERT_THRESHOLD   } };  // The timer's starting point const TIME_LIMIT = 20; </script>

Now, let’s have a look at our variables:

let timePassed = 0; let timeLeft = TIME_LIMIT; let timerInterval = null; let remainingPathColor = COLOR_CODES.info.color;

We can identify two different types of variables here:

  1. Variables in which the values are directly re-assigned in our methods:
    • timerInterval: Changes when we start or stop the timer
    • timePassed: Changes each second when the timer is running
  2. Variables in which the values change when other variables change:
    • timeLeft: Changes when the value of timePassed changes
    • remainingPathColor: Changes when the value of timeLeft breaches the specified threshold

It is essential to identify that difference between those two types as it allows us to use different features of the framework. Let’s go through each of the type separately.

Variables in which values are directly re-assigned

Let’s think what we want to happen when we change the timePassed value. We want to calculate how much time is left, check if we should change the top ring’s color, and trigger re-render on a part of our view with new values. 

Vue comes with its own reactivity system that updates the view to match the new values of specific properties. To add a property to Vue’s reactivity system we need to declare that property on a data object in our component. By doing that,Vue will create a getter and a setter for each property that will track changes in that property and respond accordingly.

<script> // Same as before  export default {   data() {     return {       timePassed: 0,       timerInterval: null     };   } </script>

There are two important things we need to remember.

  1. We need to declare all reactive variables in our data object up front. That means if we know that a variable will exist but we don’t know what the value will be, we still need to declare it with some value. If we forgot to declare it in data it will not be reactive, even if it is added later.
  2. When declaring our data option object, we always need to return a new object instance (using return). This is vital because, if we don’t follow this rule, the declared properties will be shared between all instances of the component.

You can see that second issue in action:

Variables in which values change when other variable change

These variables rely on the value of another variable. For example, timeLeft relies purely on timePassed. In our original example that uses vanilla JavaScript, we were calculating that value in the interval that was responsible for changing the value of timePassed. With Vue, we can extract that value to a computed property.

computed property is a function that returns a value. These values are bound to the dependency values and only update when required. Even more importantly, computed properties are cached, meaning they remember the values that the computed property depends on and calculate the new value only if that dependent property value changed. If the value does not change, the previously cached value is returned.

<script> // Same as before  computed: {     timeLeft() {       return TIME_LIMIT - this.timePassed;     }   } } </script>

The function passed to the computed property must be a pure function. It can’t cause any side effects and must return a value. Also, the output value must only be dependent on the values passed into the function.

Now, we can move more logic to computed properties:

  • circleDasharray: This returns a value previously that is calculated in the setCircleDasharray method.
  • formattedTimeLeft: This returns a value from the formatTime method.
  • timeFraction: This is an abstraction of the calculateTimeFraction method.
  • remainingPathColor: This is an abstraction of the setRemainingPathColor method.
<script> // Same as before  computed: {     circleDasharray() {       return `$  {(this.timeFraction * FULL_DASH_ARRAY).toFixed(0)} 283`;     },      formattedTimeLeft() {       const timeLeft = this.timeLeft;       const minutes = Math.floor(timeLeft / 60);       let seconds = timeLeft % 60;       if (seconds < 10) {         seconds = `0$  {seconds}`;       }       return `$  {minutes}:$  {seconds}`;     },      timeLeft() {       return TIME_LIMIT - this.timePassed;     },      timeFraction() {       const rawTimeFraction = this.timeLeft / TIME_LIMIT;       return rawTimeFraction - (1 / TIME_LIMIT) * (1 - rawTimeFraction);     },      remainingPathColor() {       const { alert, warning, info } = COLOR_CODES;       if (this.timeLeft <= alert.threshold) {         return alert.color;       } else if (this.timeLeft <= warning.threshold) {         return warning.color;       } else {         return info.color;       }     }   } </script>

We now have all the values we need! But now we need to put them to use in our template.

Using data and computed properties in the template

Here’s where we left off with our template:

 <template>   <div class="base-timer">     <svg class="base-timer__svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">       <g class="base-timer__circle">         <circle class="base-timer__path-elapsed" cx="50" cy="50" r="45"></circle>         <path           id="base-timer-path-remaining"           stroke-dasharray="283"           class="base-timer__path-remaining $  {remainingPathColor}"           d="             M 50, 50             m -45, 0             a 45,45 0 1,0 90,0             a 45,45 0 1,0 -90,0           "         ></path>       </g>     </svg>     <span       id="base-timer-label"       class="base-timer__label"     >         $  {formatTime(timeLeft)}     </span>   </div> </template>

Let’s start with formatTime(timeLeft). How we can dynamically bind the rendered value to our formattedTimeLeftcomputed property?

Vue uses HTML-based template syntax that allowsus to declaratively bind the rendered DOM to the underlying data of the Vue instance. That means all properties are available in the template section. To render any of them, we use text interpolation using the “Mustache” syntax (double curly braces, or {{ }}).

<span   id="base-timer-label"   class="base-timer__label" >   {{ formattedTimeLeft }}  </span>

Next will be stroke-dasharray. We can see we don’t want to render that value. Instead, we want to change the value of the <path> attribute. Mustache cannot be used inside HTML attributes, but fear not! Vue comes with another way: the v-bind directive. We can bind a value to an attribute like this:

<path  v-bind:stroke-dasharray="circleDasharray"></path>

To facilitate the usage of that directive, we can also use a shorthand.

<path  :stroke-dasharray="circleDasharray"></path>

The last one is remainingPathColor, which adds a proper class to an element. We can do that using the same v-bind directive as above, but assign the value to the class attribute of an element.

<path  :class="remainingPathColor"></path>

Let’s have a look at our template after changes.

<template>   <div class="base-timer">     <svg class="base-timer__svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">       <g class="base-timer__circle">         <circle class="base-timer__path-elapsed" cx="50" cy="50" r="45"></circle>         <path           :stroke-dasharray="circleDasharray"           class="base-timer__path-remaining"           :class="remainingPathColor"           d="             M 50, 50             m -45, 0             a 45,45 0 1,0 90,0             a 45,45 0 1,0 -90,0           "         ></path>       </g>     </svg>     <span class="base-timer__label">{{ formattedTimeLeft }}</span>   </div> </template>

We have our template ready, we moved all variables to data or computed, and we got rid off most of the methods by creating corresponding computed properties. We are still missing one vital part, though: we need to start our timer.

Methods and component lifecycle hooks

If we look at our startTimer method, we can see that all the calculations, changes in attributes, etc. happen in the interval.

function startTimer() {   timerInterval = setInterval(() => {     timePassed = timePassed += 1;     timeLeft = TIME_LIMIT - timePassed;     document.getElementById("base-timer-label").innerHTML = formatTime(       timeLeft     );     setCircleDasharray();     setRemainingPathColor(timeLeft);     if (timeLeft === 0) {       onTimesUp();     }   }, 1000); }

Since we’ve already moved all that logic into the computed property, all we need to do in our timerInterval is change the value of timePassed — the rest will happen magically in the computed properties

<script> // Same as before  methods: {   startTimer() {     this.timerInterval = setInterval(() => (this.timePassed += 1), 1000);   } } </script>

We have the method ready, but we still don’t call it anywhere. Each Vue component comes with a series of hooks that allows us to run a specific logic within a specific period of the component’s lifecycle. These are called lifecycle hooks. In our case, as we want to call our method immediately when the component gets loaded. That makes mounted the lifecycle hook what we want.

<script> // Same as before  mounted() {   this.startTimer(); },  // Same methods as before </script> 

That’s it, we just turned our timer into a consistent and reusable component using Vue!

Let’s say we now want to use this component in another component. That requires a few things:

  1. First, we import the component.
  2. Next, we register the component.
  3. Finally, we instantiate the component in the template.
// App.vue  import BaseTimer from "./components/BaseTimer"  export default {   components: {     BaseTimer   } }; 

That’s a wrap!

This example shows how we can move a component from vanilla JavaScript to a component-based front-end framework, like Vue. 

We can now treat the timer as a standalone component where all the markup, logic and styling is contained in a way that won’t leak out to or conflict with other elements. Components are often children of a larger parent component that assembles multiple components together — like a form or perhaps a card — where the parent’s properties can be accessed and shared. Here’s an example of the timer component where it’s taking orders from a parent component

I hope I got you interested in Vue and the power of components! I’d encourage you to go to Vue docs to get more detailed description of the features we used in our example. There’s so much Vue can do!

The post Moving from Vanilla JavaScript to a Reusable Vue Component appeared first on CSS-Tricks.

CSS-Tricks

, , , , ,

Get Moving (or not) with CSS Motion Path

We just linked up the idea that offset-path can be cleverly used to set type on a path. Don’t miss Michelle Barker’s experimentation either, with drawing paths or animating text along a path.

Dan Wilson has also been following this tech for quite a while and points out why the sudden surge of interest in this:

With the release of Firefox 72 on January 7, 2020, CSS Motion Path is now in Firefox, new Edge (slated for a January 15, 2020 stable release), Chrome, and Opera (and other Blink-based browsers). That means each of these browsers supports a common baseline of offset-path: path()offset-distance, and offset-rotate.

Dan’s post does a great job of covering the basics, including some things you might not think of, like the fact that the path itself can be animated.

Direct Link to ArticlePermalink

The post Get Moving (or not) with CSS Motion Path appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

Moving Rainbow Underlines

I absolutely love the design of the Sandwich site. Among many beautiful features are these headlines with rainbow underlines that move as you scroll. It’s not scroll-jacking — it’s just a minor design feature that uses scroll position to enact a little movement.

To draw the rainbows themselves, we could use a linear gradient with hard-stops, the same kinda concept as drawing stripes in CSS. That’s a big ol’ chunk of CSS, which is fine, but I see they’ve opted for a background-image instead. Here’s that as an SVG, which is 661 bytes (tiny tiny). We can make it look like an underline by setting the background-size to limit the height and position it along the bottom with background-position.

We’ll do it on an inline element so the underline breaks where the words break:

h1 {   span {     background-image: url(spectrum.svg);     background-repeat: repeat-x;     background-size: 100vw 0.2em;     background-position: left bottom 5px;    } }

To animate it, we move the background-position-x. Not a particularly performant thing to animate, but we’re not really animating it anyway — it’s just moving based on scroll position. Rather than manually manipulate the background-position-x, we’ll set it with a custom property, then manipulate the custom property with JavaScript.

background-position-x: var(--scrollPos);

Updating that variable while the page scrolls is easy peezy:

window.addEventListener("scroll", e => {   let scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;    let newPos = scrollTop + "px";   document.documentElement.style.setProperty('--scrollPos', newPos); });

Here it is working!

See the Pen
Rainbow Underlines
by Chris Coyier (@chriscoyier)
on CodePen.

See that kinda janky line where I’m either using document.body or document.documentElement? That’s a stupid cross-browser thing where the “scrolling element” is different in Safari versus everything else.

While doing this I learned that you can use document.scrollingElement instead to avoid the pain there. I’ll leave a comment in the code about that, but leave the original line for posterity.

The post Moving Rainbow Underlines appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

Moving from Gulp to Parcel

Ben Frain just made some notes about the switch from Gulp to Parcel, a relatively new “web application bundler” which, from a quick look at things, is similar to webpack but without all the hassle of setting things up. One of the things I’ve always disliked about webpack is that you kinda have to teach it what CSS, HTML and JS are before making whatever modifications you want to those files. However, Parcel does a lot of the asset management and configuration stuff for us which is super neat — hence, Parcel claim that it requires “zero configuration.”

If you’d like to learn more about Parcel then there’s a great post by Indrek Lasn that details how to get started and even shows off a little bit about how Parcel is often faster than alternatives like webpack. We also just published a post by Kingsley Silas that explains how to use Parcel with React.

Direct Link to ArticlePermalink

The post Moving from Gulp to Parcel appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

Moving a Self-Hosted WordPress Site to WordPress.com

I have a habit of getting some hosting when I need a new WordPress site. That is, a self-installed, self-hosted WordPress.org site. That’s served me well over the years. I like my control. But along with that control comes a certain level of extra responsibility that sometimes just isn’t worth it.

That’s the case for me now with my little blog Email is Good.

Right from the get-go, I knew I wanted Email is Good to be as absolutely simple as could be. At the moment, I can’t prioritize a fancy custom design or really any specialized functionality at all. All I want is a simple, clean blog in which to publish blog posts. And as powerful and flexible as WordPress is, it’s still extra good at that use case.

Email is Good uses an untouched, stock copy of the TwentySixteen theme.

I’d like to move it over to WordPress.com, so that I don’t have to deal with hosting, upgrades, backups, security… it’ll just host my simple blog and I can unburden myself of that little spoonful of technical debt.

Their docs for this are there, but a little on the light side, so I’ll document my process here.

Set up the WordPress.com side first

There is a nice clean URL for kicking off a new WordPress.com site:

https://wordpress.com/start/

There isn’t really a one-click just suck everything over in one shot system. Instead, you set up the site on WordPress.com, deal with the domain, and import the content. It might feel a little weird, but this first step is just kinda re-setting up the basics:

Deal with the domain

By “domain”, I mean the URL that you may already own. I own “email-is-good.com” which is what I want to continue to use.

During setup you can buy a domain (or get a free one! They’ll give you a wordpress.com or .blog subdomain), but since I’m moving a site here, I’ll select the option that I already own the domain.

My domain name is already registered on GoDaddy.com. I could just leave the domain name there and map the domain over to WordPress.com. I think that’s generally a smart thing to do, but I wanted to try what seems to be the default which is transferring it over to WordPress.com.

Part of the beauty of transferring the domain is there is no settings to screw up, as it will be handled by WordPress.com

I went through a process of basically re-registering the domain with WordPress.com.

In order to actually transfer the domain, I had to go to GoDaddy and “unlock” the domain as well as request a transfer authorization code.

If you’re transferring a domain, it can take a little while.

The note on the page above tells me it might take a full week to complete. It took me one day less. I got the success email on February 18th instead of 19th.

I did have to “flip the switch”, as the email suggests, to use the WordPress nameservers.

But before I did, I made sure the new WordPress.com site had all the old content!

Exporting Content & Media

There is an export tool baked right into WordPress. Find it under Tools.

You’ll get an .xml file as output. Mine was called:

emailisgood.wordpress.2019-02-12.xml

Importing Content & Media

On the WordPress.com side, there is a big Import option right in the sidebar. In those options, there is a WordPress option to choose.

Drag and drop the .xml file there.

Mine was pretty quick, but I imagine it could take a while. You’ll even get an email when it’s done.

All my content and media made the journey just fine!

Clean Up

I had to do a little cleanup here and there to get the site exactly as it was. My site is so basic, it was hardly any work, but it’s worth knowing you might have to mop up a little. For example, the site already had a contact page, so I had to nuke the one that was imported (which was using a contact form plugin I didn’t need any more anyway) and make sure it was all functional.

Another thing that didn’t make the trip to the new site was the widgets. I had a sidebar with some widgets that I had to re-build, but that was no big deal. I literally copy-pasted the content from them from the old site before I flipped the switch.

So now! I’ve ditched a pile of technical debt. No more worrying about my SSL certifiate. No more having to manually follow up with any hosting company about downtime. Performance is largely in the hands of someone else.

I just have a simple site where I can write write write.

Video!

If it’s helpful for you to watch me talk all this out, I’ve put it on YouTube:

The post Moving a Self-Hosted WordPress Site to WordPress.com appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]