Home Backend Development Golang Making a Clean, friendly Spinner in Go/Templ

Making a Clean, friendly Spinner in Go/Templ

Sep 10, 2024 pm 06:30 PM

The unhelpful HTML

You guys might think that making a consistent, clean and professional spinbox would be a simple task in HTML... However, to our despair, there is no standard attrib to tell an input that it should only accept integer or decimal values, all input filtering must be JS. Outch!

I'm going to be implementing this functionality with Go, a-h/Templ, Tailwind and my beloved Alpine.js to make life easy.

Adding the Skeleton

We start by writing a basic template for our integer spinbox:

templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) {
  ...
}
Copy after login

We define IntInterval as follows:

type IntInterval struct {
  A, B int
}
Copy after login

With the interval, we will set min and max of the input. As we are making an integer spinbox, the step will always be set to '1'.

templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) {
  <input type="number" placeholder="Enter Int…"
    step="1"
    if interval != nil {
      min={ strconv.Itoa(interval.A) }
      max={ strconv.Itoa(interval.B) }
    } ...>
}
Copy after login

Adding CSS

Let's now start adding some tw classes, following are some special properties and pseudo-elements that control the rendering of the input.
select-none [-moz-user-select:none] [-ms-user-select:none] [-o-user-select:none] [-webkit-user-select:none]

The following extra classes are used to remove the default spinner buttons:
[&::-webkit-inner-spin-button]:[-webkit-appearance:none] [&::-webkit-outer-spin-button]:[-webkit-appearance:none] [-moz-appearance:textfield]

Finally, let's add some basic padding, ring, colors, etc...
block w-full rounded-l-md py-2 px-2.5 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-400 bg-gray-50 sm:text-sm sm:leading-6

Adding it to our template, we get the following:

templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) {
  <input type="number" placeholder="Enter Int…"
    step="1"
    if interval != nil {
      min={ strconv.Itoa(interval.A) }
      max={ strconv.Itoa(interval.B) }
    }
    class="block w-full rounded-l-md py-2 px-2.5 text-gray-900 ring-1
 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-none
 focus:ring-2 focus:ring-primary-400 bg-gray-50 sm:text-sm sm:leading-6
 select-none [-moz-user-select:none] [-ms-user-select:none] [-o-user-select:none]
 [-webkit-user-select:none] [&::-webkit-inner-spin-button]:[-webkit-appearance:none] 
[&::-webkit-outer-spin-button]:[-webkit-appearance:none] [-moz-appearance:textfield]">
}
Copy after login

Now you should get a very text-like input, with some basic validation if you hover your mouse over it. We will add the functionality to check for valid integer inputs in the next section.

Implementing the Filter

The basic idea of an integer spinbox is of an input that only accepts integers. I initially attempted to implement this function by using HTML's pattern attribute as follows:

<input type="number" pattern="[0-9]+" ... >
Copy after login

The pattern attribute takes a regex string and uses it to validate the user input, however, it doesn't prevent invalid input from being entered in the first place. Actually, it was made for some simple client-side validation.

The 'oninput' event

Every time the user presses any key inside the input box, a oninput event is generated. capture this event with Alpine's syntax x-on:input and rectify the value accordingly for the input element. Let's create a parent div with an x-data attrib set, and add a function that will allow us to check if input is at all a Number... After which we can round the value accordingly.

<div x-data="{isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }}">
  <input ... x-on:input="$el.value = isNumber($el.value) ? Math.round($el.value) : null">
</div>
Copy after login

For those who don't know Alpine, $el here is used to refer to the current DOM element.

Custom Spinners

In the parent div created previously, we add the following class="flex" and add an x-ref="spinbox" attrib to the input so that our buttons can modify it's state through the magic property $refs.spinbox:

<div ... class="flex">
  <input ... x-ref="spinbox">
</div>
Copy after login

We then add a new child after the input, which will contain our buttons:

<div ...>
  <input ... x-ref="spinbox">
  <div class="flex flex-col-reverse">
    <!-- Decrement input's value -->
    <button type="button" class="flex-1 ...">-</button>
    <!-- Increment input's value -->
    <button type="button" class="flex-1 ...">+</button>
  </div>
</div>
Copy after login

Here, we use flex-col-reverse as an easy way to keep the tab order correct, it should first tab to '-', then '+'.

We then add the event handlers to the buttons using x-on:click, the full code (excluding CSS) is as follows:

<div ... x-data="{
        inc() { var e = $refs.spinbox; e.value = Math.min(Number(e.value) + Number(e.step), e.max); },
        dec() { var e = $refs.spinbox; e.value = Math.max(Number(e.value) - Number(e.step), e.min); },
        isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }
      }">
  <input ... x-ref="spinbox" x-on:input="$el.value = isNumber($el.value) ? Math.round($el.value) : null">
  <div ...>
    <!-- Decrement input's value -->
    <button type="button" ... x-on:click="dec">-</button>
    <!-- Increment input's value -->
    <button type="button" ... x-on:click="inc">+</button>
  </div>
</div>
Copy after login

We have to convert e.value and e.step before doing any arithmetic as those are strings.

When it comes to CSS for the spinners buttons, they are styled very similarly to the input, the full code is below .

Making a Clean, friendly Spinner in Go/Templ

The final template

templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) {
  <!-- Disable inner & outer spinner buttons, use buttons to render increment and decrement input value... -->
  <div class="flex-1">
    @InputLabel(name, label + " " + interval.toString(), tooltip)

    <input type="number" placeholder="Enter Int…" step="1"
        if interval != nil {
          min={ strconv.Itoa(interval.A) } max={ strconv.Itoa(interval.B) }
        }
        name={ name } value={ value }
        class="block w-full rounded-l-md py-2 px-2.5 text-gray-900 ring-1
 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-none
 focus:ring-2 focus:ring-primary-400 bg-gray-50 sm:text-sm sm:leading-6
 select-none [-moz-user-select:none] [-ms-user-select:none] [-o-user-select:none]
 [-webkit-user-select:none] [&::-webkit-inner-spin-button]:[-webkit-appearance:none] 
[&::-webkit-outer-spin-button]:[-webkit-appearance:none] [-moz-appearance:textfield]"
        x-on:input="$el.value = !isNumber($el.value) ? null : Math.round($el.value)"
        x-ref="spinbox"
        autocomplete="off"
        >

        <div class="flex flex-col-reverse font-medium">
          <!-- Decrement input's value -->
          <button type="button" class="flex-1 px-1 leading-none
 transition-colors ease-linear duration-100 rounded-br-md text-center
 text-sm bg-gray-100 hover:bg-gray-200 text-gray-500 hover:text-gray-900
 ring-1 ring-inset ring-gray-300 focus:outline-none focus:ring-inset
 focus:ring-2 focus:ring-primary-400 select-none [-moz-user-select:none]
 [-ms-user-select:none] [-o-user-select:none] [-webkit-user-select:none]" x-on:click="dec">-</button>
          <!-- Increment input's value -->
          <button type="button" class="flex-1 px-1 leading-none
 transition-colors ease-linear duration-100 rounded-tr-md text-center
 text-sm bg-gray-100 hover:bg-gray-200 text-gray-500 hover:text-gray-900
 ring-1 ring-inset ring-gray-300 focus:outline-none focus:ring-inset
 focus:ring-2 focus:ring-primary-400 select-none [-moz-user-select:none]
 [-ms-user-select:none] [-o-user-select:none] [-webkit-user-select:none]" x-on:click="inc">+</button>
        </div>
    </div>
  </div>
}
Copy after login

Enjoy :)

Works on

  • Mozilla Firefox 130.0 (64-bit)
  • Version 128.0.6613.120 (Official Build) (64-bit)

The above is the detailed content of Making a Clean, friendly Spinner in Go/Templ. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

See all articles