Saturday, April 27, 2024
HomeWeb developmentBrighten Up Your Astro Website with KwesForms and Rive — SitePoint

Brighten Up Your Astro Website with KwesForms and Rive — SitePoint


On this article, I’ll present you easy methods to add KwesForms to your Astro website after which convey the shape to life utilizing customized occasions and Rive.

Animated GIF of name field error

Customized occasions can be utilized to regulate the completely different states of a Rive animation every time an “occasion” within the kind happens. This may very well be when a area turns into invalid, or when the shape has been efficiently submitted.

In case you’re eager to leap forward, I’ve created an instance repo containing all of the code, and a stay preview:

Desk of Contents

Getting Began with Astro

To get began with Astro, you’ve a few choices. You possibly can both comply with the pointers for putting in Astro with the Automated CLI, or (my most well-liked strategy) set up Astro manually.

Create a web page

In case you’ve put in Astro manually, create a brand new file known as index.astro within the following listing: src/pages.

Create a part

Create a brand new file known as rive-form.astro within the src/elements listing.

Add the part to the web page

Add the next to render the RiveForm part within the index web page:



---
import RiveForm from '../elements/rive-form.astro';
---

<RiveForm />

For the remainder of this text, I’ll be including code to the rive-form.astro file.

The src could be seen within the repo right here: rive-kwes-forms/src/pages/index.astro.

Getting Began with KwesForms

I used KwesForms for a consumer challenge not too long ago, and beloved the expertise. There are, in fact, some ways to deal with kind information, however I discovered utilizing KwesForms actually helped simplify the requirement to have each client- and server-side validation!

To get began, go forward and enroll (it’s free). There are two methods to incorporate the KwesFroms code in your website: you may both set up by way of npm, or use a script aspect. On this instance, I’ll be utilizing the script aspect.

Screenshot of KwesForms setup

The remaining 5 steps within the setup part will information you thru easy methods to add an HTML kind aspect to your website.

Including KwesFroms script to Astro

When utilizing client-sides scripts with Astro, you would possibly wish to choose out of processing utilizing the is:inline directive. This tells Astro to go away the script alone and to render it within the HTML as a script aspect.

In your rive-form.astro file, add the next:

// src/elements/rive-form.astro

- <script src="https://kwesforms.com/v2/kwes-script.js" defer></script>
+ <script is:inline src="https://kwesforms.com/v2/kwes-script.js" defer></script>

Including KwesForms HTML

Right here’s the code I’ve used within the instance (utilizing Tailwind):

// src/elements/rive-form.astro

<script is:inline src="https://kwesforms.com/v2/kwes-script.js" defer></script>

<kind
  id="riveForm"
  class="kwes-form flex flex-col gap-6"
  motion="https://kwesforms.com/api/overseas/varieties/abc123"
  data-kw-no-reload
>
  <div class="flex gap-4">
    <div class="develop">
      <label for="title">Identify</label>
      <enter id="riveFormName" sort="textual content" title="title" data-kw-rules="required" />
    </div>
    <div class="develop">
      <label for="electronic mail">Electronic mail</label>
      <enter id="riveFormEmail" sort="electronic mail" title="electronic mail" data-kw-rules="required|electronic mail" required />
    </div>
  </div>
  <div>
    <label for="title">Message</label>
    <textarea id="riveFormMessage" title="message" rows="4" data-kw-rules="required"></textarea>
  </div>
  <button sort="submit">Ship Message</button>
</kind>

The src could be seen within the repo right here: rive-kwes-forms/src/elements.rive-form.astro.

There are a few attributes that I’ve used to configure my kind. You’ll discover on all the inputs I’ve added the next: data-kw-rules="required". This tells KwesFroms that these fields should comprise a worth earlier than the shape could be thought-about legitimate. I’ve used an extra attribute on the e-mail area to make sure solely legitimate electronic mail addresses are used — for instance, data-kw-rules="required|electronic mail".

You possibly can see all of the validation guidelines within the KwesForms kind documentation.

With the shape arrange, it’s now time so as to add a Rive animation.

What’s Rive?

Rive is tremendous cool, because it permits designers and animators to create an animation utilizing a browser-based interface, and as soon as it’s full, builders can merely obtain a file.

Modifying Astro’s Vite config

To make use of a .riv file with Astro, there’s a small quantity of config required so the Astro compiler is aware of what to do with recordsdata that finish in .riv.

To make use of Rive with Astro, add the next to your astro.config.mjs file:



import { defineConfig } from 'astro/config';

export default defineConfig({
  vite: {
    assetsInclude: ['**/*.riv'],
  },
});

Obtain Rive animation

The following step is to discover a Rive animation to make use of, or, when you’re feeling artistic you may create your individual. There are a great deal of neighborhood examples that may be downloaded and used without spending a dime.

The file I’m utilizing, Animated Login Character, was created by Juan Carlos Cruz from the Rive crew. To get began, obtain the file and reserve it in your public listing.

I’ve saved mine in public/rive/2244-7248-animated-login-character.riv.

The src could be seen within the repo right here: rive-kwes-forms/public/rive.

Initializing Rive

To initialize the Rive canvas, add the next to your rive-form.astro file:

// src/elements/rive-form.astro

<script>
  const r = new rive.Rive({
    src: '/rive/2244-7248-animated-login-character.riv',
    canvas: doc.getElementById('canvas'),
    autoplay: true,
    stateMachines: 'Login Machine',
  });
</script>
<script is:inline src="https://unpkg.com/@rive-app/canvas@2.7.0"></script>
<canvas id="canvas" width="800" top="600"></canvas>

The following half includes including occasion listeners to every of the shape parts to allow them to kick the Rive animation into its completely different animation states.

Rive state machines

You’ll see on the obtain web page that this animation has a variety of “states” outlined. These are the completely different states of the animation that may be triggered when sure kind occasions happen.

Screenshot of Rive State machines

Rive state machines could be one of many following varieties:

  • a set off that has a hearth() perform
  • a quantity that has a worth quantity property
  • a Boolean that has a worth Boolean property

The kind of state machines outlined in an animation will decide the way you invoke them out of your kind’s occasion listeners. (I’ll come again to this in only a second.)

Including Occasion Listeners

I’ve given every area within the kind an id attribute, and from right here I can connect the required occasion listeners for every occasion I’d wish to faucet into.

These occasions are particular to KwesForms. You possibly can see all of the customized occasions within the KwesForms documentation. Right here’s the code for the shape:

const kind = doc.getElementById('riveForm');

kind.addEventListener('kwSubmitted', perform () {
  console.log('kind: kwSubmitted');
});

kind.addEventListener('kwHasErrors', () => {
  console.log('kind: kwHasErrors');
});

And right here’s the code for the e-mail area. These are the usual JavaScript occasions for focus and blur. I’ve added the identical for the title and message fields:

const title = doc.getElementById('riveFormName');

title.addEventListener('focus', () => {
  console.log('title: focus');
});

title.addEventListener('blur', () => {
  console.log('title: blur');
});

Triggering Rive State Machines from Kind Occasions

That is the place all the pieces comes collectively. At any time when a kind occasion happens, I can invoke one of many states from the animation.

Making a getTrigger perform

Simply beneath the initialization code, add the next code snippet:

<script>
  const r = new rive.Rive({
  ...

+  const getTrigger = (title) => {
+    return r.stateMachineInputs('Login Machine').discover((enter) => enter.title === title);
+  };

</script>

This perform accepts a title parameter. That is the title of the state as seen earlier on the obtain web page. The perform returns an occasion of Rive’s stateMachineInputs, which permits values to be set, which in flip kicks the animation into its completely different states.

Calling a Set off from an Occasion Listener

At any time when the shape has errors, I hook into the KwesForms kwHasErrors occasion and name the trigFail set off utilizing the hearth perform:

kind.addEventListener('kwHasErrors', () => {
  console.log('kind: kwHasErrors');
+  const set off = getTrigger('trigFail');
+  set off.hearth();
});

At any time when the title area receives focus, I set isChecking to true, and wherever the title area is blurred, I set isChecking to false:

title.addEventListener('focus', () => {
  console.log('title: focus');
+  const set off = getTrigger('isChecking');
+  set off.worth = true;
});

title.addEventListener('blur', () => {
  console.log('title: blur');
+  const set off = getTrigger('isChecking');
+  set off.worth = false;
});

At any time when the e-mail area receives focus, I set isHandsUp to true, and every time the e-mail area is blurred, I set isHandsUp to false:

electronic mail.addEventListener('focus', () => {
  console.log('electronic mail: focus');
+  const set off = getTrigger('isHandsUp');
+  set off.worth = true;
});

electronic mail.addEventListener('blur', () => {
  console.log('electronic mail: blur');
+  const set off = getTrigger('isHandsUp');
+  set off.worth = false;
})

Animated GIF of email field error

Conclusion

Through the use of a mixture of KwesForms occasions and commonplace JavaScript occasions with Rive animations, kind errors could be surfaced in nearly any means you may think about.

When you have any questions regarding something I’ve coated on this put up, be at liberty to return discover me on Twitter/X: PaulieScanlon.

Need extra information on Astro? Try out our model new e-book on SitePoint Premium: Unleashing the Energy of Astro, by Tamas Piros, which can present you easy methods to get essentially the most out of essentially the most out of this contemporary all-in-one framework to construct sooner, content-focused web sites



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments