# Client API

Composables and components from vuesho/client.

`vuesho/client` exports the composables and components that your components, layouts and custom pages use to read the current page, the site, the router and the color mode. Call a composable in `<script setup>`. Most composables return refs:

```vue title="src/components/PageFooter.vue"
<script setup lang="ts">
import { usePage, useSite } from "vuesho/client";

const page = usePage();
const { name } = useSite();
</script>

<template>
  <p>{{ page.pageData.title }}, from {{ name }}.</p>
</template>
```

`md` writes a [component's Markdown](/ai#component-markdown) for LLMs. `getHighlighter()` loads your site's highlighter with its code themes, for code that a component highlights in the browser. It also exports the types [`ContentPage`](/layouts#custom-layout), [`PageOf`](/layouts#typed-pages) and [`Theme`](/theme).

## Page and Site Data [#page-and-site-data]

### `usePage()` [#usepage]

A ref of the current page. Every page has `url` and `pageData`, the data a layout renders, like `title`. `kind` is one of these:

| `kind`      | Page                                        | Fields                                           |
| ----------- | ------------------------------------------- | ------------------------------------------------ |
| `content`   | A [content source's](/content-sources) page | `type`, its source's key, and `data`             |
| `custom`    | A [custom page](/custom-pages)              | `props` and `contentOf`, from `definePage()`     |
| `view`      | A page that a [plugin](/routes#views) adds  | `type`, the view's name, `props` and `contentOf` |
| `not-found` | The not found page                          | None                                             |
| `error`     | A page that failed to render on the server  | None                                             |

`usePage<typeof app>()` types the page from your config. Once `kind` is narrowed to `content`, `page.data` has the frontmatter fields, and with multiple sources, narrowing `type` narrows `page.data` to one source's fields:

```vue title="src/components/PageDate.vue"
<script setup lang="ts">
import { usePage } from "vuesho/client";
import type app from "../../vuesho.config";

const page = usePage<typeof app>(); // [!code highlight]
</script>

<template>
  <time v-if="page.kind === 'content' && page.data.date">{{ page.data.date }}</time>
</template>
```

### `useSite()` [#usesite]

The site in the current page's language, as refs. `localizePath()` returns a path in another language, for [translated links](/i18n):

### UseSite

| Prop           | Type                                                      | Description                                                                                                                      |
| -------------- | --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `name`         | `Readonly<Ref<string \| undefined, string \| undefined>>` | The site's name in this language.                                                                                                |
| `description`  | `Readonly<Ref<string \| undefined, string \| undefined>>` | The site's description in this language.                                                                                         |
| `lang`         | `Readonly<Ref<string, string>>`                           | The document's language.                                                                                                         |
| `dir`          | `Readonly<Ref<"ltr" \| "rtl", "ltr" \| "rtl">>`           | The text direction in this language.                                                                                             |
| `localizePath` | `(lang: string, path: string) => string`                  | Gives a path in a language, with its prefix unless `i18n.hideLocale: "default-locale"` hides it. Throws for an unknown language. |

### `usePageTree()` [#usepagetree]

A ref of the page tree in the reader's language, which the sidebar renders. `vuesho/page-tree` has functions to search it, like `findSiblings()`:

```vue title="src/components/FurtherReading.vue"
<script setup lang="ts">
import { computed } from "vue";
import { usePage, usePageTree } from "vuesho/client";
import { findSiblings } from "vuesho/page-tree";
import { Card, Cards } from "vuesho/ui/components/card";

const page = usePage();
const tree = usePageTree();
const peers = computed(
  () => findSiblings(tree.value, page.value.url).filter((node) => node.type === "page"), // [!code highlight]
);
</script>

<template>
  <Cards>
    <Card v-for="peer in peers" :key="peer.url" :href="peer.url" :description="peer.description">
      <template #title><component :is="peer.name" /></template>
    </Card>
  </Cards>
</template>
```

A node's `name` and `icon` are components, rendered with `<component :is>`. The whole app shares the tree, so run a function that changes nodes, like `visit()`, on a copy.

<Accordions>
<Accordion title="Functions in vuesho/page-tree">
### PageTreeHelpers

| Prop               | Type                                                                                                                                            | Description                                                                                                  |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `selectTreeRoot`   | `(tree: Root, path: string) => Root`                                                                                                            | The page tree of the folder at `path` from the content root: `selectTreeRoot(usePageTree().value, "docs")`.  |
| `flattenTree`      | `(nodes: Node[]) => Item[]`                                                                                                                     | The pages in a list of nodes, in sidebar order, with a folder's index page before its children.              |
| `findPath`         | `(nodes: Node[], matcher: (node: Node) => boolean, options?: { includeSeparator?: boolean; }) => Node[] \| null`                                | The nodes from the root to the first node the matcher accepts, or `null`.                                    |
| `findNeighbour`    | `(tree: Root, url: string, options?: { separateRoot?: boolean; }) => { previous?: Item; next?: Item; }`                                         | The pages before and after the page at `url`, within its root folder unless `separateRoot` is `false`.       |
| `getPageTreeRoots` | `(tree: Root \| Folder) => (Root \| Folder)[]`                                                                                                  | The tree and its root folders, which the sidebar shows as tabs.                                              |
| `findSiblings`     | `(tree: Root \| Record<string, Root>, url: string) => Node[]`                                                                                   | The other nodes in the folder of the page at `url`.                                                          |
| `findParent`       | `(from: Root \| Folder, url: string) => Root \| Folder \| undefined`                                                                            | The folder of the page at `url`, the tree itself, or none when no page is at `url`.                          |
| `findProjection`   | `(from: Folder, to: Folder, page: Item) => Item \| undefined`                                                                                   | The page in root folder `to` at the same file path that `page` has in root folder `from`.                    |
| `visit`            | `<R extends Node \| Root>(root: R, visitor: <T extends Node \| Root>(node: T, parent?: Root \| Folder) => "skip" \| "break" \| T \| void) => R` | Visits every node depth first. The visitor returns `skip`, `break`, or a node that replaces the current one. |
</Accordion>
</Accordions>

### `useDataRoute()` [#usedataroute]

Takes a [data route's](/routes#data-routes) path, as a string, a ref or a getter, and returns a ref of its value. The server sends the value with the page, so the page has it from its first render. For a path the page didn't receive, the value is `undefined` until it loads:

```vue title="src/components/Stars.vue"
<script setup lang="ts">
import { useDataRoute } from "vuesho/client";

const stars = useDataRoute<{ count: number }>("/api/stars.json");
</script>

<template>
  <span v-if="stars">{{ stars.count }} stars</span>
</template>
```

## Routes and Links [#routes-and-links]

### `Link` [#link]

A link on your site. A link to a page navigates without reloading the document, and loads the page when the reader hovers over it. A URL on another site opens in a new tab:

```vue title="src/components/GetStarted.vue"
<script setup lang="ts">
import { Link } from "vuesho/client";
</script>

<template>
  <Link href="/install">Get started</Link>
  <Link href="https://github.com/acme/docs">GitHub</Link>
</template>
```

A path starts from your site's root, and `Link` adds the [base path](/deploying#base-path):

### LinkProps

| Prop        | Type                   | Description                                                                                                                                                                                                   |
| ----------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `href?`     | `string \| undefined`  | A site path without the base path, a path relative to the page (`../api`), a hash, or a URL.                                                                                                                  |
| `external?` | `boolean \| undefined` | Whether the URL points to another site and opens in a new tab. By default, URLs with a scheme or `//` do.                                                                                                     |
| `prefetch?` | `boolean \| undefined` | Whether the page loads when the reader points at the link. Default: `true`                                                                                                                                    |
| `scroll?`   | `boolean \| undefined` | `true` scrolls to the URL's hash, or to the top, once the page shows, and `false` keeps the scroll position. By default, the page scrolls when the path or hash changes, but not when only the query changes. |

### `addBasePath()` [#addbasepath]

Adds the base path to a site path, for a URL that no `Link` renders, like a file in `public/`:

```vue title="src/components/Logo.vue"
<script setup lang="ts">
import { addBasePath } from "vuesho/client";
</script>

<template>
  <img :src="addBasePath('/logo.png')" alt="Acme" />
</template>
```

### `useRoute()` [#useroute]

The current page's route, as a reactive object. Its `path` has no base path, and `href` is the URL in the address bar:

### Route

| Prop     | Type                                 | Description                                                                 |
| -------- | ------------------------------------ | --------------------------------------------------------------------------- |
| `path`   | `string`                             | The page's path, without the base path.                                     |
| `query`  | `Record<string, string>`             | The URL's query. A repeated key has its last value.                         |
| `hash`   | `string`                             | The hash with its `#`, or an empty string.                                  |
| `params` | `Record<string, string \| string[]>` | The params of a custom page, a view, or a content page from a dynamic file. |
| `href`   | `string`                             | The URL in the address bar, with the base path, the query and the hash.     |

A page built to HTML has no query, so render a component that reads `query` only after the app mounts.

### `useRouter()` [#userouter]

The router, which navigates from code. `push()` and `replace()` take a site path, and `pending` is `true` while a page loads:

```vue title="src/components/VersionSelect.vue"
<script setup lang="ts">
import { useRouter } from "vuesho/client";

const router = useRouter();
const go = (event: Event) => router.push((event.target as HTMLSelectElement).value); // [!code highlight]
</script>

<template>
  <select aria-label="Version" @change="go">
    <option value="/docs">Latest</option>
    <option value="/v1/docs">v1</option>
  </select>
  <p v-if="router.pending.value" role="status">Loading…</p>
</template>
```

`{ scroll: false }` keeps the scroll position. `refresh()` reloads the current page from the server and keeps the position, for a [CMS](/content-sources/sanity)'s live preview. `beforeEach()` and `afterEach()` add [router hooks](/theme#router-hooks).

<Accordions>
<Accordion title="The router">
### Router

| Prop           | Type                                                           | Description                                                                                                                                                                              |
| -------------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `currentRoute` | `Readonly<ShallowRef<Route>>`                                  | The route of the page on screen.                                                                                                                                                         |
| `pending`      | `Readonly<ShallowRef<boolean>>`                                | Whether a navigation is loading its page.                                                                                                                                                |
| `resolve`      | `(href: string) => RouteLocation \| undefined`                 | Tells where a link leads, or gives `undefined` when it leaves the site.                                                                                                                  |
| `push`         | `(href: string, options?: NavigationOptions) => Promise<void>` | Goes to a site path, resolved from the page, in a new history entry. On failure, it loads the document.                                                                                  |
| `replace`      | `(href: string, options?: NavigationOptions) => Promise<void>` | Goes to a site path like `push`, replacing the current history entry.                                                                                                                    |
| `back`         | `() => void`                                                   | Goes to the previous entry, like the browser's back button.                                                                                                                              |
| `forward`      | `() => void`                                                   | Goes to the next entry, like the browser's forward button.                                                                                                                               |
| `prefetch`     | `(href: string) => void`                                       | Loads the page a link leads to, so navigating to it shows it at once, as `Link` does on hover.                                                                                           |
| `refresh`      | `() => Promise<void>`                                          | Loads the page on screen again from the server, with the page tree, as after a content change, and keeps the scroll position. The router hooks run as for a navigation to the same page. |
| `beforeEach`   | `(hook: BeforeEachHook) => () => void`                         | Adds a hook that runs before a page shows. Returns a function that removes it.                                                                                                           |
| `afterEach`    | `(hook: AfterEachHook) => () => void`                          | Adds a hook that runs once the app has moved to a page. Returns a function that removes it.                                                                                              |
</Accordion>
</Accordions>

## Layouts and Color Mode [#layouts-and-color-mode]

### `useColorMode()` [#usecolormode]

Returns the [color mode](/styling#color-mode) as two refs. `preference` is the reader's choice, `"light"`, `"dark"` or `"system"`, and a component can set it. `isDark` is whether the page is dark:

```vue title="src/components/ColorModeButton.vue"
<script setup lang="ts">
import { useColorMode } from "vuesho/client";

const { preference, isDark } = useColorMode();
</script>

<template>
  <button type="button" @click="preference = isDark ? 'light' : 'dark'">
    Switch the color mode
  </button>
</template>
```

`isDark` is `undefined` on the server and until the app is mounted, and so is `preference` unless the color mode is fixed. Style a page for dark mode with `.dark` in CSS, and use `isDark` for what a script draws, like a chart.

<Callout title="Fixed Color Modes">
When the color mode is fixed, or the page sets `colorMode`, setting `preference` keeps the reader's choice, which shows once the color mode isn't fixed.
</Callout>

### `useLayoutProps()` [#uselayoutprops]

A computed ref of the layout props for a layout component from `vuesho/ui`, like `DocsLayout`. It merges the props from the config, the themes and the plugins, and keeps only the props that the component declares. The second argument's props win, nested objects merge key by key, and a list like `links` replaces the shared one:

```ts
import { useLayoutProps } from "vuesho/client";
import { DocsLayout, type DocsLayoutProps } from "vuesho/ui/layouts/docs";

const layoutProps = useLayoutProps<DocsLayoutProps>(DocsLayout, {
  sidebar: { collapsible: false },
});
```

A layout built from UI parts binds them with `v-bind`, as [Building From UI Parts](/layouts#building-from-ui-parts) shows.

### Slot Composables [#slot-composables]

A custom layout renders the theme's [slots](/theme#slots) with these composables, one for each kind of slot:

```ts
import { useAddingSlot, useReplacingSlot, useWrappingSlot } from "vuesho/client";

// A component that renders every component in the slot, or `undefined` without any.
const PageBottom = useAddingSlot("page-bottom");
// The last component in the slot, or `undefined` without any.
const NavTitle = useReplacingSlot("nav-title");
// A component that renders its default slot inside every component in the slot.
const PageContent = useWrappingSlot("page-content");
```

## Components [#components]

### `Image` [#image]

An image, optimized and lazily loaded like [Markdown images](/markdown/images#image-component). `src` takes the URL that the browser requests: a Vite import, or a path in `public/` with the [base path](/deploying#base-path):

```vue title="src/components/Hero.vue"
<script setup lang="ts">
import { Image, addBasePath } from "vuesho/client";
</script>

<template>
  <Image :src="addBasePath('/hero.png')" alt="The editor" :width="1200" :height="630" preload />
</template>
```

## Pages [#pages]

### `definePage()` [#definepage]

Declares a [custom page's](/custom-pages) data and props. `definePage()` is a macro, so call it once, at the top level of the script, with an object literal that refers only to imports:

```vue title="src/pages/about.vue"
<script setup lang="ts">
import { definePage } from "vuesho/client";

definePage({ data: { title: "About", description: "Who writes these docs." } });
</script>
```

### `useBuildError()` [#usebuilderror]

Returns a function that fails `vuesho build` with an error from the current page, for a mistake that would otherwise show only on the deployed site. On a server, the page fails too, unless it renders on request. In the browser, the function does nothing:

```vue title="src/components/Video.vue"
<script setup lang="ts">
import { useBuildError } from "vuesho/client";

const props = defineProps<{ id?: string }>();
const fail = useBuildError();
if (!props.id) fail("<Video> needs the id of a video."); // [!code highlight]
</script>

<template>
  <iframe v-if="id" :src="`https://www.youtube-nocookie.com/embed/${id}`" title="Video" />
</template>
```
