chore: improve types (#115)

* wip: improve types

* feat: improve types

* Apply suggestions from code review

Co-authored-by: Sylvain Marroufin <marroufin.sylvain@gmail.com>

* chore: update

* chore: enable ci typecheck

* chore: fix

Co-authored-by: Sylvain Marroufin <marroufin.sylvain@gmail.com>
This commit is contained in:
Anthony Fu
2022-11-23 18:30:18 +08:00
committed by GitHub
parent 32d1f21299
commit edc1bd677b
30 changed files with 114 additions and 64 deletions

View File

@@ -41,6 +41,9 @@ jobs:
- name: Lint
run: yarn lint
- name: Typecheck
run: yarn typecheck
- name: Build
run: yarn build

View File

@@ -41,6 +41,9 @@ jobs:
- name: Lint
run: yarn lint
- name: Typecheck
run: yarn typecheck
- name: Build
run: yarn build

12
build.config.ts Normal file
View File

@@ -0,0 +1,12 @@
import fs from 'node:fs/promises'
import { join, resolve } from 'node:path'
import { defineBuildConfig } from 'unbuild'
export default defineBuildConfig({
hooks: {
'rollup:done': async (ctx) => {
// copy env.d.ts to dist
await fs.copyFile(resolve('src/env.d.ts'), join(ctx.options.outDir, 'env.d.ts'))
}
}
})

View File

@@ -60,6 +60,13 @@
<script setup>
useHead({
title: '@nuxthq/ui',
meta: [
{ name: 'viewport', content: 'width=device-width, initial-scale=1, maximum-scale=1' }
],
link: [
{ rel: 'stylesheet', href: 'https://rsms.me/inter/inter.css' }
],
bodyAttrs: {
class: 'antialiased font-sans text-gray-700 bg-gray-50 dark:bg-gray-900 dark:text-gray-200 bg-white dark:bg-black'
}

View File

@@ -3,15 +3,6 @@ import nuxtUI from '../src/module'
// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config
export default defineNuxtConfig({
meta: {
title: '@nuxthq/ui',
meta: [
{ name: 'viewport', content: 'width=device-width, initial-scale=1, maximum-scale=1' }
],
link: [
{ rel: 'stylesheet', href: 'https://rsms.me/inter/inter.css' }
]
},
modules: [
nuxtUI
],

View File

@@ -20,6 +20,7 @@
"dev": "nuxi dev docs",
"build:docs": "nuxi generate docs",
"lint": "eslint --ext .ts,.js,.vue .",
"typecheck": "nuxi typecheck",
"prepare": "nuxi prepare docs",
"release": "yarn lint && standard-version && git push --follow-tags"
},
@@ -48,6 +49,7 @@
"eslint": "^8.27.0",
"nuxt": "^3.0.0",
"standard-version": "^9.5.0",
"unbuild": "^1.0.1",
"vue-tsc": "^1.0.9"
},
"build": {

6
src/env.d.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
import type { DefaultPreset } from './runtime/presets/default'
declare module '#build/ui' {
declare const preset: DefaultPreset
export default preset
}

View File

@@ -6,9 +6,9 @@
:aria-label="ariaLabel"
v-bind="buttonProps"
>
<Icon v-if="isLeading" :name="leadingIconName" :class="leadingIconClass" aria-hidden="true" />
<Icon v-if="isLeading && leadingIconName" :name="leadingIconName" :class="leadingIconClass" aria-hidden="true" />
<slot><span :class="truncate ? 'text-left break-all line-clamp-1' : ''">{{ label }}</span></slot>
<Icon v-if="isTrailing" :name="trailingIconName" :class="trailingIconClass" aria-hidden="true" />
<Icon v-if="isTrailing && trailingIconName" :name="trailingIconName" :class="trailingIconClass" aria-hidden="true" />
</component>
</template>

View File

@@ -38,7 +38,7 @@ import {
MenuItems,
MenuItem
} from '@headlessui/vue'
import type { Ref, PropType } from 'vue'
import type { PropType } from 'vue'
import type { RouteLocationNormalized } from 'vue-router'
import { ref, computed, onMounted } from 'vue'
import { defu } from 'defu'
@@ -153,13 +153,14 @@ function resolveItemClass ({ active, disabled }: { active: boolean, disabled: bo
}
// https://github.com/tailwindlabs/headlessui/blob/f66f4926c489fc15289d528294c23a3dc2aee7b1/packages/%40headlessui-vue/src/components/menu/menu.ts#L131
const menuApi: Ref<any> = ref(null)
const menuApi = ref<any>(null)
let openTimeout: NodeJS.Timeout | null = null
let closeTimeout: NodeJS.Timeout | null = null
onMounted(() => {
setTimeout(() => {
// @ts-expect-error internals
const menuProvides = trigger.value?.$.provides
if (!menuProvides) {
return

View File

@@ -18,15 +18,19 @@ const props = defineProps({
}
})
const nuxtApp = useNuxtApp()
const state = useState('u-icons', () => ({}))
const state = useState<Record<string, Required<IconifyIcon> | Promise<void> | null>>('u-icons', () => ({}))
const isFetching = computed(() => !!state.value?.[props.name]?.then)
const icon = computed<IconifyIcon | null>(() => !state.value?.[props.name] || state.value[props.name].then ? null : state.value[props.name])
const isFetching = computed(() => state.value?.[props.name] && ('then' in state.value?.[props.name]!))
const icon = computed<Required<IconifyIcon> | null>(() =>
!state.value?.[props.name] || 'then' in state.value[props.name]!
? null
: state.value[props.name] as Required<IconifyIcon>
)
const component = computed(() => nuxtApp.vueApp.component(props.name))
const loadIconComponent = (name: string) => {
state.value = state.value || {}
if (nuxtApp.vueApp.component(props.name) || state.value[name] || state.value[name] === null) { return state.value[name] }
if (nuxtApp.vueApp.component(props.name) || state.value[name] || state.value[name] == null) { return state.value[name] }
state.value[name] = loadIcon(name)
.then((res) => { state.value[name] = res })

View File

@@ -8,7 +8,7 @@
<router-link
v-else
v-slot="{ href, navigate, isActive, isExactActive }"
v-bind="$props"
v-bind="$props as RouterLinkProps"
custom
>
<a
@@ -25,10 +25,11 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { PropType } from 'vue'
import type { RouteLocationNormalized } from 'vue-router'
import type { RouteLocationNormalized, RouterLinkProps } from 'vue-router'
import { RouterLink } from 'vue-router'
const props = defineProps({
// @ts-expect-error internal props
...RouterLink.props,
to: {
type: [String, Object] as PropType<string | RouteLocationNormalized>,

View File

@@ -2,7 +2,7 @@
<div class="rounded-md p-4" :class="variantClass">
<div class="flex">
<div class="flex-shrink-0">
<Icon :name="iconName" :class="iconClass" class="h-5 w-5" />
<Icon v-if="iconName" :name="iconName" :class="iconClass" class="h-5 w-5" />
</div>
<div class="ml-3 flex-1 md:flex md:justify-between">
<p v-if="title" class="text-sm leading-5" :class="titleClass">

View File

@@ -90,7 +90,7 @@ const emit = defineEmits(['update:modelValue', 'focus', 'blur'])
const isChecked = computed({
get () {
return props.modelValue
return !!props.modelValue
},
set (value) {
emit('update:modelValue', value)

View File

@@ -13,22 +13,21 @@
:autocomplete="autocomplete"
:spellcheck="spellcheck"
:class="inputClass"
@input="onInput($event.target.value)"
@input="onInput(($event.target as any).value)"
@focus="$emit('focus', $event)"
@blur="$emit('blur', $event)"
>
<slot />
<div v-if="isLeading" :class="iconLeadingWrapperClass">
<Icon :name="iconName" :class="iconClass" />
<Icon v-if="iconName" :name="iconName" :class="iconClass" />
</div>
<div v-if="isTrailing" :class="iconTrailingWrapperClass">
<Icon :name="iconName" :class="iconClass" />
<Icon v-if="iconName" :name="iconName" :class="iconClass" />
</div>
</div>
</template>
<script setup lang="ts">
import type { Ref } from 'vue'
import { ref, computed, onMounted } from 'vue'
import Icon from '../elements/Icon.vue'
import { classNames } from '../../utils'
@@ -129,11 +128,11 @@ const props = defineProps({
const emit = defineEmits(['update:modelValue', 'focus', 'blur'])
const input: Ref<HTMLInputElement> = ref(null)
const input = ref<HTMLInputElement | null>(null)
const autoFocus = () => {
if (props.autofocus) {
input.value.focus()
input.value?.focus()
}
}

View File

@@ -7,7 +7,7 @@
:required="required"
:disabled="disabled"
:class="selectClass"
@input="onInput($event.target.value)"
@input="onInput(($event.target as any).value)"
>
<template v-for="(option, index) in normalizedOptionsWithPlaceholder">
<optgroup

View File

@@ -16,12 +16,12 @@
<slot :open="open" :disabled="buttonDisabled">
<button :class="selectCustomClass" :disabled="disabled" type="button">
<slot name="label">
<span v-if="modelValue" class="block truncate">{{ modelValue[textAttribute] }}</span>
<span v-if="modelValue" class="block truncate">{{ (modelValue as any)[textAttribute] }}</span>
<span v-else class="block truncate u-text-gray-400">{{ placeholder }}</span>
</slot>
<slot name="icon">
<span :class="iconWrapperClass">
<Icon :name="icon" :class="iconClass" aria-hidden="true" />
<Icon v-if="icon" :name="icon" :class="iconClass" aria-hidden="true" />
</span>
</slot>
</button>
@@ -58,7 +58,7 @@
</div>
<span v-if="selected" :class="resolveOptionIconClass({ active })">
<Icon :name="listOptionIcon" :class="listOptionIconSizeClass" aria-hidden="true" />
<Icon v-if="listOptionIcon" :name="listOptionIcon" :class="listOptionIconSizeClass" aria-hidden="true" />
</span>
</li>
</ComboboxOption>
@@ -323,7 +323,7 @@ function resolveOptionIconClass ({ active }: { active: boolean }) {
)
}
function onUpdate (event) {
function onUpdate (event: any) {
if (query.value && searchInput.value?.$el) {
query.value = ''
// explicitly set input text because `ComboboxInput` `displayValue` is not reactive

View File

@@ -11,7 +11,7 @@
:placeholder="placeholder"
:autocomplete="autocomplete"
:class="textareaClass"
@input="onInput($event.target.value)"
@input="onInput(($event.target as any).value)"
@focus="$emit('focus', $event)"
@blur="$emit('blur', $event)"
/>
@@ -19,7 +19,6 @@
</template>
<script setup lang="ts">
import type { Ref } from 'vue'
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { classNames } from '../../utils'
import $ui from '#build/ui'
@@ -95,11 +94,11 @@ const props = defineProps({
const emit = defineEmits(['update:modelValue', 'focus', 'blur'])
const textarea: Ref<HTMLTextAreaElement> = ref(null)
const textarea = ref<HTMLTextAreaElement | null>(null)
const autoFocus = () => {
if (props.autofocus) {
textarea.value.focus()
textarea.value?.focus()
}
}

View File

@@ -134,6 +134,7 @@ onMounted(() => {
onMounted(() => {
setTimeout(() => {
// @ts-expect-error internals
const popoverProvides = comboboxInput.value?.$.provides
if (!popoverProvides) {
return
@@ -203,7 +204,7 @@ function onClear () {
}
defineExpose({
updateQuery: (q) => {
updateQuery: (q: string) => {
query.value = q
},
comboboxApi,

View File

@@ -72,7 +72,7 @@ defineProps({
}
})
function highlight ({ indices, value }, i = 1) {
function highlight ({ indices, value }: { indices: number[][], value:string }, i = 1): string {
const pair = indices[indices.length - i]
if (!pair) {
return value

View File

@@ -5,7 +5,7 @@
v-slot="{ isActive }"
:key="index"
v-bind="link"
:class="[baseClass, spacingClass]"
:class="[baseClass, spacingClass].join(' ')"
:active-class="activeClass"
:inactive-class="inactiveClass"
@click="link.click && link.click()"

View File

@@ -12,6 +12,7 @@
import type { PropType } from 'vue'
import { computed, toRef } from 'vue'
import { defu } from 'defu'
import type { VirtualElement } from '@popperjs/core'
import { usePopper } from '../../composables/usePopper'
import type { PopperOptions } from '../../types'
import $ui from '#build/ui'
@@ -22,7 +23,7 @@ const props = defineProps({
default: false
},
virtualElement: {
type: Object,
type: Object as PropType<VirtualElement>,
required: true
},
wrapperClass: {

View File

@@ -56,6 +56,7 @@ import type { PropType } from 'vue'
import Icon from '../elements/Icon.vue'
import { useTimer } from '../../composables/useTimer'
import { classNames } from '../../utils'
import type { ToastNotificationAction } from '../../types'
import $ui from '#build/ui'
const props = defineProps({
@@ -172,7 +173,7 @@ function onClose () {
emit('close')
}
function onAction (action) {
function onAction (action: ToastNotificationAction) {
if (timer) {
timer.stop()
}

View File

@@ -17,11 +17,12 @@
</template>
<script setup lang="ts">
import type { ToastNotification } from '../../types'
import Notification from './Notification.vue'
import { useNuxtApp, useState } from '#imports'
const { $toast } = useNuxtApp()
const notifications = useState('notifications', () => [])
const notifications = useState<ToastNotification[]>('notifications', () => [])
</script>
<script lang="ts">

View File

@@ -17,8 +17,8 @@
</template>
<script setup lang="ts">
import type { Ref, PropType } from 'vue'
import { computed, ref, onMounted } from 'vue'
import type { PropType } from 'vue'
import { defu } from 'defu'
import { Popover, PopoverButton, PopoverPanel } from '@headlessui/vue'
import { usePopper } from '../../composables/usePopper'
@@ -72,13 +72,14 @@ const popperOptions = computed<PopperOptions>(() => defu({}, props.popperOptions
const [trigger, container] = usePopper(popperOptions.value)
// https://github.com/tailwindlabs/headlessui/blob/f66f4926c489fc15289d528294c23a3dc2aee7b1/packages/%40headlessui-vue/src/components/popover/popover.ts#L151
const popoverApi: Ref<any> = ref(null)
const popoverApi = ref<any>(null)
let openTimeout: NodeJS.Timeout | null = null
let closeTimeout: NodeJS.Timeout | null = null
onMounted(() => {
setTimeout(() => {
// @ts-expect-error internals
const popoverProvides = trigger.value?.$.provides
if (!popoverProvides) {
return

View File

@@ -1,6 +1,6 @@
import { ref, onMounted, watchEffect } from 'vue'
import type { Ref } from 'vue'
import { popperGenerator, defaultModifiers } from '@popperjs/core/lib/popper-lite'
import { popperGenerator, defaultModifiers, VirtualElement } from '@popperjs/core/lib/popper-lite'
import type { Instance } from '@popperjs/core'
import { omitBy, isUndefined } from 'lodash-es'
import flip from '@popperjs/core/lib/modifiers/flip'
@@ -8,6 +8,7 @@ import offset from '@popperjs/core/lib/modifiers/offset'
import preventOverflow from '@popperjs/core/lib/modifiers/preventOverflow'
import computeStyles from '@popperjs/core/lib/modifiers/computeStyles'
import eventListeners from '@popperjs/core/lib/modifiers/eventListeners'
import { MaybeElement, unrefElement } from '@vueuse/core'
import type { PopperOptions } from '../types'
export const createPopper = popperGenerator({
@@ -25,21 +26,22 @@ export function usePopper ({
resize = true,
placement,
strategy
}: PopperOptions, virtualReference: Ref<Object> = null) {
const reference: Ref<HTMLElement> = ref(null)
const popper: Ref<HTMLElement> = ref(null)
const instance: Ref<Instance> = ref(null)
}: PopperOptions, virtualReference?: Ref<Element | VirtualElement>) {
const reference = ref<MaybeElement>(null)
const popper = ref<MaybeElement>(null)
const instance = ref<Instance | null>(null)
onMounted(() => {
watchEffect((onInvalidate) => {
if (!popper.value) { return }
if (!reference.value && !virtualReference.value) { return }
if (!reference.value && !virtualReference?.value) { return }
const popperEl = popper.value.$el || popper.value
const referenceEl = virtualReference?.value || reference.value.$el || reference.value
const popperEl = unrefElement(popper)
const referenceEl = virtualReference?.value || unrefElement(reference)
// if (!(referenceEl instanceof HTMLElement)) { return }
if (!(popperEl instanceof HTMLElement)) { return }
if (!referenceEl) { return }
instance.value = createPopper(referenceEl, popperEl, omitBy({
placement,
@@ -76,5 +78,5 @@ export function usePopper ({
})
})
return [reference, popper, instance]
return [reference, popper, instance] as const
}

View File

@@ -1,10 +1,10 @@
import { Ref, ref, computed } from 'vue-demi'
import { ref, computed } from 'vue-demi'
import { useTimestamp } from '@vueuse/core'
export function useTimer (cb: (...args: unknown[]) => any, interval: number) {
let timer: number | null = null
const timestamp = useTimestamp({ controls: true })
const startTime: Ref<number | null> = ref(null)
const startTime = ref<number | null>(null)
const remaining = computed(() => {
if (!startTime.value) {
@@ -46,7 +46,7 @@ export function useTimer (cb: (...args: unknown[]) => any, interval: number) {
}
function resume () {
startTime.value += (Date.now() - timestamp.timestamp.value)
startTime.value = (startTime.value || 0) + (Date.now() - timestamp.timestamp.value)
timestamp.resume()
set()
}

View File

@@ -1,9 +1,8 @@
import type { Ref } from 'vue'
import { defineNuxtPlugin, useState } from '#app'
import type { ToastNotification } from '../types'
export default defineNuxtPlugin(() => {
const notifications: Ref<ToastNotification[]> = useState('notifications', () => [])
const notifications = useState<ToastNotification[]>('notifications', () => [])
function addNotification (notification: Partial<ToastNotification>) {
const body = {

View File

@@ -1,4 +1,4 @@
export default (variantColors: string[]) => {
export default function defaultPreset (variantColors: string[]) {
const button = {
base: 'font-medium focus:outline-none disabled:cursor-not-allowed disabled:opacity-75 focus:ring-offset-white dark:focus:ring-offset-black',
rounded: 'rounded-md',
@@ -570,3 +570,5 @@ export default (variantColors: string[]) => {
contextMenu
}
}
export type DefaultPreset = ReturnType<typeof defaultPreset>

View File

@@ -1,3 +1,8 @@
export interface ToastNotificationAction {
label: string,
click: Function
}
export interface ToastNotification {
id: string
title: string
@@ -5,10 +10,8 @@ export interface ToastNotification {
type: string
icon?: string
timeout: number
actions?: {
label: string,
click: Function
}[]
actions?: ToastNotificationAction[]
click?: Function
callback?: Function
}

View File

@@ -1,3 +1,14 @@
{
"extends": "./docs/.nuxt/tsconfig.json"
"extends": "./docs/.nuxt/tsconfig.json",
"compilerOptions": {
"module": "esnext"
},
"include": [
"./**/*",
"./docs/.nuxt/nuxt.d.ts"
],
"exclude": [
"node_modules",
"dist"
]
}