# Direction

Reads the text direction an element renders in.

Source: https://webjs.dev/ui/docs/components/direction

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
  cardActionClass, cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';
import { inputClass } from '#components/ui/input.ts';
import { labelClass } from '#components/ui/label.ts';

const translations = {
  en: {
    dir: 'ltr',
    values: {
      title: 'Login to your account',
      description: 'Enter your email below to login to your account',
      signUp: 'Sign Up',
      email: 'Email',
      emailPlaceholder: 'm@example.com',
      password: 'Password',
      forgotPassword: 'Forgot your password?',
      login: 'Login',
      loginWithGoogle: 'Login with Google',
    },
  },
  ar: {
    dir: 'rtl',
    values: {
      title: 'تسجيل الدخول إلى حسابك',
      description: 'أدخل بريدك الإلكتروني أدناه لتسجيل الدخول إلى حسابك',
      signUp: 'إنشاء حساب',
      email: 'البريد الإلكتروني',
      emailPlaceholder: 'm@example.com',
      password: 'كلمة المرور',
      forgotPassword: 'نسيت كلمة المرور؟',
      login: 'تسجيل الدخول',
      loginWithGoogle: 'تسجيل الدخول باستخدام Google',
    },
  },
  he: {
    dir: 'rtl',
    values: {
      title: 'התחבר לחשבון שלך',
      description: 'הזן את האימייל שלך למטה כדי להתחבר לחשבון שלך',
      signUp: 'הירשם',
      email: 'אימייל',
      emailPlaceholder: 'm@example.com',
      password: 'סיסמה',
      forgotPassword: 'שכחת את הסיסמה?',
      login: 'התחבר',
      loginWithGoogle: 'התחבר עם Google',
    },
  },
};

// The provider is the dir attribute: every part styles itself with logical
// properties, so dir="rtl" on the card flips the whole layout.
export default function CardRtl() {
  const lang = 'ar';
  const { dir, values: t } = translations[lang];

  return html`
    <div data-slot="card" data-size="default" dir=${dir} lang=${lang} class=${cn(cardClass(), 'w-full max-w-sm')}>
      <div data-slot="card-header" class=${cardHeaderClass()}>
        <div data-slot="card-title" class=${cardTitleClass()}>${t.title}</div>
        <div data-slot="card-description" class=${cardDescriptionClass()}>${t.description}</div>
        <div data-slot="card-action" class=${cardActionClass()}>
          <button type="button" data-slot="button" data-variant="link" data-size="default" class=${buttonClass({ variant: 'link' })}>${t.signUp}</button>
        </div>
      </div>
      <div data-slot="card-content" class=${cardContentClass()}>
        <form>
          <div class="flex flex-col gap-6">
            <div class="grid gap-2">
              <label data-slot="label" for="email-rtl" class=${labelClass()}>${t.email}</label>
              <input data-slot="input" id="email-rtl" type="email" placeholder=${t.emailPlaceholder} required class=${inputClass()}>
            </div>
            <div class="grid gap-2">
              <div class="flex items-center">
                <label data-slot="label" for="password-rtl" class=${labelClass()}>${t.password}</label>
                <a href="#" class="ms-auto inline-block text-sm underline-offset-4 hover:underline">${t.forgotPassword}</a>
              </div>
              <input data-slot="input" id="password-rtl" type="password" required class=${inputClass()}>
            </div>
          </div>
        </form>
      </div>
      <div data-slot="card-footer" class=${cn(cardFooterClass(), 'flex-col gap-2')}>
        <button type="submit" data-slot="button" data-variant="default" data-size="default" class=${cn(buttonClass(), 'w-full')}>${t.login}</button>
        <button type="button" data-slot="button" data-variant="outline" data-size="default" class=${cn(buttonClass({ variant: 'outline' }), 'w-full')}>${t.loginWithGoogle}</button>
      </div>
    </div>
  `;
}
```

## Installation

```bash
npx @webjsdev/ui add direction
```

### Copy and paste the following code into your project.

````ts title="components/ui/direction.ts"
/**
 * Direction: right-to-left and left-to-right layout. Tier-1, and deliberately
 * thin, because the platform already has the provider: the `dir` attribute.
 *
 * shadcn parity:
 *   DirectionProvider dir="rtl"  → dir="rtl" on any ancestor element (the
 *                                  page's <html>, or one region of it)
 *   useDirection()               → readDirection(element)
 *
 * shadcn needs a React provider so its Radix components can read the
 * direction. Here every component styles itself with logical properties
 * (`ps-*`, `ms-*`, `start-*`, `text-start`, `rounded-s-*`), which the browser
 * resolves from the nearest `dir`, so setting `dir="rtl"` on an ancestor is
 * the whole of it: padding, alignment, icon sides and inner corners all flip
 * with no script. `readDirection()` is for the rare code that must branch on
 * the direction itself, such as a keyboard handler mapping ArrowLeft to
 * "next" in RTL.
 *
 * A11y (required for accessible output): set `dir` together with `lang` on
 * the same element (`<html lang="ar" dir="rtl">`), since a screen reader picks
 * its voice from `lang` and the layout comes from `dir`. Arrow-key navigation
 * should follow the visual direction, which is what `readDirection()` is for.
 *
 * @example
 * ```html
 * <section dir="rtl" lang="ar">
 *   <button class=${buttonClass()} type="button">حفظ</button>
 * </section>
 * ```
 */

export type Direction = 'ltr' | 'rtl';

/**
 * The direction in effect for an element: the nearest ancestor's `dir`
 * attribute (`auto` and anything else count as left-to-right), else
 * left-to-right. Reads attributes only, so it also runs during server
 * rendering where there is no computed style.
 */
export function readDirection(el: Element | null | undefined): Direction {
  const holder = el?.closest?.('[dir]');
  return holder?.getAttribute('dir')?.toLowerCase() === 'rtl' ? 'rtl' : 'ltr';
}
````

### Update the import paths to match your project setup.

## Usage

Every kit component styles itself with logical properties (`ps-*`, `ms-*`, `start-*`, `text-start`), which the browser resolves from the nearest `dir` attribute, so setting `dir="rtl"` on an ancestor is the whole of it. Set `lang` on the same element, since a screen reader picks its voice from `lang`.

```html
<html lang="ar" dir="rtl">
  <body>
    <!-- Your app content -->
  </body>
</html>
```

One region of a page can carry its own direction the same way:

```ts
<section lang="ar" dir="rtl">
  <button type="button" data-slot="button" class=${buttonClass()}>حفظ</button>
</section>
```

## useDirection

The `readDirection()` helper returns the direction in effect for an element: the nearest ancestor's `dir`, else `ltr`. It reads attributes only, so it also runs during server rendering. Reach for it in code that must branch on the direction itself, such as a keyboard handler mapping ArrowLeft to next in RTL.

```ts
import { readDirection } from '#components/ui/direction.ts';

class MyComponent extends WebComponent {
  render() {
    const direction = readDirection(this);
    return html`<div>Current direction: ${direction}</div>`;
  }
}
```
