setup @headlessui/vue package

This commit is contained in:
Robin Malfait
2020-09-16 18:19:54 +02:00
parent 672afbe9f8
commit f20b7f845b
27 changed files with 4280 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
rules: {
'react-hooks/rules-of-hooks': 'off',
'react-hooks/exhaustive-deps': 'off',
},
}
+408
View File
@@ -0,0 +1,408 @@
<h3 align="center">
@headlessui/vue
</h3>
<p align="center">
A set of completely unstyled, fully accessible UI components for Vue 3, designed to integrate
beautifully with Tailwind CSS.
</p>
<p align="center">
<a href="https://www.npmjs.com/package/@headlessui/vue"><img src="https://img.shields.io/npm/dt/@headlessui/vue.svg" alt="Total Downloads"></a>
<a href="https://github.com/tailwindlabs/headlessui/releases"><img src="https://img.shields.io/npm/v/@headlessui/vue.svg" alt="Latest Release"></a>
<a href="https://github.com/tailwindlabs/headlessui/blob/master/LICENSE"><img src="https://img.shields.io/npm/l/@headlessui/vue.svg" alt="License"></a>
</p>
## Installation
Please note that **this library only supports Vue 3**.
```sh
# npm
npm install @headlessui/vue
# Yarn
yarn add @headlessui/vue
```
## Components
_This project is still in early development. New components will be added regularly over the coming months._
- [Menu Button](#menu-button-dropdown)
### Roadmap
This project is still in early development, but the plan is to build out all of the primitives we need to provide interactive Vue examples of all of the components included in [Tailwind UI](https://tailwindui.com), the commercial component directory that helps us fund the development of our open-source work like [Tailwind CSS](https://tailwindcss.com).
This includes things like:
- Listboxes
- Toggles
- Modals
- Tabs
- Slide-overs
- Mobile menus
- Accordions
...and more in the future.
We'll be continuing to develop new components on an on-going basis, with a goal of reaching a pretty fleshed out v1.0 by the end of the year.
## Menu Button (Dropdown)
[View complete demo on CodeSandbox](https://codesandbox.io/s/flamboyant-glade-b2jb4?file=/src/App.vue)
The `Menu` component and related child components are used to quickly build custom dropdown components that are fully accessible out of the box, including correct ARIA attribute management and robust keyboard navigation support.
- [Basic example](#basic-example)
- [Styling](#styling)
- [Transitions](#transitions)
- [Component API](#component-api)
### Basic example
Menu Buttons are built using the `Menu`, `MenuButton`, `MenuItems`, and `MenuItem` components.
The `MenuButton` will automatically open/close the `MenuItems` when clicked, and when the menu is open, the list of items receives focus and is automatically navigable via the keyboard.
```vue
<template>
<Menu>
<MenuButton>
More
</MenuButton>
<MenuItems>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings">
Account settings
</a>
</MenuItem>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings">
Documentation
</a>
</MenuItem>
<MenuItem v-slot="{ active }" disabled>
<span :class="{ 'bg-blue-500': active }">
Invite a friend (coming soon!)
</span>
</MenuItem>
</MenuItems>
</Menu>
</template>
<script>
import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'
export default {
components: {
Menu,
MenuButton,
MenuItems,
MenuItem,
},
}
</script>
```
### Styling the active item
This is a headless component so there are no styles included by default. Instead, the components expose useful information via [scoped slots](https://v3.vuejs.org/guide/component-slots.html#scoped-slots) that you can use to apply the styles you'd like to apply yourself.
To style the active `MenuItem` you can read the `active` slot prop, which tells you whether or not that menu item is the item that is currently focused via the mouse or keyboard.
You can use this state to conditionally apply whatever active/focus styles you like, for instance a blue background like is typical in most operating systems.
```vue
<template>
<Menu>
<MenuButton>
More
</MenuButton>
<MenuItems>
<!-- Use the `active` state to conditionally style the active item. -->
<MenuItem v-slot="{ active }">
<a href="/settings" :class="active ? 'bg-blue-500 text-white' : 'bg-white text-black'">
Settings
</a>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
### Showing/hiding the menu
By default, your `MenuItems` instance will be shown/hidden automatically based on the internal `open` state tracked within the `Menu` component itself.
```vue
<template>
<Menu>
<MenuButton>
More
</MenuButton>
<!-- By default, this will automatically show/hide when the MenuButton is pressed. -->
<MenuItems>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings">
Account settings
</a>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
If you'd rather handle this yourself (perhaps because you need to add an extra wrapper element for one reason or another), you can add a `static` prop to the `MenuItems` instance to tell it to always render, and inspect the `open` slot prop provided by the `Menu` to control which element is shown/hidden yourself.
```vue
<template>
<Menu v-slot="{ open }">
<MenuButton>
More
</MenuButton>
<div v-show="open">
<!-- Using `static`, `MenuItems` is always rendered and ignores the `open` state. -->
<MenuItems static>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings">
Account settings
</a>
</MenuItem>
<!-- ... -->
</MenuItems>
</div>
</Menu>
</template>
```
### Disabling an item
Use the `disabled` prop to disable a `MenuItem`. This will make it unselectable via keyboard navigation, and it will be skipped when pressing the up/down arrows.
```vue
<template>
<Menu>
<MenuButton>
More
</MenuButton>
<MenuItems>
<MenuItem disabled>
<span class="opacity-75">Invite a friend (coming soon!)</span>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
### Transitions
To animate the opening/closing of the menu panel, use Vue's built-in `transition` component. All you need to do is wrap your `MenuItems` instance in a `<transition>` element and the transition will be applied automatically.
```vue
<template>
<Menu>
<MenuButton>
More
</MenuButton>
<transition
enter-active-class="transition duration-100 ease-out"
enter-from-class="transform scale-95 opacity-0"
enter-to-class="transform scale-100 opacity-100"
leave-active-class="transition duration-75 ease-out"
leave-from-class="transform scale-100 opacity-100"
leave-to-class="transform scale-95 opacity-0"
>
<MenuItems>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings">
Account settings
</a>
</MenuItem>
<!-- ... -->
</MenuItems>
</transition>
</Menu>
</template>
```
### Rendering additional content
The `Menu` component is not limited to rendering only its related subcomponents. You can render anything you like within a menu, which gives you complete control over exactly what you are building.
For example, if you'd like to add a little header section to the menu with some extra information in it, just render an extra `div` with your content in it.
```vue
<template>
<Menu>
<MenuButton>
More
</MenuButton>
<MenuItems>
<div class="px-4 py-3">
<p class="text-sm leading-5">Signed in as</p>
<p class="text-sm font-medium leading-5 text-gray-900 truncate">tom@example.com</p>
</div>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings">
Account settings
</a>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
Note that only `MenuItem` instances will be navigable via the keyboard.
### Rendering a different element for a component
By default, the `Menu` and its subcomponents each render a default element that is sensible for that component.
For example, `MenuButton` renders a `button` by default, and `MenuItems` renders a `div`. `Menu` and `MenuItem` interestingly _do not render an extra element_, and instead render their children directly by default.
This is easy to change using the `as` prop, which exists on every component.
```vue
<template>
<!-- Render a `div` instead of no wrapper element -->
<Menu as="div">
<MenuButton>
More
</MenuButton>
<!-- Render a `ul` instead of a `div` -->
<MenuItems as="ul">
<!-- Render an `li` instead of no wrapper element -->
<MenuItem as="li" v-slot="{ active }">
<a href="/account-settings" :class="{ 'bg-blue-500': active }">
Account settings
</a>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
To tell an element to render its children directly with no wrapper element, use `as="template"`.
```vue
<template>
<Menu>
<!-- Render no wrapper, instead pass in a button manually -->
<MenuButton as="template">
<button>
More
</button>
</MenuButton>
<MenuItems>
<MenuItem v-slot="{ active }">
<a href="/account-settings" :class="{ 'bg-blue-500': active }">
Account settings
</a>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
### Component API
#### Menu
```vue
<Menu v-slot="{ open }">
<MenuButton>More options</MenuButton>
<MenuItems>
<MenuItem><!-- ... --></MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
```
##### Props
| Prop | Type | Default | Description |
| ---- | ------------------- | --------------------------------- | ---------------------------------------------------------- |
| `as` | String \| Component | `template` _(no wrapper element_) | The element or component the `MenuItems` should render as. |
##### Slot props
| Prop | Type | Description |
| ------ | ------- | -------------------------------- |
| `open` | Boolean | Whether or not the menu is open. |
#### MenuButton
```vue
<MenuButton v-slot="{ open }">
<span>More options</span>
<ChevronRightIcon :class="open ? 'transform rotate-90' : ''" />
</MenuButton>
```
##### Props
| Prop | Type | Default | Description |
| ---- | ------------------- | -------- | ---------------------------------------------------------- |
| `as` | String \| Component | `button` | The element or component the `MenuItems` should render as. |
##### Slot props
| Prop | Type | Description |
| ------ | ------- | -------------------------------- |
| `open` | Boolean | Whether or not the menu is open. |
#### MenuItems
```vue
<MenuItems>
<MenuItem><!-- ... --></MenuItem>
<!-- ... -->
</MenuItem>
```
##### Props
| Prop | Type | Default | Description |
| -------- | ------------------- | ------- | --------------------------------------------------------------------------- |
| `as` | String \| Component | `div` | The element or component the `MenuItems` should render as. |
| `static` | Boolean | `false` | Whether the element should ignore the internally managed open/closed state. |
##### Slot props
| Prop | Type | Description |
| ------ | ------- | -------------------------------- |
| `open` | Boolean | Whether or not the menu is open. |
#### MenuItem
```vue
<MenuItem v-slot="{ active }">
<a href="/settings" :class="active ? 'bg-blue-500 text-white' : 'bg-white text-black'">
Settings
</a>
</MenuItem>
```
##### Props
| Prop | Type | Default | Description |
| ---------- | ------------------- | --------------------------------- | ------------------------------------------------------------------------------------- |
| `as` | String \| Component | `template` _(no wrapper element)_ | The element or component the `MenuItem` should render as. |
| `disabled` | Boolean | `false` | Whether or not the item should be disabled for keyboard navigation and ARIA purposes. |
##### Slot props
| Prop | Type | Description |
| ---------- | ------- | ---------------------------------------------------------------------------------- |
| `active` | Boolean | Whether or not the item is the active/focused item in the list. |
| `disabled` | Boolean | Whether or not the item is the disabled for keyboard navigation and ARIA purposes. |
@@ -0,0 +1,4 @@
node_modules
.DS_Store
dist
*.local
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Headless UI - Playground</title>
<link rel="stylesheet" href="https://rsms.me/inter/inter.css" />
</head>
<body class="w-full h-full antialiased text-gray-900 font-sans">
<div class="h-full w-full" id="app"></div>
<script type="module" src="/examples/src/main.js"></script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

@@ -0,0 +1,35 @@
<template>
<div class="flex flex-col h-screen overflow-hidden font-sans antialiased text-gray-900 bg-white">
<header
class="relative z-10 flex items-center justify-between flex-shrink-0 px-4 py-4 bg-white border-b border-gray-200 sm:px-6 lg:px-8"
>
<a href="/">
<img
class="w-auto h-6"
src="https://tailwindui.com/img/tailwindui-logo.svg"
alt="Tailwind UI"
/>
</a>
</header>
<main class="flex-1 overflow-auto bg-gray-50">
<MenuWithPopper />
<!-- <MenuWithTailwind /> -->
<KeyCaster />
</main>
</div>
</template>
<script>
import KeyCaster from './KeyCaster.vue'
import MenuWithPopper from './components/menu-with-popper.vue'
import MenuWithTailwind from './components/menu-with-tailwind.vue'
export default {
name: 'App',
components: {
MenuWithPopper,
MenuWithTailwind,
KeyCaster,
},
}
</script>
@@ -0,0 +1,74 @@
<template>
<div
class="fixed z-50 px-4 py-2 overflow-hidden text-2xl tracking-wide text-blue-100 bg-blue-800 rounded-md shadow cursor-default pointer-events-none select-none right-4 bottom-4"
v-if="keys.length > 0"
>
{{
keys
.slice()
.reverse()
.join(' ')
}}
</div>
</template>
<script>
import { defineComponent, ref } from 'vue'
const isMac = navigator.userAgent.indexOf('Mac OS X') !== -1
const KeyDisplay = isMac
? {
ArrowUp: '↑',
ArrowDown: '↓',
ArrowLeft: '←',
ArrowRight: '→',
Home: '↖',
End: '↘',
Alt: '⌥',
CapsLock: '⇪',
Meta: '⌘',
Shift: '⇧',
Control: '⌃',
Backspace: '⌫',
Delete: '⌦',
Enter: '↵',
Escape: '⎋',
Tab: '⇥',
ShiftTab: '⇤',
PageUp: '⇞',
PageDown: '⇟',
' ': '␣',
}
: {
ArrowUp: '↑',
ArrowDown: '↓',
ArrowLeft: '←',
ArrowRight: '→',
Meta: 'Win',
Control: 'Ctrl',
Backspace: '⌫',
Delete: 'Del',
Escape: 'Esc',
PageUp: 'PgUp',
PageDown: 'PgDn',
' ': '␣',
}
export default defineComponent({
setup() {
const keys = ref([])
window.addEventListener('keydown', event => {
keys.value.unshift(
event.shiftKey && event.key !== 'Shift'
? KeyDisplay[`Shift${event.key}`] ?? event.key
: KeyDisplay[event.key] ?? event.key
)
setTimeout(() => keys.value.pop(), 2000)
})
return { keys }
},
})
</script>
@@ -0,0 +1,113 @@
<template>
<div class="flex justify-center w-screen h-full p-12 bg-gray-50">
<div class="relative inline-block text-left">
<Menu>
<span class="inline-flex rounded-md shadow-sm">
<MenuButton
ref="reference"
class="inline-flex justify-center w-full px-4 py-2 text-sm font-medium leading-5 text-gray-700 transition duration-150 ease-in-out bg-white border border-gray-300 rounded-md hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:bg-gray-50 active:text-gray-800"
>
<span>Options</span>
<svg class="w-5 h-5 ml-2 -mr-1" viewBox="0 0 20 20" fill="currentColor">
<path
fillRule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clipRule="evenodd"
/>
</svg>
</MenuButton>
</span>
<transition
enter-active-class="transition-opacity duration-100 ease-out"
enter-from-class="transform scale-95 opacity-0"
enter-to-class="transform scale-100 opacity-100"
leave-active-class="transition-opacity duration-75 ease-out"
leave-from-class="transform scale-100 opacity-100"
leave-to-class="transform scale-95 opacity-0"
>
<MenuItems
ref="popper"
class="absolute right-0 w-56 origin-top-right bg-white border border-gray-200 divide-y divide-gray-100 rounded-md shadow-lg outline-none"
>
<div class="px-4 py-3">
<p class="text-sm leading-5">Signed in as</p>
<p class="text-sm font-medium leading-5 text-gray-900 truncate">tom@example.com</p>
</div>
<div class="py-1">
<MenuItem as="a" :className="resolveClass" href="#account-settings">
Account Settings
</MenuItem>
<MenuItem v-slot="data">
<a href="#support" :class="resolveClass(data)">Support</a>
</MenuItem>
<MenuItem as="a" :className="resolveClass" disabled href="#new-feature">
New feature (soon)
</MenuItem>
<MenuItem as="a" :className="resolveClass" href="#license">License</MenuItem>
</div>
<div class="py-1">
<MenuItem as="a" :className="resolveClass" href="#sign-out">Sign out</MenuItem>
</div>
</MenuItems>
</transition>
</Menu>
</div>
</div>
</template>
<script>
import { defineComponent, h, ref, onMounted, watchEffect, watch } from 'vue'
import { createPopper } from '@popperjs/core'
import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'
function classNames(...classes) {
return classes.filter(Boolean).join(' ')
}
function usePopper(options) {
const reference = ref(null)
const popper = ref(null)
onMounted(() => {
watchEffect(onInvalidate => {
const popperEl = popper.value.el || popper.value
const referenceEl = reference.value.el || reference.value
if (!(referenceEl instanceof HTMLElement)) return
if (!(popperEl instanceof HTMLElement)) return
const { destroy } = createPopper(referenceEl, popperEl, options)
onInvalidate(destroy)
})
})
return [reference, popper]
}
export default {
components: { Menu, MenuButton, MenuItems, MenuItem },
setup(props, context) {
const [reference, popper] = usePopper({
placement: 'bottom-end',
strategy: 'fixed',
modifiers: [{ name: 'offset', options: { offset: [0, 10] } }],
})
return {
reference,
popper,
resolveClass({ active, disabled }) {
return classNames(
'flex justify-between w-full px-4 py-2 text-sm leading-5 text-left',
active ? 'bg-gray-100 text-gray-900' : 'text-gray-700',
disabled && 'cursor-not-allowed opacity-50'
)
},
}
},
}
</script>
@@ -0,0 +1,93 @@
<template>
<div class="flex justify-center w-screen h-full p-12 bg-gray-50">
<div class="relative inline-block text-left">
<Menu>
<span class="rounded-md shadow-sm">
<MenuButton
class="inline-flex justify-center w-full px-4 py-2 text-sm font-medium leading-5 text-gray-700 transition duration-150 ease-in-out bg-white border border-gray-300 rounded-md hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:bg-gray-50 active:text-gray-800"
>
<span>Options</span>
<svg class="w-5 h-5 ml-2 -mr-1" viewBox="0 0 20 20" fill="currentColor">
<path
fillRule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clipRule="evenodd"
/>
</svg>
</MenuButton>
</span>
<transition
enter-active-class="transition duration-100 ease-out"
enter-from-class="transform scale-95 opacity-0"
enter-to-class="transform scale-100 opacity-100"
leave-active-class="transition duration-75 ease-out"
leave-from-class="transform scale-100 opacity-100"
leave-to-class="transform scale-95 opacity-0"
>
<MenuItems
class="absolute right-0 w-56 mt-2 origin-top-right bg-white border border-gray-200 divide-y divide-gray-100 rounded-md shadow-lg outline-none"
>
<div class="px-4 py-3">
<p class="text-sm leading-5">Signed in as</p>
<p class="text-sm font-medium leading-5 text-gray-900 truncate">tom@example.com</p>
</div>
<div class="py-1">
<CustomMenuItem href="#account-settings">Account Settings</CustomMenuItem>
<CustomMenuItem href="#support">Support</CustomMenuItem>
<CustomMenuItem disabled href="#new-feature">New feature (soon)</CustomMenuItem>
<CustomMenuItem href="#license">License</CustomMenuItem>
</div>
<div class="py-1">
<CustomMenuItem href="#sign-out">Sign out</CustomMenuItem>
</div>
</MenuItems>
</transition>
</Menu>
</div>
</div>
</template>
<script>
import { defineComponent, h } from 'vue'
import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'
function classNames(...classes) {
return classes.filter(Boolean).join(' ')
}
const CustomMenuItem = defineComponent({
components: { Menu, MenuButton, MenuItems, MenuItem },
setup(props, { slots }) {
return () => {
return h(MenuItem, ({ active, disabled }) => {
return h(
'a',
{
class: classNames(
'flex justify-between w-full text-left px-4 py-2 text-sm leading-5',
active ? 'bg-indigo-500 text-white' : 'text-gray-700',
disabled && 'cursor-not-allowed opacity-50'
),
},
[
h('span', { class: classNames(active && 'font-bold') }, slots.default()),
h('kbd', { class: classNames('font-sans', active && 'text-indigo-50') }, '⌘K'),
]
)
})
}
},
})
export default {
components: {
Menu,
MenuButton,
MenuItems,
MenuItem,
CustomMenuItem,
},
}
</script>
@@ -0,0 +1,6 @@
import { createApp } from 'vue'
import App from './App.vue'
import 'tailwindcss/tailwind.css'
createApp(App).mount('#app')
+42
View File
@@ -0,0 +1,42 @@
{
"name": "@headlessui/vue",
"version": "0.0.0",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"module": "dist/headlessui.esm.js",
"license": "MIT",
"files": [
"dist"
],
"engines": {
"node": ">=10"
},
"repository": {
"type": "git",
"url": "git+https://github.com/tailwindlabs/headlessui.git",
"directory": "packages/@headlessui-vue"
},
"publishConfig": {
"access": "public"
},
"scripts": {
"playground": "vite",
"build": "../../scripts/build.sh",
"test": "../../scripts/test.sh",
"lint": "../../scripts/lint.sh"
},
"devDependencies": {
"@popperjs/core": "^2.4.4",
"@tailwindcss/ui": "^0.6.0",
"@testing-library/vue": "^5.0.4",
"@types/debounce": "^1.2.0",
"@types/node": "^14.6.4",
"@vue/compiler-sfc": "^3.0.0-rc.10",
"@vue/test-utils": "^2.0.0-beta.4",
"husky": "^4.3.0",
"tailwindcss": "^1.8.8",
"tsdx": "^0.13.3",
"vite": "^1.0.0-rc.4",
"vue": "^3.0.0-rc.10"
}
}
@@ -0,0 +1 @@
module.exports = require('../../postcss.config.js')
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,491 @@
import {
defineComponent,
ref,
provide,
inject,
onMounted,
onUnmounted,
computed,
nextTick,
InjectionKey,
Ref,
} from 'vue'
import { match } from '../../utils/match'
import { render } from '../../utils/render'
import { useId } from '../../hooks/use-id'
enum MenuStates {
Open,
Closed,
}
// TODO: This must already exist somewhere, right? 🤔
// Ref: https://www.w3.org/TR/uievents-key/#named-key-attribute-values
enum Key {
Space = ' ',
Enter = 'Enter',
Escape = 'Escape',
Backspace = 'Backspace',
ArrowUp = 'ArrowUp',
ArrowDown = 'ArrowDown',
Home = 'Home',
End = 'End',
PageUp = 'PageUp',
PageDown = 'PageDown',
Tab = 'Tab',
}
enum Focus {
FirstItem,
PreviousItem,
NextItem,
LastItem,
SpecificItem,
Nothing,
}
type MenuItemDataRef = Ref<{ textValue: string; disabled: boolean }>
type StateDefinition = {
// State
menuState: Ref<MenuStates>
buttonRef: Ref<HTMLButtonElement | null>
itemsRef: Ref<HTMLDivElement | null>
items: Ref<{ id: string; dataRef: MenuItemDataRef }[]>
searchQuery: Ref<string>
activeItemIndex: Ref<number | null>
// State mutators
toggleMenu(): void
closeMenu(): void
openMenu(): void
goToItem(focus: Focus, id?: string): void
search(value: string): void
clearSearch(): void
registerItem(id: string, dataRef: MenuItemDataRef): void
unregisterItem(id: string): void
}
const MenuContext = Symbol('MenuContext') as InjectionKey<StateDefinition>
function useMenuContext(component: string) {
const context = inject(MenuContext)
if (context === undefined) {
const err = new Error(`<${component} /> is missing a parent <Menu /> component.`)
if (Error.captureStackTrace) Error.captureStackTrace(err, useMenuContext)
throw err
}
return context
}
export const Menu = defineComponent({
props: { as: { type: [Object, String], default: 'template' } },
setup(props, { slots, attrs }) {
const menuState = ref<StateDefinition['menuState']['value']>(MenuStates.Closed)
const buttonRef = ref<StateDefinition['buttonRef']['value']>(null)
const itemsRef = ref<StateDefinition['itemsRef']['value']>(null)
const items = ref<StateDefinition['items']['value']>([])
const searchQuery = ref<StateDefinition['searchQuery']['value']>('')
const activeItemIndex = ref<StateDefinition['activeItemIndex']['value']>(null)
function calculateActiveItemIndex(focus: Focus, id?: string) {
if (items.value.length <= 0) return null
const currentActiveItemIndex = activeItemIndex.value ?? -1
const nextActiveIndex = match(focus, {
[Focus.FirstItem]: () => items.value.findIndex(item => !item.dataRef.disabled),
[Focus.PreviousItem]: () => {
const idx = items.value
.slice()
.reverse()
.findIndex((item, idx, all) => {
if (currentActiveItemIndex !== -1 && all.length - idx - 1 >= currentActiveItemIndex)
return false
return !item.dataRef.disabled
})
if (idx === -1) return idx
return items.value.length - 1 - idx
},
[Focus.NextItem]: () => {
return items.value.findIndex((item, idx) => {
if (idx <= currentActiveItemIndex) return false
return !item.dataRef.disabled
})
},
[Focus.LastItem]: () => {
const idx = items.value
.slice()
.reverse()
.findIndex(item => !item.dataRef.disabled)
if (idx === -1) return idx
return items.value.length - 1 - idx
},
[Focus.SpecificItem]: () => items.value.findIndex(item => item.id === id),
[Focus.Nothing]: () => null,
})
if (nextActiveIndex === -1) return activeItemIndex.value
return nextActiveIndex
}
const api = {
menuState,
buttonRef,
itemsRef,
items,
searchQuery,
activeItemIndex,
toggleMenu() {
menuState.value = match(menuState.value, {
[MenuStates.Closed]: MenuStates.Open,
[MenuStates.Open]: MenuStates.Closed,
})
},
closeMenu: () => (menuState.value = MenuStates.Closed),
openMenu: () => (menuState.value = MenuStates.Open),
goToItem(focus: Focus, id?: string) {
const nextActiveItemIndex = calculateActiveItemIndex(focus, id)
if (searchQuery.value === '' && activeItemIndex.value === nextActiveItemIndex) return
searchQuery.value = ''
activeItemIndex.value = nextActiveItemIndex
},
search(value: string) {
searchQuery.value += value
const match = items.value.findIndex(
item => item.dataRef.textValue.startsWith(searchQuery.value) && !item.dataRef.disabled
)
if (match === -1 || match === activeItemIndex.value) {
return
}
activeItemIndex.value = match
},
clearSearch() {
searchQuery.value = ''
},
registerItem(id: string, dataRef: MenuItemDataRef) {
// @ts-expect-error The expected type comes from property 'dataRef' which is declared here on type '{ id: string; dataRef: { textValue: string; disabled: boolean; }; }'
items.value.push({ id, dataRef })
},
unregisterItem(id: string) {
const nextItems = items.value.slice()
const currentActiveItem =
activeItemIndex.value !== null ? nextItems[activeItemIndex.value] : null
const idx = nextItems.findIndex(a => a.id === id)
if (idx !== -1) nextItems.splice(idx, 1)
items.value = nextItems
activeItemIndex.value = (() => {
if (idx === activeItemIndex.value) return null
if (currentActiveItem === null) return null
// If we removed the item before the actual active index, then it would be out of sync. To
// fix this, we will find the correct (new) index position.
return nextItems.indexOf(currentActiveItem)
})()
},
}
onMounted(() => {
function handler(event: PointerEvent) {
if (event.defaultPrevented) return
if (menuState.value !== MenuStates.Open) return
if (!itemsRef.value?.contains(event.target as HTMLElement)) {
api.closeMenu()
nextTick(() => buttonRef.value?.focus())
}
}
window.addEventListener('pointerdown', handler)
onUnmounted(() => window.removeEventListener('pointerdown', handler))
})
// @ts-expect-error Types of property 'dataRef' are incompatible.
provide(MenuContext, api)
return () => {
const slot = { open: menuState.value === MenuStates.Open }
return render({ props, slot, slots, attrs })
}
},
})
export const MenuButton = defineComponent({
props: { as: { type: [Object, String], default: 'button' } },
render() {
const api = useMenuContext('MenuButton')
const slot = { open: api.menuState.value === MenuStates.Open }
const propsWeControl = {
ref: 'el',
id: this.id,
type: 'button',
'aria-haspopup': true,
'aria-controls': api.itemsRef.value?.id,
'aria-expanded': api.menuState.value === MenuStates.Open ? true : undefined,
onKeyDown: this.handleKeyDown,
onFocus: this.handleFocus,
onPointerUp: this.handlePointerUp,
onPointerDown: this.handlePointerDown,
}
return render({
props: { ...this.$props, ...propsWeControl },
slot,
attrs: this.$attrs,
slots: this.$slots,
})
},
setup() {
const api = useMenuContext('MenuButton')
const id = `headlessui-menu-button-${useId()}`
function handleKeyDown(event: KeyboardEvent) {
switch (event.key) {
// Ref: https://www.w3.org/TR/wai-aria-practices-1.2/#keyboard-interaction-13
case Key.Space:
case Key.Enter:
case Key.ArrowDown:
event.preventDefault()
api.openMenu()
nextTick(() => {
api.itemsRef.value?.focus()
api.goToItem(Focus.FirstItem)
})
break
case Key.ArrowUp:
event.preventDefault()
api.openMenu()
nextTick(() => {
api.itemsRef.value?.focus()
api.goToItem(Focus.LastItem)
})
break
}
}
function handlePointerDown(event: PointerEvent) {
// We have a `pointerdown` event listener in the menu for the 'outside click', so we just want
// to prevent going there if we happen to click this button.
event.preventDefault()
}
function handlePointerUp() {
api.toggleMenu()
nextTick(() => api.itemsRef.value?.focus())
}
function handleFocus() {
if (api.menuState.value === MenuStates.Open) api.itemsRef.value?.focus()
}
return {
id,
el: api.buttonRef,
handleKeyDown,
handlePointerDown,
handlePointerUp,
handleFocus,
}
},
})
export const MenuItems = defineComponent({
props: {
as: { type: [Object, String], default: 'div' },
static: { type: Boolean, default: false },
},
render() {
const api = useMenuContext('MenuItems')
// `static` is a reserved keyword, therefore aliasing it...
const { static: isStatic, ...passThroughProps } = this.$props
if (!isStatic && api.menuState.value === MenuStates.Closed) return null
const slot = { open: api.menuState.value === MenuStates.Open }
const propsWeControl = {
'aria-activedescendant':
api.activeItemIndex.value === null
? undefined
: api.items.value[api.activeItemIndex.value]?.id,
'aria-labelledby': api.buttonRef.value?.id,
id: this.id,
onKeyDown: this.handleKeyDown,
role: 'menu',
tabIndex: 0,
ref: 'el',
}
return render({
props: { ...passThroughProps, ...propsWeControl },
slot,
attrs: this.$attrs,
slots: this.$slots,
})
},
setup() {
const api = useMenuContext('MenuItems')
const id = `headlessui-menu-items-${useId()}`
const searchDebounce = ref<ReturnType<typeof setTimeout> | null>(null)
function handleKeyDown(event: KeyboardEvent) {
if (searchDebounce.value) clearTimeout(searchDebounce.value)
switch (event.key) {
// Ref: https://www.w3.org/TR/wai-aria-practices-1.2/#keyboard-interaction-12
case Key.Enter:
api.closeMenu()
if (api.activeItemIndex.value !== null) {
const { id } = api.items.value[api.activeItemIndex.value]
document.getElementById(id)?.click()
nextTick(() => api.buttonRef.value?.focus())
}
break
case Key.ArrowDown:
return api.goToItem(Focus.NextItem)
case Key.ArrowUp:
return api.goToItem(Focus.PreviousItem)
case Key.Home:
case Key.PageUp:
return api.goToItem(Focus.FirstItem)
case Key.End:
case Key.PageDown:
return api.goToItem(Focus.LastItem)
case Key.Escape:
api.closeMenu()
nextTick(() => api.buttonRef.value?.focus())
break
case Key.Tab:
return event.preventDefault()
default:
if (event.key.length === 1) {
api.search(event.key)
searchDebounce.value = setTimeout(() => api.clearSearch(), 350)
}
break
}
}
return {
id,
el: api.itemsRef,
handleKeyDown,
}
},
})
export const MenuItem = defineComponent({
props: {
as: { type: [Object, String], default: 'template' },
disabled: { type: Boolean, default: false },
class: { type: [String, Function], required: false },
className: { type: [String, Function], required: false },
onClick: { type: Function, required: false },
},
setup(props, { slots, attrs }) {
const api = useMenuContext('MenuItem')
const id = `headlessui-menu-item-${useId()}`
const { disabled, class: defaultClass, className = defaultClass } = props
const active = computed(() => {
return api.activeItemIndex.value !== null
? api.items.value[api.activeItemIndex.value].id === id
: false
})
const dataRef = ref<MenuItemDataRef['value']>({ disabled: disabled, textValue: '' })
onMounted(() => {
const textValue = document
.getElementById(id)
?.textContent?.toLowerCase()
.trim()
if (textValue !== undefined) dataRef.value.textValue = textValue
})
onMounted(() => api.registerItem(id, dataRef))
onUnmounted(() => api.unregisterItem(id))
function handlePointerEnter() {
if (disabled) return
api.goToItem(Focus.SpecificItem, id)
}
function handleFocus() {
if (disabled) return api.goToItem(Focus.Nothing)
api.goToItem(Focus.SpecificItem, id)
}
function handlePointerLeave() {
if (disabled) return
api.goToItem(Focus.Nothing)
}
function handleMouseMove() {
if (disabled) return
if (active.value) return
api.goToItem(Focus.SpecificItem, id)
}
function handlePointerUp(event: PointerEvent) {
if (disabled) return
event.preventDefault()
api.closeMenu()
nextTick(() => api.buttonRef.value?.focus())
}
function handleClick(event: MouseEvent) {
if (disabled) return event.preventDefault()
if (props.onClick) return props.onClick(event)
}
return () => {
const slot = { active: active.value, disabled }
const propsWeControl = {
id,
role: 'menuitem',
tabIndex: -1,
class: resolvePropValue(className, slot),
disabled: disabled === true ? disabled : undefined,
'aria-disabled': disabled === true ? disabled : undefined,
onClick: handleClick,
onFocus: handleFocus,
onMouseMove: handleMouseMove,
onPointerEnter: handlePointerEnter,
onPointerLeave: handlePointerLeave,
onPointerUp: handlePointerUp,
}
return render({
props: { ...props, ...propsWeControl },
slot,
attrs,
slots,
})
}
},
})
function resolvePropValue<TProperty, TBag>(property: TProperty, bag: TBag) {
if (property === undefined) return undefined
if (typeof property === 'function') return property(bag)
return property
}
@@ -0,0 +1,14 @@
if (process.env.JEST_WORKER_ID !== undefined) {
beforeEach(() => {
id = 0
})
}
let id = 0
function generateId() {
return ++id
}
export function useId() {
return generateId()
}
@@ -0,0 +1,15 @@
import * as HeadlessUI from './index'
/**
* Looks a bit of a silly test, however this ensures that we don't accidentally expose something to
* the outside world that we didn't want!
*/
it('should expose the correct components', () => {
expect(Object.keys(HeadlessUI)).toEqual([
// Menu
'Menu',
'MenuButton',
'MenuItems',
'MenuItem',
])
})
+1
View File
@@ -0,0 +1 @@
export * from './components/menu/menu'
@@ -0,0 +1,158 @@
export enum MenuButtonState {
Open,
Closed,
}
export enum MenuState {
Open,
Closed,
}
type MenuButtonOptions = { attributes?: Record<string, string | null>; textContent?: string } & (
| { state: MenuButtonState.Closed }
| { state: MenuButtonState.Open }
)
export function assertMenuButton(button: HTMLElement | null, options: MenuButtonOptions) {
try {
if (button === null) return expect(button).not.toBe(null)
// Ensure menu button have these properties
expect(button.hasAttribute('id')).toBe(true)
expect(button.hasAttribute('aria-haspopup')).toBe(true)
if (options.state === MenuButtonState.Open) {
expect(button.hasAttribute('aria-controls')).toBe(true)
expect(button.getAttribute('aria-expanded')).toBe('true')
}
if (options.state === MenuButtonState.Closed) {
expect(button.getAttribute('aria-controls')).toBeNull()
expect(button.getAttribute('aria-expanded')).toBeNull()
}
if (options.textContent) {
expect(button.textContent?.trim()).toBe(options.textContent.trim())
}
// Ensure menu button has the following attributes
for (let attributeName in options.attributes) {
expect(button.getAttribute(attributeName)).toEqual(options.attributes[attributeName])
}
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, assertMenuButton)
throw err
}
}
export function assertMenuButtonLinkedWithMenu(
button: HTMLElement | null,
menu: HTMLElement | null
) {
try {
if (button === null) return expect(button).not.toBe(null)
if (menu === null) return expect(menu).not.toBe(null)
// Ensure link between button & menu is correct
expect(button.getAttribute('aria-controls')).toBe(menu.getAttribute('id'))
expect(menu.getAttribute('aria-labelledby')).toBe(button.getAttribute('id'))
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, assertMenuButtonLinkedWithMenu)
throw err
}
}
export function assertMenuLinkedWithMenuItem(menu: HTMLElement | null, item: HTMLElement | null) {
try {
if (menu === null) return expect(menu).not.toBe(null)
if (item === null) return expect(item).not.toBe(null)
// Ensure link between menu & menu item is correct
expect(menu.getAttribute('aria-activedescendant')).toBe(item.getAttribute('id'))
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, assertMenuLinkedWithMenuItem)
throw err
}
}
export function assertNoActiveMenuItem(menu: HTMLElement | null) {
try {
if (menu === null) return expect(menu).not.toBe(null)
// Ensure we don't have an active menu
expect(menu.hasAttribute('aria-activedescendant')).toBe(false)
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, assertNoActiveMenuItem)
throw err
}
}
type MenuOptions = { attributes?: Record<string, string | null> } & (
| { state: MenuState.Closed }
| { state: MenuState.Open }
)
export function assertMenu(menu: HTMLElement | null, options: MenuOptions) {
try {
if (options.state === MenuState.Open) {
if (menu === null) return expect(menu).not.toBe(null)
// Check that some attributes exists, doesn't really matter what the values are at this point in
// time, we just require them.
expect(menu.hasAttribute('aria-labelledby')).toBe(true)
// Check that we have the correct values for certain attributes
expect(menu.getAttribute('role')).toBe('menu')
// Check that the menu is focused
expect(document.activeElement).toBe(menu)
// Ensure menu button has the following attributes
for (let attributeName in options.attributes) {
expect(menu.getAttribute(attributeName)).toEqual(options.attributes[attributeName])
}
}
if (options.state === MenuState.Closed) {
expect(menu).toBeNull()
}
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, assertMenu)
throw err
}
}
type MenuItemOptions = { tag: string; attributes?: Record<string, string | null> }
export function assertMenuItem(item: HTMLElement | null, options?: MenuItemOptions) {
try {
if (item === null) return expect(item).not.toBe(null)
// Check that some attributes exists, doesn't really matter what the values are at this point in
// time, we just require them.
expect(item.hasAttribute('id')).toBe(true)
// Check that we have the correct values for certain attributes
expect(item.getAttribute('role')).toBe('menuitem')
expect(item.getAttribute('tabindex')).toBe('-1')
if (options?.tag) {
expect(item.tagName.toLowerCase()).toBe(options.tag)
}
// Ensure menu item has the following attributes
for (let attributeName in options?.attributes) {
expect(item.getAttribute(attributeName)).toEqual(options?.attributes[attributeName])
}
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, assertMenuItem)
throw err
}
}
export function assertActiveElement(element: HTMLElement | null) {
try {
if (element === null) return expect(element).not.toBe(null)
expect(document.activeElement).toBe(element)
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, assertActiveElement)
throw err
}
}
@@ -0,0 +1,130 @@
import { nextTick } from 'vue'
import { fireEvent } from '@testing-library/dom'
export const Keys: Record<string, Partial<KeyboardEvent>> = {
Space: { key: ' ' },
Enter: { key: 'Enter' },
Escape: { key: 'Escape' },
Backspace: { key: 'Backspace' },
ArrowUp: { key: 'ArrowUp' },
ArrowDown: { key: 'ArrowDown' },
Home: { key: 'Home' },
End: { key: 'End' },
PageUp: { key: 'PageUp' },
PageDown: { key: 'PageDown' },
Tab: { key: 'Tab' },
}
export function shift(event: Partial<KeyboardEvent>) {
return { ...event, shiftKey: true }
}
export function word(input: string): Partial<KeyboardEvent>[] {
return input.split('').map(key => ({ key }))
}
export async function type(events: Partial<KeyboardEvent>[]) {
jest.useFakeTimers()
try {
if (document.activeElement === null) return expect(document.activeElement).not.toBe(null)
const element = document.activeElement
events.forEach(event => {
fireEvent.keyDown(element, event)
})
// We don't want to actually wait in our tests, so let's advance
jest.runAllTimers()
await new Promise<void>(nextTick)
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, type)
throw err
} finally {
jest.useRealTimers()
}
}
export async function press(event: Partial<KeyboardEvent>) {
return type([event])
}
export async function click(element: Document | Element | Window | null) {
try {
if (element === null) return expect(element).not.toBe(null)
fireEvent.pointerDown(element)
fireEvent.mouseDown(element)
fireEvent.pointerUp(element)
fireEvent.mouseUp(element)
fireEvent.click(element)
await new Promise<void>(nextTick)
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, click)
throw err
}
}
export async function focus(element: Document | Element | Window | null) {
try {
if (element === null) return expect(element).not.toBe(null)
fireEvent.focus(element)
await new Promise<void>(nextTick)
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, focus)
throw err
}
}
export async function mouseMove(element: Document | Element | Window | null) {
try {
if (element === null) return expect(element).not.toBe(null)
fireEvent.mouseMove(element)
await new Promise<void>(nextTick)
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, mouseMove)
throw err
}
}
export async function hover(element: Document | Element | Window | null) {
try {
if (element === null) return expect(element).not.toBe(null)
fireEvent.pointerOver(element)
fireEvent.pointerEnter(element)
fireEvent.mouseOver(element)
await new Promise<void>(nextTick)
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, hover)
throw err
}
}
export async function unHover(element: Document | Element | Window | null) {
try {
if (element === null) return expect(element).not.toBe(null)
fireEvent.pointerOut(element)
fireEvent.pointerLeave(element)
fireEvent.mouseOut(element)
fireEvent.mouseLeave(element)
await new Promise<void>(nextTick)
} catch (err) {
if (Error.captureStackTrace) Error.captureStackTrace(err, unHover)
throw err
}
}
@@ -0,0 +1,17 @@
type FunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends (...args: any[]) => any ? K : never
}[keyof T] &
string
export function suppressConsoleLogs<T extends unknown[]>(
cb: (...args: T) => void,
type: FunctionPropertyNames<typeof global.console> = 'warn'
) {
return (...args: T) => {
const spy = jest.spyOn(global.console, type).mockImplementation(jest.fn())
return new Promise<void>((resolve, reject) => {
Promise.resolve(cb(...args)).then(resolve, reject)
}).finally(() => spy.mockRestore())
}
}
@@ -0,0 +1,53 @@
import { mount } from '@vue/test-utils'
import { logDOM, fireEvent } from '@testing-library/dom'
const mountedWrappers = new Set()
export function render(
TestComponent: any,
options?: Omit<Parameters<typeof mount>[1], 'attachTo'>
) {
const div = document.createElement('div')
const baseElement = document.body
const container = baseElement.appendChild(div)
const attachTo = document.createElement('div')
container.appendChild(attachTo)
const wrapper = mount(TestComponent, {
...options,
attachTo,
})
mountedWrappers.add(wrapper)
container.appendChild(wrapper.element)
return {
debug() {
logDOM(div)
},
}
}
function cleanup() {
mountedWrappers.forEach(cleanupAtWrapper)
}
function cleanupAtWrapper(wrapper) {
if (wrapper.element.parentNode && wrapper.element.parentNode.parentNode === document.body) {
document.body.removeChild(wrapper.element.parentNode)
}
try {
wrapper.unmount()
} catch {
} finally {
mountedWrappers.delete(wrapper)
}
}
if (typeof afterEach === 'function') {
afterEach(() => cleanup())
}
export { fireEvent }
@@ -0,0 +1,24 @@
export function match<TValue extends string | number = string, TReturnValue = unknown>(
value: TValue,
lookup: Record<TValue, TReturnValue | ((...args: any[]) => TReturnValue)>,
...args: any[]
): TReturnValue {
if (value in lookup) {
const returnValue = lookup[value]
return typeof returnValue === 'function' ? returnValue(...args) : returnValue
}
const error = new Error(
`Tried to handle "${value}" but there is no handler defined. Only defined handlers are: ${Object.keys(
lookup
)
.map(key => `"${key}"`)
.join(', ')}.`
)
if (Error.captureStackTrace) {
Error.captureStackTrace(error, match)
}
throw error
}
@@ -0,0 +1,32 @@
import { h, cloneVNode, Slots } from 'vue'
export function render({
props,
attrs,
slots,
slot,
}: {
props: Record<string, any>
slot: Record<string, any>
attrs: Record<string, any>
slots: Slots
}) {
const { as, ...passThroughProps } = props
const children = slots.default?.(slot)
if (as === 'template') {
if (Object.keys(passThroughProps).length > 0 || 'class' in attrs) {
const [firstChild, ...other] = children ?? []
if (other.length > 0)
throw new Error('You should only render 1 child or use the `as="..."` prop')
return cloneVNode(firstChild, passThroughProps as Record<string, any>)
}
return children
}
return h(as, passThroughProps, children)
}
@@ -0,0 +1 @@
module.exports = require('../../tailwind.config.js')
+32
View File
@@ -0,0 +1,32 @@
{
"include": ["src", "types"],
"compilerOptions": {
"module": "esnext",
"lib": ["dom", "esnext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"baseUrl": "./",
"paths": {
"@headlessui/vue": ["src"],
"*": ["src/*", "node_modules/*"]
},
"types": ["@types/node", "vue", "@types/jest"],
"esModuleInterop": true,
"target": "es5",
"allowJs": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"resolveJsonModule": true,
"isolatedModules": true
},
"exclude": ["node_modules", "dist"]
}
@@ -0,0 +1,3 @@
{
"extends": "./tsconfig.json"
}
+21
View File
@@ -0,0 +1,21 @@
const TailwindUIPlugin = ({
root, // project root directory, absolute path
app, // Koa app instance
server, // raw http server instance
watcher, // chokidar file watcher instance
resolver, // chokidar file watcher instance
}) => {
app.use(async (ctx, next) => {
if (ctx.path === '/') ctx.path = '/examples'
if (ctx.path.endsWith('@headlessui/vue')) {
ctx.type = 'ts'
ctx.path = '/src/index.ts'
}
await next()
})
}
module.exports = {
configureServer: [TailwindUIPlugin],
}