# 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.

Transitions let an element fade, slide or grow as a condition shows or hides it, like a menu that fades out, an accordion panel that opens or a toast that pops in. In Unframework you wrap the element in `<Transition>`, and it gets Vue's enter and leave classes, which your stylesheet animates. Think of a menu that vanishes in the middle of its fade, a panel that jumps open with no transition at all, or a timer that guesses how long the animation takes before it removes the element.

This page walks you through animating what a condition renders. We'll look at:

- **A transition on a condition:** the classes, and what each framework does.
- **Swapping two elements:** a ternary or an else-if chain, where one leaves as the other enters.
- **What the compiler checks:** the child, `name` and `appear`.
- **What isn't guaranteed:** the timing that differs between frameworks.

## A transition on a condition

Import `Transition` and put it around a condition. It holds one element, or one conditional whose every branch is one element. `name` is the prefix of its classes, `v` when you leave it out:

<!-- prettier-ignore -->
```tsx [Menu.uf.tsx]
import "./Menu.css";
import { Transition, ref } from "@uxfront/unframework";

// A menu, open at first, that leaves with the `fade` transition.
export default function Menu() {
  const open = ref(true);

  return (
    <nav class="menu" aria-label="Account">
      <button type="button" aria-expanded={open.value} onClick={() => (open.value = !open.value)}>
        Account
      </button>
      <Transition name="fade">
        {open.value && (
          <ul class="items">
            <li>Profile</li>
            <li>Sign out</li>
          </ul>
        )}
      </Transition>
    </nav>
  );
}
```

When the element enters, it carries `fade-enter-from` and `fade-enter-active` before it is first painted. Two frames later, `fade-enter-from` goes and `fade-enter-to` comes, and at the end of its transition both others go too. Leaving runs the same with `fade-leave-from`, `fade-leave-active` and `fade-leave-to`, and the element stays in its place until its transition ends. So the stylesheet gives the `-active` classes a transition, and the `-from` or `-to` classes the state the element animates from or to:

<!-- prettier-ignore -->
```css [Menu.css]
.menu {
  padding: 8px;
  background-color: rgb(243, 244, 246);
}

.items {
  margin: 8px 0 0;
  padding-left: 16px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 100ms ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
```

The end is the element's own `transitionend` or `animationend`, or its longest duration and delay, whichever comes first. With no transition in the stylesheet, the classes come and go within two frames. The server renders the settled menu, with no class of the transition.

Vue writes its own `<Transition>`. React, Solid and Qwik run the classes with a small helper that keeps the leaving element in the DOM until its leave ends, Svelte with transition functions on `in:` and `out:`, and Angular with a directive and `animate.leave`. Astro renders once, on the server, so it renders the settled child:

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [Menu.tsx]
import {
  type CSSProperties,
  type ReactElement,
  type ReactNode,
  type Ref,
  cloneElement,
  useCallback,
  useLayoutEffect,
  useRef,
  useState,
  useSyncExternalStore,
} from "react";
import "./Menu.uf.tsx.css";

export interface MenuAttributes {
  className?: string;
  style?: CSSProperties;
}

export default function Menu({ className, style, ...attributes }: MenuAttributes) {
  const [open, setOpen] = useState(true);
  const openRef = useRef(open);

  return (
    <nav
      className={cx("menu", className)}
      aria-label="Account"
      style={style}
      data-uf-e688a71a=""
      {...scopeAttributes(attributes)}
    >
      <button
        type="button"
        aria-expanded={open}
        onClick={() => {
          openRef.current = !openRef.current;
          setOpen(openRef.current);
        }}
        data-uf-e688a71a=""
      >
        Account
      </button>
      <Transition name="fade">
        {open ? (
          <ul key={0} className="items" data-uf-e688a71a="">
            <li data-uf-e688a71a="">Profile</li>
            <li data-uf-e688a71a="">Sign out</li>
          </ul>
        ) : null}
      </Transition>
    </nav>
  );
}

/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") {
      if (part) names.push(part);
    } else if (part && typeof part === "object") {
      for (const [key, on] of Object.entries(part)) {
        if (on) names.push(key);
      }
    }
  }
  return names.join(" ");
}

/** 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 key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}

/** One element a `Transition` renders: its key, its last render and the phase it is in. */
interface TransitionEntry {
  key: string;
  node: ReactElement<{ className?: string; ref?: Ref<Element> }>;
  phase?: "enter" | "leave";
  step: "from" | "to";
  time: number;
}

/** Subscribes to nothing: whether the component renders on a client never changes once it does. */
function subscribeNothing(): () => void {
  return () => {};
}

/**
 * Runs Vue's transition classes of `name` on the element `children` renders, keyed by its
 * branch, as it enters and leaves: `-from` and `-active` first, `-to` for `-from` two frames
 * later, and none once the element's own `transitionend` or `animationend` fires, or its longest
 * duration and delay pass. A leaving element stays, as it last rendered, until its leave ends.
 */
function Transition({
  name,
  appear = false,
  children,
}: {
  name: string;
  appear?: boolean;
  children: ReactElement<{ className?: string; ref?: Ref<Element> }> | null;
}): ReactNode {
  // False on the server and while the client hydrates: only a client mount runs `appear`.
  const client = useSyncExternalStore(
    subscribeNothing,
    () => true,
    () => false,
  );
  const [shown, setShown] = useState(children);
  const [entries, setEntries] = useState<TransitionEntry[]>(() =>
    children
      ? [
          {
            key: String(children.key),
            node: children,
            ...(appear && client ? { phase: "enter" as const } : {}),
            step: "from",
            time: 0,
          },
        ]
      : [],
  );
  const elements = useRef(new Map<string, Element>());
  const [register] = useState(() => (key: string, element: Element | null) => {
    if (element) elements.current.set(key, element);
    else elements.current.delete(key);
  });
  if (children !== shown) {
    setShown(children);
    const before = shown === null ? undefined : String(shown.key);
    const after = children === null ? undefined : String(children.key);
    if (before !== after) {
      // The shown element leaves as it last rendered, and the new one enters.
      const next = entries.flatMap((each): TransitionEntry[] => {
        if (each.key === after) return [];
        return each.key === before && each.phase !== "leave" && shown
          ? [{ key: each.key, node: shown, phase: "leave", step: "from", time: 0 }]
          : [each];
      });
      if (children && after !== undefined)
        next.push({ key: after, node: children, phase: "enter", step: "from", time: 0 });
      setEntries(next);
    }
  }
  useLayoutEffect(() => {
    const stops: (() => void)[] = [];
    const settle = (entry: TransitionEntry) =>
      setEntries((list) =>
        entry.phase === "leave"
          ? list.filter((each) => each !== entry)
          : list.map((each) =>
              each === entry ? { key: each.key, node: each.node, step: "from", time: 0 } : each,
            ),
      );
    for (const entry of entries) {
      const element = elements.current.get(entry.key);
      if (!entry.phase || !element) continue;
      if (entry.step === "from") {
        let frame = requestAnimationFrame(() => {
          frame = requestAnimationFrame(() => {
            const style = getComputedStyle(element);
            const longest = (delays: string, durations: string) => {
              const each = (list: string) =>
                list.split(", ").map((time) => Number(time.slice(0, -1)) * 1000);
              const delay = each(delays);
              return Math.max(
                0,
                ...each(durations).map(
                  (duration, index) => duration + (delay[index % delay.length] ?? 0),
                ),
              );
            };
            const time = Math.max(
              longest(style.transitionDelay, style.transitionDuration),
              longest(style.animationDelay, style.animationDuration),
            );
            if (!time) settle(entry);
            else
              setEntries((list) =>
                list.map((each) => (each === entry ? { ...each, step: "to", time } : each)),
              );
          });
        });
        stops.push(() => cancelAnimationFrame(frame));
        continue;
      }
      const end = (event?: Event) => {
        if (event && event.target !== element) return;
        settle(entry);
      };
      element.addEventListener("transitionend", end);
      element.addEventListener("animationend", end);
      const timer = setTimeout(end, entry.time + 1);
      stops.push(() => {
        clearTimeout(timer);
        element.removeEventListener("transitionend", end);
        element.removeEventListener("animationend", end);
      });
    }
    return () => {
      for (const stop of stops) stop();
    };
  }, [entries]);
  return entries.map((entry) => {
    const node = entry.phase === "leave" || !children ? entry.node : children;
    const classes = entry.phase
      ? [`${name}-${entry.phase}-${entry.step}`, `${name}-${entry.phase}-active`]
      : [];
    return (
      <TransitionItem
        key={entry.key}
        id={entry.key}
        node={node}
        className={[node.props.className, ...classes].filter(Boolean).join(" ") || undefined}
        register={register}
      />
    );
  });
}

/** Renders one element of a `Transition` with its classes, its own ref kept beside the transition's. */
function TransitionItem({
  id,
  node,
  className,
  register,
}: {
  id: string;
  node: ReactElement<{ className?: string; ref?: Ref<Element> }>;
  className: string | undefined;
  register: (key: string, element: Element | null) => void;
}): ReactNode {
  const own = node.props.ref;
  const ref = useCallback(
    (element: Element) => {
      register(id, element);
      const detach = attachRef(own, element);
      return () => {
        register(id, null);
        detach();
      };
    },
    [id, own, register],
  );
  return cloneElement(node, { className, ref });
}

/** Gives a ref the element, as React would, and returns what takes it back. */
function attachRef(ref: Ref<Element> | undefined, element: Element): () => void {
  if (typeof ref === "function") {
    const cleanup = ref(element);
    return typeof cleanup === "function" ? cleanup : () => ref(null);
  }
  if (ref) ref.current = element;
  return () => {
    if (ref) ref.current = null;
  };
}
```

#vue

<!-- prettier-ignore -->
```vue [Menu.vue]
<script setup lang="ts">
import { ref } from "vue";

const open = ref(true);
</script>

<template>
  <nav class="menu" aria-label="Account" data-uf-e688a71a="">
    <button
      type="button"
      :aria-expanded="open"
      data-uf-e688a71a=""
      @click="open = !open"
    >Account</button>
    <Transition name="fade">
      <ul v-if="open" class="items" data-uf-e688a71a="">
        <li data-uf-e688a71a="">Profile</li>
        <li data-uf-e688a71a="">Sign out</li>
      </ul>
    </Transition>
  </nav>
</template>

<style src="./Menu.uf.tsx.css"></style>
```

#svelte

<!-- prettier-ignore -->
```svelte [Menu.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts">
  import type { ClassValue } from "svelte/elements";
  import type { TransitionConfig } from "svelte/transition";
  import "./Menu.uf.tsx.css";

  type Props = { class?: ClassValue; style?: string };

  let { class: className, style, ...attributes }: Props = $props();

  let open = $state(true);

  /** 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;
  }

  /** The stop of the classes each element runs now, which its next phase stops first. */
  const transitionRuns = new WeakMap<Element, () => void>();

  /** Runs `name`'s classes of one phase on the element, as Vue's `<Transition>` does. */
  function transitionClasses(
    element: Element,
    name: string,
    phase: "enter" | "leave",
  ): () => TransitionConfig {
    return () => {
      // A phase that starts while the other runs, as Svelte reverses one, takes over from it.
      transitionRuns.get(element)?.();
      const from = `${name}-${phase}-from`;
      const active = `${name}-${phase}-active`;
      const to = `${name}-${phase}-to`;
      const event = phase === "enter" ? "introend" : "outroend";
      let frame = 0;
      const stop = () => {
        cancelAnimationFrame(frame);
        element.removeEventListener(event, stop);
        element.classList.remove(from, active, to);
        if (transitionRuns.get(element) === stop) transitionRuns.delete(element);
      };
      transitionRuns.set(element, stop);
      element.addEventListener(event, stop, { once: true });
      element.classList.add(from, active);
      frame = requestAnimationFrame(() => {
        frame = requestAnimationFrame(() => {
          element.classList.remove(from);
          element.classList.add(to);
        });
      });
      const style = getComputedStyle(element);
      const longest = (delays: string, durations: string) => {
        const each = (list: string) =>
          list.split(", ").map((time) => Number(time.slice(0, -1)) * 1000);
        const delay = each(delays);
        return Math.max(
          0,
          ...each(durations).map(
            (duration, index) => duration + (delay[index % delay.length] ?? 0),
          ),
        );
      };
      return {
        duration: Math.max(
          longest(style.transitionDelay, style.transitionDuration),
          longest(style.animationDelay, style.animationDuration),
        ),
      };
    };
  }

  /** Runs `name`'s enter classes, as `in:` starts it. */
  function enter(element: Element, name: string): () => TransitionConfig {
    return transitionClasses(element, name, "enter");
  }

  /** Runs `name`'s leave classes, as `out:` starts it. */
  function leave(element: Element, name: string): () => TransitionConfig {
    return transitionClasses(element, name, "leave");
  }
</script>

<nav
  class={["menu", className]}
  aria-label="Account"
  {style}
  data-uf-e688a71a=""
  {...scopeAttributes(attributes)}
>
  <button
    type="button"
    aria-expanded={open}
    onclick={() => (open = !open)}
    data-uf-e688a71a=""
  >Account</button
  >{#if open}
    <ul in:enter={"fade"} out:leave={"fade"} class="items" data-uf-e688a71a="">
      <li data-uf-e688a71a="">Profile</li
      ><li data-uf-e688a71a="">Sign out</li>
    </ul>
  {/if}
</nav>
```

#angular

<!-- prettier-ignore -->
```ts [menu.ts]
import {
  type AnimationCallbackEvent,
  Component,
  DestroyRef,
  Directive,
  ElementRef,
  type OnInit,
  Renderer2,
  ViewEncapsulation,
  afterNextRender,
  inject,
  input,
  signal,
} from "@angular/core";

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

/** A transition's conditional: the branch it shows, and whether it has rendered once. */
@Directive({ selector: "ng-container[ufTransitionRegion]" })
export class TransitionRegion {
  readonly ufTransitionRegion = input.required<number>();
  ready = false;

  constructor() {
    afterNextRender(() => {
      this.ready = true;
    });
  }
}

/** Runs Vue's transition classes of `ufTransition` on its element as it enters and leaves. */
@Directive({ selector: "[ufTransition]", exportAs: "ufTransition" })
export class Transition implements OnInit {
  readonly ufTransition = input.required<string>();
  readonly ufTransitionAppear = input(false);
  readonly ufTransitionBranch = input<number>();
  private readonly region = inject(TransitionRegion, { optional: true });
  private readonly element: Element = inject<ElementRef<Element>>(ElementRef).nativeElement;
  private entering = false;
  private stopEnter: (() => void) | undefined;

  constructor() {
    afterNextRender({
      write: () => {
        if (this.entering) this.stopEnter = this.run("enter");
      },
    });
    inject(DestroyRef).onDestroy(() => this.stopEnter?.());
  }

  ngOnInit(): void {
    // Only an element with a branch of its own reads the region: one of a transition without a
    // conditional finds the region of a transition around it, which says nothing of its own.
    this.entering =
      (this.ufTransitionBranch() !== undefined && Boolean(this.region?.ready)) ||
      this.ufTransitionAppear();
  }

  /**
   * `(animate.leave)`: runs the leave when the region shows another branch than the element's,
   * and lets the element go at once when it still shows it: something around it removed it.
   */
  leave(event: AnimationCallbackEvent): void {
    this.stopEnter?.();
    if (!this.region || this.region.ufTransitionRegion() === this.ufTransitionBranch()) {
      event.animationComplete();
      return;
    }
    this.run("leave", () => event.animationComplete());
  }

  private run(phase: "enter" | "leave", done?: () => void): () => void {
    const { element } = this;
    const from = `${this.ufTransition()}-${phase}-from`;
    const active = `${this.ufTransition()}-${phase}-active`;
    const to = `${this.ufTransition()}-${phase}-to`;
    let frame = 0;
    let timer: ReturnType<typeof setTimeout> | undefined;
    const stop = () => {
      cancelAnimationFrame(frame);
      clearTimeout(timer);
      element.removeEventListener("transitionend", end);
      element.removeEventListener("animationend", end);
      element.classList.remove(from, active, to);
    };
    const end = (event?: Event) => {
      if (event && event.target !== element) return;
      stop();
      done?.();
    };
    element.classList.add(from, active);
    frame = requestAnimationFrame(() => {
      frame = requestAnimationFrame(() => {
        element.classList.remove(from);
        element.classList.add(to);
        const style = getComputedStyle(element);
        const longest = (delays: string, durations: string) => {
          const each = (list: string) =>
            list.split(", ").map((time) => Number(time.slice(0, -1)) * 1000);
          const delay = each(delays);
          return Math.max(
            0,
            ...each(durations).map(
              (duration, index) => duration + (delay[index % delay.length] ?? 0),
            ),
          );
        };
        const time = Math.max(
          longest(style.transitionDelay, style.transitionDuration),
          longest(style.animationDelay, style.animationDuration),
        );
        if (!time) {
          end();
          return;
        }
        element.addEventListener("transitionend", end);
        element.addEventListener("animationend", end);
        timer = setTimeout(end, time + 1);
      });
    });
    return stop;
  }
}

@Component({
  selector: "uf-menu",
  imports: [ScopeAttributes, Transition, TransitionRegion],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let open = this.open();
    <nav
      class="menu"
      aria-label="Account"
      [class]="this.class()"
      [style]="this.style()"
      data-uf-e688a71a=""
      [ufScope]="this.host"
    >
      <button
        type="button"
        [attr.aria-expanded]="open"
        (click)="onAccount()"
        data-uf-e688a71a=""
      >Account</button>
      <ng-container [ufTransitionRegion]="(open) ? 0 : -1">
        @if (open) {
          <ul
            [ufTransition]="'fade'"
            [ufTransitionBranch]="0"
            #transition="ufTransition"
            (animate.leave)="transition.leave($event)"
            class="items"
            data-uf-e688a71a=""
          >
            <li data-uf-e688a71a="">Profile</li>
            <li data-uf-e688a71a="">Sign out</li>
          </ul>
        }
      </ng-container>
    </nav>
  `,
  styleUrl: "./Menu.uf.tsx.css",
  encapsulation: ViewEncapsulation.None,
})
export default class Menu {
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  protected readonly open = signal(true);

  protected onAccount() {
    this.open.set(!this.open());
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

<!-- prettier-ignore -->
```tsx [Menu.tsx]
import {
  type JSX,
  Show,
  children,
  createComputed,
  createSignal,
  onCleanup,
  sharedConfig,
  untrack,
} from "solid-js";
import { isServer } from "solid-js/web";
import "./Menu.uf.tsx.css";

export default function Menu(props: { class?: string; style?: JSX.CSSProperties }) {
  const [open, setOpen] = createSignal(true);

  return (
    <nav
      class={props.class ? `menu ${props.class}` : "menu"}
      aria-label="Account"
      data-uf-e688a71a=""
      style={props.style}
      {...scopeAttributes(props)}
    >
      <button
        type="button"
        aria-expanded={open()}
        onClick={() => setOpen(!open())}
        data-uf-e688a71a=""
      >
        Account
      </button>
      <Transition name="fade">
        <Show when={open()}>
          <ul class="items" data-uf-e688a71a="">
            <li data-uf-e688a71a="">Profile</li>
            <li data-uf-e688a71a="">Sign out</li>
          </ul>
        </Show>
      </Transition>
    </nav>
  );
}

/** 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;
}

/** Runs Vue's transition classes of `name` on the element `children` renders as it enters and leaves. */
function Transition(props: { name: string; appear?: boolean; children: JSX.Element }): JSX.Element {
  // The server renders the child as it is, and resolves it nowhere else, so it renders it once.
  const resolved = children(() => (isServer ? undefined : props.children));
  const [kept, setKept] = createSignal<Element[]>([]);
  const stops = new Set<() => void>();
  onCleanup(() => {
    for (const stop of stops) stop();
  });
  const run = (element: Element, phase: "enter" | "leave", done?: () => void) => {
    const from = `${props.name}-${phase}-from`;
    const active = `${props.name}-${phase}-active`;
    const to = `${props.name}-${phase}-to`;
    let frame = 0;
    let timer: ReturnType<typeof setTimeout> | undefined;
    const stop = () => {
      stops.delete(stop);
      cancelAnimationFrame(frame);
      clearTimeout(timer);
      element.removeEventListener("transitionend", end);
      element.removeEventListener("animationend", end);
      element.classList.remove(from, active, to);
    };
    const end = (event?: Event) => {
      if (event && event.target !== element) return;
      stop();
      done?.();
    };
    stops.add(stop);
    element.classList.add(from, active);
    frame = requestAnimationFrame(() => {
      frame = requestAnimationFrame(() => {
        element.classList.remove(from);
        element.classList.add(to);
        const style = getComputedStyle(element);
        const longest = (delays: string, durations: string) => {
          const each = (list: string) =>
            list.split(", ").map((time) => Number(time.slice(0, -1)) * 1000);
          const delay = each(delays);
          return Math.max(
            0,
            ...each(durations).map(
              (duration, index) => duration + (delay[index % delay.length] ?? 0),
            ),
          );
        };
        const time = Math.max(
          longest(style.transitionDelay, style.transitionDuration),
          longest(style.animationDelay, style.animationDuration),
        );
        if (!time) {
          end();
          return;
        }
        element.addEventListener("transitionend", end);
        element.addEventListener("animationend", end);
        timer = setTimeout(end, time + 1);
      });
    });
  };
  let current: Element | undefined;
  let first = true;
  const hydrating = Boolean(sharedConfig.context);
  createComputed(() => {
    // The server resolves nothing here, and has no `Element`.
    if (isServer) return;
    const value = resolved();
    const next = value instanceof Element ? value : undefined;
    untrack(() => {
      const initial = first;
      first = false;
      if (next === current) return;
      const previous = current;
      current = next;
      const entering = next !== undefined && (initial ? Boolean(props.appear) && !hydrating : true);
      if (previous) {
        run(previous, "leave", () => setKept((list) => list.filter((each) => each !== previous)));
      }
      setKept((list) => [...list.filter((each) => each !== next), ...(next ? [next] : [])]);
      if (next && entering) run(next, "enter");
    });
  });
  return <>{isServer ? props.children : kept()}</>;
}
```

#qwik

<!-- prettier-ignore -->
```tsx [Menu.tsx]
import {
  type CSSProperties,
  type ClassList,
  component$,
  useConstant,
  useSignal,
  useStyles$,
  useVisibleTask$,
} from "@qwik.dev/core";
import { isServer } from "@qwik.dev/core/build";
import styles from "./Menu.uf.tsx.css?inline";

export default component$<{ class?: ClassList; style?: CSSProperties }>(
  ({ class: className, style, ...attributes }) => {
    useStyles$(styles);

    const open = useSignal(true);

    const fadeState = useConstant((): TransitionState => ({
      current: open.value ? 0 : -1,
      elements: [],
      entering: [],
    }));
    const fadeShown = useSignal<number[]>([open.value ? 0 : -1].filter((index) => index >= 0));
    useVisibleTask$(
      ({ track }) => {
        const next = track(() => (open.value ? 0 : -1));
        const previous = fadeState.current;
        if (next === previous) return;
        fadeState.current = next;
        if (next >= 0) {
          // Shown again while it leaves: its leave stops, and it stays as it is.
          stopTransition(fadeState.elements[next]);
          if (!fadeShown.value.includes(next)) {
            fadeState.entering.push(next);
            fadeShown.value = [...fadeShown.value, next];
            // Qwik renders the branch within the frame, unless a condition around the transition
            // hides it: then the mark goes, so the element it shows later enters only with appear.
            requestAnimationFrame(() =>
              requestAnimationFrame(() => {
                const left = fadeState.entering.indexOf(next);
                if (left >= 0) fadeState.entering.splice(left, 1);
              }),
            );
          }
        }
        const leaving = previous < 0 ? undefined : fadeState.elements[previous];
        if (!leaving) {
          fadeShown.value = fadeShown.value.filter((index) => index !== previous);
          return;
        }
        runTransition(leaving, "fade", "leave", () => {
          if (fadeState.current !== previous)
            fadeShown.value = fadeShown.value.filter((index) => index !== previous);
        });
      },
      { strategy: "document-ready" },
    );

    return (
      <nav
        class={["menu", className]}
        aria-label="Account"
        data-uf-e688a71a=""
        {...scopeAttributes(attributes)}
        style={style}
      >
        <button
          type="button"
          aria-expanded={open.value}
          onClick$={() => (open.value = !open.value)}
          data-uf-e688a71a=""
        >
          Account
        </button>
        <>
          {fadeShown.value.includes(0) && (
            <ul class="items" data-uf-e688a71a="" ref={transition(fadeState, "fade", 0, false)}>
              <li data-uf-e688a71a="">Profile</li>
              <li data-uf-e688a71a="">Sign out</li>
            </ul>
          )}
        </>
      </nav>
    );
  },
);

/** 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 key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}

/**
 * A transition's state: the branch shown, each branch's element, and the branches a change of the
 * branch shown adds, which enter. Qwik serialises it, so it holds no function.
 */
interface TransitionState {
  current: number;
  elements: Element[];
  entering: number[];
}

/** What stops the phase each element runs now, which its next phase stops first. */
const transitionStops = new WeakMap<Element, () => void>();

/** Stops the phase an element runs, if any, with its classes and without its `done`. */
function stopTransition(element: Element | undefined): void {
  if (element) transitionStops.get(element)?.();
}

/**
 * Runs Vue's transition classes of `name` of one phase on `element`, then `done`: `-from` and
 * `-active`, `-to` for `-from` two frames later, and none once the element's own
 * `transitionend` or `animationend` fires, or its longest duration and delay pass. A phase the
 * element still runs stops first.
 */
function runTransition(
  element: Element,
  name: string,
  phase: "enter" | "leave",
  done?: () => void,
): void {
  transitionStops.get(element)?.();
  const from = `${name}-${phase}-from`;
  const active = `${name}-${phase}-active`;
  const to = `${name}-${phase}-to`;
  let frame = 0;
  let timer: ReturnType<typeof setTimeout> | undefined;
  const stop = () => {
    cancelAnimationFrame(frame);
    clearTimeout(timer);
    element.removeEventListener("transitionend", end);
    element.removeEventListener("animationend", end);
    element.classList.remove(from, active, to);
    if (transitionStops.get(element) === stop) transitionStops.delete(element);
  };
  transitionStops.set(element, stop);
  const end = (event?: Event) => {
    if (event && event.target !== element) return;
    stop();
    done?.();
  };
  element.classList.add(from, active);
  frame = requestAnimationFrame(() => {
    frame = requestAnimationFrame(() => {
      element.classList.remove(from);
      element.classList.add(to);
      const style = getComputedStyle(element);
      const longest = (delays: string, durations: string) => {
        const each = (list: string) =>
          list.split(", ").map((time) => Number(time.slice(0, -1)) * 1000);
        const delay = each(delays);
        return Math.max(
          0,
          ...each(durations).map(
            (duration, index) => duration + (delay[index % delay.length] ?? 0),
          ),
        );
      };
      const time = Math.max(
        longest(style.transitionDelay, style.transitionDuration),
        longest(style.animationDelay, style.animationDuration),
      );
      if (!time) {
        end();
        return;
      }
      element.addEventListener("transitionend", end);
      element.addEventListener("animationend", end);
      timer = setTimeout(end, time + 1);
    });
  });
}

/**
 * The ref of a transition's element: it records the element, and runs its enter when a change of
 * the branch shown added it, or with `appear`, as the transition first mounts. An element that
 * a condition around the transition shows again enters only with `appear`, as on Vue. Qwik calls
 * a ref again when its value changes, and each render makes a new one, so it takes an element
 * once. It calls the element's own ref first.
 */
function transition(
  state: TransitionState,
  name: string,
  index: number,
  appear: boolean,
  own?: ((element: Element) => void) | { value: Element | undefined },
): (element: Element) => void {
  return (element) => {
    if (typeof own === "function") own(element);
    else if (own) own.value = element;
    // Qwik's server render calls a ref too, with no DOM: the server renders the settled child.
    if (isServer) return;
    if (state.elements[index] === element) return;
    state.elements[index] = element;
    const entering = state.entering.indexOf(index);
    if (entering >= 0) state.entering.splice(entering, 1);
    if (entering >= 0 || appear) runTransition(element, name, "enter");
  };
}
```

#astro

<!-- prettier-ignore -->
```astro [Menu.astro]
---
import "./Menu.uf.tsx.css";

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 = true as boolean;
---

<nav
  class:list={["menu", className]}
  aria-label="Account"
  style={style}
  data-uf-e688a71a=""
  {...scopeAttributes(Astro.props)}
>
  <button type="button" aria-expanded={open} data-uf-e688a71a="">Account</button>
  {open ? (
    <ul class="items" data-uf-e688a71a="">
      <li data-uf-e688a71a="">Profile</li>
      <li data-uf-e688a71a="">Sign out</li>
    </ul>
  ) : null}
</nav>
```

::

`appear` runs the enter when the element first mounts on the client too, such as a toast that pops in: `<Transition name="pop" appear>`. Without it, only a change of the condition runs a transition.

## Swapping two elements

A ternary or an else-if chain in a `<Transition>` swaps one element for another. The old one runs its leave while the new one runs its enter, so both are in the DOM until the leave ends, and then only the new one stays. A swap transitions even when both branches are the same tag:

<!-- prettier-ignore -->
```tsx [Steps.uf.tsx]
import "./Steps.css";
import { Transition, ref } from "@uxfront/unframework";

// Two conditionals of one tag in a transition each: a ternary swap, and an else-if chain.
export default function Steps() {
  const first = ref(true);
  const step = ref(1);

  return (
    <section class="steps" aria-label="Checkout">
      <button type="button" onClick={() => (first.value = !first.value)}>
        Swap
      </button>
      <Transition name="swap">
        {first.value ? <p class="card">Cart</p> : <p class="card">Payment</p>}
      </Transition>
      <button type="button" onClick={() => (step.value = (step.value % 3) + 1)}>
        Next
      </button>
      <Transition name="step">
        {step.value === 1 ? (
          <p class="step">Step one</p>
        ) : step.value === 2 ? (
          <p class="step">Step two</p>
        ) : (
          <p class="step">Step three</p>
        )}
      </Transition>
    </section>
  );
}
```

The two elements sit side by side while they swap, so give the `-leave-active` class a `position: absolute` if the old one shouldn't push the new one down.

## What the compiler checks

`<Transition>` holds one element, or one conditional whose every branch is one element or nothing. Two elements, text or a component as its child is rejected, [UF3057](/docs/reference/diagnostics#UF3057): wrap a component in an element, and keep the condition inside the `<Transition>`:

<!-- prettier-ignore -->
```tsx [Disclosure.uf.tsx]
// UF3057 transition-child: `<Transition>` holds one element, or one conditional of elements, so
// two elements, text and a component as its child are rejected.
import { Transition } from "@uxfront/unframework";

function Hint() {
  return <p>Hint</p>;
}

export default function Disclosure() {
  return (
    <section>
      <Transition>
        <p>First</p>
        <p>Second</p>
      </Transition>
      <Transition>Saved</Transition>
      <Transition>
        <Hint />
      </Transition>
    </section>
  );
}
```

`name` is a string literal that isn't empty, and `appear` is the bare attribute, `{true}` or `{false}`. A bound `name`, an empty one or a bound `appear` is rejected, [UF3058](/docs/reference/diagnostics#UF3058): to switch between two transitions, write two `<Transition>` elements in a conditional.

A `<Transition>` inside a list's body isn't supported yet: transitions on a list's rows are `TransitionGroup`'s, which is still to come. `mode` and JavaScript hooks aren't supported either. A component whose whole render is a `<Transition>` takes no `class` or `style` from its parent, [UF3045](/docs/reference/diagnostics#UF3045).

## What isn't guaranteed

The child goes at once, with no leave, when the component that holds the `<Transition>` unmounts or a condition around the `<Transition>` turns false, as on Vue. Only a change of the transition's own child runs a leave. A few things differ between frameworks:

- Whether `appear`'s enter runs as a server render hydrates. The page settles to the server's HTML either way.
- The order of the two elements while they swap.
- How it looks when the condition turns back while the leave still runs. Vue removes the leaving element and enters a new one, Svelte reverses the leave, and Angular keeps the old element leaving beside the new one. Either way the element ends with no class of the transition.
- Whether a leaving element still updates. It keeps its last render everywhere but in Qwik.
- When a [directive](/docs/components/directives)'s `unmounted` runs on an element that leaves. It runs when the leave starts on Vue, Solid and Angular, and when it ends on React, Svelte and Qwik, so by the end of the leave it has run everywhere.
- A bound `class` on the element that changes during a transition, which can cut it short.
- `prefers-reduced-motion`, which no framework reads for you, as Vue doesn't. Give the `-active` classes no transition inside a `@media (prefers-reduced-motion: reduce)` rule.
- How long Svelte keeps a leaving element: it reads the element's duration as the leave starts, rather than waiting for `transitionend`.

The tests of your components see each transition settled: the harness waits for every running transition and animation to end before it captures the page. The decision behind this page is [ADR-0100](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0100-transition.md). The rule is on [the semantics page](/docs/reference/semantics#transition).
