Directives
Directives let you give an element a behaviour you write once and reuse anywhere, like keeping the focus inside a dialog, closing a menu on a click outside it, or focusing a field once it shows. In Unframework you declare one with defineDirective, and an element applies it as v-focus-trap={open.value}. Think of the same onMounted and onUnmounted pair copied into every dialog, a listener left on document after the menu is gone, or a focus trap that forgets where the focus came from.
This page walks you through writing a directive and applying it. We'll look at:
- A directive of your own:
defineDirective, its hooks, and what each framework receives. - A function as the value: a click outside that calls the component back.
- When the hooks run: the browser only, in Vue's order.
- What the compiler checks: names, values and what isn't supported yet.
A directive of your own
Let's start with a focus trap. A directive lives in a .uf.ts module, beside your composables or in a module of its own, and is a named export whose name is v and an upper-case letter. defineDirective<T> takes the value's type, and an object of hooks: mounted(el, value), updated(el, value, oldValue) and unmounted(el). This one keeps each element's state in a WeakMap the hooks share:
// A focus trap (ADR-0099): once its element is in the document, the focus moves to its first
// control, and Tab and Shift+Tab stay among its controls. When it leaves, the focus returns to
// what had it before. Each element's state lives in a table the hooks share.
import { defineDirective } from "@uxfront/unframework";
interface Trap {
previous: HTMLElement | null;
onKeydown: (event: KeyboardEvent) => void;
}
const FOCUSABLE =
"button:not([disabled]), [href], input:not([disabled]), [tabindex]:not([tabindex='-1'])";
const traps = new WeakMap<HTMLElement, Trap>();
export const vFocusTrap = defineDirective<boolean>({
mounted(el, active) {
const onKeydown = (event: KeyboardEvent) => {
if (event.key !== "Tab") return;
const controls = [...el.querySelectorAll<HTMLElement>(FOCUSABLE)];
const first = controls[0];
const last = controls.at(-1);
if (!first || !last) return;
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
traps.set(el, { previous, onKeydown });
el.addEventListener("keydown", onKeydown);
if (active) el.querySelector<HTMLElement>(FOCUSABLE)?.focus();
},
unmounted(el) {
const trap = traps.get(el);
if (!trap) return;
el.removeEventListener("keydown", trap.onKeydown);
traps.delete(el);
trap.previous?.focus();
},
});
A component imports it by name and applies it in kebab case, vFocusTrap as v-focus-trap. The dialog renders behind a condition, so its mounted runs once the dialog is in the document, and its unmounted once the condition removes it:
import { ref } from "@uxfront/unframework";
import { vFocusTrap } from "./focusTrap.uf.ts";
export default function Settings() {
const open = ref(false);
function close() {
open.value = false;
}
function onKeydown(event: KeyboardEvent) {
if (event.key === "Escape") close();
}
return (
<section class="settings" aria-label="Settings">
<button type="button" onClick={() => (open.value = true)}>
Open
</button>
{open.value ? (
<div
role="dialog"
aria-label="Preferences"
tabindex="-1"
class="dialog"
v-focus-trap={open.value}
onKeydown={onKeydown}
>
<button type="button">Theme</button>
<button type="button">Language</button>
<button type="button" onClick={close}>
Close
</button>
</div>
) : null}
</section>
);
}
Each framework receives the directive in its own idiom. Vue gets its own custom directive, Svelte an attachment, Solid a ref factory and Angular an attribute directive. React and Qwik have no directive, so they get the plain hooks, which a small helper in each component runs. Astro runs nothing in the page, so it writes no file for a directive, and its component renders the dialog without it:
interface Trap {
previous: HTMLElement | null;
onKeydown: (event: KeyboardEvent) => void;
}
const FOCUSABLE =
"button:not([disabled]), [href], input:not([disabled]), [tabindex]:not([tabindex='-1'])";
const traps = new WeakMap<HTMLElement, Trap>();
export const vFocusTrap = {
mounted(el: HTMLElement, active: boolean) {
const onKeydown = (event: KeyboardEvent) => {
if (event.key !== "Tab") return;
const controls = [...el.querySelectorAll<HTMLElement>(FOCUSABLE)];
const first = controls[0];
const last = controls.at(-1);
if (!first || !last) return;
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
traps.set(el, { previous, onKeydown });
el.addEventListener("keydown", onKeydown);
if (active) el.querySelector<HTMLElement>(FOCUSABLE)?.focus();
},
unmounted(el: HTMLElement) {
const trap = traps.get(el);
if (!trap) return;
el.removeEventListener("keydown", trap.onKeydown);
traps.delete(el);
trap.previous?.focus();
},
};
A component's own .uf.tsx module may declare a directive too, without export, for its components alone. Every output that applies it declares it, with the constants its hooks read.
A function as the value
Now let's look at a click outside. Its value is a function the directive calls when a click lands outside its element, so the menu decides what closing means. Pass a setup function by its name, as you'd pass a listener: a function written in place would be a new value at every render on some frameworks.
// Click outside (ADR-0099): the value is a function the directive calls when a click lands
// outside its element. The listener is the document's, added once the element is mounted and
// removed once it leaves; `updated` keeps the function the last render gave.
import { defineDirective } from "@uxfront/unframework";
interface Outside {
callback: () => void;
onClick: (event: MouseEvent) => void;
}
const outsides = new WeakMap<HTMLElement, Outside>();
export const vClickOutside = defineDirective<() => void>({
mounted(el, callback) {
const outside: Outside = {
callback,
onClick: (event) => {
if (!el.contains(event.target as Node)) outside.callback();
},
};
outsides.set(el, outside);
document.addEventListener("click", outside.onClick);
},
updated(el, callback) {
const outside = outsides.get(el);
if (outside) outside.callback = callback;
},
unmounted(el) {
const outside = outsides.get(el);
if (outside) document.removeEventListener("click", outside.onClick);
outsides.delete(el);
},
});
The directive sits on the menu, which is rendered from the start, so its document listener is in place before any click:
import { defineEmits, ref } from "@uxfront/unframework";
import { vClickOutside } from "./clickOutside.uf.ts";
export default function ProfileMenu() {
const emit = defineEmits<{ closed: [] }>();
const open = ref(false);
function close() {
if (!open.value) return;
open.value = false;
emit("closed");
}
return (
<section class="profile-menu" aria-label="Profile">
<div class="menu" v-click-outside={close}>
<button type="button" aria-expanded={open.value} onClick={() => (open.value = !open.value)}>
Account
</button>
{open.value ? (
<ul aria-label="Account actions">
<li>
<button type="button">Settings</button>
</li>
<li>
<button type="button">Sign out</button>
</li>
</ul>
) : null}
</div>
<p>Outside the menu</p>
</section>
);
}
Vue resolves vClickOutside from <script setup> by its name, and passes close as written:
<script setup lang="ts">
import { vClickOutside } from "./vClickOutside";
import { ref } from "vue";
const emit = defineEmits<{ closed: [] }>();
const open = ref(false);
function close() {
if (!open.value) return;
open.value = false;
emit("closed");
}
</script>
<template>
<section class="profile-menu" aria-label="Profile">
<div v-click-outside="close" class="menu">
<button type="button" :aria-expanded="open" @click="open = !open">Account</button>
<ul v-if="open" aria-label="Account actions">
<li>
<button type="button">Settings</button>
</li>
<li>
<button type="button">Sign out</button>
</li>
</ul>
</div>
<p>Outside the menu</p>
</section>
</template>
React keeps close one stable function, Angular makes it an arrow member and Qwik a QRL, so updated runs on no framework just because the component rendered again.
A directive on each row
A directive works on each row a list renders, and on each element a scoped slot's fill renders, and its value may read the row's item or the fill's props. Each element gets its own hooks, with its own value: renaming one row runs updated on that row alone, and removing a row runs unmounted on it alone. On Solid, a scoped fill whose child passes it new props renders a new element, so its directive runs unmounted and mounted there instead (semantics). Here each row traces its label, one row applies two directives, one listens beside its directive, and one's value reads the component's state too:
import { ref } from "@uxfront/unframework";
import { vMark } from "./mark.uf.ts";
import Picker from "./Picker.uf.tsx";
import { vTrace } from "./trace.uf.ts";
// A directive on each row a list renders, and on each element a scoped fill renders, whose value
// reads the row's item or the fill's props (ADR-0108): each element gets its own hooks with its
// own value. A row applies two such directives, another listens beside one, another's value
// reads the component's state too, and one in a branch of a row reads what the branch narrows.
export default function Menu() {
const items = ref<{ id: string; label: string; note?: string }[]>([
{ id: "a", label: "Alpha", note: "First" },
{ id: "b", label: "Beta" },
{ id: "c", label: "Gamma" },
]);
const prefix = ref("Open");
const focused = ref(0);
return (
<section class="menu" aria-label="Menu">
<ul aria-label="Items">
{items.value.map((item) => (
<li key={item.id} data-name={item.id} v-trace={item.label}>
{item.label}
{item.note ? (
<b data-name={`note-${item.id}`} v-trace={item.note}>
{item.note}
</b>
) : null}
</li>
))}
</ul>
<ul aria-label="Marked">
{items.value.map((item) => (
<li key={item.id} data-name={`both-${item.id}`} v-trace={item.label} v-mark={item.id}>
{item.label}
</li>
))}
</ul>
<div class="focus">
{items.value.map((item) => (
<button
key={item.id}
type="button"
data-name={`focus-${item.id}`}
onFocusin={() => focused.value++}
v-trace={item.label}
>
Focus {item.label}
</button>
))}
</div>
<output>{focused.value}</output>
<ul aria-label="Prefixed">
{items.value.map((item) => (
<li
key={item.id}
data-name={`prefixed-${item.id}`}
v-trace={`${prefix.value} ${item.label}`}
>
{item.label}
</li>
))}
</ul>
<Picker>
{{
option: ({ option }) => (
<span data-name={`option-${option.id}`} v-trace={`${prefix.value} ${option.label}`}>
{option.label}
</span>
),
}}
</Picker>
<button
type="button"
onClick={() =>
(items.value = items.value.map((item) =>
item.id === "a" ? { id: "a", label: "Alpha 2", note: "First" } : item,
))
}
>
Rename first
</button>
<button type="button" onClick={() => (items.value = [...items.value].reverse())}>
Reverse
</button>
<button
type="button"
onClick={() => (items.value = items.value.filter((item) => item.id !== "b"))}
>
Remove second
</button>
<button
type="button"
onClick={() => (items.value = [...items.value, { id: "d", label: "Delta" }])}
>
Add item
</button>
<button type="button" onClick={() => (prefix.value = "Close")}>
Change prefix
</button>
</section>
);
}
React has no directive, so each row makes its ref callback from its value as it renders, through the function a useElementDirective(vTrace) call at the component's top level returns. Qwik's row passes it as it renders too, ref={collectValues(traceElements, [item.label])}, so a value that also reads the component's state renders the row again when that state changes. Vue, Svelte, Solid and Angular apply a directive to each row already.
When the hooks run
The hooks run in the browser only. The server never runs one, so the server's HTML holds nothing a hook writes, and hydration has nothing of it to compare:
mountedruns once per element, once the element is in the DOM, with that render's value.updatedruns after a render in which the value changed, asObject.iscompares it, with the new value and the previous one. A render that leaves the value the same doesn't run it, though Vue calls a directive after every update of its component.unmountedruns once, when the element leaves the DOM or its component unmounts. The element may already be detached, as it is on Vue.
Within one render, every unmounted runs before any mounted, a descendant's hook runs before its ancestor's, and siblings' in document order, which is Vue's own order. React, Solid, Angular and Qwik keep it through a small queue, one for the whole page, so a hook may run in a microtask after the framework's own, and a directive from a .uf.ts module sorts with a component's own. The semantics contract has the rule, and the few cases outside it.
What the compiler checks
A directive is declared once, as a top-level const that defineDirective<T> initialises, with method hooks that read their parameters, the browser's globals, and the module's constants and imports. Anything else is UF2037: a call in a setup, no type argument, an unknown hook, or a hook that calls the authoring API. The names of Vue's own directives, like v-if and v-show, stay Vue's.
An element applies a directive the module declares or imports, or it's UF3055. A directive goes on an element, with a value, which isn't an object or array literal or a function written in place, or it's UF3056. Pass a state, a derived value, a prop, a setup function or a primitive instead.
The value's type is the T of the directive's defineDirective<T>. TypeScript doesn't type a dashed JSX attribute, so your editor accepts v-focus-trap={1}. With the tsgo type oracle, typeOracle: "tsgo" in your configuration, the compiler checks each value where it's written, narrowed by its branch, and reports one of another type as UF6007. The default oracle doesn't check it.
These aren't supported yet:
- Arguments and modifiers, like
v-focus-trap:outerandv-focus-trap_once. Pass what the directive needs as its value. - A directive among a spread's keys.
Keep in mind that TypeScript doesn't read v-focus-trap as a use of vFocusTrap, so a lint rule like no-unused-vars flags the import. We recommend ignoring names that start with v and an upper-case letter in your .uf.tsx files, as this repository's own lint config does: varsIgnorePattern: "^(?:_|v[A-Z][A-Za-z0-9]*$)".
Teleport
<Teleport to> mounts an element elsewhere on the page, like a dialog. Every framework mounts it once the component has mounted, never on the server.
Transitions
A transition runs Vue's enter and leave classes on an element as a condition shows or hides it, so your CSS animates it on every framework.