Gemini 3
This commit is contained in:
48
src/App.vue
Normal file
48
src/App.vue
Normal file
@@ -0,0 +1,48 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import DialogProvider from './components/DialogProvider.vue'
|
||||
import { useDialog } from './composables/useDialog'
|
||||
import UserInputDialog from './components/UserInputDialog.vue'
|
||||
|
||||
const { open } = useDialog()
|
||||
const lastResult = ref<string>('None')
|
||||
|
||||
const triggerDialog = async () => {
|
||||
try {
|
||||
const result = await open(UserInputDialog, {
|
||||
title: 'Change Username',
|
||||
initialValue: 'GentooUser',
|
||||
})
|
||||
|
||||
lastResult.value = `Success: "${result.text}" at ${new Date(result.timestamp).toLocaleTimeString()}`
|
||||
} catch (error) {
|
||||
lastResult.value = 'Rejected/Cancelled'
|
||||
console.log(error)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="app-container">
|
||||
<h1>Vue 3 Dialog Concept</h1>
|
||||
<p>
|
||||
Last Result: <code>{{ lastResult }}</code>
|
||||
</p>
|
||||
|
||||
<button @click="triggerDialog">Open Dialog</button>
|
||||
|
||||
<!-- The Provider must be present in the tree -->
|
||||
<DialogProvider />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
:root {
|
||||
font-family: sans-serif;
|
||||
}
|
||||
.app-container {
|
||||
max-width: 600px;
|
||||
margin: 2rem auto;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
128
src/__tests__/type.tests.ts
Normal file
128
src/__tests__/type.tests.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
import { describe, it, expectTypeOf } from 'vitest'
|
||||
import { defineComponent } from 'vue'
|
||||
import { useDialog } from '../composables/useDialog'
|
||||
import type { DialogReturnType, DialogProps } from '../types'
|
||||
|
||||
const { open } = useDialog()
|
||||
|
||||
describe('Dialog Type Inference', () => {
|
||||
describe('DialogReturnType', () => {
|
||||
it('infers payload from simple defineComponent emits', () => {
|
||||
const Comp = defineComponent({
|
||||
emits: {
|
||||
submit: (payload: { id: number }) => true,
|
||||
cancel: () => true,
|
||||
},
|
||||
})
|
||||
|
||||
expectTypeOf<DialogReturnType<typeof Comp>>().toEqualTypeOf<{ id: number }>()
|
||||
})
|
||||
|
||||
it('infers undefined when submit has no payload (object syntax)', () => {
|
||||
const Comp = defineComponent({
|
||||
emits: {
|
||||
// strict definition: no arguments
|
||||
submit: () => true,
|
||||
cancel: () => true,
|
||||
},
|
||||
})
|
||||
|
||||
// Parameters<() => void>[0] is undefined
|
||||
expectTypeOf<DialogReturnType<typeof Comp>>().toEqualTypeOf<undefined>()
|
||||
})
|
||||
|
||||
it('infers any when submit has implicit payload (array syntax)', () => {
|
||||
const Comp = defineComponent({
|
||||
// array definition implies (...args: any[]) => any
|
||||
emits: ['submit', 'cancel'],
|
||||
})
|
||||
|
||||
expectTypeOf<DialogReturnType<typeof Comp>>().toBeAny()
|
||||
})
|
||||
|
||||
it('infers string payload from script setup simulation', () => {
|
||||
// Simulating a component type with strict $props (like generated by vue-tsc)
|
||||
type ScriptSetupComp = new () => {
|
||||
$props: {
|
||||
onSubmit?: (payload: string) => void
|
||||
onCancel?: () => void
|
||||
someProp: number
|
||||
}
|
||||
}
|
||||
|
||||
expectTypeOf<DialogReturnType<ScriptSetupComp>>().toEqualTypeOf<string>()
|
||||
})
|
||||
|
||||
it('returns void if submit emit is missing', () => {
|
||||
const Comp = defineComponent({
|
||||
emits: {
|
||||
cancel: () => true,
|
||||
},
|
||||
})
|
||||
|
||||
expectTypeOf<DialogReturnType<typeof Comp>>().toEqualTypeOf<void>()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DialogProps', () => {
|
||||
it('extracts props excluding lifecycle emits', () => {
|
||||
const Comp = defineComponent({
|
||||
props: {
|
||||
username: { type: String, required: true },
|
||||
age: Number,
|
||||
},
|
||||
emits: ['submit', 'cancel'],
|
||||
})
|
||||
|
||||
type Props = DialogProps<typeof Comp>
|
||||
|
||||
// Should include defined props
|
||||
expectTypeOf<Props>().toHaveProperty('username')
|
||||
expectTypeOf<Props>().toHaveProperty('age')
|
||||
|
||||
// Should NOT include library-managed listeners
|
||||
expectTypeOf<Props>().not.toHaveProperty('onSubmit')
|
||||
expectTypeOf<Props>().not.toHaveProperty('onCancel')
|
||||
})
|
||||
|
||||
it('allows native attributes if not explicitly excluded', () => {
|
||||
const Comp = defineComponent({})
|
||||
// Native props are usually allowed by component definitions unless strict
|
||||
type Props = DialogProps<typeof Comp>
|
||||
|
||||
// Class and Style are standard component props
|
||||
expectTypeOf<Props>().toHaveProperty('class')
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDialog integration', () => {
|
||||
it('open() returns Promise of inferred type', async () => {
|
||||
const Comp = defineComponent({
|
||||
emits: {
|
||||
submit: (val: boolean) => true,
|
||||
},
|
||||
})
|
||||
|
||||
const result = await open(Comp)
|
||||
expectTypeOf(result).toEqualTypeOf<boolean>()
|
||||
})
|
||||
|
||||
it('open() accepts correct props', () => {
|
||||
const Comp = defineComponent({
|
||||
props: {
|
||||
msg: { type: String, required: true },
|
||||
},
|
||||
emits: ['submit'],
|
||||
})
|
||||
|
||||
// valid
|
||||
open(Comp, { msg: 'hello' })
|
||||
|
||||
// @ts-expect-error missing required prop
|
||||
open(Comp, {})
|
||||
|
||||
// @ts-expect-error wrong prop type
|
||||
open(Comp, { msg: 123 })
|
||||
})
|
||||
})
|
||||
})
|
||||
102
src/components/DialogProvider.vue
Normal file
102
src/components/DialogProvider.vue
Normal file
@@ -0,0 +1,102 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, nextTick, watch } from 'vue'
|
||||
import { useDialog } from '../composables/useDialog'
|
||||
|
||||
const { activeDialogs } = useDialog()
|
||||
const dialogRefs = ref<Record<string, HTMLDialogElement>>({})
|
||||
|
||||
// Watch for new dialogs to trigger showModal()
|
||||
watch(
|
||||
() => activeDialogs.value.length,
|
||||
async (newLen, oldLen) => {
|
||||
if (newLen > oldLen) {
|
||||
await nextTick()
|
||||
const latest = activeDialogs.value[activeDialogs.value.length - 1]
|
||||
if (latest) {
|
||||
dialogRefs.value[latest.id]?.showModal()
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
const handleClose = (id: string, action: 'resolve' | 'reject', payload?: any) => {
|
||||
const index = activeDialogs.value.findIndex((d) => d.id === id)
|
||||
if (index === -1) return
|
||||
|
||||
const dialog = activeDialogs.value[index]
|
||||
const el = dialogRefs.value[id]
|
||||
if (!dialog) return
|
||||
|
||||
// Trigger close animation if defined in CSS, then cleanup
|
||||
if (el) el.close()
|
||||
|
||||
if (action === 'resolve') {
|
||||
dialog.resolve(payload)
|
||||
} else {
|
||||
dialog.reject(new Error('Dialog closed or cancelled'))
|
||||
}
|
||||
|
||||
// Remove from DOM
|
||||
activeDialogs.value.splice(index, 1)
|
||||
delete dialogRefs.value[id]
|
||||
}
|
||||
|
||||
// Handle native 'cancel' event (ESC key)
|
||||
const onNativeCancel = (e: Event, id: string) => {
|
||||
e.preventDefault() // We handle the close logic manually for consistency
|
||||
handleClose(id, 'reject')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<dialog
|
||||
v-for="item in activeDialogs"
|
||||
:key="item.id"
|
||||
:ref="
|
||||
(el) => {
|
||||
if (el) dialogRefs[item.id] = el as HTMLDialogElement
|
||||
}
|
||||
"
|
||||
class="v-dialog-native"
|
||||
@cancel="(e) => onNativeCancel(e, item.id)"
|
||||
>
|
||||
<component
|
||||
:is="item.component"
|
||||
v-bind="item.props"
|
||||
@submit="(payload: any) => handleClose(item.id, 'resolve', payload)"
|
||||
@cancel="() => handleClose(item.id, 'reject')"
|
||||
/>
|
||||
</dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.v-dialog-native {
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
|
||||
max-width: 90vw;
|
||||
max-height: 90vh;
|
||||
}
|
||||
|
||||
.v-dialog-native::backdrop {
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
|
||||
/* Optional: Simple entry animation */
|
||||
.v-dialog-native[open] {
|
||||
animation: fade-in 0.2s ease-out;
|
||||
}
|
||||
|
||||
@keyframes fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.95);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
49
src/components/UserInputDialog.vue
Normal file
49
src/components/UserInputDialog.vue
Normal file
@@ -0,0 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
|
||||
const props = defineProps<{
|
||||
title?: string;
|
||||
initialValue?: string;
|
||||
}>();
|
||||
|
||||
// The return type of open() is inferred from this interface
|
||||
const emit = defineEmits<{
|
||||
(e: 'submit', payload: { text: string; timestamp: number }): void;
|
||||
(e: 'cancel'): void;
|
||||
}>();
|
||||
|
||||
const inputValue = ref(props.initialValue || '');
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!inputValue.value) return;
|
||||
emit('submit', {
|
||||
text: inputValue.value,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="dialog-content">
|
||||
<h3>{{ title || 'Input Required' }}</h3>
|
||||
|
||||
<input
|
||||
v-model="inputValue"
|
||||
type="text"
|
||||
placeholder="Type something..."
|
||||
autofocus
|
||||
@keyup.enter="handleSubmit"
|
||||
/>
|
||||
|
||||
<div class="actions">
|
||||
<button class="btn-cancel" @click="emit('cancel')">Cancel</button>
|
||||
<button class="btn-confirm" @click="handleSubmit">Confirm</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.dialog-content { padding: 1.5rem; display: flex; flex-direction: column; gap: 1rem; }
|
||||
.actions { display: flex; gap: 0.5rem; justify-content: flex-end; margin-top: 1rem; }
|
||||
button { padding: 0.5rem 1rem; cursor: pointer; }
|
||||
</style>
|
||||
34
src/composables/useDialog.ts
Normal file
34
src/composables/useDialog.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { ref, markRaw, type Component } from 'vue'
|
||||
import type { DialogInstance, DialogProps, DialogReturnType } from '../types'
|
||||
|
||||
// Global state to hold active dialogs
|
||||
const activeDialogs = ref<DialogInstance[]>([])
|
||||
|
||||
export function useDialog() {
|
||||
/**
|
||||
* Opens a component inside a native <dialog>.
|
||||
* * @param component The Vue component to render. Must emit 'submit' to resolve or 'cancel' to reject.
|
||||
* @param props Props to pass to the component.
|
||||
* @returns A Promise resolved with the payload of the 'submit' event.
|
||||
*/
|
||||
const open = <C extends Component>(
|
||||
component: C,
|
||||
props?: DialogProps<C>,
|
||||
): Promise<DialogReturnType<C>> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
activeDialogs.value.push({
|
||||
id: crypto.randomUUID(),
|
||||
// markRaw is crucial to prevent Vue from making the component definition reactive
|
||||
component: markRaw(component),
|
||||
props: props || {},
|
||||
resolve,
|
||||
reject,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
open,
|
||||
activeDialogs, // Exposed for the Provider
|
||||
}
|
||||
}
|
||||
5
src/main.ts
Normal file
5
src/main.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { createApp } from 'vue'
|
||||
import App from '@/App.vue'
|
||||
|
||||
createApp(App)
|
||||
.mount('#app')
|
||||
36
src/types.ts
Normal file
36
src/types.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import type { Component } from 'vue'
|
||||
|
||||
/**
|
||||
* Helper to infer the 'submit' event payload from the component instance.
|
||||
* * ARGS: Must use 'any[]' for arguments to ensure proper inference (contravariance).
|
||||
* If we used 'unknown[]', it would fail to match specific payload types (e.g., string).
|
||||
* * RETURN: Can use 'unknown' for the return type as it is covariant.
|
||||
*/
|
||||
export type DialogReturnType<C> = C extends new (...args: any) => any
|
||||
? InstanceType<C>['$props'] extends infer P
|
||||
? P extends { onSubmit?: infer F }
|
||||
? F extends (...args: any[]) => unknown
|
||||
? Parameters<F>[0]
|
||||
: void
|
||||
: void
|
||||
: void
|
||||
: void
|
||||
|
||||
/**
|
||||
* Helper to extract props from the component definition.
|
||||
*/
|
||||
export type DialogProps<C> = C extends new (...args: any) => any
|
||||
? Omit<InstanceType<C>['$props'], 'onSubmit' | 'onCancel'>
|
||||
: never
|
||||
|
||||
export interface DialogInstance {
|
||||
id: string
|
||||
component: Component
|
||||
// Must be 'any' to allow v-bind to accept the object without strict type checking against the component definition
|
||||
props: Record<string, any>
|
||||
// Must be 'any' because this interface erases the generic type 'T' of the Promise.
|
||||
// (val: string) => void is assignable to (val: any) => void, but NOT to (val: unknown) => void.
|
||||
resolve: (val: any) => void
|
||||
reject: (reason?: any) => void
|
||||
}
|
||||
Reference in New Issue
Block a user