Tip calculator
Number and range inputs bound to states, with totals derived from them.
<script lang="ts">
const TIPS = [10, 15, 18, 20, 25]
// Number inputs bound with bind:value store numbers; validate keeps them in range.
const bill = state(84.5, { validate: (v) => Math.max(0, Number(v) || 0) })
const tip = state(18, { validate: (v) => Math.min(100, Math.max(0, Number(v) || 0)) })
const people = state(2, { validate: (v) => Math.max(1, Math.round(Number(v) || 1)) })
const tipAmount = derived(() => (bill * tip) / 100)
const total = derived(() => bill + tipAmount)
const each = derived(() => total / people)
const money = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })
</script>
<div class="calc">
<div class="inputs">
<label>
Bill
<input type="number" min="0" step="0.01" bind:value={bill} />
</label>
<div class="field">
<span>Tip</span>
<div class="tips">
{TIPS.map((t) => (
<button key={t} class={{ on: tip === t }} onClick={() => tip.set(t)}>{t}%</button>
))}
</div>
<input type="range" min="0" max="40" bind:value={tip} aria-label="Custom tip" />
</div>
<label>
People
<div class="stepper">
<button aria-label="Fewer people" disabled={people <= 1} onClick={() => people.set(people - 1)}>−</button>
<input type="number" min="1" bind:value={people} />
<button aria-label="More people" onClick={() => people.set(people + 1)}>+</button>
</div>
</label>
</div>
<div class="result">
<div>
<small>Per person</small>
<strong>{money.format(each)}</strong>
</div>
<dl>
<dt>Tip ({tip}%)</dt>
<dd>{money.format(tipAmount)}</dd>
<dt>Total</dt>
<dd>{money.format(total)}</dd>
</dl>
</div>
</div>
<style>
.calc {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 1rem;
}
.inputs {
display: grid;
gap: 0.875rem;
}
label,
.field {
display: grid;
gap: 0.35rem;
color: var(--muted);
font-size: 0.8rem;
font-weight: 500;
}
input {
color: var(--fg);
font-variant-numeric: tabular-nums;
}
.tips {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 4px;
}
.tips button {
padding: 0;
font-size: 0.8rem;
}
.tips button.on {
border-color: var(--fg);
background: var(--fg);
color: var(--bg);
}
.stepper {
display: grid;
grid-template-columns: 2.25rem 1fr 2.25rem;
gap: 4px;
}
.stepper button {
min-height: 2.25rem;
padding: 0;
}
.stepper input {
min-width: 0;
text-align: center;
}
.result {
display: grid;
align-content: space-between;
gap: 1rem;
padding: 1.25rem;
border-radius: 0.75rem;
background: var(--fg);
color: var(--bg);
}
small {
display: block;
opacity: 0.6;
font-size: 0.75rem;
}
strong {
font-size: 2.5rem;
font-weight: 600;
letter-spacing: -0.04em;
line-height: 1.1;
font-variant-numeric: tabular-nums;
}
dl {
display: grid;
grid-template-columns: 1fr auto;
gap: 0.25rem;
margin: 0;
font-size: 0.85rem;
}
dt {
opacity: 0.6;
}
dd {
margin: 0;
font-variant-numeric: tabular-nums;
}
</style>