# Twoslash

TypeScript type information in code blocks.

[Twoslash](https://twoslash.netlify.app) runs TypeScript on a code block when the site builds, and shows a name's type and doc comment in a popup on hover. Hover one below:

```ts twoslash
import { useColorMode } from "vuesho/client";

const { preference, isDark } = useColorMode();
```

## Setup [#setup]

### Install the Packages [#install-the-packages-step]

Twoslash needs TypeScript 6's JavaScript API, which TypeScript 7 doesn't have. `twoslash-vue` adds Vue support:

```npm
npm i -D @vuesho/twoslash twoslash-vue typescript@6
```

### Add the Plugin [#add-the-plugin-step]

```ts title="vuesho.config.ts"
import { createSite, recommendedPreset } from "vuesho/config";
import { defineDocs } from "vuesho/content";
import { twoslashPlugin } from "@vuesho/twoslash"; // [!code ++]

const docs = defineDocs();

export default createSite(docs.toSource()).plugins(
  recommendedPreset(),
  twoslashPlugin(), // [!code ++]
);
```

The plugin adds the popup styles, and works with any [highlighter](/markdown/code-blocks#other-highlighters).

### Write a Code Block [#write-a-code-block-step]

Add `twoslash` after the language of a `ts`, `tsx`, `js`, `jsx`, `json` or `vue` code block. Imports in the block resolve from the project root:

````md
```ts twoslash
const greeting = "Hello";
```
````

## Notations [#notations]

A Twoslash comment changes what the block shows, and doesn't appear in the output:

| Notation             | Result                                                                                              |
| -------------------- | --------------------------------------------------------------------------------------------------- |
| `// ^?`              | Shows the type of the name above the caret                                                          |
| `// ^\|`             | Shows the completions at the caret                                                                  |
| `// ^^^`             | Highlights the code above the carets                                                                |
| `// @log: text`      | Adds a message under the line above, and `@warn`, `@error` or `@annotate` adds one in another style |
| `// ---cut---`       | Hides the code above it, which is still type-checked                                                |
| `// @filename: a.ts` | Starts another file, which the next files can import                                                |
| `// @strict: false`  | Sets a `tsconfig.json` option for the block                                                         |
| `// @showEmit`       | Shows the JavaScript that TypeScript emits, instead of the code                                     |

```ts twoslash tab="Output"
// @noErrors
import { addBasePath } from "vuesho/client";

// @log: Adds the site's base path
const href = addBasePath("/guide");
//    ^?
href.toUpperCase();
//   ^^^^^^^^^^^
href.slic;
//       ^|
```

````md tab="Input"
```ts twoslash
// @noErrors
import { addBasePath } from "vuesho/client";

// @log: Adds the site's base path
const href = addBasePath("/guide");
//    ^?
href.toUpperCase();
//   ^^^^^^^^^^^
href.slic;
//       ^|
```
````

See the [Twoslash notation reference](https://twoslash.netlify.app/refs/notations) for every notation.

### Errors [#errors]

A type error fails the build at its line. `// @errors` lists the error codes to expect and show in the block, and `// @noErrors` hides every error:

```ts twoslash tab="Output"
// @errors: 2322
const count: number = "one";
```

````md tab="Input"
```ts twoslash
// @errors: 2322
const count: number = "one";
```
````

### Reusing Code [#reusing-code]

To reuse code in a later block on the page:

- `include <name>` after the language saves the block's code.
- `// @include: <name>` inserts it into a later block.
- A `// - <part>` line marks a part, and `// @include: <name>-<part>` inserts only the lines above it.

<Tabs :items='["Output","Input"]'>
<Tab value="Output">
```ts twoslash include setup
const user = { name: "Alice" };
// - user
const admin = { ...user, role: "admin" };
```

```ts twoslash
// @include: setup-user
// ---cut---
user.name;
// ^?
```
</Tab>

<Tab value="Input">
````md
```ts twoslash include setup
const user = { name: "Alice" };
// - user
const admin = { ...user, role: "admin" };
```

```ts twoslash
// @include: setup-user
// ---cut---
user.name;
// ^?
```
````
</Tab>
</Tabs>

## Vue Code Blocks [#vue-code-blocks]

A `vue` block is type-checked as a single-file component, including its `<template>`. A `tsx` or `jsx` block is checked as Vue JSX:

```vue twoslash tab="Output"
<script setup lang="ts">
import { useColorMode } from "vuesho/client";

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

<template>
  <p v-if="isDark">The page is dark.</p>
</template>
```

````md tab="Input"
```vue twoslash
<script setup lang="ts">
import { useColorMode } from "vuesho/client";

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

<template>
  <p v-if="isDark">The page is dark.</p>
</template>
```
````

## Options [#options]

`twoslashPlugin()` takes the options of [Shiki's Twoslash transformer](https://shiki.style/packages/twoslash), like `processHoverInfo`:

### TwoslashPluginOptions

| Prop                | Type                                                                                                                          | Description                                                                                                                           |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `langs?`            | `string[] \| undefined`                                                                                                       | The languages the transformer applies to. Default: `['ts', 'tsx', 'js', 'jsx', 'json', 'vue']`                                        |
| `explicitTrigger?`  | `boolean \| RegExp \| undefined`                                                                                              | Applies the transformer only to code blocks with `twoslash` in their meta. Default: `true`                                            |
| `twoslasher?`       | `TwoslashShikiFunction \| undefined`                                                                                          | A twoslasher instead of the one from `twoslash-vue`.                                                                                  |
| `twoslashOptions?`  | `CreateTwoslashVueOptions \| undefined`                                                                                       | The twoslasher's options, like `compilerOptions` and `vueCompilerOptions`.                                                            |
| `jsdoc?`            | `boolean \| undefined`                                                                                                        | Renders JSDoc comments in hover popups. Default: `true`                                                                               |
| `completionIcons?`  | `false \| Partial<Record<string, ElementContent>> \| undefined`                                                               | Icons for completion items by kind, instead of the defaults. `false` renders none.                                                    |
| `customTagIcons?`   | `false \| Partial<Record<string, ElementContent>> \| undefined`                                                               | Icons for custom tag lines by tag name, instead of the defaults. `false` renders none.                                                |
| `processHoverInfo?` | `((info: string) => string) \| undefined`                                                                                     | Formats the type info text, which might not be valid TypeScript. Default: `defaultHoverInfoProcessor`                                 |
| `processHoverDocs?` | `((docs: string) => string) \| undefined`                                                                                     | Formats the docs text, which is Markdown.                                                                                             |
| `disableTriggers?`  | `(string \| RegExp)[] \| undefined`                                                                                           | Triggers that skip Twoslash transformation on the code block meta Default: `['notwoslash', 'no-twoslash']`                            |
| `langAlias?`        | `Record<string, string> \| undefined`                                                                                         | Mapping from language alias to language name                                                                                          |
| `filter?`           | `((lang: string, code: string, options: CodeToHastOptions, context?: ShikiTransformerContextCommon) => boolean) \| undefined` | Custom filter function to apply this transformer to When specified, `langs`, `explicitTrigger`, and `disableTriggers` will be ignored |
| `includesMap?`      | `Map<string, string> \| undefined`                                                                                            | A map to store code for `@include` directive Provide your own instance if you want to clear the map between each transformation       |
| `throws?`           | `boolean \| undefined`                                                                                                        | Strictly throw when there is an error Default: `true`                                                                                 |
| `onTwoslashError?`  | `((error: unknown, code: string, lang: string, options: CodeToHastOptions) => string \| void) \| undefined`                   | Custom error handler for twoslash errors When specified, `throws` will be ignored Optionally return a string to replace the code      |
| `onShikiError?`     | `((error: unknown, code: string, lang: string) => void) \| undefined`                                                         | Custom error handler for Shiki errors When specified, `throws` will be ignored                                                        |
| `typesCache?`       | `TwoslashTypesCache \| undefined`                                                                                             | The options for caching resolved types                                                                                                |

### Caching [#caching]

`twoslashFileCache()` saves each block's types in `node_modules/.vuesho/twoslash`, or in the folder of `dir`, so the next build and `vuesho dev` read them instead of running TypeScript:

```ts title="vuesho.config.ts"
import { twoslashFileCache, twoslashPlugin } from "@vuesho/twoslash";

createSite(docs.toSource()).plugins(
  recommendedPreset(),
  twoslashPlugin({ typesCache: twoslashFileCache() }), // [!code highlight]
);
```

An edit of a block's code runs it again, but an edit of a type it imports or an upgrade of a dependency does not. After either, clear the folder before the next build:

```bash
rm -rf node_modules/.vuesho/twoslash
```

## Custom Popups [#custom-popups]

To change how the popups open, place your own `TwoslashPopups.vue` in `src/components/content/`. It receives the HTML of the block's popups, and in the code block, the button with the ID `` `${id}-${i}` `` opens popup `i`:

### TwoslashPopupsProps

| Prop     | Type       | Description                                                                                          |
| -------- | ---------- | ---------------------------------------------------------------------------------------------------- |
| `id`     | `string`   | The code block's ID. The trigger of popup `i`, a button in the code's HTML, has the ID `${id}-${i}`. |
| `popups` | `string[]` | The HTML of each of the code block's popups.                                                         |

This component opens each popup on click, in a [Reka UI](https://reka-ui.com) popover:

```vue title="src/components/content/TwoslashPopups.vue"
<script setup lang="ts">
import { onMounted, shallowRef } from "vue";
import { PopoverAnchor, PopoverContent, PopoverPortal, PopoverRoot } from "reka-ui";

const props = defineProps<{ id: string; popups: string[] }>();
const open = shallowRef<{ html: string; trigger: HTMLElement }>();

onMounted(() => {
  props.popups.forEach((html, i) => {
    const trigger = document.getElementById(`${props.id}-${i}`);
    trigger?.addEventListener("click", () => (open.value = { html, trigger })); // [!code highlight]
  });
});
</script>

<template>
  <PopoverRoot :open="!!open" @update:open="(value) => !value && (open = undefined)">
    <PopoverAnchor :reference="open?.trigger" />
    <PopoverPortal>
      <PopoverContent class="fd-twoslash-popover" side="bottom" :side-offset="4">
        <div v-html="open?.html" />
      </PopoverContent>
    </PopoverPortal>
  </PopoverRoot>
</template>
```

`fd-twoslash-popover` applies the default style to a popup. For popups that open on hover, use `Popup`, `PopupTrigger` and `PopupContent` from `@vuesho/twoslash/ui`.
