Currency Input
Money field that formats as you type (Rp 12.500.000), keeps the caret in place, and posts the plain number. Optional quick amount chips.
Minimum Rp10.000, maximum Rp10.000.000
Minimum Rp10.000, maximum Rp10.000.000
Minimum Rp10.000, maximum Rp10.000.000
Minimum Rp10.000, maximum Rp10.000.000
Minimum Rp10.000, maximum Rp10.000.000
@php
$panel = 'grid gap-4 rounded-xl border border-line bg-surface p-5';
$balance = 'flex items-baseline justify-between';
$balanceLabel = 'text-sm text-muted';
$balanceValue = 'text-lg font-semibold text-ink tabular-nums';
@endphp
<div class="{{ $panel }}">
<div class="{{ $balance }}">
<span class="{{ $balanceLabel }}">Current balance</span>
<span class="{{ $balanceValue }}">Rp 245.000</span>
</div>
<x-markas.currency-input
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000, maximum Rp10.000.000"
:min="10000"
:max="10000000"
:value="100000"
:presets="[50000, 100000, 250000, 500000, 1000000]"
/>
<x-markas.button>Top up balance</x-markas.button>
</div>import { Button } from "@/components/markas/Button";
import { CurrencyInput } from "@/components/markas/CurrencyInput";
const panel = "grid gap-4 rounded-xl border border-line bg-surface p-5";
const balance = "flex items-baseline justify-between";
const balanceLabel = "text-sm text-muted";
const balanceValue = "text-lg font-semibold text-ink tabular-nums";
export default function CurrencyInputExample() {
return (
<div className={panel}>
<div className={balance}>
<span className={balanceLabel}>Current balance</span>
<span className={balanceValue}>Rp 245.000</span>
</div>
<CurrencyInput
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000, maximum Rp10.000.000"
min={10000}
max={10000000}
defaultValue={100000}
presets={[50000, 100000, 250000, 500000, 1000000]}
/>
<Button>Top up balance</Button>
</div>
);
}<script setup lang="ts">
import { ref } from "vue";
import Button from "@/components/markas/Button.vue";
import CurrencyInput from "@/components/markas/CurrencyInput.vue";
const panel = "grid gap-4 rounded-xl border border-line bg-surface p-5";
const balance = "flex items-baseline justify-between";
const balanceLabel = "text-sm text-muted";
const balanceValue = "text-lg font-semibold text-ink tabular-nums";
const amount = ref<number | null>(100000);
</script>
<template>
<div :class="panel">
<div :class="balance">
<span :class="balanceLabel">Current balance</span>
<span :class="balanceValue">Rp 245.000</span>
</div>
<CurrencyInput
v-model="amount"
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000, maximum Rp10.000.000"
:min="10000"
:max="10000000"
:presets="[50000, 100000, 250000, 500000, 1000000]"
/>
<Button>Top up balance</Button>
</div>
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import CurrencyInput from "$lib/components/markas/CurrencyInput.svelte";
const panel = "grid gap-4 rounded-xl border border-line bg-surface p-5";
const balance = "flex items-baseline justify-between";
const balanceLabel = "text-sm text-muted";
const balanceValue = "text-lg font-semibold text-ink tabular-nums";
</script>
<div class={panel}>
<div class={balance}>
<span class={balanceLabel}>Current balance</span>
<span class={balanceValue}>Rp 245.000</span>
</div>
<CurrencyInput
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000, maximum Rp10.000.000"
min={10000}
max={10000000}
defaultValue={100000}
presets={[50000, 100000, 250000, 500000, 1000000]}
/>
<Button>Top up balance</Button>
</div>---
import Button from "@/components/markas/Button.astro";
import CurrencyInput from "@/components/markas/CurrencyInput.astro";
const panel = "grid gap-4 rounded-xl border border-line bg-surface p-5";
const balance = "flex items-baseline justify-between";
const balanceLabel = "text-sm text-muted";
const balanceValue = "text-lg font-semibold text-ink tabular-nums";
---
<div class={panel}>
<div class={balance}>
<span class={balanceLabel}>Current balance</span>
<span class={balanceValue}>Rp 245.000</span>
</div>
<CurrencyInput
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000, maximum Rp10.000.000"
min={10000}
max={10000000}
defaultValue={100000}
presets={[50000, 100000, 250000, 500000, 1000000]}
/>
<Button>Top up balance</Button>
</div>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { CurrencyInput } from "./markas/currency-input.component";
@Component({
selector: "markas-example",
imports: [Button, CurrencyInput],
template: `
<div [class]="panel">
<div [class]="balance">
<span [class]="balanceLabel">Current balance</span>
<span [class]="balanceValue">Rp 245.000</span>
</div>
<markas-currency-input
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000, maximum Rp10.000.000"
[min]="10000"
[max]="10000000"
[defaultValue]="100000"
[presets]="presets"
/>
<button markas-button>Top up balance</button>
</div>
`,
})
export default class CurrencyInputExample {
protected readonly panel =
"grid gap-4 rounded-xl border border-line bg-surface p-5";
protected readonly balance = "flex items-baseline justify-between";
protected readonly balanceLabel = "text-sm text-muted";
protected readonly balanceValue =
"text-lg font-semibold text-ink tabular-nums";
protected readonly presets = [50000, 100000, 250000, 500000, 1000000];
}Examples
US dollars
Billed in US dollars at the end of each month
Billed in US dollars at the end of each month
Billed in US dollars at the end of each month
Billed in US dollars at the end of each month
Billed in US dollars at the end of each month
<x-markas.currency-input
label="Monthly budget"
name="budget"
currency="USD"
hint="Billed in US dollars at the end of each month"
:value="1250.5"
:presets="[100, 500, 1000, 5000]"
presets-label="Suggested budgets"
/>import { CurrencyInput } from "@/components/markas/CurrencyInput";
export default function Example() {
return (
<CurrencyInput
label="Monthly budget"
name="budget"
currency="USD"
hint="Billed in US dollars at the end of each month"
defaultValue={1250.5}
presets={[100, 500, 1000, 5000]}
presetsLabel="Suggested budgets"
/>
);
}<script setup lang="ts">
import { ref } from "vue";
import CurrencyInput from "@/components/markas/CurrencyInput.vue";
const budget = ref<number | null>(1250.5);
</script>
<template>
<CurrencyInput
v-model="budget"
label="Monthly budget"
name="budget"
currency="USD"
hint="Billed in US dollars at the end of each month"
:presets="[100, 500, 1000, 5000]"
presets-label="Suggested budgets"
/>
</template><script lang="ts">
import CurrencyInput from "$lib/components/markas/CurrencyInput.svelte";
</script>
<CurrencyInput
label="Monthly budget"
name="budget"
currency="USD"
hint="Billed in US dollars at the end of each month"
defaultValue={1250.5}
presets={[100, 500, 1000, 5000]}
presetsLabel="Suggested budgets"
/>---
import CurrencyInput from "@/components/markas/CurrencyInput.astro";
---
<CurrencyInput
label="Monthly budget"
name="budget"
currency="USD"
hint="Billed in US dollars at the end of each month"
defaultValue={1250.5}
presets={[100, 500, 1000, 5000]}
presetsLabel="Suggested budgets"
/>import { Component } from "@angular/core";
import { CurrencyInput } from "./markas/currency-input.component";
@Component({
selector: "markas-example",
imports: [CurrencyInput],
template: `
<markas-currency-input
label="Monthly budget"
name="budget"
currency="USD"
hint="Billed in US dollars at the end of each month"
[defaultValue]="1250.5"
[presets]="presets"
presetsLabel="Suggested budgets"
/>
`,
})
export default class CurrencyInputUsdExample {
protected readonly presets = [100, 500, 1000, 5000];
}States
Amount exceeds your daily limit of Rp5.000.000
Amount exceeds your daily limit of Rp5.000.000
Amount exceeds your daily limit of Rp5.000.000
Amount exceeds your daily limit of Rp5.000.000
Amount exceeds your daily limit of Rp5.000.000
@php
$stack = 'grid gap-5';
@endphp
<div class="{{ $stack }}">
<x-markas.currency-input label="Transfer amount" error="Amount exceeds your daily limit of Rp5.000.000" :value="7500000" />
<x-markas.currency-input label="Admin fee" :value="2500" disabled />
<x-markas.currency-input label="Opening balance" placeholder="0" />
</div>import { CurrencyInput } from "@/components/markas/CurrencyInput";
const stack = "grid gap-5";
export default function Example() {
return (
<div className={stack}>
<CurrencyInput
label="Transfer amount"
error="Amount exceeds your daily limit of Rp5.000.000"
defaultValue={7500000}
/>
<CurrencyInput label="Admin fee" defaultValue={2500} disabled />
<CurrencyInput label="Opening balance" placeholder="0" />
</div>
);
}<script setup lang="ts">
import { ref } from "vue";
import CurrencyInput from "@/components/markas/CurrencyInput.vue";
const stack = "grid gap-5";
const transfer = ref<number | null>(7500000);
const fee = ref<number | null>(2500);
const opening = ref<number | null>(null);
</script>
<template>
<div :class="stack">
<CurrencyInput
v-model="transfer"
label="Transfer amount"
error="Amount exceeds your daily limit of Rp5.000.000"
/>
<CurrencyInput v-model="fee" label="Admin fee" disabled />
<CurrencyInput v-model="opening" label="Opening balance" placeholder="0" />
</div>
</template><script lang="ts">
import CurrencyInput from "$lib/components/markas/CurrencyInput.svelte";
const stack = "grid gap-5";
</script>
<div class={stack}>
<CurrencyInput
label="Transfer amount"
error="Amount exceeds your daily limit of Rp5.000.000"
defaultValue={7500000}
/>
<CurrencyInput label="Admin fee" defaultValue={2500} disabled />
<CurrencyInput label="Opening balance" placeholder="0" />
</div>---
import CurrencyInput from "@/components/markas/CurrencyInput.astro";
const stack = "grid gap-5";
---
<div class={stack}>
<CurrencyInput
label="Transfer amount"
error="Amount exceeds your daily limit of Rp5.000.000"
defaultValue={7500000}
/>
<CurrencyInput label="Admin fee" defaultValue={2500} disabled />
<CurrencyInput label="Opening balance" placeholder="0" />
</div>import { Component } from "@angular/core";
import { CurrencyInput } from "./markas/currency-input.component";
@Component({
selector: "markas-example",
imports: [CurrencyInput],
template: `
<div [class]="stack">
<markas-currency-input
label="Transfer amount"
error="Amount exceeds your daily limit of Rp5.000.000"
[defaultValue]="7500000"
/>
<markas-currency-input label="Admin fee" [defaultValue]="2500" disabled />
<markas-currency-input label="Opening balance" placeholder="0" />
</div>
`,
})
export default class CurrencyInputStatesExample {
protected readonly stack = "grid gap-5";
}Donation with suggested amounts
Support the village library
Every rupiah goes to new books for 300 students.
Minimum Rp5.000
Support the village library
Every rupiah goes to new books for 300 students.
Minimum Rp5.000
Support the village library
Every rupiah goes to new books for 300 students.
Minimum Rp5.000
Support the village library
Every rupiah goes to new books for 300 students.
Minimum Rp5.000
Support the village library
Every rupiah goes to new books for 300 students.
Minimum Rp5.000
@php
$panel = 'grid gap-4';
$heading = 'grid gap-1';
$title = 'text-base font-semibold text-ink';
$text = 'text-sm text-muted';
@endphp
<div class="{{ $panel }}">
<div class="{{ $heading }}">
<p class="{{ $title }}">Support the village library</p>
<p class="{{ $text }}">Every rupiah goes to new books for 300 students.</p>
</div>
<x-markas.currency-input
label="Donation amount"
name="donation"
placeholder="0"
:min="5000"
hint="Minimum Rp5.000"
:presets="[25000, 50000, 100000, 1500000]"
presets-label="Suggested donations"
/>
<x-markas.button variant="secondary">Continue to payment</x-markas.button>
</div>import { Button } from "@/components/markas/Button";
import { CurrencyInput } from "@/components/markas/CurrencyInput";
const panel = "grid gap-4";
const heading = "grid gap-1";
const title = "text-base font-semibold text-ink";
const text = "text-sm text-muted";
export default function Example() {
return (
<div className={panel}>
<div className={heading}>
<p className={title}>Support the village library</p>
<p className={text}>Every rupiah goes to new books for 300 students.</p>
</div>
<CurrencyInput
label="Donation amount"
name="donation"
placeholder="0"
min={5000}
hint="Minimum Rp5.000"
presets={[25000, 50000, 100000, 1500000]}
presetsLabel="Suggested donations"
/>
<Button variant="secondary">Continue to payment</Button>
</div>
);
}<script setup lang="ts">
import { ref } from "vue";
import Button from "@/components/markas/Button.vue";
import CurrencyInput from "@/components/markas/CurrencyInput.vue";
const panel = "grid gap-4";
const heading = "grid gap-1";
const title = "text-base font-semibold text-ink";
const text = "text-sm text-muted";
const donation = ref<number | null>(null);
</script>
<template>
<div :class="panel">
<div :class="heading">
<p :class="title">Support the village library</p>
<p :class="text">Every rupiah goes to new books for 300 students.</p>
</div>
<CurrencyInput
v-model="donation"
label="Donation amount"
name="donation"
placeholder="0"
:min="5000"
hint="Minimum Rp5.000"
:presets="[25000, 50000, 100000, 1500000]"
presets-label="Suggested donations"
/>
<Button variant="secondary">Continue to payment</Button>
</div>
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import CurrencyInput from "$lib/components/markas/CurrencyInput.svelte";
const panel = "grid gap-4";
const heading = "grid gap-1";
const title = "text-base font-semibold text-ink";
const text = "text-sm text-muted";
</script>
<div class={panel}>
<div class={heading}>
<p class={title}>Support the village library</p>
<p class={text}>Every rupiah goes to new books for 300 students.</p>
</div>
<CurrencyInput
label="Donation amount"
name="donation"
placeholder="0"
min={5000}
hint="Minimum Rp5.000"
presets={[25000, 50000, 100000, 1500000]}
presetsLabel="Suggested donations"
/>
<Button variant="secondary">Continue to payment</Button>
</div>---
import Button from "@/components/markas/Button.astro";
import CurrencyInput from "@/components/markas/CurrencyInput.astro";
const panel = "grid gap-4";
const heading = "grid gap-1";
const title = "text-base font-semibold text-ink";
const text = "text-sm text-muted";
---
<div class={panel}>
<div class={heading}>
<p class={title}>Support the village library</p>
<p class={text}>Every rupiah goes to new books for 300 students.</p>
</div>
<CurrencyInput
label="Donation amount"
name="donation"
placeholder="0"
min={5000}
hint="Minimum Rp5.000"
presets={[25000, 50000, 100000, 1500000]}
presetsLabel="Suggested donations"
/>
<Button variant="secondary">Continue to payment</Button>
</div>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { CurrencyInput } from "./markas/currency-input.component";
@Component({
selector: "markas-example",
imports: [Button, CurrencyInput],
template: `
<div [class]="panel">
<div [class]="heading">
<p [class]="title">Support the village library</p>
<p [class]="text">Every rupiah goes to new books for 300 students.</p>
</div>
<markas-currency-input
label="Donation amount"
name="donation"
placeholder="0"
[min]="5000"
hint="Minimum Rp5.000"
[presets]="presets"
presetsLabel="Suggested donations"
/>
<button markas-button variant="secondary">Continue to payment</button>
</div>
`,
})
export default class CurrencyInputDonationExample {
protected readonly panel = "grid gap-4";
protected readonly heading = "grid gap-1";
protected readonly title = "text-base font-semibold text-ink";
protected readonly text = "text-sm text-muted";
protected readonly presets = [25000, 50000, 100000, 1500000];
}Installation
npx markasui@latest add currency-inputpnpm dlx markasui@latest add currency-inputyarn dlx markasui@latest add currency-inputbunx --bun markasui@latest add currency-input- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Install the dependency:
npm install alpinejs - Copy the component source below to
resources/views/components/markas/currency-input.blade.php.
@props([
'label' => null,
'hint' => null,
'error' => null,
'currency' => 'IDR',
'min' => null,
'max' => null,
'value' => null,
'presets' => [],
'presetsLabel' => 'Quick amounts',
'name' => null,
])
@php
// wire:model.live without its own timing gets the 150 ms debounce Livewire gives text inputs, so a burst of changes sends one request, not one per change.
$liveModel = fn (string $key) => preg_match('/^wire:model(\.[\w-]+)*\.live(\.|$)/', $key) && ! preg_match('/\.(debounce|throttle|blur|change|lazy|enter)(\.|$)/', $key);
$attributes = new \Illuminate\View\ComponentAttributeBag(collect($attributes->getAttributes())->mapWithKeys(fn ($bound, $key) => [$liveModel($key) ? $key.'.debounce.150ms' : $key => $bound])->all());
$wrapper = 'grid gap-1.5';
$labelClass = 'text-sm font-medium text-ink';
$control = 'flex h-11 w-full items-center gap-2 rounded-md border border-line bg-surface px-3 text-base transition-colors duration-150 ease-out has-[:disabled]:cursor-not-allowed has-[:disabled]:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[[aria-invalid=true]]:border-danger motion-reduce:transition-none';
$prefix = 'shrink-0 font-medium text-muted select-none';
$field = 'h-full min-w-0 flex-1 bg-transparent font-medium text-ink tabular-nums outline-none placeholder:text-faint disabled:cursor-not-allowed disabled:text-muted';
$chips = 'flex flex-wrap gap-2 pt-1';
$chip = 'inline-flex h-8 items-center rounded-full border border-line bg-surface px-3 text-sm font-medium text-ink tabular-nums transition-[background-color,border-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 aria-pressed:border-primary aria-pressed:bg-primary-soft motion-reduce:transition-none';
$hintClass = 'text-sm text-muted';
$errorClass = 'text-sm text-danger';
// Separators and short units per currency. IDR follows id-ID, USD follows en-US.
$currencies = [
'IDR' => ['symbol' => 'Rp', 'group' => '.', 'decimal' => ',', 'fraction' => 0, 'short' => '', 'units' => [[1000000, 'jt'], [1000, 'rb']]],
'USD' => ['symbol' => '$', 'group' => ',', 'decimal' => '.', 'fraction' => 2, 'short' => '$', 'units' => [[1000000, 'M'], [1000, 'K']]],
];
$c = $currencies[$currency] ?? $currencies['IDR'];
// 12500000 -> "12.500.000". Decimals show only when they are not zero.
$formatAmount = function (float $amount) use ($c): string {
[$int, $frac] = array_pad(explode('.', number_format(abs($amount), $c['fraction'], '.', '')), 2, '');
return preg_replace('/\B(?=(\d{3})+(?!\d))/', $c['group'], $int).(preg_match('/[1-9]/', $frac) ? $c['decimal'].$frac : '');
};
// 50000 -> "50rb", 1500000 -> "1,5jt", 1000 USD -> "$1K".
$shortAmount = function (float $amount) use ($c, $formatAmount): string {
foreach ($c['units'] as [$size, $suffix]) {
if ($amount >= $size) {
$scaled = rtrim(rtrim(number_format($amount / $size, 1, '.', ''), '0'), '.');
return $c['short'].str_replace('.', $c['decimal'], $scaled).$suffix;
}
}
return $c['short'].$formatAmount($amount);
};
$value = $value === null || $value === '' ? null : (float) $value;
// Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
$idKey = 'markas-currency-input|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $name).'|';
for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
$__env->markAsRenderedOnce($idKey.$idIndex);
$id = $attributes->get('id') ?? 'markas-currency-input-'.hash('xxh32', $idKey.$idIndex);
$currencyId = $id.'-currency';
$messageId = $error ? $id.'-error' : ($hint ? $id.'-hint' : null);
$disabled = (bool) $attributes->get('disabled');
@endphp
{{-- Formats as you type, keeps the caret in place, and posts the plain number through a hidden input named `name`. wire:model and x-model bind that number on the root (x-modelable). --}}
<div
class="{{ $wrapper }}"
x-data="{
c: @js($c),
min: @js($min === null ? null : (float) $min),
max: @js($max === null ? null : (float) $max),
value: @js($value),
{{-- Amount the field shows or is animating to. When value changes from outside (wire:model, x-model), the field follows. --}}
shown: @js($value),
frame: 0,
init() {
this.$watch('value', (next) => {
const amount = next === null || next === '' ? null : Number(next);
if (amount === this.shown) return;
cancelAnimationFrame(this.frame);
this.shown = amount;
this.$refs.field.value = amount === null || Number.isNaN(amount) ? '' : this.format(amount);
});
},
group(digits) {
return digits.replace(/\B(?=(\d{3})+(?!\d))/g, this.c.group);
},
format(amount) {
const [int = '0', frac = ''] = Math.abs(amount).toFixed(this.c.fraction).split('.');
return this.group(int) + (/[1-9]/.test(frac) ? this.c.decimal + frac : '');
},
parse(raw) {
const [head = '', ...tail] = this.c.fraction ? raw.split(this.c.decimal) : [raw];
const int = head.replace(/\D/g, '').replace(/^0+(?=\d)/, '');
const frac = tail.join('').replace(/\D/g, '').slice(0, this.c.fraction);
if (! int && ! tail.length) return { text: '', value: null };
const whole = int || '0';
return { text: this.group(whole) + (tail.length ? this.c.decimal + frac : ''), value: Number(`${whole}.${frac || '0'}`) };
},
significant(text) {
return [...text].filter((ch) => /\d/.test(ch) || (this.c.fraction > 0 && ch === this.c.decimal)).length;
},
clamp(n) {
return Math.min(Math.max(n, this.min ?? -Infinity), this.max ?? Infinity);
},
input(event) {
cancelAnimationFrame(this.frame);
const field = event.target;
const count = this.significant(field.value.slice(0, field.selectionStart ?? field.value.length));
const parsed = this.parse(field.value);
field.value = parsed.text;
let position = 0;
for (let seen = 0; position < parsed.text.length && seen < count; position++) if (this.significant(parsed.text[position])) seen++;
field.setSelectionRange(position, position);
this.shown = parsed.value;
this.value = parsed.value;
},
skipSeparator(event) {
const field = event.target;
const at = field.selectionStart;
if (at === null || at !== field.selectionEnd) return;
if (event.key === 'Backspace' && field.value[at - 1] === this.c.group) field.setSelectionRange(at - 1, at - 1);
if (event.key === 'Delete' && field.value[at] === this.c.group) field.setSelectionRange(at + 1, at + 1);
},
blur() {
if (this.value === null || this.value === '') return;
this.shown = this.clamp(Number(this.value));
this.value = this.shown;
this.$refs.field.value = this.format(this.value);
},
pick(preset) {
const target = this.clamp(preset);
const from = Number(this.value ?? 0);
const field = this.$refs.field;
this.shown = target;
this.value = target;
cancelAnimationFrame(this.frame);
if (matchMedia('(prefers-reduced-motion: reduce)').matches) return (field.value = this.format(target));
let start;
const step = 10 ** this.c.fraction;
const tick = (now) => {
start ??= now;
const t = Math.min((now - start) / 400, 1);
field.value = this.format(Math.round((from + (target - from) * (1 - (1 - t) ** 3)) * step) / step);
if (t < 1) this.frame = requestAnimationFrame(tick);
};
this.frame = requestAnimationFrame(tick);
},
destroy() {
cancelAnimationFrame(this.frame);
},
}"
x-modelable="value"
{{ $attributes->whereStartsWith(['wire:model', 'x-model']) }}
>
@if ($label)
<label for="{{ $id }}" class="{{ $labelClass }}">{{ $label }}</label>
@endif
<div class="{{ $control }}">
<span id="{{ $currencyId }}" class="{{ $prefix }}">{{ $c['symbol'] }}</span>
<input
x-ref="field"
x-on:input="input($event)"
x-on:keydown="skipSeparator($event)"
x-on:blur="blur()"
{{ $attributes->whereDoesntStartWith(['wire:model', 'x-model'])->merge([
'id' => $id,
'type' => 'text',
'inputmode' => $c['fraction'] ? 'decimal' : 'numeric',
'autocomplete' => 'off',
'value' => $value === null ? '' : $formatAmount($value),
'aria-invalid' => $error ? 'true' : null,
'aria-describedby' => trim($currencyId.' '.$messageId),
])->class([$field]) }}
/>
</div>
@if ($name)
<input type="hidden" name="{{ $name }}" value="{{ $value ?? '' }}" x-bind:value="value ?? ''" />
@endif
@if ($error)
<p id="{{ $id }}-error" class="{{ $errorClass }}">{{ $error }}</p>
@elseif ($hint)
<p id="{{ $id }}-hint" class="{{ $hintClass }}">{{ $hint }}</p>
@endif
@if (count($presets) > 0)
<div role="group" aria-label="{{ $presetsLabel }}" class="{{ $chips }}">
@foreach ($presets as $preset)
<button
type="button"
aria-pressed="{{ $value !== null && (float) $preset === $value ? 'true' : 'false' }}"
x-bind:aria-pressed="String(value !== null && value !== '' && Number(value) === {{ (float) $preset }})"
@if ($disabled) disabled @endif
x-on:click="pick({{ (float) $preset }})"
class="{{ $chip }}"
>{{ $shortAmount((float) $preset) }}</button>
@endforeach
</div>
@endif
</div>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/CurrencyInput.tsx.
"use client";
import {
useEffect,
useId,
useRef,
useState,
type ChangeEvent,
type ComponentProps,
type FocusEvent,
type KeyboardEvent,
type ReactNode,
} from "react";
const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control =
"flex h-11 w-full items-center gap-2 rounded-md border border-line bg-surface px-3 text-base transition-colors duration-150 ease-out has-[:disabled]:cursor-not-allowed has-[:disabled]:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[[aria-invalid=true]]:border-danger motion-reduce:transition-none";
const prefix = "shrink-0 font-medium text-muted select-none";
const field =
"h-full min-w-0 flex-1 bg-transparent font-medium text-ink tabular-nums outline-none placeholder:text-faint disabled:cursor-not-allowed disabled:text-muted";
const chips = "flex flex-wrap gap-2 pt-1";
const chip =
"inline-flex h-8 items-center rounded-full border border-line bg-surface px-3 text-sm font-medium text-ink tabular-nums transition-[background-color,border-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 aria-pressed:border-primary aria-pressed:bg-primary-soft motion-reduce:transition-none";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";
/** Separators and short units per currency. IDR follows id-ID, USD follows en-US. */
const CURRENCIES = {
IDR: {
symbol: "Rp",
group: ".",
decimal: ",",
fraction: 0,
short: "",
units: [
[1e6, "jt"],
[1e3, "rb"],
],
},
USD: {
symbol: "$",
group: ",",
decimal: ".",
fraction: 2,
short: "$",
units: [
[1e6, "M"],
[1e3, "K"],
],
},
} as const;
type Currency = (typeof CURRENCIES)[keyof typeof CURRENCIES];
const COUNT_MS = 400;
const cx = (...c: (string | false | null | undefined)[]) =>
c.filter(Boolean).join(" ");
const reducedMotion = () =>
typeof matchMedia === "function" &&
matchMedia("(prefers-reduced-motion: reduce)").matches;
const groupDigits = (digits: string, c: Currency) =>
digits.replace(/\B(?=(\d{3})+(?!\d))/g, c.group);
/** 12500000 -> "12.500.000". Decimals show only when they are not zero. */
function formatAmount(value: number, c: Currency) {
const [int = "0", frac = ""] = Math.abs(value).toFixed(c.fraction).split(".");
return groupDigits(int, c) + (/[1-9]/.test(frac) ? c.decimal + frac : "");
}
/** 50000 -> "50rb", 1500000 -> "1,5jt", 1000 USD -> "$1K". */
function shortAmount(value: number, c: Currency) {
const unit = c.units.find(([size]) => value >= size);
if (!unit) return c.short + formatAmount(value, c);
const scaled = String(Number((value / unit[0]).toFixed(1)));
return c.short + scaled.replace(".", c.decimal) + unit[1];
}
/** Typed text -> clean grouped text and its number (null when empty). */
function parseTyped(raw: string, c: Currency) {
const [head = "", ...tail] = c.fraction ? raw.split(c.decimal) : [raw];
const int = head.replace(/\D/g, "").replace(/^0+(?=\d)/, "");
const hasDecimal = tail.length > 0;
const frac = tail.join("").replace(/\D/g, "").slice(0, c.fraction);
if (!int && !hasDecimal) return { text: "", value: null };
const whole = int || "0";
return {
text: groupDigits(whole, c) + (hasDecimal ? c.decimal + frac : ""),
value: Number(`${whole}.${frac || "0"}`),
};
}
/** Digits (and the decimal mark) are what the caret position is counted in. */
const significant = (text: string, c: Currency) =>
[...text].filter(
(ch) => /\d/.test(ch) || (c.fraction > 0 && ch === c.decimal),
).length;
function caretAfter(text: string, count: number, c: Currency) {
let position = 0;
for (let seen = 0; position < text.length && seen < count; position++)
if (significant(text[position] ?? "", c)) seen++;
return position;
}
export type CurrencyInputProps = Omit<
ComponentProps<"input">,
"type" | "value" | "defaultValue" | "onChange" | "min" | "max"
> & {
label?: ReactNode;
hint?: ReactNode;
error?: ReactNode;
currency?: keyof typeof CURRENCIES;
min?: number;
max?: number;
defaultValue?: number | null;
/** Quick amount chips below the field. */
presets?: number[];
presetsLabel?: string;
onValueChange?: (value: number | null) => void;
};
export function CurrencyInput({
label,
hint,
error,
currency = "IDR",
min,
max,
defaultValue = null,
presets = [],
presetsLabel = "Quick amounts",
onValueChange,
name,
id,
disabled,
className,
onKeyDown,
onBlur,
...props
}: CurrencyInputProps) {
const c = CURRENCIES[currency];
const generatedId = useId();
const inputId = id ?? generatedId;
const currencyId = `${inputId}-currency`;
const messageId = error
? `${inputId}-error`
: hint
? `${inputId}-hint`
: undefined;
const [value, setValue] = useState<number | null>(defaultValue);
const [text, setText] = useState(() =>
defaultValue === null ? "" : formatAmount(defaultValue, c),
);
const frame = useRef(0);
useEffect(() => () => cancelAnimationFrame(frame.current), []);
const clamp = (n: number) =>
Math.min(Math.max(n, min ?? -Infinity), max ?? Infinity);
const commit = (next: number | null) => {
setValue(next);
onValueChange?.(next);
};
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
cancelAnimationFrame(frame.current);
const input = event.currentTarget;
const count = significant(
input.value.slice(0, input.selectionStart ?? input.value.length),
c,
);
const parsed = parseTyped(input.value, c);
// Write the formatted text first so the caret can be placed before React re-renders.
input.value = parsed.text;
const position = caretAfter(parsed.text, count, c);
input.setSelectionRange(position, position);
setText(parsed.text);
commit(parsed.value);
};
/** Backspace or Delete next to a separator removes the digit behind it instead. */
const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
onKeyDown?.(event);
const input = event.currentTarget;
const at = input.selectionStart;
if (at === null || at !== input.selectionEnd) return;
if (event.key === "Backspace" && input.value[at - 1] === c.group)
input.setSelectionRange(at - 1, at - 1);
if (event.key === "Delete" && input.value[at] === c.group)
input.setSelectionRange(at + 1, at + 1);
};
const handleBlur = (event: FocusEvent<HTMLInputElement>) => {
onBlur?.(event);
if (value === null) return;
const next = clamp(value);
setText(formatAmount(next, c));
if (next !== value) commit(next);
};
/** Jump to a preset, counting the digits up or down on the way. */
const pick = (preset: number) => {
const target = clamp(preset);
const from = value ?? 0;
commit(target);
cancelAnimationFrame(frame.current);
if (reducedMotion() || typeof requestAnimationFrame !== "function") {
setText(formatAmount(target, c));
return;
}
let start: number | undefined;
const tick = (now: number) => {
start ??= now;
const t = Math.min((now - start) / COUNT_MS, 1);
const eased = 1 - (1 - t) ** 3;
const step = 10 ** c.fraction;
setText(
formatAmount(
Math.round((from + (target - from) * eased) * step) / step,
c,
),
);
if (t < 1) frame.current = requestAnimationFrame(tick);
};
frame.current = requestAnimationFrame(tick);
};
return (
<div className={wrapper}>
{label && (
<label htmlFor={inputId} className={labelClass}>
{label}
</label>
)}
<div className={control}>
<span id={currencyId} className={prefix}>
{c.symbol}
</span>
<input
id={inputId}
type="text"
inputMode={c.fraction ? "decimal" : "numeric"}
autoComplete="off"
value={text}
disabled={disabled}
aria-invalid={error ? true : undefined}
aria-describedby={cx(currencyId, messageId)}
className={cx(field, className)}
{...props}
onChange={handleChange}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
/>
</div>
{name && <input type="hidden" name={name} value={value ?? ""} />}
{error ? (
<p id={`${inputId}-error`} className={errorClass}>
{error}
</p>
) : hint ? (
<p id={`${inputId}-hint`} className={hintClass}>
{hint}
</p>
) : null}
{presets.length > 0 && (
<div role="group" aria-label={presetsLabel} className={chips}>
{presets.map((preset) => (
<button
key={preset}
type="button"
aria-pressed={value === preset}
disabled={disabled}
className={chip}
onClick={() => pick(preset)}
>
{shortAmount(preset, c)}
</button>
))}
</div>
)}
</div>
);
}- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/CurrencyInput.vue.
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, useId, watch } from "vue";
defineOptions({ inheritAttrs: false });
/** Separators and short units per currency. IDR follows id-ID, USD follows en-US. */
const CURRENCIES = {
IDR: {
symbol: "Rp",
group: ".",
decimal: ",",
fraction: 0,
short: "",
units: [
[1e6, "jt"],
[1e3, "rb"],
],
},
USD: {
symbol: "$",
group: ",",
decimal: ".",
fraction: 2,
short: "$",
units: [
[1e6, "M"],
[1e3, "K"],
],
},
} as const;
type Currency = (typeof CURRENCIES)[keyof typeof CURRENCIES];
const props = withDefaults(
defineProps<{
label?: string;
hint?: string;
error?: string;
currency?: keyof typeof CURRENCIES;
min?: number;
max?: number;
/** Quick amount chips below the field. */
presets?: number[];
presetsLabel?: string;
name?: string;
id?: string;
disabled?: boolean;
}>(),
{
label: undefined,
hint: undefined,
error: undefined,
currency: "IDR",
min: undefined,
max: undefined,
presets: () => [],
presetsLabel: "Quick amounts",
name: undefined,
id: undefined,
disabled: false,
},
);
const model = defineModel<number | null>({ default: null });
const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control =
"flex h-11 w-full items-center gap-2 rounded-md border border-line bg-surface px-3 text-base transition-colors duration-150 ease-out has-[:disabled]:cursor-not-allowed has-[:disabled]:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[[aria-invalid=true]]:border-danger motion-reduce:transition-none";
const prefix = "shrink-0 font-medium text-muted select-none";
const field =
"h-full min-w-0 flex-1 bg-transparent font-medium text-ink tabular-nums outline-none placeholder:text-faint disabled:cursor-not-allowed disabled:text-muted";
const chips = "flex flex-wrap gap-2 pt-1";
const chip =
"inline-flex h-8 items-center rounded-full border border-line bg-surface px-3 text-sm font-medium text-ink tabular-nums transition-[background-color,border-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 aria-pressed:border-primary aria-pressed:bg-primary-soft motion-reduce:transition-none";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";
const COUNT_MS = 400;
const reducedMotion = () =>
typeof matchMedia === "function" &&
matchMedia("(prefers-reduced-motion: reduce)").matches;
const groupDigits = (digits: string, c: Currency) =>
digits.replace(/\B(?=(\d{3})+(?!\d))/g, c.group);
/** 12500000 -> "12.500.000". Decimals show only when they are not zero. */
function formatAmount(value: number, c: Currency) {
const [int = "0", frac = ""] = Math.abs(value).toFixed(c.fraction).split(".");
return groupDigits(int, c) + (/[1-9]/.test(frac) ? c.decimal + frac : "");
}
/** 50000 -> "50rb", 1500000 -> "1,5jt", 1000 USD -> "$1K". */
function shortAmount(value: number, c: Currency) {
const unit = c.units.find(([size]) => value >= size);
if (!unit) return c.short + formatAmount(value, c);
const scaled = String(Number((value / unit[0]).toFixed(1)));
return c.short + scaled.replace(".", c.decimal) + unit[1];
}
/** Typed text -> clean grouped text and its number (null when empty). */
function parseTyped(raw: string, c: Currency) {
const [head = "", ...tail] = c.fraction ? raw.split(c.decimal) : [raw];
const int = head.replace(/\D/g, "").replace(/^0+(?=\d)/, "");
const hasDecimal = tail.length > 0;
const frac = tail.join("").replace(/\D/g, "").slice(0, c.fraction);
if (!int && !hasDecimal) return { text: "", value: null };
const whole = int || "0";
return {
text: groupDigits(whole, c) + (hasDecimal ? c.decimal + frac : ""),
value: Number(`${whole}.${frac || "0"}`),
};
}
/** Digits (and the decimal mark) are what the caret position is counted in. */
const significant = (text: string, c: Currency) =>
[...text].filter(
(ch) => /\d/.test(ch) || (c.fraction > 0 && ch === c.decimal),
).length;
function caretAfter(text: string, count: number, c: Currency) {
let position = 0;
for (let seen = 0; position < text.length && seen < count; position++)
if (significant(text[position] ?? "", c)) seen++;
return position;
}
const c = computed(() => CURRENCIES[props.currency]);
const generatedId = useId();
const inputId = computed(() => props.id ?? generatedId);
const currencyId = computed(() => `${inputId.value}-currency`);
const describedBy = computed(() =>
[
currencyId.value,
props.error
? `${inputId.value}-error`
: props.hint
? `${inputId.value}-hint`
: undefined,
]
.filter(Boolean)
.join(" "),
);
const text = ref(
model.value === null ? "" : formatAmount(model.value, c.value),
);
let frame = 0;
let own: number | null = model.value;
onBeforeUnmount(() => cancelAnimationFrame(frame));
// Values set from outside (v-model) reformat the field; our own updates are skipped.
watch(model, (next) => {
if (next === own) return;
own = next;
cancelAnimationFrame(frame);
text.value = next === null ? "" : formatAmount(next, c.value);
});
const clamp = (n: number) =>
Math.min(Math.max(n, props.min ?? -Infinity), props.max ?? Infinity);
function commit(next: number | null) {
own = next;
model.value = next;
}
function onInput(event: Event) {
cancelAnimationFrame(frame);
const input = event.target as HTMLInputElement;
const count = significant(
input.value.slice(0, input.selectionStart ?? input.value.length),
c.value,
);
const parsed = parseTyped(input.value, c.value);
// Write the formatted text first so the caret can be placed before Vue re-renders.
input.value = parsed.text;
const position = caretAfter(parsed.text, count, c.value);
input.setSelectionRange(position, position);
text.value = parsed.text;
commit(parsed.value);
}
/** Backspace or Delete next to a separator removes the digit behind it instead. */
function onKeydown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
const at = input.selectionStart;
if (at === null || at !== input.selectionEnd) return;
if (event.key === "Backspace" && input.value[at - 1] === c.value.group)
input.setSelectionRange(at - 1, at - 1);
if (event.key === "Delete" && input.value[at] === c.value.group)
input.setSelectionRange(at + 1, at + 1);
}
function onBlur() {
if (model.value === null) return;
const next = clamp(model.value);
text.value = formatAmount(next, c.value);
if (next !== model.value) commit(next);
}
/** Jump to a preset, counting the digits up or down on the way. */
function pick(preset: number) {
const target = clamp(preset);
const from = model.value ?? 0;
commit(target);
cancelAnimationFrame(frame);
if (reducedMotion() || typeof requestAnimationFrame !== "function") {
text.value = formatAmount(target, c.value);
return;
}
let start: number | undefined;
const tick = (now: number) => {
start ??= now;
const t = Math.min((now - start) / COUNT_MS, 1);
const eased = 1 - (1 - t) ** 3;
const step = 10 ** c.value.fraction;
text.value = formatAmount(
Math.round((from + (target - from) * eased) * step) / step,
c.value,
);
if (t < 1) frame = requestAnimationFrame(tick);
};
frame = requestAnimationFrame(tick);
}
</script>
<template>
<div :class="wrapper">
<label v-if="props.label" :for="inputId" :class="labelClass">{{
props.label
}}</label>
<div :class="control">
<span :id="currencyId" :class="prefix">{{ c.symbol }}</span>
<input
:id="inputId"
type="text"
:inputmode="c.fraction ? 'decimal' : 'numeric'"
autocomplete="off"
:value="text"
:disabled="props.disabled"
:aria-invalid="props.error ? 'true' : undefined"
:aria-describedby="describedBy"
:class="field"
v-bind="$attrs"
@input="onInput"
@keydown="onKeydown"
@blur="onBlur"
/>
</div>
<input
v-if="props.name"
type="hidden"
:name="props.name"
:value="model ?? ''"
/>
<p v-if="props.error" :id="`${inputId}-error`" :class="errorClass">
{{ props.error }}
</p>
<p v-else-if="props.hint" :id="`${inputId}-hint`" :class="hintClass">
{{ props.hint }}
</p>
<div
v-if="props.presets.length > 0"
role="group"
:aria-label="props.presetsLabel"
:class="chips"
>
<button
v-for="preset in props.presets"
:key="preset"
type="button"
:aria-pressed="model === preset ? 'true' : 'false'"
:disabled="props.disabled"
:class="chip"
@click="pick(preset)"
>
{{ shortAmount(preset, c) }}
</button>
</div>
</div>
</template>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/lib/components/markas/CurrencyInput.svelte.
<script lang="ts" module>
/** Separators and short units per currency. IDR follows id-ID, USD follows en-US. */
const CURRENCIES = {
IDR: {
symbol: "Rp",
group: ".",
decimal: ",",
fraction: 0,
short: "",
units: [
[1e6, "jt"],
[1e3, "rb"],
],
},
USD: {
symbol: "$",
group: ",",
decimal: ".",
fraction: 2,
short: "$",
units: [
[1e6, "M"],
[1e3, "K"],
],
},
} as const;
type Currency = (typeof CURRENCIES)[keyof typeof CURRENCIES];
export type CurrencyCode = keyof typeof CURRENCIES;
const groupDigits = (digits: string, c: Currency) =>
digits.replace(/\B(?=(\d{3})+(?!\d))/g, c.group);
/** 12500000 -> "12.500.000". Decimals show only when they are not zero. */
function formatAmount(value: number, c: Currency) {
const [int = "0", frac = ""] = Math.abs(value)
.toFixed(c.fraction)
.split(".");
return groupDigits(int, c) + (/[1-9]/.test(frac) ? c.decimal + frac : "");
}
/** 50000 -> "50rb", 1500000 -> "1,5jt", 1000 USD -> "$1K". */
function shortAmount(value: number, c: Currency) {
const unit = c.units.find(([size]) => value >= size);
if (!unit) return c.short + formatAmount(value, c);
const scaled = String(Number((value / unit[0]).toFixed(1)));
return c.short + scaled.replace(".", c.decimal) + unit[1];
}
/** Typed text -> clean grouped text and its number (null when empty). */
function parseTyped(raw: string, c: Currency) {
const [head = "", ...tail] = c.fraction ? raw.split(c.decimal) : [raw];
const int = head.replace(/\D/g, "").replace(/^0+(?=\d)/, "");
const hasDecimal = tail.length > 0;
const frac = tail.join("").replace(/\D/g, "").slice(0, c.fraction);
if (!int && !hasDecimal) return { text: "", value: null };
const whole = int || "0";
return {
text: groupDigits(whole, c) + (hasDecimal ? c.decimal + frac : ""),
value: Number(`${whole}.${frac || "0"}`),
};
}
/** Digits (and the decimal mark) are what the caret position is counted in. */
const significant = (text: string, c: Currency) =>
[...text].filter(
(ch) => /\d/.test(ch) || (c.fraction > 0 && ch === c.decimal),
).length;
function caretAfter(text: string, count: number, c: Currency) {
let position = 0;
for (let seen = 0; position < text.length && seen < count; position++)
if (significant(text[position] ?? "", c)) seen++;
return position;
}
</script>
<script lang="ts">
import { onDestroy, untrack } from "svelte";
import type { HTMLInputAttributes } from "svelte/elements";
const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control =
"flex h-11 w-full items-center gap-2 rounded-md border border-line bg-surface px-3 text-base transition-colors duration-150 ease-out has-[:disabled]:cursor-not-allowed has-[:disabled]:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[[aria-invalid=true]]:border-danger motion-reduce:transition-none";
const prefix = "shrink-0 font-medium text-muted select-none";
const field =
"h-full min-w-0 flex-1 bg-transparent font-medium text-ink tabular-nums outline-none placeholder:text-faint disabled:cursor-not-allowed disabled:text-muted";
const chips = "flex flex-wrap gap-2 pt-1";
const chip =
"inline-flex h-8 items-center rounded-full border border-line bg-surface px-3 text-sm font-medium text-ink tabular-nums transition-[background-color,border-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 aria-pressed:border-primary aria-pressed:bg-primary-soft motion-reduce:transition-none";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";
const COUNT_MS = 400;
const reducedMotion = () =>
typeof matchMedia === "function" &&
matchMedia("(prefers-reduced-motion: reduce)").matches;
type Props = Omit<
HTMLInputAttributes,
"type" | "value" | "min" | "max" | "children"
> & {
label?: string;
hint?: string;
error?: string;
currency?: CurrencyCode;
min?: number;
max?: number;
/** Amount, bindable with bind:value. */
value?: number | null;
defaultValue?: number | null;
/** Quick amount chips below the field. */
presets?: number[];
presetsLabel?: string;
onValueChange?: (value: number | null) => void;
};
let {
label,
hint,
error,
currency = "IDR",
min,
max,
value = $bindable(),
defaultValue = null,
presets = [],
presetsLabel = "Quick amounts",
onValueChange,
name,
id,
disabled,
class: className,
onkeydown,
onblur,
...rest
}: Props = $props();
const c = $derived(CURRENCIES[currency]);
const generatedId = $props.id();
const inputId = $derived(id ?? generatedId);
const currencyId = $derived(`${inputId}-currency`);
const messageId = $derived(
error ? `${inputId}-error` : hint ? `${inputId}-hint` : undefined,
);
let current = $state<number | null>(
untrack(() => value ?? defaultValue ?? null),
);
let text = $state(
untrack(() => (current === null ? "" : formatAmount(current, c))),
);
let frame = 0;
// onDestroy juga berjalan saat render server, tempat cancelAnimationFrame tidak ada.
onDestroy(() => {
if (frame) cancelAnimationFrame(frame);
});
// Values set from outside (bind:value) reformat the field; our own updates are skipped.
$effect.pre(() => {
const next = value;
if (next === undefined || next === untrack(() => current)) return;
cancelAnimationFrame(frame);
current = next;
text =
next === null
? ""
: formatAmount(
next,
untrack(() => c),
);
});
const clamp = (n: number) =>
Math.min(Math.max(n, min ?? -Infinity), max ?? Infinity);
function commit(next: number | null) {
current = next;
value = next;
onValueChange?.(next);
}
function handleInput(event: Event & { currentTarget: HTMLInputElement }) {
cancelAnimationFrame(frame);
const input = event.currentTarget;
const count = significant(
input.value.slice(0, input.selectionStart ?? input.value.length),
c,
);
const parsed = parseTyped(input.value, c);
// Write the formatted text first so the caret can be placed before Svelte updates.
input.value = parsed.text;
const position = caretAfter(parsed.text, count, c);
input.setSelectionRange(position, position);
text = parsed.text;
commit(parsed.value);
}
/** Backspace or Delete next to a separator removes the digit behind it instead. */
function handleKeydown(
event: KeyboardEvent & { currentTarget: HTMLInputElement },
) {
onkeydown?.(event);
const input = event.currentTarget;
const at = input.selectionStart;
if (at === null || at !== input.selectionEnd) return;
if (event.key === "Backspace" && input.value[at - 1] === c.group)
input.setSelectionRange(at - 1, at - 1);
if (event.key === "Delete" && input.value[at] === c.group)
input.setSelectionRange(at + 1, at + 1);
}
function handleBlur(event: FocusEvent & { currentTarget: HTMLInputElement }) {
onblur?.(event);
if (current === null) return;
const next = clamp(current);
text = formatAmount(next, c);
if (next !== current) commit(next);
}
/** Jump to a preset, counting the digits up or down on the way. */
function pick(preset: number) {
const target = clamp(preset);
const from = current ?? 0;
commit(target);
cancelAnimationFrame(frame);
if (reducedMotion() || typeof requestAnimationFrame !== "function") {
text = formatAmount(target, c);
return;
}
let start: number | undefined;
const tick = (now: number) => {
start ??= now;
const t = Math.min((now - start) / COUNT_MS, 1);
const eased = 1 - (1 - t) ** 3;
const step = 10 ** c.fraction;
text = formatAmount(
Math.round((from + (target - from) * eased) * step) / step,
c,
);
if (t < 1) frame = requestAnimationFrame(tick);
};
frame = requestAnimationFrame(tick);
}
</script>
<div class={wrapper}>
{#if label}
<label for={inputId} class={labelClass}>{label}</label>
{/if}
<div class={control}>
<span id={currencyId} class={prefix}>{c.symbol}</span>
<input
id={inputId}
type="text"
inputmode={c.fraction ? "decimal" : "numeric"}
autocomplete="off"
value={text}
{disabled}
aria-invalid={error ? true : undefined}
aria-describedby={[currencyId, messageId].filter(Boolean).join(" ")}
class={[field, className]}
{...rest}
oninput={handleInput}
onkeydown={handleKeydown}
onblur={handleBlur}
/>
</div>
{#if name}
<input type="hidden" {name} value={current ?? ""} />
{/if}
{#if error}
<p id={`${inputId}-error`} class={errorClass}>{error}</p>
{:else if hint}
<p id={`${inputId}-hint`} class={hintClass}>{hint}</p>
{/if}
{#if presets.length > 0}
<div role="group" aria-label={presetsLabel} class={chips}>
{#each presets as preset (preset)}
<button
type="button"
aria-pressed={current === preset}
{disabled}
class={chip}
onclick={() => pick(preset)}>{shortAmount(preset, c)}</button
>
{/each}
</div>
{/if}
</div>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/components/markas/CurrencyInput.astro.
---
import type { HTMLAttributes } from "astro/types";
const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control =
"flex h-11 w-full items-center gap-2 rounded-md border border-line bg-surface px-3 text-base transition-colors duration-150 ease-out has-[:disabled]:cursor-not-allowed has-[:disabled]:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[[aria-invalid=true]]:border-danger motion-reduce:transition-none";
const prefix = "shrink-0 font-medium text-muted select-none";
const field =
"h-full min-w-0 flex-1 bg-transparent font-medium text-ink tabular-nums outline-none placeholder:text-faint disabled:cursor-not-allowed disabled:text-muted";
const chips = "flex flex-wrap gap-2 pt-1";
const chip =
"inline-flex h-8 items-center rounded-full border border-line bg-surface px-3 text-sm font-medium text-ink tabular-nums transition-[background-color,border-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 aria-pressed:border-primary aria-pressed:bg-primary-soft motion-reduce:transition-none";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";
/** Separators and short units per currency. IDR follows id-ID, USD follows en-US. */
const CURRENCIES = {
IDR: {
symbol: "Rp",
group: ".",
decimal: ",",
fraction: 0,
short: "",
units: [
[1e6, "jt"],
[1e3, "rb"],
],
},
USD: {
symbol: "$",
group: ",",
decimal: ".",
fraction: 2,
short: "$",
units: [
[1e6, "M"],
[1e3, "K"],
],
},
} as const;
type Currency = (typeof CURRENCIES)[keyof typeof CURRENCIES];
const groupDigits = (digits: string, c: Currency) =>
digits.replace(/\B(?=(\d{3})+(?!\d))/g, c.group);
/** 12500000 -> "12.500.000". Decimals show only when they are not zero. */
function formatAmount(value: number, c: Currency) {
const [int = "0", frac = ""] = Math.abs(value).toFixed(c.fraction).split(".");
return groupDigits(int, c) + (/[1-9]/.test(frac) ? c.decimal + frac : "");
}
/** 50000 -> "50rb", 1500000 -> "1,5jt", 1000 USD -> "$1K". */
function shortAmount(value: number, c: Currency) {
const unit = c.units.find(([size]) => value >= size);
if (!unit) return c.short + formatAmount(value, c);
const scaled = String(Number((value / unit[0]).toFixed(1)));
return c.short + scaled.replace(".", c.decimal) + unit[1];
}
type Props = Omit<HTMLAttributes<"input">, "type" | "value" | "min" | "max"> & {
label?: string;
hint?: string;
error?: string;
currency?: keyof typeof CURRENCIES;
min?: number;
max?: number;
defaultValue?: number | null;
/** Quick amount chips below the field. */
presets?: number[];
presetsLabel?: string;
};
const {
label,
hint,
error,
currency = "IDR",
min,
max,
defaultValue = null,
presets = [],
presetsLabel = "Quick amounts",
name,
id,
disabled,
class: className,
...rest
} = Astro.props;
const c = CURRENCIES[currency];
const inputId = id ?? `markas-currency-input-${crypto.randomUUID().slice(0, 8)}`;
const currencyId = `${inputId}-currency`;
const messageId = error ? `${inputId}-error` : hint ? `${inputId}-hint` : undefined;
---
<markas-currency-input
class="contents"
data-currency={currency}
data-min={min}
data-max={max}
data-value={defaultValue ?? ""}
>
<div class={wrapper}>
{label && <label for={inputId} class={labelClass}>{label}</label>}
<div class={control}>
<span id={currencyId} class={prefix}>{c.symbol}</span>
<input
id={inputId}
type="text"
inputmode={c.fraction ? "decimal" : "numeric"}
autocomplete="off"
value={defaultValue === null ? "" : formatAmount(defaultValue, c)}
disabled={disabled}
aria-invalid={error ? "true" : undefined}
aria-describedby={[currencyId, messageId].filter(Boolean).join(" ")}
class:list={[field, className]}
data-field
{...rest}
/>
</div>
{name && <input type="hidden" name={name} value={defaultValue ?? ""} data-hidden />}
{
error ? (
<p id={`${inputId}-error`} class={errorClass}>{error}</p>
) : hint ? (
<p id={`${inputId}-hint`} class={hintClass}>{hint}</p>
) : null
}
{
presets.length > 0 && (
<div role="group" aria-label={presetsLabel} class={chips}>
{presets.map((preset) => (
<button
type="button"
aria-pressed={defaultValue === preset ? "true" : "false"}
disabled={disabled}
data-preset={preset}
class={chip}
>
{shortAmount(preset, c)}
</button>
))}
</div>
)
}
</div>
</markas-currency-input>
<script>
// Separators per currency, as in the markup above: IDR follows id-ID, USD follows en-US.
const CURRENCIES = {
IDR: { group: ".", decimal: ",", fraction: 0 },
USD: { group: ",", decimal: ".", fraction: 2 },
} as const;
type Currency = (typeof CURRENCIES)[keyof typeof CURRENCIES];
const groupDigits = (digits: string, c: Currency) =>
digits.replace(/\B(?=(\d{3})+(?!\d))/g, c.group);
function formatAmount(value: number, c: Currency) {
const [int = "0", frac = ""] = Math.abs(value)
.toFixed(c.fraction)
.split(".");
return groupDigits(int, c) + (/[1-9]/.test(frac) ? c.decimal + frac : "");
}
/** Typed text -> clean grouped text and its number (null when empty). */
function parseTyped(raw: string, c: Currency) {
const [head = "", ...tail] = c.fraction ? raw.split(c.decimal) : [raw];
const int = head.replace(/\D/g, "").replace(/^0+(?=\d)/, "");
const hasDecimal = tail.length > 0;
const frac = tail.join("").replace(/\D/g, "").slice(0, c.fraction);
if (!int && !hasDecimal) return { text: "", value: null };
const whole = int || "0";
return {
text: groupDigits(whole, c) + (hasDecimal ? c.decimal + frac : ""),
value: Number(`${whole}.${frac || "0"}`),
};
}
/** Digits (and the decimal mark) are what the caret position is counted in. */
const significant = (text: string, c: Currency) =>
[...text].filter(
(ch) => /\d/.test(ch) || (c.fraction > 0 && ch === c.decimal),
).length;
function caretAfter(text: string, count: number, c: Currency) {
let position = 0;
for (let seen = 0; position < text.length && seen < count; position++)
if (significant(text[position] ?? "", c)) seen++;
return position;
}
const COUNT_MS = 400;
// Each field keeps its own amount, so it is a custom element: it also works for markup
// added later and for pages reached through view transitions.
class MarkasCurrencyInput extends HTMLElement {
private frame = 0;
private ready = false;
connectedCallback() {
const input = this.querySelector<HTMLInputElement>("[data-field]");
if (this.ready || !input) return;
this.ready = true;
const c = CURRENCIES[this.dataset.currency as keyof typeof CURRENCIES];
input.addEventListener("input", () => {
cancelAnimationFrame(this.frame);
const count = significant(
input.value.slice(0, input.selectionStart ?? input.value.length),
c,
);
const parsed = parseTyped(input.value, c);
input.value = parsed.text;
const position = caretAfter(parsed.text, count, c);
input.setSelectionRange(position, position);
this.commit(parsed.value);
});
// Backspace or Delete next to a separator removes the digit behind it instead.
input.addEventListener("keydown", (event) => {
const at = input.selectionStart;
if (at === null || at !== input.selectionEnd) return;
if (event.key === "Backspace" && input.value[at - 1] === c.group)
input.setSelectionRange(at - 1, at - 1);
if (event.key === "Delete" && input.value[at] === c.group)
input.setSelectionRange(at + 1, at + 1);
});
input.addEventListener("blur", () => {
const value = this.value;
if (value === null) return;
const next = this.clamp(value);
input.value = formatAmount(next, c);
if (next !== value) this.commit(next);
});
this.addEventListener("click", (event) => {
const chip = (event.target as Element).closest<HTMLElement>(
"[data-preset]",
);
if (chip) this.pick(input, Number(chip.dataset.preset), c);
});
}
disconnectedCallback() {
cancelAnimationFrame(this.frame);
}
private get value() {
return this.dataset.value ? Number(this.dataset.value) : null;
}
private clamp(n: number) {
const min = this.dataset.min ? Number(this.dataset.min) : -Infinity;
const max = this.dataset.max ? Number(this.dataset.max) : Infinity;
return Math.min(Math.max(n, min), max);
}
private commit(next: number | null) {
this.dataset.value = next === null ? "" : String(next);
const hidden = this.querySelector<HTMLInputElement>("[data-hidden]");
if (hidden) hidden.value = this.dataset.value;
this.querySelectorAll("[data-preset]").forEach((chip) =>
chip.setAttribute(
"aria-pressed",
String(Number(chip.getAttribute("data-preset")) === next),
),
);
this.dispatchEvent(
new CustomEvent("markas-change", { detail: next, bubbles: true }),
);
}
/** Jump to a preset, counting the digits up or down on the way. */
private pick(
input: HTMLInputElement,
preset: number,
c: Currency,
) {
const target = this.clamp(preset);
const from = this.value ?? 0;
this.commit(target);
cancelAnimationFrame(this.frame);
if (matchMedia("(prefers-reduced-motion: reduce)").matches) {
input.value = formatAmount(target, c);
return;
}
let start: number | undefined;
const tick = (now: number) => {
start ??= now;
const t = Math.min((now - start) / COUNT_MS, 1);
const eased = 1 - (1 - t) ** 3;
const step = 10 ** c.fraction;
input.value = formatAmount(
Math.round((from + (target - from) * eased) * step) / step,
c,
);
if (t < 1) this.frame = requestAnimationFrame(tick);
};
this.frame = requestAnimationFrame(tick);
}
}
if (!customElements.get("markas-currency-input"))
customElements.define("markas-currency-input", MarkasCurrencyInput);
</script>- Make sure Tailwind CSS v4 and markas.css are installed. See Installation.
- Copy the component source below to
src/app/markas/currency-input.component.ts.
import {
booleanAttribute,
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
effect,
inject,
input,
model,
signal,
untracked,
} from "@angular/core";
const wrapper = "grid gap-1.5";
const labelClass = "text-sm font-medium text-ink";
const control =
"flex h-11 w-full items-center gap-2 rounded-md border border-line bg-surface px-3 text-base transition-colors duration-150 ease-out has-[:disabled]:cursor-not-allowed has-[:disabled]:bg-subtle has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary has-[[aria-invalid=true]]:border-danger motion-reduce:transition-none";
const prefix = "shrink-0 font-medium text-muted select-none";
const field =
"h-full min-w-0 flex-1 bg-transparent font-medium text-ink tabular-nums outline-none placeholder:text-faint disabled:cursor-not-allowed disabled:text-muted";
const chips = "flex flex-wrap gap-2 pt-1";
const chip =
"inline-flex h-8 items-center rounded-full border border-line bg-surface px-3 text-sm font-medium text-ink tabular-nums transition-[background-color,border-color,scale] duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-95 disabled:pointer-events-none disabled:opacity-50 aria-pressed:border-primary aria-pressed:bg-primary-soft motion-reduce:transition-none";
const hintClass = "text-sm text-muted";
const errorClass = "text-sm text-danger";
/** Separators and short units per currency. IDR follows id-ID, USD follows en-US. */
const CURRENCIES = {
IDR: {
symbol: "Rp",
group: ".",
decimal: ",",
fraction: 0,
short: "",
units: [
[1e6, "jt"],
[1e3, "rb"],
],
},
USD: {
symbol: "$",
group: ",",
decimal: ".",
fraction: 2,
short: "$",
units: [
[1e6, "M"],
[1e3, "K"],
],
},
} as const;
type Currency = (typeof CURRENCIES)[keyof typeof CURRENCIES];
export type CurrencyCode = keyof typeof CURRENCIES;
const COUNT_MS = 400;
const reducedMotion = () =>
typeof matchMedia === "function" &&
matchMedia("(prefers-reduced-motion: reduce)").matches;
const groupDigits = (digits: string, c: Currency) =>
digits.replace(/\B(?=(\d{3})+(?!\d))/g, c.group);
/** 12500000 -> "12.500.000". Decimals show only when they are not zero. */
function formatAmount(value: number, c: Currency) {
const [int = "0", frac = ""] = Math.abs(value).toFixed(c.fraction).split(".");
return groupDigits(int, c) + (/[1-9]/.test(frac) ? c.decimal + frac : "");
}
/** 50000 -> "50rb", 1500000 -> "1,5jt", 1000 USD -> "$1K". */
function shortAmount(value: number, c: Currency) {
const unit = c.units.find(([size]) => value >= size);
if (!unit) return c.short + formatAmount(value, c);
const scaled = String(Number((value / unit[0]).toFixed(1)));
return c.short + scaled.replace(".", c.decimal) + unit[1];
}
/** Typed text -> clean grouped text and its number (null when empty). */
function parseTyped(raw: string, c: Currency) {
const [head = "", ...tail] = c.fraction ? raw.split(c.decimal) : [raw];
const int = head.replace(/\D/g, "").replace(/^0+(?=\d)/, "");
const hasDecimal = tail.length > 0;
const frac = tail.join("").replace(/\D/g, "").slice(0, c.fraction);
if (!int && !hasDecimal) return { text: "", value: null };
const whole = int || "0";
return {
text: groupDigits(whole, c) + (hasDecimal ? c.decimal + frac : ""),
value: Number(`${whole}.${frac || "0"}`),
};
}
/** Digits (and the decimal mark) are what the caret position is counted in. */
const significant = (text: string, c: Currency) =>
[...text].filter(
(ch) => /\d/.test(ch) || (c.fraction > 0 && ch === c.decimal),
).length;
function caretAfter(text: string, count: number, c: Currency) {
let position = 0;
for (let seen = 0; position < text.length && seen < count; position++)
if (significant(text[position] ?? "", c)) seen++;
return position;
}
let nextId = 0;
/**
* Host stays out of layout; id, name, placeholder, aria-label, and class move to the field.
* `[(value)]` binds the amount (a number, or null when empty).
*/
@Component({
selector: "markas-currency-input",
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: "contents",
"[attr.id]": "null",
"[attr.name]": "null",
"[attr.placeholder]": "null",
"[attr.aria-label]": "null",
},
template: `
<div [class]="wrapper">
@if (label()) {
<label [for]="inputId()" [class]="labelClass">{{ label() }}</label>
}
<div [class]="control">
<span [id]="currencyId()" [class]="prefix">{{ c().symbol }}</span>
<input
[id]="inputId()"
type="text"
[attr.inputmode]="c().fraction ? 'decimal' : 'numeric'"
autocomplete="off"
[value]="text()"
[disabled]="disabled()"
[attr.placeholder]="placeholder() ?? null"
[attr.aria-label]="ariaLabel() ?? null"
[attr.aria-invalid]="error() ? 'true' : null"
[attr.aria-describedby]="describedBy()"
[class]="fieldClasses()"
(input)="handleInput($event)"
(keydown)="handleKeydown($event)"
(blur)="handleBlur()"
/>
</div>
@if (name()) {
<input type="hidden" [name]="name()" [value]="current() ?? ''" />
}
@if (error()) {
<p [id]="inputId() + '-error'" [class]="errorClass">{{ error() }}</p>
} @else if (hint()) {
<p [id]="inputId() + '-hint'" [class]="hintClass">{{ hint() }}</p>
}
@if (presets().length > 0) {
<div role="group" [attr.aria-label]="presetsLabel()" [class]="chips">
@for (preset of presets(); track preset) {
<button
type="button"
[attr.aria-pressed]="current() === preset"
[disabled]="disabled()"
[class]="chip"
(click)="pick(preset)"
>
{{ short(preset) }}
</button>
}
</div>
}
</div>
`,
})
export class CurrencyInput {
readonly label = input<string>();
readonly hint = input<string>();
readonly error = input<string>();
readonly currency = input<CurrencyCode>("IDR");
readonly min = input<number>();
readonly max = input<number>();
readonly defaultValue = input<number | null>(null);
/** Amount. Emits valueChange on every change, so `[(value)]` works. */
readonly value = model<number | null | undefined>(undefined);
/** Quick amount chips below the field. */
readonly presets = input<number[]>([]);
readonly presetsLabel = input("Quick amounts");
readonly name = input<string>();
readonly placeholder = input<string>();
readonly ariaLabel = input<string | undefined>(undefined, {
alias: "aria-label",
});
readonly disabled = input(false, { transform: booleanAttribute });
readonly id = input<string>();
readonly userClass = input("", { alias: "class" });
protected readonly wrapper = wrapper;
protected readonly labelClass = labelClass;
protected readonly control = control;
protected readonly prefix = prefix;
protected readonly chips = chips;
protected readonly chip = chip;
protected readonly hintClass = hintClass;
protected readonly errorClass = errorClass;
protected readonly c = computed(() => CURRENCIES[this.currency()]);
private readonly generatedId = `markas-currency-input-${nextId++}`;
protected readonly inputId = computed(() => this.id() ?? this.generatedId);
protected readonly currencyId = computed(() => `${this.inputId()}-currency`);
protected readonly describedBy = computed(() => {
const message = this.error()
? `${this.inputId()}-error`
: this.hint()
? `${this.inputId()}-hint`
: "";
return [this.currencyId(), message].filter(Boolean).join(" ");
});
protected readonly fieldClasses = computed(() =>
[field, this.userClass()].filter(Boolean).join(" "),
);
protected readonly current = signal<number | null>(null);
protected readonly text = signal("");
private frame = 0;
constructor() {
// The first value (value, else defaultValue) and later values set from outside reformat
// the field; our own updates are skipped.
let started = false;
effect(() => {
const outside = this.value();
const next = started ? outside : (outside ?? this.defaultValue());
if (next === undefined || next === untracked(this.current)) {
started = true;
return;
}
started = true;
cancelAnimationFrame(this.frame);
this.current.set(next);
this.text.set(next === null ? "" : formatAmount(next, this.c()));
});
inject(DestroyRef).onDestroy(() => cancelAnimationFrame(this.frame));
}
protected short(preset: number) {
return shortAmount(preset, this.c());
}
private clamp(n: number) {
return Math.min(
Math.max(n, this.min() ?? -Infinity),
this.max() ?? Infinity,
);
}
private commit(next: number | null) {
this.current.set(next);
this.value.set(next);
}
protected handleInput(event: Event) {
cancelAnimationFrame(this.frame);
const c = this.c();
const field = event.target as HTMLInputElement;
const count = significant(
field.value.slice(0, field.selectionStart ?? field.value.length),
c,
);
const parsed = parseTyped(field.value, c);
// Write the formatted text first so the caret can be placed before Angular renders.
field.value = parsed.text;
const position = caretAfter(parsed.text, count, c);
field.setSelectionRange(position, position);
this.text.set(parsed.text);
this.commit(parsed.value);
}
/** Backspace or Delete next to a separator removes the digit behind it instead. */
protected handleKeydown(event: KeyboardEvent) {
const field = event.target as HTMLInputElement;
const group = this.c().group;
const at = field.selectionStart;
if (at === null || at !== field.selectionEnd) return;
if (event.key === "Backspace" && field.value[at - 1] === group)
field.setSelectionRange(at - 1, at - 1);
if (event.key === "Delete" && field.value[at] === group)
field.setSelectionRange(at + 1, at + 1);
}
protected handleBlur() {
const value = this.current();
if (value === null) return;
const next = this.clamp(value);
this.text.set(formatAmount(next, this.c()));
if (next !== value) this.commit(next);
}
/** Jump to a preset, counting the digits up or down on the way. */
protected pick(preset: number) {
const c = this.c();
const target = this.clamp(preset);
const from = this.current() ?? 0;
this.commit(target);
cancelAnimationFrame(this.frame);
if (reducedMotion() || typeof requestAnimationFrame !== "function") {
this.text.set(formatAmount(target, c));
return;
}
let start: number | undefined;
const tick = (now: number) => {
start ??= now;
const t = Math.min((now - start) / COUNT_MS, 1);
const eased = 1 - (1 - t) ** 3;
const step = 10 ** c.fraction;
this.text.set(
formatAmount(
Math.round((from + (target - from) * eased) * step) / step,
c,
),
);
if (t < 1) this.frame = requestAnimationFrame(tick);
};
this.frame = requestAnimationFrame(tick);
}
}Usage
<x-markas.currency-input
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000"
:min="10000"
:value="old('amount', 100000)"
:presets="[50000, 100000, 250000, 500000]"
/>Needs Alpine.js. The form receives amount=100000, a plain number without separators.
Livewire
<x-markas.currency-input label="Amount" wire:model.live.debounce.400ms="amount" :presets="[50000, 100000]" />wire:model binds the plain number (for example 12500000), not the formatted text. Server changes reformat the field. Preset chips update the property as well.
import { CurrencyInput } from "@/components/markas/CurrencyInput";
<CurrencyInput
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000"
min={10000}
defaultValue={100000}
presets={[50000, 100000, 250000, 500000]}
onValueChange={setAmount}
/>;<script setup lang="ts">
import { ref } from "vue";
import CurrencyInput from "@/components/markas/CurrencyInput.vue";
const amount = ref<number | null>(100000);
</script>
<template>
<CurrencyInput
v-model="amount"
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000"
:min="10000"
:presets="[50000, 100000, 250000, 500000]"
/>
</template><script lang="ts">
import CurrencyInput from "$lib/components/markas/CurrencyInput.svelte";
let amount = $state<number | null>(100000);
</script>
<CurrencyInput
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000"
min={10000}
bind:value={amount}
presets={[50000, 100000, 250000, 500000]}
/>---
import CurrencyInput from "@/components/markas/CurrencyInput.astro";
---
<CurrencyInput
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000"
min={10000}
defaultValue={100000}
presets={[50000, 100000, 250000, 500000]}
/>A small custom element formats while typing and fills the hidden input. It dispatches a bubbling markas-change event with the amount (or null) as detail.
import { Component, signal } from "@angular/core";
import { CurrencyInput } from "./markas/currency-input.component";
@Component({
selector: "app-top-up",
imports: [CurrencyInput],
template: `
<markas-currency-input
label="Top-up amount"
name="amount"
hint="Minimum Rp10.000"
[min]="10000"
[(value)]="amount"
[presets]="presets"
/>
`,
})
export class TopUp {
amount = signal<number | null>(100000);
presets = [50000, 100000, 250000, 500000];
}id, name, placeholder, aria-label, and class land on the visible field.
- IDR is the default:
Rpprefix, dot thousands (12.500.000), no decimals.currency="USD"switches to$, comma thousands, and up to two decimals (1,250.50). - Separators are added while typing and the caret stays next to the digit you typed. Backspace or Delete beside a separator removes the neighbouring digit.
- The visible field has no
name. Passnameto render a hidden input with the plain number, ready for a regular form post. minandmaxclamp the amount on blur and when a chip is picked. Validate on the server too.- Chips count the digits to the new amount in 400ms. With reduced motion the amount changes instantly.
- Attributes and
classgo to the visible field.
Props
| Name | Type | Default | Description |
|---|---|---|---|
label | string | - | Label text, linked to the field through for and id. |
hint | string | - | Hint below the field. Hidden while an error is shown. |
error | string | - | Error message. Turns on aria-invalid and the danger border. |
currency | 'IDR' | 'USD' | IDR | IDR shows Rp with dot thousands and no decimals. USD shows $ with comma thousands and up to two decimals. |
min | number | - | Lowest value. The amount is clamped on blur and when a chip is picked. |
max | number | - | Highest value. The amount is clamped on blur and when a chip is picked. |
value / defaultValue / v-model | number | null | null | Starting amount. Blade uses value, React uses defaultValue with onValueChange, Vue uses v-model. |
name | string | - | Name of a hidden input that submits the plain number, for example 12500000. The visible field has no name. |
presets | number[] | [] | Quick amount chips shown below the field, labelled short (50rb, 1jt, $1K). Picking one counts the digits to the new amount. |
presetsLabel | string | Quick amounts | Accessible name of the chip group. |
id | string | auto | Id of the visible field. Generated automatically when empty. |
bind:value / [(value)] | number | null | - | Svelte and Angular. Two-way binding of the amount. Svelte also takes onValueChange; Angular emits valueChange. |
markas-change | CustomEvent<number | null> | - | Astro only. Bubbling event with the new amount as detail. |
Accessibility
- The label is linked to the field, and the currency symbol, hint, and error are read through aria-describedby.
- The field uses inputmode numeric or decimal so phones show a number keypad.
- Chips are toggle buttons in a labelled group; the chip that matches the amount has aria-pressed true.
- With reduced motion picking a chip sets the amount instantly instead of counting.
Related components
More markasui components with the same classes in every framework.
- Bottom NavigationMobile app style bottom bar. A pill glides to the selected item, its label rises in, and the bar can shrink to icons while content scrolls.
- Card StackLayered stack of cards. Swipe, arrow keys, or buttons throw the top card away and the next one rises. Loops, with a position indicator.
- Chat MessageMessage in an AI conversation. User bubbles on the right, assistant replies with an avatar, hover actions, a typing indicator, and optional token streaming.
- DockmacOS style dock. Icons grow smoothly toward the pointer or focus, show a label above, mark open items with a dot, and bounce on launch.
- Drag ElementsArea of cards or stickers you can drag around with light momentum, kept inside its bounds. Arrow keys move a focused item, Escape puts it back.
- Dynamic IslandBlack pill inspired by the iPhone Dynamic Island. It morphs smoothly between idle, compact, and expanded states while its content crossfades.