useDensity
The spacing preset. One class on <html> retunes --sa-space-unit, and every spacing token follows.
vue
<script setup lang="ts">
import { useDensity } from '@core/theme/useDensity'
import { Button } from '@shared/components/ui/button'
import { Input } from '@shared/components/ui/input'
import { Label } from '@shared/components/ui/label'
import { onBeforeUnmount } from 'vue'
const DENSITIES = ['compact', 'default', 'comfortable'] as const
const { setDensity, currentDensity } = useDensity()
const original = currentDensity.value
onBeforeUnmount(() => setDensity(original))
</script>
<template>
<div class="flex flex-col gap-5">
<div class="flex flex-wrap items-center gap-2">
<Button
v-for="density in DENSITIES"
:key="density"
size="sm"
variant="outline"
:aria-pressed="currentDensity === density"
@click="setDensity(density)"
>
{{ density }}
</Button>
</div>
<div class="flex flex-col gap-4 rounded-lg border border-border p-4">
<div class="grid gap-2">
<Label for="density-demo-name">Full name</Label>
<Input id="density-demo-name" model-value="Amina Haddad" />
</div>
<div class="grid gap-2">
<Label for="density-demo-email">Email</Label>
<Input id="density-demo-email" model-value="amina@example.com" />
</div>
<div class="flex gap-2">
<Button size="sm">
Save
</Button>
<Button size="sm" variant="outline">
Cancel
</Button>
</div>
</div>
</div>
</template>Import
ts
import { useDensity } from '@core/theme/useDensity'Signature
ts
function useDensity(): {
setDensity: (density: Density) => void
currentDensity: Readonly<Ref<Density>>
}Density is 'compact' | 'default' | 'comfortable'.
Returns
| Member | Type | Description |
|---|---|---|
setDensity | (density: Density) => void | Swaps the sa-density-* class on <html>. |
currentDensity | Readonly<Ref<Density>> | The active preset. |
Example
vue
<script setup lang="ts">
import { useDensity } from '@core/theme/useDensity'
const DENSITIES = ['compact', 'default', 'comfortable'] as const
const { setDensity, currentDensity } = useDensity()
</script>
<template>
<div class="flex flex-wrap items-center gap-2">
<button
v-for="density in DENSITIES"
:key="density"
type="button"
:aria-pressed="currentDensity === density"
@click="setDensity(density)"
>
{{ density }}
</button>
</div>
</template>Notes
- The three classes are mutually exclusive.
setDensityremoves all of them before adding the one you asked for, so calling it twice leaves one class behind, not two. - It is a module-scope singleton, and it applies nothing on the first call.
config.ui.densityholds the stored value and the config wiring replays it at boot. setDensityno-ops when there is nodocument.
Related
useTypography— the type-scale equivalent.useTheme— density is part of a theme snapshot.- Theming — the spacing tokens themselves.