# Directives

> defineDirective declares a behaviour an element takes, like a focus trap, and v-name applies it. Every framework runs its hooks in the browser, in Vue's order.

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:

<!-- prettier-ignore -->
```ts [focusTrap.uf.ts]
// 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:

<!-- prettier-ignore -->
```tsx [Settings.uf.tsx]
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:

::framework-switcher

#react

<!-- prettier-ignore -->
```ts [vFocusTrap.ts]
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();
  },
};
```

#vue

<!-- prettier-ignore -->
```ts [vFocusTrap.ts]
import type { ObjectDirective } from "vue";

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: ObjectDirective<HTMLElement, boolean> = {
  mounted(el, { value: 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();
  },
};
```

#svelte

<!-- prettier-ignore -->
```ts [vFocusTrap.svelte.ts]
import { untrack } from "svelte";
import type { Attachment } from "svelte/attachments";

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 function vFocusTrap(getValue: () => boolean): Attachment<HTMLElement> {
  const hooks = {
    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();
    },
  };
  return (element) => {
    untrack(() => hooks.mounted(element, untrack(getValue)));
    return () => hooks.unmounted(element);
  };
}
```

#angular

<!-- prettier-ignore -->
```ts [v-focus-trap.ts]
import { DestroyRef, Directive, ElementRef, afterRenderEffect, inject, input } from "@angular/core";

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>();

/** The hooks of a directive, which `runDirective` runs on its element. */
interface DirectiveHooks<E extends Element, T> {
  mounted?(el: E, value: T): unknown;
  updated?(el: E, value: T, oldValue: T): unknown;
  unmounted?(el: E): unknown;
}

/** The checks `watchDocument` calls, and its observer while it has any. */
const documentWatches: { checks: Set<() => void>; observer?: MutationObserver } = {
  checks: new Set(),
};

/**
 * Calls `check` after each change to the document's tree, through one `MutationObserver` for
 * every watch, and returns the end of the watch.
 */
function watchDocument(check: () => void): () => void {
  const { checks } = documentWatches;
  if (!documentWatches.observer) {
    documentWatches.observer = new MutationObserver(() => {
      for (const each of [...checks]) each();
    });
    documentWatches.observer.observe(document, { childList: true, subtree: true });
  }
  checks.add(check);
  return () => {
    checks.delete(check);
    if (!checks.size) {
      documentWatches.observer?.disconnect();
      documentWatches.observer = undefined;
    }
  };
}

/**
 * Each directive's elements: the value each last received, whether `mounted` ran, whether it
 * left its caller's list, how many runs took it up, and the end of its watch on the document.
 */
const directiveStates = new WeakMap<
  object,
  WeakMap<
    Element,
    { value: unknown; mounted: boolean; left: boolean; runs: number; unwatch: () => void }
  >
>();

/**
 * The check of a directive's elements: `mounted` once an element is in the document, and
 * `unmounted` once it leaves. A caller that lists its elements passes `follow`, which takes an
 * element out of the list as it leaves and back in if it returns, for the caller's next run to
 * mount it with the value of then; meanwhile the element belongs to a weak watch alone
 * (`watchLeft`). Declared apart from `runDirective`, whose scope holds
 * the element, so nothing it makes keeps a left element alive.
 */
function directiveCheck<E extends Element, T>(
  directive: DirectiveHooks<E, T>,
  elements: WeakMap<
    Element,
    { value: unknown; mounted: boolean; left: boolean; runs: number; unwatch: () => void }
  >,
  follow: { leave(element: E): void; back(element: E): void } | undefined,
): (target: E) => void {
  const check = (target: E): void => {
    const current = elements.get(target);
    if (!current || current.mounted === target.isConnected) return;
    if (current.left) {
      // Back in the document, it rejoins the list, and the caller's next run mounts it with the
      // value of then.
      if (target.isConnected) follow?.back(target);
      return;
    }
    current.mounted = target.isConnected;
    if (current.mounted) {
      const mounted = current.value as T;
      queueHook(target, () => directive.mounted?.(target, mounted), "mounted");
      return;
    }
    queueHook(target, () => directive.unmounted?.(target), "unmounted");
    if (!follow) return;
    current.left = true;
    current.unwatch();
    current.unwatch = watchLeft(target, check);
    follow.leave(target);
  };
  return check;
}

/**
 * Watches an element that left its caller's list through a `WeakRef`: `check` runs on it
 * after each change of the document while it lives, and the watch ends once it is collected.
 */
function watchLeft<E extends Element>(element: E, check: (target: E) => void): () => void {
  const left = new WeakRef(element);
  const unwatch = watchDocument(() => {
    const kept = left.deref();
    if (kept) check(kept);
    else unwatch();
  });
  return unwatch;
}

/**
 * Runs a directive's hooks on its element: `mounted` once the element is in the document,
 * `updated` for a value that changed while it is, and `unmounted` once it leaves, which
 * projected content may do and come back. A caller that lists its elements passes `follow`
 * (`directiveCheck`): an element that left the list stays with its weak watch, and one that is gone
 * for good is collected, which ends its watch at the next change of the document. The stop it
 * returns, called when the element's owner goes, unmounts the element a microtask later, unless a
 * later run took it up or it left a list.
 */
function runDirective<E extends Element, T>(
  directive: DirectiveHooks<E, T>,
  element: E,
  value: T,
  follow?: { leave(element: E): void; back(element: E): void },
): () => void {
  let own = directiveStates.get(directive);
  if (!own) {
    own = new WeakMap();
    directiveStates.set(directive, own);
  }
  const elements = own;
  const check = directiveCheck(directive, elements, follow);
  let state = elements.get(element);
  if (state?.left) {
    // A left element its caller lists again: it is followed as any other.
    state.left = false;
    state.unwatch();
    state.unwatch = watchDocument(() => check(element));
  }
  if (state) {
    state.runs += 1;
    if (!Object.is(value, state.value)) {
      const previous = state.value as T;
      state.value = value;
      if (state.mounted) {
        queueHook(element, () => directive.updated?.(element, value, previous), "updated");
      }
    }
  } else {
    state = {
      value,
      mounted: false,
      left: false,
      runs: 0,
      unwatch: watchDocument(() => check(element)),
    };
    elements.set(element, state);
  }
  check(element);
  const taken = state;
  const runs = taken.runs;
  return () => {
    queueMicrotask(() => {
      if (elements.get(element) !== taken || taken.runs !== runs || taken.left) return;
      taken.unwatch();
      elements.delete(element);
      if (taken.mounted) queueHook(element, () => directive.unmounted?.(element), "unmounted");
    });
  };
}

/**
 * Runs a directive's hook once the turn ends, as Vue runs them: every `unmounted` first, then
 * a descendant's before its ancestor's and siblings' in document order, one element's in the
 * order they came, with the hooks every other output queued.
 */
function queueHook(
  element: Element,
  run: () => void,
  hook: "mounted" | "updated" | "unmounted",
): void {
  const key: unique symbol = Symbol.for("unframework.directive-hooks@2");
  const scope = globalThis as typeof globalThis & {
    [key]?: { element: Element; run: () => void; hook: "mounted" | "updated" | "unmounted" }[];
  };
  const queued = scope[key];
  if (queued) {
    queued.push({ element, run, hook });
    return;
  }
  scope[key] = [{ element, run, hook }];
  queueMicrotask(() => {
    const hooks = scope[key] ?? [];
    scope[key] = undefined;
    // Every `unmounted` runs first, but one after its own element's `mounted` this turn, as
    // StrictMode's, which keeps its place among the rest. A leaving one moves up together
    // with the element's hooks before it, which keep their order.
    const first = new Set<(typeof hooks)[number]>();
    const entered = new Set<Element>();
    for (const each of hooks) {
      if (each.hook === "mounted") entered.add(each.element);
      if (each.hook !== "unmounted" || entered.has(each.element)) continue;
      for (const earlier of hooks) {
        if (earlier.element === each.element) first.add(earlier);
        if (earlier === each) break;
      }
    }
    hooks.sort((a, b) => {
      if (first.has(a) !== first.has(b)) return first.has(a) ? -1 : 1;
      if (a.element === b.element) return 0;
      if (a.element.contains(b.element)) return 1;
      if (b.element.contains(a.element)) return -1;
      return a.element.compareDocumentPosition(b.element) & Node.DOCUMENT_POSITION_FOLLOWING
        ? -1
        : 1;
    });
    for (const each of hooks) {
      try {
        each.run();
      } catch (error) {
        reportError(error);
      }
    }
  });
}

@Directive({ selector: "[vFocusTrap]" })
export class VFocusTrap {
  readonly vFocusTrap = input.required<boolean>();
  private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);

  constructor() {
    const hooks = {
      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();
      },
    };
    const element = this.element.nativeElement;
    let stop: (() => void) | undefined;
    afterRenderEffect(() => {
      stop = runDirective(hooks, element, this.vFocusTrap());
    });
    inject(DestroyRef).onDestroy(() => stop?.());
  }
}
```

#solid

<!-- prettier-ignore -->
```ts [vFocusTrap.ts]
import { onCleanup, onMount, untrack } from "solid-js";

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 function vFocusTrap(getValue: () => boolean): (element: HTMLElement) => void {
  const hooks = {
    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();
    },
  };
  let target: HTMLElement | undefined;
  const current = untrack(getValue);
  onMount(() => {
    const element = target;
    if (element) queueHook(element, () => hooks.mounted(element, current), "mounted");
  });
  onCleanup(() => {
    const element = target;
    if (element) queueHook(element, () => hooks.unmounted(element), "unmounted");
  });
  return (element) => {
    target = element;
  };
}

/**
 * Runs a directive's hook once the turn ends, as Vue runs them: every `unmounted` first, then
 * a descendant's before its ancestor's and siblings' in document order, one element's in the
 * order they came, with the hooks every other output queued.
 */
function queueHook(
  element: Element,
  run: () => void,
  hook: "mounted" | "updated" | "unmounted",
): void {
  const key: unique symbol = Symbol.for("unframework.directive-hooks@2");
  const scope = globalThis as typeof globalThis & {
    [key]?: { element: Element; run: () => void; hook: "mounted" | "updated" | "unmounted" }[];
  };
  const queued = scope[key];
  if (queued) {
    queued.push({ element, run, hook });
    return;
  }
  scope[key] = [{ element, run, hook }];
  queueMicrotask(() => {
    const hooks = scope[key] ?? [];
    scope[key] = undefined;
    // Every `unmounted` runs first, but one after its own element's `mounted` this turn, as
    // StrictMode's, which keeps its place among the rest. A leaving one moves up together
    // with the element's hooks before it, which keep their order.
    const first = new Set<(typeof hooks)[number]>();
    const entered = new Set<Element>();
    for (const each of hooks) {
      if (each.hook === "mounted") entered.add(each.element);
      if (each.hook !== "unmounted" || entered.has(each.element)) continue;
      for (const earlier of hooks) {
        if (earlier.element === each.element) first.add(earlier);
        if (earlier === each) break;
      }
    }
    hooks.sort((a, b) => {
      if (first.has(a) !== first.has(b)) return first.has(a) ? -1 : 1;
      if (a.element === b.element) return 0;
      if (a.element.contains(b.element)) return 1;
      if (b.element.contains(a.element)) return -1;
      return a.element.compareDocumentPosition(b.element) & Node.DOCUMENT_POSITION_FOLLOWING
        ? -1
        : 1;
    });
    for (const each of hooks) {
      try {
        each.run();
      } catch (error) {
        reportError(error);
      }
    }
  });
}
```

#qwik

<!-- prettier-ignore -->
```ts [vFocusTrap.ts]
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();
  },
};
```

#astro

<!-- prettier-ignore -->
```astro [Settings.astro]
---
interface Props {
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { class: className, style } = Astro.props;

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const name of Object.keys(props)) if (name.startsWith("data-uf-")) scope[name] = "";
  return scope;
}

const open = false as boolean;
---

<section
  class:list={["settings", className]}
  aria-label="Settings"
  style={style}
  {...scopeAttributes(Astro.props)}
>
  <button type="button">Open</button>
  {open ? (
    <div role="dialog" aria-label="Preferences" tabindex="-1" class="dialog">
      <button type="button">Theme</button>
      <button type="button">Language</button>
      <button type="button">Close</button>
    </div>
  ) : null}
</section>
```

::

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.

<!-- prettier-ignore -->
```ts [clickOutside.uf.ts]
// 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:

<!-- prettier-ignore -->
```tsx [ProfileMenu.uf.tsx]
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:

<!-- prettier-ignore -->
```vue [ProfileMenu.vue]
<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](/docs/reference/semantics#outside-the-contract)). 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:

<!-- prettier-ignore -->
```tsx [Menu.uf.tsx]
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:

- `mounted` runs once per element, once the element is in the DOM, with that render's value.
- `updated` runs after a render in which the value changed, as `Object.is` compares 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.
- `unmounted` runs 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](/docs/reference/semantics#directives) 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](/docs/reference/diagnostics#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](/docs/reference/diagnostics#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](/docs/reference/diagnostics#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](/docs/tooling/configuration#fields), the compiler checks each value where it's written, narrowed by its branch, and reports one of another type as [UF6007](/docs/reference/diagnostics#UF6007). The default oracle doesn't check it.

These aren't supported yet:

- Arguments and modifiers, like `v-focus-trap:outer` and `v-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]*$)"`.
