# All files / src/typography WritingDirection.tsx

100% Statements 230/230
100% Branches 19/19
100% Functions 4/4
100% Lines 230/230

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    2311x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    580x
    580x
    580x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    125x
    125x
    124x
    124x
    124x
    125x
    125x
    125x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    188x
    188x
    188x
    188x
    132x
    3x
    3x
    129x
    129x
    129x
    129x
    129x
    129x
    188x
    188x
    188x
    2x
    188x
    188x
    188x
    188x
    188x
    188x
    188x
    188x
    3x
    3x
    187x
    187x
    187x
     "use client";
    import {
      Children,
      cloneElement,
      createContext,
      useCallback,
      useContext,
      useEffect,
      useMemo,
      useState,
      type ReactElement,
    } from "react";
    import { type UseStateInitializer } from "../types.js";

    /**
     * Note: unlike the `dir` DOM attribute, the `"auto"` value is not supported.
     *
     * @remarks \@since 6.0.0
     */
    export type Dir = "ltr" | "rtl";

    /** @remarks \@since 6.0.0 */
    export type DefaultDir = UseStateInitializer<Dir>;

    /** @remarks \@since 2.3.0 */
    export interface WritingDirectionContext {
      /**
       * The current writing direction that is being inherited.
       */
      dir: Dir;

      /**
       * Toggles the current writing direction for the first parent `Dir` component.
       */
      toggleDir(): void;
    }

    /** @internal */
    interface InheritableContext extends WritingDirectionContext {
      root: boolean;
    }

    const context = createContext<InheritableContext>({
      root: true,
      dir: "ltr",
      toggleDir: () => {
        if (process.env.NODE_ENV !== "production") {
          throw new Error(
            "Tried to toggle the current writing direction without initializing the `Dir` component."
          );
        }
      },
    });
    context.displayName = "WritingDirection";
    const { Provider } = context;

    /**
     * Gets the writing direction context which provides access to the current `dir`
     * and a `toggleDir` function.
     *
     * @example
     * Manually Changing the Writing Direction
     * ```tsx
     * import { useDir } from "@react-md/core";
     *
     * function Example() {
     *   const { dir, toggleDir } = useDir();
     *
     *   return (
     *     <>
     *       <p>{`The current dir is: "${dir}"`}</p>
     *       <button type="button" onClick={toggleDir}>Toggle</button>
     *     </>
     *   );
     * }
     * ```
     *
     * @remarks \@since 6.0.0
     */
    export function useDir(): Readonly<WritingDirectionContext> {
      const { root: _root, ...current } = useContext(context);
      return current;
    }

    /** @remarks \@since 6.0.0 */
    export interface WritingDirectionProps {
      /**
       * A single ReactElement child. If the `WritingDirection` has a parent
       * `WritingDirection`, the child will have the `dir` prop cloned into this
       * element.
       */
      children: ReactElement<{ dir?: Dir }>;

      /**
       * The default writing direction for your app or a subtree. To change the
       * current writing direction, use the `useDir` hook to get access to the
       * current `dir` and the `toggleDir` function.
       *
       * @defaultValue `"ltr"`
       * @see {@link DEFAULT_WRITING_DIRECTION}
       */
      defaultDir?: DefaultDir;
    }

    /**
     * In the browser, this will default to the `<html>`'s `dir` value if one
     * exists. If the `dir` attribute does not exist, it will default to `"ltr"`.
     *
     * In node environments, this will default to `"ltr"`.
     *
     * @remarks \@since 6.0.0
     */
    export const DEFAULT_WRITING_DIRECTION = (): Dir => {
      let dir: Dir = "ltr";
      if (typeof document !== "undefined") {
        const rootDir = document.documentElement.getAttribute("dir");
        dir = rootDir === "rtl" ? "rtl" : "ltr";
      }

      return dir;
    };

    /**
     * **Client Component**
     *
     * The `WritingDirection` component is used to handle the current writing
     * direction within your app as well as conditionally updating the writing
     * direction for small sections in your app. When this component is used for the
     * first time near the root of your React component tree, the current direction
     * will be applied to the root `<html>` element. Otherwise the current dir will
     * be cloned into the child element so it can be passed as a prop.
     *
     * Note: Since the `dir` is cloned into the child element, you need to make sure
     * that the child is either a DOM element or the `dir` prop is passed from your
     * custom component.
     *
     * @example
     * Root Setup
     * ```tsx
     * import { createRoot } from "react-dom/client";
     * import { WritingDirection } from "@react-md/core";
     * import App from "./App.js":
     *
     * const container = document.getElementById("root");
     * const root = createRoot(container);
     *
     * root.render(
     *   <WritingDirection>
     *     <App />
     *   </WritingDirection>
     * );
     * ```
     *
     * @example
     * Supporting RTL Languages
     * ```tsx
     * import { createRoot } from "react-dom/client";
     * import { WritingDirection } from "@react-md/core";
     * import type { Dir } from "@react-md/core";
     * import App from "./App.js":
     *
     * const container = document.getElementById("root");
     * const root = createRoot(container);
     *
     * // see https://meta.wikimedia.org/wiki/Template:List_of_language_names_ordered_by_code
     * const SUPPORTED_RTL_LANGUAGES = [
     *   "ar",
     *   "arc",
     *   "ckb",
     *   "dv",
     *   "fa",
     *   "ha",
     *   "he",
     *   "khw",
     *   "ks",
     *   "ps",
     *   "sd",
     *   "ur",
     *   "uz_AF",
     *   "ti",
     * ];
     *
     * const defaultDir = (): Dir => {
     *   if (SUPPORTED_RTL_LANGUAGES.includes(navigator.language)) {
     *     return "rtl"
     *   }
     *
     *   return "ltr";
     * }
     *
     * root.render(
     *   <WritingDirection defaultDir={defaultDir}>
     *     <App />
     *   </WritingDirection>
     * );
     * ```
     *
     * @remarks \@since 6.0.0
     */
    export function WritingDirection(props: WritingDirectionProps): ReactElement {
      const { children, defaultDir = DEFAULT_WRITING_DIRECTION } = props;
      const { root } = useContext(context);
      const [dir, setDir] = useState(defaultDir);
      useEffect(() => {
        if (!root || typeof document === "undefined") {
          return;
        }

        document.documentElement.setAttribute("dir", dir);

        return () => {
          document.documentElement.removeAttribute("dir");
        };
      }, [dir, root]);

      const toggleDir = useCallback(() => {
        setDir((prevDir) => (prevDir === "ltr" ? "rtl" : "ltr"));
      }, []);

      const value = useMemo<InheritableContext>(
        () => ({ root: false, dir, toggleDir }),
        [dir, toggleDir]
      );
      let child = Children.only(children);
      if (!root) {
        child = cloneElement(child, { dir });
      }

      return <Provider value={value}>{child}</Provider>;
    }