fix(forms): align settings and plugin form validation

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-11-28 15:57:25 +08:00
co-authored by Codex
parent 40cab881d0
commit be58d38aef
9 changed files with 99 additions and 71 deletions
+1 -1
View File
@@ -17,7 +17,7 @@
},
"dependencies": {
"@boxicons/vue": "1.0.1",
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.3",
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.4",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@lucide/vue": "^1.77.0",
+6 -6
View File
@@ -195,8 +195,8 @@ importers:
specifier: 1.0.1
version: 1.0.1(vue@3.5.46(typescript@6.0.3))
'@codex-proxy/ui':
specifier: github:zyycn/codex-proxy-ui#v0.13.3
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/05fa24802b1847ddf0e938dbb466d66f583234fd(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
specifier: github:zyycn/codex-proxy-ui#v0.13.4
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
'@fontsource-variable/inter':
specifier: ^5.3.0
version: 5.3.0
@@ -456,9 +456,9 @@ packages:
resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}
engines: {node: '>= 20.12.0'}
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/05fa24802b1847ddf0e938dbb466d66f583234fd':
resolution: {gitHosted: true, integrity: sha512-zTrW8FLOxd7JFfIJFuQXwaKQ+ZHrdylGOiwCdlwL16b93Wb7Z28hiFecxh2ELNxWyCK07bR96iqLjxf4coIafw==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/05fa24802b1847ddf0e938dbb466d66f583234fd}
version: 0.13.3
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d':
resolution: {gitHosted: true, integrity: sha512-6VttYlRECaLbR39j3VXBAradAwxo4PACMiorKz8WyVTnRWqKnvMxt2zhxu1GTHmQ9jJFg8Y/spfCuFP3P/Ym/Q==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d}
version: 0.13.4
engines: {node: '>=24'}
peerDependencies:
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
@@ -3590,7 +3590,7 @@ snapshots:
fast-wrap-ansi: 0.2.2
sisteransi: 1.0.5
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/05fa24802b1847ddf0e938dbb466d66f583234fd(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
dependencies:
'@ant-design/colors': 8.0.1
'@ant-design/fast-color': 3.0.1
@@ -182,7 +182,7 @@ export default function installPluginBridge(initial: PluginBridgeInitial) {
queueMicrotask(() => {
if (!form.isConnected || !submitter.isConnected)
return
if (!submitter.formNoValidate && !form.reportValidity())
if (!form.noValidate && !submitter.formNoValidate && !form.reportValidity())
return
form.dispatchEvent(new SubmitEvent('submit', { bubbles: true, cancelable: true, submitter }))
})
@@ -1,9 +1,8 @@
<script setup lang="ts">
import type { ResetWindowWeights } from '@/api'
import { ZButton, ZDialog } from '@codex-proxy/ui'
import { ref, shallowRef, useId, watch } from 'vue'
import { ZButton, ZDialog, ZForm } from '@codex-proxy/ui'
import { ref, shallowRef, useId, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { validSchedulingWeight } from '../utils/scheduling'
import ResetWindowWeightsFields from './ResetWindowWeightsFields.vue'
const props = defineProps<{
@@ -14,6 +13,7 @@ const emit = defineEmits<{ confirm: [config: ResetWindowWeights] }>()
const open = defineModel<boolean>({ required: true })
const { t } = useI18n({ useScope: 'global' })
const formId = useId()
const formRef = useTemplateRef<InstanceType<typeof ZForm>>('formElement')
const draft = ref({ fiveHour: '', weekly: '', monthly: '' })
const submitted = shallowRef(false)
@@ -21,6 +21,7 @@ function replaceDraft(config: ResetWindowWeights) {
for (const key of Object.keys(draft.value) as (keyof ResetWindowWeights)[])
draft.value[key] = String(config[key])
submitted.value = false
formRef.value?.clearValidate()
}
watch(open, (value) => {
@@ -28,9 +29,9 @@ watch(open, (value) => {
replaceDraft(props.config)
}, { immediate: true })
function confirm() {
async function confirm() {
submitted.value = true
if (!Object.values(draft.value).every(validSchedulingWeight))
if (!await formRef.value?.validate().catch(() => false))
return
emit('confirm', {
fiveHour: Number(draft.value.fiveHour),
@@ -43,9 +44,9 @@ function confirm() {
<template>
<ZDialog v-model="open" :title="t('settings.rotation.quotaResetPrioritySettings')" :description="t('settings.resetPriority.description')" width="36rem">
<form :id="formId" class="grid gap-5" novalidate @submit.prevent="confirm">
<ZForm :id="formId" ref="formElement" class="gap-5" :model="{ resetWindowWeights: draft }" novalidate @submit="confirm">
<ResetWindowWeightsFields v-model="draft" :submitted="submitted" :help="t('settings.resetPriority.windowHelp')" />
</form>
</ZForm>
<template #footer>
<ZButton class="mr-auto" @click="replaceDraft(defaults)">
{{ t('common.actions.reset') }}
@@ -4,11 +4,12 @@ import { ZFormItem, ZIconButton, ZInput, ZPopover } from '@codex-proxy/ui'
import { CircleHelp } from '@lucide/vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { validSchedulingWeight } from '../utils/scheduling'
import { schedulingWeightRule } from '../utils/scheduling'
defineProps<{ submitted: boolean, help: string }>()
const model = defineModel<Record<keyof ResetWindowWeights, string>>({ required: true })
const { t } = useI18n({ useScope: 'global' })
const weightRule = computed(() => schedulingWeightRule(t('settings.scheduling.enterValueFromToUpToOne')))
const periods = computed(() => [
{
key: 'fiveHour',
@@ -43,8 +44,8 @@ const periods = computed(() => [
</ZPopover>
</div>
<div class="grid grid-cols-3 gap-3">
<ZFormItem v-for="period in periods" :key="period.key" class="min-w-0" :label="period.label" :error="submitted && !validSchedulingWeight(model[period.key]) ? t('settings.scheduling.enterValueFromToUpToOne') : undefined">
<ZInput v-model="model[period.key]" type="number" min="0" max="10" step="0.1" :aria-label="period.label" :aria-invalid="submitted && !validSchedulingWeight(model[period.key])" />
<ZFormItem v-for="period in periods" :key="period.key" class="min-w-0" :label="period.label" :prop="`resetWindowWeights.${period.key}`" :rules="weightRule">
<ZInput v-model="model[period.key]" type="number" min="0" max="10" step="0.1" :aria-label="period.label" :validate-event="submitted" />
</ZFormItem>
</div>
</section>
@@ -1,11 +1,11 @@
<script setup lang="ts">
import type { SmartSchedulingConfig } from '@/api'
import { ZButton, ZDialog, ZFormItem, ZIconButton, ZInput, ZPopover } from '@codex-proxy/ui'
import { ZButton, ZDialog, ZForm, ZFormItem, ZIconButton, ZInput, ZPopover } from '@codex-proxy/ui'
import { CircleHelp } from '@lucide/vue'
import { computed, reactive, ref, shallowRef, useId, watch } from 'vue'
import { computed, reactive, ref, shallowRef, useId, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { validSchedulingWeight as validWeight } from '../utils/scheduling'
import { schedulingWeightRule } from '../utils/scheduling'
import ResetWindowWeightsFields from './ResetWindowWeightsFields.vue'
const props = defineProps<{
@@ -19,6 +19,7 @@ const { t } = useI18n({ useScope: 'global' })
const open = defineModel<boolean>({ required: true })
const formId = useId()
const formRef = useTemplateRef<InstanceType<typeof ZForm>>('formElement')
interface WeightGroup {
id: 'runtime' | 'quota' | 'queue'
title: string
@@ -85,15 +86,7 @@ const draft = reactive({
queueWeight: '',
})
const submitted = shallowRef(false)
const errors = computed(() => Object.fromEntries(fields.value.map(({ key }) => {
const valid = validWeight(draft[key])
return [
key,
valid
? undefined
: t('settings.scheduling.enterValueFromToUpToOne'),
]
})))
const weightRule = computed(() => schedulingWeightRule(t('settings.scheduling.enterValueFromToUpToOne')))
const emptyWeights = computed(() => fields.value.every(({ key }) => Number(draft[key]) === 0))
function replaceDraft(config: SmartSchedulingConfig) {
@@ -102,6 +95,7 @@ function replaceDraft(config: SmartSchedulingConfig) {
for (const key of Object.keys(windows.value) as (keyof typeof windows.value)[])
windows.value[key] = String(config.resetWindowWeights[key])
submitted.value = false
formRef.value?.clearValidate()
}
watch(open, (value) => {
@@ -109,9 +103,9 @@ watch(open, (value) => {
replaceDraft(props.config)
}, { immediate: true })
function confirm() {
async function confirm() {
submitted.value = true
if (Object.values(errors.value).some(Boolean) || emptyWeights.value || !Object.values(windows.value).every(validWeight))
if (!await formRef.value?.validate().catch(() => false) || emptyWeights.value)
return
emit('confirm', {
resetWindowWeights: {
@@ -132,13 +126,13 @@ function confirm() {
<template>
<ZDialog v-model="open" :title="t('settings.rotation.smartSchedulingSettings')" :description="t('settings.scheduling.description')" width="36rem">
<form :id="formId" class="grid gap-5" novalidate @submit.prevent="confirm">
<ZForm :id="formId" ref="formElement" class="gap-5" :model="{ ...draft, resetWindowWeights: windows }" novalidate @submit="confirm">
<section v-for="group in groups" :key="group.id" class="grid gap-3">
<h3 class="m-0 text-z font-emphasis">
{{ group.title }}
</h3>
<div class="grid gap-4" :class="group.id === 'runtime' ? 'sm:grid-cols-3' : 'sm:grid-cols-2'">
<ZFormItem v-for="field in group.fields" :key="field.key" :label="field.label" :error="submitted ? errors[field.key] : undefined">
<ZFormItem v-for="field in group.fields" :key="field.key" :label="field.label" :prop="field.key" :rules="weightRule">
<template #label-extra>
<ZPopover class="-my-1" trigger="hover-click" placement="top-start">
<template #reference="{ open: helpOpen }">
@@ -151,7 +145,7 @@ function confirm() {
</p>
</ZPopover>
</template>
<ZInput v-model="draft[field.key]" type="number" min="0" max="10" step="0.1" :placeholder="t('settings.scheduling.zeroWeightHelp')" :aria-label="field.label" />
<ZInput v-model="draft[field.key]" :validate-event="submitted" type="number" min="0" max="10" step="0.1" :placeholder="t('settings.scheduling.zeroWeightHelp')" :aria-label="field.label" />
</ZFormItem>
</div>
</section>
@@ -159,7 +153,7 @@ function confirm() {
<p v-if="submitted && emptyWeights" role="alert" class="m-0 text-z-sm text-z-danger">
{{ t('settings.scheduling.weightsRequired') }}
</p>
</form>
</ZForm>
<template #footer>
<ZButton class="mr-auto" @click="replaceDraft(defaults)">
{{ t('common.actions.reset') }}
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { ZFormItem as FormItem, ZButton, ZDialog, ZInput } from '@codex-proxy/ui'
import { computed, reactive, shallowRef, useId, watch } from 'vue'
import type { FormRules } from '@codex-proxy/ui'
import { ZButton, ZDialog, ZForm, ZFormItem, ZInput } from '@codex-proxy/ui'
import { computed, reactive, shallowRef, useId, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
@@ -13,32 +14,56 @@ const { t } = useI18n({ useScope: 'global' })
const open = defineModel<boolean>({ default: false })
const formId = useId()
const formRef = useTemplateRef<InstanceType<typeof ZForm>>('formElement')
const router = useRouter()
const auth = useAuthStore()
const { loading, run } = useAsyncAction()
const submitted = shallowRef(false)
const form = reactive({ currentPassword: '', newPassword: '', confirmation: '' })
const passwordError = computed(() => {
if (!submitted.value)
return undefined
if ([
...form.newPassword.trim(),
].length < 12) {
return t('settings.password.validation.minLength')
}
if (new TextEncoder().encode(form.newPassword).length > 1024)
return t('settings.password.newPasswordCannotExceedBytes')
if (form.newPassword === form.currentPassword)
return t('settings.password.validation.unchanged')
return undefined
})
const confirmationError = computed(() => submitted.value && form.confirmation !== form.newPassword
? t('settings.password.validation.mismatch')
: undefined)
const rules = computed<FormRules<typeof form>>(() => ({
currentPassword: {
required: true,
message: t('settings.password.enterCurrentPassword'),
},
newPassword: [
{
required: true,
message: t('settings.password.validation.minLength'),
},
{
validator: (_rule, value: string) => Array.from(value.trim()).length >= 12,
message: t('settings.password.validation.minLength'),
},
{
validator: (_rule, value: string) => new TextEncoder().encode(value).length <= 1024,
message: t('settings.password.newPasswordCannotExceedBytes'),
},
{
validator: (_rule, value: string) => value !== form.currentPassword,
message: t('settings.password.validation.unchanged'),
},
],
confirmation: [
{
required: true,
message: t('settings.password.enterNewPasswordAgain'),
},
{
validator: (_rule, value: string) => value === form.newPassword,
message: t('settings.password.validation.mismatch'),
},
],
}))
function revalidateDependentField(prop: 'newPassword' | 'confirmation') {
if (submitted.value)
void formRef.value?.getField(prop)?.validate('change').catch(() => false)
}
function clearForm() {
Object.assign(form, { currentPassword: '', newPassword: '', confirmation: '' })
submitted.value = false
formRef.value?.clearValidate()
}
watch(open, (value) => {
@@ -48,7 +73,7 @@ watch(open, (value) => {
async function submit() {
submitted.value = true
if (!form.currentPassword || passwordError.value || confirmationError.value)
if (loading.value || !await formRef.value?.validate().catch(() => false))
return
await run(async () => {
await changeAdminPassword({ currentPassword: form.currentPassword, newPassword: form.newPassword })
@@ -64,17 +89,17 @@ async function submit() {
<template>
<ZDialog v-model="open" :title="t('settings.password.changeAdministratorPassword')" :description="t('settings.password.changeDescription')" width="28rem" :show-close="!loading" :close-on-click-modal="!loading" :close-on-press-escape="!loading" @closed="clearForm">
<form :id="formId" class="grid gap-5" @submit.prevent="submit">
<FormItem :label="t('settings.password.currentPassword')" required>
<ZInput v-model="form.currentPassword" type="password" autocomplete="current-password" :placeholder="t('settings.password.enterCurrentPassword')" :disabled="loading" maxlength="4096" />
</FormItem>
<FormItem :label="t('settings.password.newPassword')" :description="t('settings.password.passwordHelp')" :error="passwordError" required>
<ZInput v-model="form.newPassword" type="password" autocomplete="new-password" :placeholder="t('settings.password.setNewPassword')" :disabled="loading" maxlength="1024" />
</FormItem>
<FormItem :label="t('settings.password.confirmNewPassword')" :error="confirmationError" required>
<ZInput v-model="form.confirmation" type="password" autocomplete="new-password" :placeholder="t('settings.password.enterNewPasswordAgain')" :disabled="loading" maxlength="1024" />
</FormItem>
</form>
<ZForm :id="formId" ref="formElement" class="gap-5" :model="form" :rules="rules" :validate-on-rule-change="false" focus-on-error novalidate @submit="submit">
<ZFormItem prop="currentPassword" :label="t('settings.password.currentPassword')">
<ZInput v-model="form.currentPassword" :validate-event="submitted" type="password" autocomplete="current-password" :placeholder="t('settings.password.enterCurrentPassword')" :disabled="loading" maxlength="4096" @input="revalidateDependentField('newPassword')" />
</ZFormItem>
<ZFormItem prop="newPassword" :label="t('settings.password.newPassword')" :description="t('settings.password.passwordHelp')">
<ZInput v-model="form.newPassword" :validate-event="submitted" type="password" autocomplete="new-password" :placeholder="t('settings.password.setNewPassword')" :disabled="loading" maxlength="1024" @input="revalidateDependentField('confirmation')" />
</ZFormItem>
<ZFormItem prop="confirmation" :label="t('settings.password.confirmNewPassword')">
<ZInput v-model="form.confirmation" :validate-event="submitted" type="password" autocomplete="new-password" :placeholder="t('settings.password.enterNewPasswordAgain')" :disabled="loading" maxlength="1024" />
</ZFormItem>
</ZForm>
<template #footer>
<ZButton :disabled="loading" @click="open = false">
{{ t('common.actions.cancel') }}
@@ -1,4 +1,11 @@
export function validSchedulingWeight(input: string) {
const value = Number(input)
return input.trim() !== '' && Number.isFinite(value) && value >= 0 && value <= 10 && Math.round(value * 10) / 10 === value
import type { FormRule } from '@codex-proxy/ui'
export function schedulingWeightRule(message: string): FormRule {
return {
validator: (_rule, input: string) => {
const value = Number(input)
return input.trim() !== '' && Number.isFinite(value) && value >= 0 && value <= 10 && Math.round(value * 10) / 10 === value
},
message,
}
}