1
0
This commit is contained in:
2025-11-18 23:54:30 +01:00
commit 678d5e6fbd
26 changed files with 12599 additions and 0 deletions

8
.editorconfig Normal file
View File

@@ -0,0 +1,8 @@
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}]
charset = utf-8
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
max_line_length = 100

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
* text=auto eol=lf

30
.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
/cypress/videos/
/cypress/screenshots/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*.tsbuildinfo

6
.prettierrc.json Normal file
View File

@@ -0,0 +1,6 @@
{
"$schema": "https://json.schemastore.org/prettierrc",
"semi": false,
"singleQuote": true,
"printWidth": 100
}

10
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,10 @@
{
"recommendations": [
"Vue.volar",
"vitest.explorer",
"dbaeumer.vscode-eslint",
"EditorConfig.EditorConfig",
"oxc.oxc-vscode",
"esbenp.prettier-vscode"
]
}

1
env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

45
eslint.config.ts Normal file
View File

@@ -0,0 +1,45 @@
import { globalIgnores } from 'eslint/config'
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript'
import pluginVue from 'eslint-plugin-vue'
import pluginVitest from '@vitest/eslint-plugin'
import pluginOxlint from 'eslint-plugin-oxlint'
import skipFormatting from '@vue/eslint-config-prettier/skip-formatting'
// To allow more languages other than `ts` in `.vue` files, uncomment the following lines:
// import { configureVueProject } from '@vue/eslint-config-typescript'
// configureVueProject({ scriptLangs: ['ts', 'tsx'] })
// More info at https://github.com/vuejs/eslint-config-typescript/#advanced-setup
export default defineConfigWithVueTs(
{
name: 'app/files-to-lint',
files: ['**/*.{ts,mts,tsx,vue}'],
},
globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**']),
pluginVue.configs['flat/essential'],
vueTsConfigs.recommended,
{
...pluginVitest.configs.recommended,
files: ['src/**/__tests__/*'],
},
{
name: 'app/custom-rules',
rules: {
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
},
},
...pluginOxlint.configs['flat/recommended'],
skipFormatting,
)

13
index.html Normal file
View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

7164
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

50
package.json Normal file
View File

@@ -0,0 +1,50 @@
{
"name": "vue-dialog",
"version": "0.0.0",
"private": true,
"type": "module",
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"scripts": {
"dev": "vite",
"build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"test:unit": "vitest",
"build-only": "vite build",
"type-check": "vue-tsc --build",
"lint:oxlint": "oxlint . --fix -D correctness --ignore-path .gitignore",
"lint:eslint": "eslint . --fix",
"lint": "run-s lint:*",
"format": "prettier --write src/"
},
"dependencies": {
"@vue/language-server": "^3.1.4",
"vue": "^3.5.24"
},
"devDependencies": {
"@prettier/plugin-oxc": "^0.0.5",
"@tsconfig/node22": "^22.0.5",
"@types/jsdom": "^27.0.0",
"@types/node": "^24.10.1",
"@vitejs/plugin-vue": "^6.0.1",
"@vitest/eslint-plugin": "^1.4.3",
"@vue/eslint-config-prettier": "^10.2.0",
"@vue/eslint-config-typescript": "^14.6.0",
"@vue/test-utils": "^2.4.6",
"@vue/tsconfig": "^0.8.1",
"eslint": "^9.39.1",
"eslint-plugin-oxlint": "~1.29.0",
"eslint-plugin-vue": "~10.5.1",
"jiti": "^2.6.1",
"jsdom": "^27.2.0",
"npm-run-all2": "^8.0.4",
"oxlint": "~1.29.0",
"prettier": "3.6.2",
"typescript": "~5.9.3",
"vite": "^7.2.2",
"vite-plugin-vue-devtools": "^8.0.5",
"vitest": "^4.0.10",
"vue-tsc": "^3.1.4"
}
}

4765
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

2
pnpm-workspace.yaml Normal file
View File

@@ -0,0 +1,2 @@
onlyBuiltDependencies:
- esbuild

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

48
src/App.vue Normal file
View 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
View 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 })
})
})
})

View 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>

View 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>

View 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
View File

@@ -0,0 +1,5 @@
import { createApp } from 'vue'
import App from '@/App.vue'
createApp(App)
.mount('#app')

36
src/types.ts Normal file
View 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
}

26
tsconfig.app.json Normal file
View File

@@ -0,0 +1,26 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": [
"env.d.ts",
"src/**/*",
"src/**/*.vue"
],
"exclude": [
"src/**/__tests__/*"
],
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"noEmit": true,
"paths": {
"@/*": [
"./src/*"
]
}
}
}

14
tsconfig.json Normal file
View File

@@ -0,0 +1,14 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.node.json"
},
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.vitest.json"
}
]
}

19
tsconfig.node.json Normal file
View File

@@ -0,0 +1,19 @@
{
"extends": "@tsconfig/node22/tsconfig.json",
"include": [
"vite.config.*",
"vitest.config.*",
"cypress.config.*",
"nightwatch.conf.*",
"playwright.config.*",
"eslint.config.*"
],
"compilerOptions": {
"noEmit": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"module": "ESNext",
"moduleResolution": "Bundler",
"types": ["node"]
}
}

11
tsconfig.vitest.json Normal file
View File

@@ -0,0 +1,11 @@
{
"extends": "./tsconfig.app.json",
"include": ["src/**/__tests__/*", "env.d.ts"],
"exclude": [],
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.vitest.tsbuildinfo",
"lib": [],
"types": ["node", "jsdom"]
}
}

18
vite.config.ts Normal file
View File

@@ -0,0 +1,18 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
// https://vite.dev/config/
export default defineConfig({
plugins: [
vue(),
vueDevTools(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
},
})

14
vitest.config.ts Normal file
View File

@@ -0,0 +1,14 @@
import { fileURLToPath } from 'node:url'
import { mergeConfig, defineConfig, configDefaults } from 'vitest/config'
import viteConfig from './vite.config'
export default mergeConfig(
viteConfig,
defineConfig({
test: {
environment: 'jsdom',
exclude: [...configDefaults.exclude, 'e2e/**'],
root: fileURLToPath(new URL('./', import.meta.url)),
},
}),
)