Currency Input
Kolom uang yang memformat saat mengetik (Rp 12.500.000), menjaga posisi kursor, dan mengirim angka murni. Opsional chip nominal cepat.
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];
}Contoh
Dolar AS
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];
}Status
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";
}Donasi dengan nominal saran
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];
}Instalasi
npx markasui@latest add currency-inputpnpm dlx markasui@latest add currency-inputyarn dlx markasui@latest add currency-inputbunx --bun markasui@latest add currency-input- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Pasang dependensi:
npm install alpinejs - Salin source komponen di bawah ini ke
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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
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>
);
}- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
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>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
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);
}
}Pemakaian
<x-markas.currency-input
label="Nominal top-up"
name="amount"
hint="Minimum Rp10.000"
presets-label="Nominal cepat"
:min="10000"
:value="old('amount', 100000)"
:presets="[50000, 100000, 250000, 500000]"
/>Butuh Alpine.js. Form menerima amount=100000, angka murni tanpa pemisah.
Livewire
<x-markas.currency-input label="Amount" wire:model.live.debounce.400ms="amount" :presets="[50000, 100000]" />wire:model terhubung ke angka polos (misalnya 12500000), bukan teks berformat. Perubahan dari server memformat ulang field. Chip preset juga memperbarui properti.
import { CurrencyInput } from "@/components/markas/CurrencyInput";
<CurrencyInput
label="Nominal top-up"
name="amount"
hint="Minimum Rp10.000"
presetsLabel="Nominal cepat"
min={10000}
defaultValue={100000}
presets={[50000, 100000, 250000, 500000]}
onValueChange={setNominal}
/>;<script setup lang="ts">
import { ref } from "vue";
import CurrencyInput from "@/components/markas/CurrencyInput.vue";
const nominal = ref<number | null>(100000);
</script>
<template>
<CurrencyInput
v-model="nominal"
label="Nominal top-up"
name="amount"
hint="Minimum Rp10.000"
presets-label="Nominal cepat"
: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]}
/>Custom element kecil memformat saat mengetik dan mengisi input tersembunyi. Ia mengirim event markas-change yang menggelembung dengan nominal (atau null) sebagai 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, dan class jatuh ke field yang terlihat.
- IDR adalah default: prefiks
Rp, pemisah ribuan titik (12.500.000), tanpa desimal.currency="USD"beralih ke$, pemisah ribuan koma, dan maksimal dua desimal (1,250.50). - Pemisah ditambahkan saat mengetik dan kursor tetap di samping angka yang diketik. Backspace atau Delete di samping pemisah menghapus angka di sebelahnya.
- Kolom yang terlihat tidak punya
name. Isinameuntuk merender input tersembunyi berisi angka murni, siap untuk form biasa. mindanmaxmembatasi nominal saat blur dan saat chip dipilih. Tetap validasi di server.- Chip menghitung angka menuju nominal baru dalam 400ms. Saat reduced motion nominal langsung berubah.
- Atribut dan
classjatuh ke kolom yang terlihat.
Props
| Nama | Tipe | Default | Keterangan |
|---|---|---|---|
label | string | - | Teks label, terhubung ke kolom lewat for dan id. |
hint | string | - | Petunjuk di bawah kolom. Disembunyikan saat error tampil. |
error | string | - | Pesan error. Menyalakan aria-invalid dan border danger. |
currency | 'IDR' | 'USD' | IDR | IDR menampilkan Rp dengan pemisah ribuan titik tanpa desimal. USD menampilkan $ dengan pemisah ribuan koma dan maksimal dua desimal. |
min | number | - | Nilai terendah. Nominal dibatasi saat blur dan saat chip dipilih. |
max | number | - | Nilai tertinggi. Nominal dibatasi saat blur dan saat chip dipilih. |
value / defaultValue / v-model | number | null | null | Nominal awal. Blade memakai value, React memakai defaultValue dengan onValueChange, Vue memakai v-model. |
name | string | - | Nama input tersembunyi yang mengirim angka murni, misalnya 12500000. Kolom yang terlihat tidak punya name. |
presets | number[] | [] | Chip nominal cepat di bawah kolom, berlabel singkat (50rb, 1jt, $1K). Memilih chip menghitung angka menuju nominal baru. |
presetsLabel | string | Quick amounts | Nama aksesibel grup chip. |
id | string | auto | Id kolom yang terlihat. Dibuat otomatis bila kosong. |
bind:value / [(value)] | number | null | - | Svelte dan Angular. Binding dua arah untuk nominal. Svelte juga menerima onValueChange; Angular memancarkan valueChange. |
markas-change | CustomEvent<number | null> | - | Khusus Astro. Event menggelembung dengan nominal baru sebagai detail. |
Aksesibilitas
- Label terhubung ke kolom, dan simbol mata uang, petunjuk, serta error dibacakan lewat aria-describedby.
- Kolom memakai inputmode numeric atau decimal sehingga ponsel menampilkan keypad angka.
- Chip adalah tombol toggle dalam grup berlabel; chip yang cocok dengan nominal punya aria-pressed true.
- Saat reduced motion memilih chip langsung mengisi nominal tanpa animasi hitung.
Komponen terkait
Komponen markasui lain dengan class yang sama di setiap framework.
- Bottom NavigationBar bawah gaya aplikasi mobile. Pill meluncur ke item terpilih, labelnya muncul, dan bar bisa menciut jadi ikon saat konten discroll.
- Card StackTumpukan kartu bertingkat. Geser, tombol panah, atau tombol navigasi membuang kartu teratas lalu kartu berikutnya naik. Berputar, dengan indikator posisi.
- Chat MessagePesan dalam percakapan AI. Gelembung user di kanan, balasan asisten dengan avatar, aksi saat hover, indikator mengetik, dan efek streaming token opsional.
- DockDock ala macOS. Ikon membesar halus mengikuti kursor atau fokus, label muncul di atas, item terbuka bertitik, dan memantul saat dibuka.
- Drag ElementsArea kartu atau stiker yang bisa diseret dengan momentum ringan di dalam batasnya. Panah menggeser item yang fokus, Escape mengembalikannya.
- Dynamic IslandPill hitam terinspirasi Dynamic Island iPhone. Memuai mulus antara keadaan idle, compact, dan expanded sambil kontennya crossfade.