feat: 优化日期时间范围选择器 (#660)

* feat: 优化日期时间范围选择器

* feat(web): 添加主页智能模型选择
This commit is contained in:
O authored and GitHub committed 2026-09-16 10:03:02 +08:00
1 parent df72bbb446
commit f06ead40dd
15 files changed
+922 -71

No files matched your search

+35 -3
View File
@@ -3,6 +3,7 @@ package control
import (
"context"
"fmt"
"sort"
"strings"
"time"
@@ -30,6 +31,7 @@ type HomeAccessKey struct {
Name string `json:"name"`
MaskedKey string `json:"masked_key"`
Protocols []protocol.Protocol `json:"protocols"`
Models []string `json:"models"`
}
type HomeBase struct {
@@ -179,7 +181,7 @@ func (s *Service) readHomeBase(
return HomeBase{}, app_errors.ErrUnauthorized
}
}
accessKeys, err := mapHomeAccessKeys(accessKeyRows)
accessKeys, err := mapHomeAccessKeys(accessKeyRows, snapshot)
if err != nil {
return HomeBase{}, err
}
@@ -338,6 +340,14 @@ func countScopedHomeModels(
allowedGroups map[uint]struct{},
accessKey state.AccessKeyView,
) int64 {
return int64(len(scopedHomeModelNames(snapshot, allowedGroups, accessKey)))
}
func scopedHomeModelNames(
snapshot *state.ConfigSnapshot,
allowedGroups map[uint]struct{},
accessKey state.AccessKeyView,
) []string {
names := make(map[string]struct{})
for groupID := range allowedGroups {
group, exists := snapshot.Groups[groupID]
@@ -357,7 +367,12 @@ func countScopedHomeModels(
names[name] = struct{}{}
}
}
return int64(len(names))
result := make([]string, 0, len(names))
for name := range names {
result = append(result, name)
}
sort.Strings(result)
return result
}
func homeExternalModelName(model state.ModelConfig) string {
@@ -486,7 +501,10 @@ func countAvailableHomeCredentialsInGroups(
return available, nil
}
func mapHomeAccessKeys(rows []homeAccessKeyRow) ([]HomeAccessKey, error) {
func mapHomeAccessKeys(
rows []homeAccessKeyRow,
snapshot *state.ConfigSnapshot,
) ([]HomeAccessKey, error) {
result := make([]HomeAccessKey, 0, len(rows))
for _, row := range rows {
if uint64(row.ID) > uint64(maxSafeInteger) {
@@ -517,10 +535,24 @@ func mapHomeAccessKeys(rows []homeAccessKeyRow) ([]HomeAccessKey, error) {
} else {
protocols = append([]protocol.Protocol(nil), protocols...)
}
accessKey, exists := snapshot.AccessKeysByID[row.ID]
if !exists || accessKey.Status != state.AccessKeyStatusActive {
return nil, fmt.Errorf(
"map home access key %d: runtime configuration mismatch: %w",
row.ID,
app_errors.ErrInternalServer,
)
}
models := scopedHomeModelNames(
snapshot,
accessibleHomeGroups(snapshot, accessKey),
accessKey,
)
result = append(result, HomeAccessKey{
ID: row.ID, Name: row.Name,
MaskedKey: maskedAccessKey(row.KeyPrefix, row.KeySuffix),
Protocols: protocols,
Models: models,
})
}
return result, nil
+7
View File
@@ -161,11 +161,17 @@ func TestReadHomeBaseUsesPersistedAndRuntimeSnapshots(t *testing.T) {
protocol.OpenAICompletions,
protocol.Gemini,
},
Models: []string{
"client-primary", "client-secondary", "client-third", "ignored-empty",
},
},
{
ID: 9, Name: "all protocols",
MaskedKey: "sk-gl-****c0de",
Protocols: protocol.DataPlaneProtocols(),
Models: []string{
"client-primary", "client-secondary", "client-third", "ignored-empty",
},
},
},
}
@@ -236,6 +242,7 @@ func TestReadAccessKeyHomeBaseScopesInventoryToRoutableModels(t *testing.T) {
}
if result.Inventory != (HomeInventory{GroupCount: 1, ModelCount: 1}) ||
len(result.AccessKeys) != 1 || result.AccessKeys[0].ID != created.ID ||
!reflect.DeepEqual(result.AccessKeys[0].Models, []string{"client-allowed"}) ||
result.CurrentAccessKey == nil || result.CurrentAccessKey.ID != created.ID {
t.Fatalf("ReadAccessKeyHomeBase() = %#v", result)
}
+1
View File
@@ -17,6 +17,7 @@
"type-check": "vue-tsc --noEmit -p tsconfig.app.json && tsc --noEmit -p tsconfig.node.json"
},
"dependencies": {
"@internationalized/date": "3.12.3",
"@lucide/vue": "1.39.0",
"@tanstack/vue-query": "5.102.8",
"reka-ui": "2.10.4",
+3
View File
@@ -14,6 +14,9 @@ importers:
.:
dependencies:
'@internationalized/date':
specifier: 3.12.3
version: 3.12.3
'@lucide/vue':
specifier: 1.39.0
version: 1.39.0(vue@3.5.42(typescript@6.0.3))
+5 -1
View File
@@ -45,6 +45,7 @@ export interface HomeBaseDto {
name: string
masked_key: string
protocols: AccessProtocol[]
models: string[]
}>
current_access_key: AccessKeyCollectionItemDto | null
}
@@ -145,7 +146,7 @@ const inventoryFields = [
'available_credential_count',
'model_count',
] as const
const accessKeyFields = ['id', 'name', 'masked_key', 'protocols'] as const
const accessKeyFields = ['id', 'name', 'masked_key', 'protocols', 'models'] as const
const statisticsFields = [
'range',
'granularity',
@@ -236,12 +237,15 @@ function projectHomeAccessKey(value: unknown): HomeBaseDto['access_keys'][number
const protocols = projectArray(record.protocols, (protocol) =>
projectEnum(protocol, knownAccessProtocols),
)
const models = projectArray(record.models, projectNonBlankTrimmedString)
if (new Set(protocols).size !== protocols.length) invalidResponse()
if (new Set(models).size !== models.length) invalidResponse()
return {
id: projectSafeInteger(record.id, { minimum: 1 }),
name: projectNonBlankTrimmedString(record.name),
masked_key: maskedKey,
protocols,
models,
}
}
+307
View File
@@ -0,0 +1,307 @@
<script setup lang="ts">
import { Check, ChevronDown } from '@lucide/vue'
import { computed, useAttrs, useId } from 'vue'
import {
ComboboxAnchor,
ComboboxContent,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxItemIndicator,
ComboboxPortal,
ComboboxRoot,
ComboboxTrigger,
} from 'reka-ui'
interface ComboboxOption {
value: string
label: string
}
defineOptions({ inheritAttrs: false })
const props = withDefaults(
defineProps<{
modelValue: string
label: string
options: ComboboxOption[]
emptyText: string
id?: string
placeholder?: string
disabled?: boolean
invalid?: boolean
describedBy?: string
size?: 'sm' | 'md' | 'touch'
spellcheck?: boolean
monospace?: boolean
}>(),
{
id: undefined,
placeholder: undefined,
disabled: false,
invalid: false,
describedBy: undefined,
size: 'md',
spellcheck: true,
monospace: false,
},
)
const emit = defineEmits<{ 'update:modelValue': [value: string] }>()
const attrs = useAttrs()
const generatedId = useId()
const inputId = computed(() => props.id ?? `${generatedId}-input`)
const normalizedOptions = computed(() => props.options.filter((option) => option.value !== ''))
function selectOption(value: unknown): void {
if (typeof value === 'string') emit('update:modelValue', value)
}
</script>
<template>
<ComboboxRoot
class="app-combobox"
:model-value="modelValue"
:disabled="disabled"
:open-on-click="true"
:reset-search-term-on-blur="true"
@update:model-value="selectOption"
>
<ComboboxAnchor
class="app-combobox__anchor"
:class="[
`app-combobox__anchor--${size}`,
{
'app-combobox__anchor--disabled': disabled,
'app-combobox__anchor--invalid': invalid,
},
]"
data-input-shell
>
<label class="sr-only" :for="inputId">{{ label }}</label>
<ComboboxInput
:id="inputId"
v-bind="attrs"
class="app-combobox__input"
:class="{ 'app-combobox__input--mono': monospace }"
:model-value="modelValue"
:placeholder="placeholder"
:disabled="disabled"
:aria-invalid="invalid || undefined"
:aria-describedby="describedBy"
:spellcheck="spellcheck"
data-input-inner
@update:model-value="emit('update:modelValue', $event)"
/>
<ComboboxTrigger class="app-combobox__trigger" :disabled="disabled">
<ChevronDown :size="16" aria-hidden="true" />
</ComboboxTrigger>
</ComboboxAnchor>
<ComboboxPortal>
<ComboboxContent
class="app-combobox__content"
position="popper"
align="start"
:side-offset="6"
:collision-padding="8"
>
<ComboboxEmpty class="app-combobox__empty">{{ emptyText }}</ComboboxEmpty>
<ComboboxItem
v-for="option in normalizedOptions"
:key="option.value"
class="app-combobox__item"
:value="option.value"
:text-value="option.label"
>
<ComboboxItemIndicator class="app-combobox__indicator">
<Check :size="15" aria-hidden="true" />
</ComboboxItemIndicator>
<span>{{ option.label }}</span>
</ComboboxItem>
</ComboboxContent>
</ComboboxPortal>
</ComboboxRoot>
</template>
<style>
.app-combobox {
display: block;
width: 100%;
min-width: 0;
}
.app-combobox__anchor {
display: flex;
width: 100%;
min-width: 0;
min-height: var(--control-md);
align-items: center;
border: 1px solid var(--color-border-control);
border-radius: var(--radius-control);
background: var(--color-surface);
color: var(--color-text);
transition:
border-color var(--duration-fast) var(--easing-standard),
box-shadow var(--duration-fast) var(--easing-standard),
opacity var(--duration-fast) var(--easing-standard);
}
.app-combobox__anchor:hover:not(.app-combobox__anchor--disabled) {
border-color: var(--color-text-faint);
}
.app-combobox__anchor--sm {
min-height: var(--control-sm);
height: var(--control-sm);
font-size: var(--text-meta);
}
.app-combobox__anchor--touch {
min-height: var(--touch-target);
}
.app-combobox__anchor--disabled {
cursor: not-allowed;
opacity: 0.55;
}
.app-combobox__anchor--invalid {
border-color: var(--color-danger);
}
.app-combobox__input {
width: 100%;
min-width: 0;
min-height: inherit;
border: 0;
outline: 0;
background: transparent;
color: var(--color-text);
padding: 0 0 0 var(--space-3);
font: inherit;
}
.app-combobox__input::placeholder {
color: var(--color-text-faint);
opacity: 1;
}
.app-combobox__input:disabled {
cursor: not-allowed;
}
.app-combobox__input:focus-visible {
outline: 0;
}
.app-combobox__input--mono {
font-family: var(--font-mono);
}
.app-combobox__trigger {
display: inline-flex;
width: var(--control-sm);
height: 100%;
min-height: inherit;
flex: none;
align-items: center;
justify-content: center;
border: 0;
background: transparent;
color: var(--color-text-faint);
padding: 0;
cursor: pointer;
}
.app-combobox__trigger:disabled {
cursor: not-allowed;
}
.app-combobox__trigger[data-state='open'] svg {
transform: rotate(180deg);
}
.app-combobox__trigger svg {
transition: transform var(--duration-fast) var(--easing-standard);
}
.app-combobox__content {
z-index: var(--z-popover);
width: var(--reka-combobox-trigger-width);
max-width: calc(100vw - 16px);
max-height: min(320px, var(--reka-combobox-content-available-height));
overflow-y: auto;
border: 1px solid var(--color-border-control);
border-radius: var(--radius-control);
background: var(--color-surface);
padding: var(--space-1);
box-shadow: var(--shadow-overlay);
transform-origin: var(--reka-combobox-content-transform-origin);
scrollbar-width: none;
-ms-overflow-style: none;
-webkit-overflow-scrolling: touch;
}
.app-combobox__content::-webkit-scrollbar {
display: none;
}
.app-combobox__content[data-state='open'] {
animation: app-combobox-in var(--duration-fast) var(--easing-standard);
}
.app-combobox__item {
position: relative;
display: flex;
min-width: 0;
min-height: 44px;
align-items: center;
border-radius: var(--radius-tag);
color: var(--color-text);
padding: 7px 10px 7px 32px;
cursor: pointer;
outline: none;
overflow-wrap: anywhere;
}
.app-combobox__item[data-highlighted] {
background: var(--color-surface-sunken);
}
.app-combobox__indicator {
position: absolute;
left: 10px;
display: inline-flex;
color: var(--color-action);
}
.app-combobox__empty {
color: var(--color-text-faint);
padding: 12px 10px;
font-size: var(--text-sm);
}
@keyframes app-combobox-in {
from {
opacity: 0;
transform: translateY(-4px) scale(0.98);
}
}
@media (max-width: 860px) {
.app-combobox__anchor--sm {
min-height: var(--touch-target);
height: var(--touch-target);
}
}
@media (prefers-reduced-motion: reduce) {
.app-combobox__content[data-state='open'] {
animation: none;
}
.app-combobox__trigger svg {
transition: none;
}
}
</style>
+484 -55
View File
@@ -1,7 +1,25 @@
<script setup lang="ts">
import { CalendarClock } from '@lucide/vue'
import { computed, ref, useId } from 'vue'
import { CalendarDate, Time, type DateValue } from '@internationalized/date'
import { CalendarClock, ChevronLeft, ChevronRight } from '@lucide/vue'
import { computed, nextTick, ref, shallowRef, useId, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import {
RangeCalendarCell,
RangeCalendarCellTrigger,
RangeCalendarGrid,
RangeCalendarGridBody,
RangeCalendarGridHead,
RangeCalendarGridRow,
RangeCalendarHeadCell,
RangeCalendarHeader,
RangeCalendarHeading,
RangeCalendarNext,
RangeCalendarPrev,
RangeCalendarRoot,
TimeFieldInput,
TimeFieldRoot,
type TimeValue,
} from 'reka-ui'
import {
dateTimePresets,
@@ -14,6 +32,11 @@ import AppButton from './AppButton.vue'
import AppPopover from './AppPopover.vue'
import FormField from './FormField.vue'
type CalendarRange = {
start: DateValue | undefined
end: DateValue | undefined
}
const props = defineProps<{
from: string
to: string
@@ -37,9 +60,12 @@ const emit = defineEmits<{
apply: []
open: []
}>()
const { t } = useI18n()
const { t, locale } = useI18n()
const open = ref(false)
const fieldID = useId()
const selectingDateRange = ref(false)
const calendarRange = shallowRef<CalendarRange>(calendarRangeFromInputs(props.from, props.to))
const calendarApplyDisabled = computed(() => props.applyDisabled || selectingDateRange.value)
const rangeDisplay = computed(
() =>
@@ -56,7 +82,15 @@ const display = computed(() => {
function changeOpen(value: boolean): void {
open.value = value
if (value) emit('open')
if (!value) {
selectingDateRange.value = false
return
}
emit('open')
void nextTick(() => {
selectingDateRange.value = false
syncCalendarRange()
})
}
function displayValue(value: string): string {
@@ -69,9 +103,73 @@ function normalizeLocalInputValue(value: string): string {
return /^\d{4,}-\d{2}-\d{2}T\d{2}:\d{2}$/u.test(value) ? `${value}:00` : value
}
function updateLocalInput(field: 'from' | 'to', value: string): void {
function inputCalendarDate(value: string): CalendarDate | undefined {
const match = normalizeLocalInputValue(value).match(/^(\d{4,})-(\d{2})-(\d{2})T/u)
if (!match) return undefined
const year = Number(match[1])
const month = Number(match[2])
const day = Number(match[3])
if (!Number.isSafeInteger(year) || year < 1) return undefined
try {
const date = new CalendarDate(year, month, day)
return date.year === year && date.month === month && date.day === day ? date : undefined
} catch {
return undefined
}
}
function calendarRangeFromInputs(from: string, to: string): CalendarRange {
return {
start: inputCalendarDate(from),
end: inputCalendarDate(to),
}
}
function syncCalendarRange(): void {
calendarRange.value = calendarRangeFromInputs(props.from, props.to)
}
function calendarDateString(value: DateValue): string {
const pad = (part: number, length = 2) => String(part).padStart(length, '0')
return `${pad(value.year, 4)}-${pad(value.month)}-${pad(value.day)}`
}
function datePart(value: string): string {
return normalizeLocalInputValue(value).match(/^(\d{4,}-\d{2}-\d{2})T/u)?.[1] ?? ''
}
function timePart(value: string): string {
return normalizeLocalInputValue(value).match(/T(\d{2}:\d{2}:\d{2})(?:\.\d{1,3})?$/u)?.[1] ?? ''
}
function inputTimeValue(value: string): Time | undefined {
const match = timePart(value).match(/^(\d{2}):(\d{2}):(\d{2})$/u)
if (!match) return undefined
return new Time(Number(match[1]), Number(match[2]), Number(match[3]))
}
function timeValueString(value: TimeValue): string {
const pad = (part: number) => String(part).padStart(2, '0')
return `${pad(value.hour)}:${pad(value.minute)}:${pad(value.second)}`
}
function combineDateAndTime(date: DateValue, currentValue: string): string {
return `${calendarDateString(date)}T${timePart(currentValue) || '00:00:00'}`
}
function calendarDateForField(field: 'from' | 'to'): DateValue | undefined {
return field === 'from' ? calendarRange.value.start : calendarRange.value.end
}
function updateLocalTime(field: 'from' | 'to', value: TimeValue | undefined): void {
emit('update:preset', undefined)
const normalized = normalizeLocalInputValue(value)
const currentValue = field === 'from' ? props.from : props.to
const selectedDate = calendarDateForField(field)
const selectedDatePart = selectedDate ? calendarDateString(selectedDate) : ''
const currentDatePart = datePart(currentValue)
const resolvedDatePart = currentDatePart || selectedDatePart
const normalized =
value && resolvedDatePart ? `${resolvedDatePart}T${timeValueString(value)}` : ''
if (field === 'from') {
emit('update:from', normalized)
} else {
@@ -82,19 +180,51 @@ function updateLocalInput(field: 'from' | 'to', value: string): void {
function selectShortcut(preset: DateTimePreset): void {
const now = Math.floor(Date.now() / 1000) * 1000
const range = resolveDateTimePreset(preset, now)
emit('update:from', localDateTimeInput(range.from_ms))
emit('update:to', localDateTimeInput(range.to_ms))
const from = localDateTimeInput(range.from_ms)
const to = localDateTimeInput(range.to_ms)
selectingDateRange.value = false
calendarRange.value = calendarRangeFromInputs(from, to)
emit('update:from', from)
emit('update:to', to)
emit('update:preset', preset)
emit('shortcut', preset, range.from_ms, range.to_ms)
if (props.applyLabel && range.to_ms > range.from_ms) open.value = false
}
function updateCalendarRange(value: CalendarRange): void {
calendarRange.value = value
emit('update:preset', undefined)
if (!value.start || !value.end) {
selectingDateRange.value = Boolean(value.start)
return
}
selectingDateRange.value = false
emit('update:from', combineDateAndTime(value.start, props.from))
emit('update:to', combineDateAndTime(value.end, props.to))
}
function formatCalendarMonth(value: DateValue): string {
const date = new Date(Date.UTC(value.year, value.month - 1, 1))
return new Intl.DateTimeFormat(locale.value, {
year: 'numeric',
month: 'long',
timeZone: 'UTC',
}).format(date)
}
function apply(): void {
if (props.applyDisabled) return
if (calendarApplyDisabled.value) return
emit('update:preset', undefined)
emit('apply')
open.value = false
}
watch(
() => [props.from, props.to] as const,
() => {
if (!selectingDateRange.value) syncCalendarRange()
},
)
</script>
<template>
@@ -133,25 +263,113 @@ function apply(): void {
{{ t(`monitor.logs.filters.quick.${shortcut}`) }}
</AppButton>
</div>
<RangeCalendarRoot
v-slot="{ grid, weekDays }"
class="app-date-range__calendar"
:model-value="calendarRange"
:locale="locale"
:number-of-months="2"
:calendar-label="t('monitor.logs.filters.calendar')"
fixed-weeks
prevent-deselect
@update:model-value="updateCalendarRange"
>
<RangeCalendarHeader class="app-date-range__calendar-header">
<RangeCalendarPrev
class="app-date-range__calendar-nav"
:aria-label="t('monitor.logs.filters.previousMonth')"
>
<ChevronLeft :size="16" aria-hidden="true" />
</RangeCalendarPrev>
<RangeCalendarHeading class="sr-only" />
<h3
v-for="month in grid"
:key="month.value.toString()"
class="app-date-range__calendar-header-heading"
aria-hidden="true"
>
{{ formatCalendarMonth(month.value) }}
</h3>
<RangeCalendarNext
class="app-date-range__calendar-nav"
:aria-label="t('monitor.logs.filters.nextMonth')"
>
<ChevronRight :size="16" aria-hidden="true" />
</RangeCalendarNext>
</RangeCalendarHeader>
<div class="app-date-range__calendar-months">
<section
v-for="month in grid"
:key="month.value.toString()"
class="app-date-range__calendar-month"
>
<h3 class="app-date-range__calendar-month-heading" aria-hidden="true">
{{ formatCalendarMonth(month.value) }}
</h3>
<RangeCalendarGrid class="app-date-range__calendar-grid">
<RangeCalendarGridHead>
<RangeCalendarGridRow>
<RangeCalendarHeadCell
v-for="weekDay in weekDays"
:key="weekDay"
class="app-date-range__calendar-weekday"
>
{{ weekDay }}
</RangeCalendarHeadCell>
</RangeCalendarGridRow>
</RangeCalendarGridHead>
<RangeCalendarGridBody>
<RangeCalendarGridRow v-for="(weekDates, index) in month.rows" :key="index">
<RangeCalendarCell
v-for="day in weekDates"
:key="day.toString()"
class="app-date-range__calendar-cell"
:date="day"
>
<RangeCalendarCellTrigger
class="app-date-range__calendar-day"
:day="day"
:month="month.value"
>
{{ day.day }}
</RangeCalendarCellTrigger>
</RangeCalendarCell>
</RangeCalendarGridRow>
</RangeCalendarGridBody>
</RangeCalendarGrid>
</section>
</div>
</RangeCalendarRoot>
<div
class="app-date-range__fields"
:class="{ 'app-date-range__fields--with-apply': applyLabel }"
>
<FormField :id="`${fieldID}-from`" :label="fromLabel" size="compact" :error="fromError">
<template #default="{ describedBy, invalid }">
<span class="app-date-range__input-shell">
<input
:id="`${fieldID}-from`"
class="app-date-range__native-input"
:value="from"
type="datetime-local"
step="1"
:aria-label="fromLabel"
:aria-describedby="describedBy"
:aria-invalid="invalid || undefined"
@input="updateLocalInput('from', ($event.target as HTMLInputElement).value)"
/>
</span>
<TimeFieldRoot
:id="`${fieldID}-from`"
v-slot="{ segments }"
class="app-date-range__input-shell app-date-range__time-field"
:model-value="inputTimeValue(from)"
:locale="locale"
:hour-cycle="24"
granularity="second"
:aria-label="fromLabel"
:aria-describedby="describedBy"
:aria-invalid="invalid || undefined"
data-input-shell
@update:model-value="updateLocalTime('from', $event)"
>
<TimeFieldInput
v-for="(segment, index) in segments"
:key="`${segment.part}:${index}`"
as="span"
class="app-date-range__time-segment"
:part="segment.part"
>
{{ segment.value }}
</TimeFieldInput>
</TimeFieldRoot>
</template>
</FormField>
<FormField
@@ -163,24 +381,35 @@ function apply(): void {
>
<template #default="{ describedBy, invalid }">
<div class="app-date-range__end-controls">
<span class="app-date-range__input-shell">
<input
:id="`${fieldID}-to`"
class="app-date-range__native-input"
:value="to"
type="datetime-local"
step="1"
:aria-label="toLabel"
:aria-describedby="describedBy"
:aria-invalid="invalid || undefined"
@input="updateLocalInput('to', ($event.target as HTMLInputElement).value)"
/>
</span>
<TimeFieldRoot
:id="`${fieldID}-to`"
v-slot="{ segments }"
class="app-date-range__input-shell app-date-range__time-field"
:model-value="inputTimeValue(to)"
:locale="locale"
:hour-cycle="24"
granularity="second"
:aria-label="toLabel"
:aria-describedby="describedBy"
:aria-invalid="invalid || undefined"
data-input-shell
@update:model-value="updateLocalTime('to', $event)"
>
<TimeFieldInput
v-for="(segment, index) in segments"
:key="`${segment.part}:${index}`"
as="span"
class="app-date-range__time-segment"
:part="segment.part"
>
{{ segment.value }}
</TimeFieldInput>
</TimeFieldRoot>
<AppButton
v-if="applyLabel"
class="app-date-range__apply"
size="compact"
:disabled="applyDisabled"
:disabled="calendarApplyDisabled"
@click="apply"
>
{{ applyLabel }}
@@ -194,7 +423,7 @@ function apply(): void {
<style>
.app-date-range__trigger {
max-width: 332px;
max-width: 380px;
}
.app-date-range__trigger > span {
@@ -209,12 +438,12 @@ function apply(): void {
.app-date-range-popover {
--date-range-control-height: var(--control-xs);
width: min(420px, var(--reka-popover-content-available-width));
width: min(500px, var(--reka-popover-content-available-width));
padding: 14px;
}
.app-date-range-popover--with-apply {
width: min(480px, var(--reka-popover-content-available-width));
width: min(520px, var(--reka-popover-content-available-width));
}
.app-date-range__shortcuts {
@@ -240,6 +469,157 @@ function apply(): void {
color: var(--color-action);
}
.app-date-range__calendar {
border-bottom: 1px solid var(--color-border-subtle);
padding: 12px 0;
}
.app-date-range__calendar-header {
display: grid;
grid-template-columns: 30px repeat(2, minmax(0, 1fr)) 30px;
align-items: center;
gap: 12px;
margin-bottom: 6px;
}
.app-date-range__calendar-header-heading,
.app-date-range__calendar-month-heading {
margin: 0;
color: var(--color-text);
font-size: var(--text-sm);
font-weight: 650;
text-align: center;
}
.app-date-range__calendar-header-heading {
min-width: 0;
}
.app-date-range__calendar-header-heading:first-of-type {
grid-column: 2;
}
.app-date-range__calendar-header-heading:last-of-type {
grid-column: 3;
}
.app-date-range__calendar-header .app-date-range__calendar-nav:last-child {
grid-column: 4;
}
.app-date-range__calendar-nav {
display: inline-flex;
width: 30px;
height: 30px;
align-items: center;
justify-content: center;
border: 0;
border-radius: var(--radius-tag);
background: transparent;
color: var(--color-text-muted);
padding: 0;
cursor: pointer;
}
.app-date-range__calendar-nav:hover:not([data-disabled]) {
background: var(--color-surface-sunken);
color: var(--color-text);
}
.app-date-range__calendar-nav:focus-visible {
outline: 2px solid var(--color-action);
outline-offset: 1px;
}
.app-date-range__calendar-nav[data-disabled] {
cursor: not-allowed;
opacity: 0.45;
}
.app-date-range__calendar-months {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.app-date-range__calendar-month {
min-width: 0;
}
.app-date-range__calendar-month-heading {
display: none;
margin-bottom: 6px;
}
.app-date-range__calendar-grid {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
}
.app-date-range__calendar-weekday {
height: 26px;
color: var(--color-text-faint);
font-size: var(--text-meta);
font-weight: 500;
text-align: center;
}
.app-date-range__calendar-cell {
height: 32px;
padding: 1px;
text-align: center;
}
.app-date-range__calendar-day {
display: inline-flex;
width: 100%;
height: 30px;
align-items: center;
justify-content: center;
border: 0;
border-radius: var(--radius-tag);
background: transparent;
color: var(--color-text-muted);
padding: 0;
font: inherit;
font-size: var(--text-meta);
cursor: pointer;
outline: 0;
}
.app-date-range__calendar-day:hover:not([data-disabled]):not([data-outside-view]),
.app-date-range__calendar-day[data-focused]:not([data-selected]) {
background: var(--color-surface-sunken);
color: var(--color-text);
}
.app-date-range__calendar-day[data-highlighted],
.app-date-range__calendar-day[data-selected] {
background: var(--color-action-soft);
color: var(--color-action);
}
.app-date-range__calendar-day[data-selection-start],
.app-date-range__calendar-day[data-selection-end] {
background: var(--color-action);
color: var(--color-action-ink);
}
.app-date-range__calendar-day[data-today] {
box-shadow: inset 0 0 0 1px var(--color-action);
}
.app-date-range__calendar-day[data-outside-view] {
visibility: hidden;
}
.app-date-range__calendar-day[data-disabled],
.app-date-range__calendar-day[data-unavailable] {
cursor: not-allowed;
opacity: 0.42;
}
.app-date-range__end-controls .app-date-range__apply {
min-height: var(--date-range-control-height);
height: var(--date-range-control-height);
@@ -292,21 +672,38 @@ function apply(): void {
color: var(--color-text);
}
.app-date-range__native-input {
position: static !important;
width: 100% !important;
height: 100% !important;
min-height: 0 !important;
border: 0 !important;
border-radius: inherit !important;
background: transparent !important;
color: var(--color-text) !important;
cursor: pointer;
font-family: var(--font-mono) !important;
font-size: var(--text-meta) !important;
.app-date-range__time-field {
gap: 0;
padding: 0 10px;
font-family: var(--font-mono);
font-size: var(--text-meta);
font-variant-numeric: tabular-nums;
opacity: 1;
padding: 0 10px !important;
cursor: text;
}
.app-date-range__time-segment {
min-width: 2ch;
border-radius: 3px;
color: var(--color-text);
caret-color: transparent;
outline: 0;
text-align: center;
}
.app-date-range__time-segment[data-reka-time-field-segment='literal'] {
min-width: auto;
color: var(--color-text-faint);
padding-inline: 1px;
pointer-events: none;
}
.app-date-range__time-segment[data-placeholder] {
color: var(--color-text-faint);
}
.app-date-range__time-segment:focus {
background: var(--color-action-soft);
color: var(--color-action);
}
.app-date-range__input-shell:focus-within {
@@ -325,14 +722,46 @@ function apply(): void {
min-height: var(--touch-target);
}
.app-date-range__calendar-months {
grid-template-columns: minmax(0, 1fr);
}
.app-date-range__calendar-header {
grid-template-columns: 30px minmax(0, 1fr) 30px;
gap: 4px;
}
.app-date-range__calendar-header-heading:first-of-type {
grid-column: 2;
}
.app-date-range__calendar-header-heading:last-of-type {
display: none;
}
.app-date-range__calendar-header .app-date-range__calendar-nav:last-child {
grid-column: 3;
}
.app-date-range__calendar-month:not(:first-child) .app-date-range__calendar-month-heading {
display: block;
}
.app-date-range__fields {
grid-template-columns: minmax(0, 1fr);
}
.app-date-range__fields--with-apply .app-date-range__end-field {
grid-column: 1;
grid-template-columns: minmax(0, 1fr) auto;
column-gap: 10px;
grid-template-columns: minmax(0, 1fr);
}
.app-date-range__fields--with-apply .app-date-range__end-controls {
row-gap: 10px;
}
.app-date-range__apply {
width: 100%;
}
}
</style>
+23 -9
View File
@@ -11,9 +11,9 @@ import { revealAccessKey } from '@/app/resources/access-keys'
import { registerEphemeralStateCleaner } from '@/app/ephemeral-state'
import { type ClipboardCopyResult, useClipboardCopy } from '@/app/use-clipboard-copy'
import AppButton from '@/components/ui/AppButton.vue'
import AppCombobox from '@/components/ui/AppCombobox.vue'
import AppConfirmDialog from '@/components/ui/AppConfirmDialog.vue'
import AppSelect from '@/components/ui/AppSelect.vue'
import AppTextInput from '@/components/ui/AppTextInput.vue'
import CodeBlock from '@/components/ui/CodeBlock.vue'
import CopyAction from '@/components/ui/CopyAction.vue'
import CopyFallbackDialog from '@/components/ui/CopyFallbackDialog.vue'
@@ -30,6 +30,8 @@ import {
clientQuickImportURL,
clientRequiredProtocol,
gatewayClients,
orderModelSuggestions,
preferredGPTModel,
type CCSwitchTargetID,
type GatewayClientID,
} from './gateway-clients'
@@ -86,6 +88,12 @@ const selectOptions = computed(() =>
label: `${accessKey.name} · ${accessKey.masked_key}`,
})),
)
const ccSwitchModelOptions = computed(() =>
orderModelSuggestions(selectedKey.value?.models ?? []).map((model) => ({
value: model,
label: model,
})),
)
const currentClient = computed(
() =>
gatewayClients.find((candidate) => candidate.id === activeClient.value) ?? gatewayClients[0]!,
@@ -297,13 +305,17 @@ watch(
{ immediate: true },
)
watch(selectedKeyID, (value, previous) => {
if (value === previous) return
invalidateSensitiveAction()
quickImportConfirmationOpen.value = false
ccSwitchModel.value = ''
selectFirstSupportedCCSwitchTarget()
})
watch(
selectedKeyID,
(value, previous) => {
if (value === previous) return
invalidateSensitiveAction()
quickImportConfirmationOpen.value = false
ccSwitchModel.value = preferredGPTModel(selectedKey.value?.models ?? [])
selectFirstSupportedCCSwitchTarget()
},
{ immediate: true },
)
watch(activeClient, (value, previous) => {
if (value === previous) return
@@ -602,10 +614,12 @@ onBeforeUnmount(() => {
· {{ t('home.ledger.connection.required') }}
</span>
</span>
<AppTextInput
<AppCombobox
id="cc-switch-primary-model"
v-model="ccSwitchModel"
:label="t('home.ledger.connection.primaryModel')"
:options="ccSwitchModelOptions"
:empty-text="t('home.ledger.connection.noModelMatches')"
:placeholder="t('home.ledger.connection.modelPlaceholder')"
:disabled="actionBusy"
:maxlength="200"
+42
View File
@@ -222,6 +222,48 @@ export function clientRequiredProtocol(
return client.id === 'cc-switch' ? ccSwitchTarget.requiredProtocol : client.requiredProtocol
}
const modelNameCollator = new Intl.Collator('en-US', {
numeric: true,
sensitivity: 'base',
})
function gptVersion(model: string): number[] | null {
const match = /^gpt-(\d+(?:\.\d+)*)/i.exec(model.trim())
return match?.[1]?.split('.').map(Number) ?? null
}
function compareVersionsDescending(left: readonly number[], right: readonly number[]): number {
const length = Math.max(left.length, right.length)
for (let index = 0; index < length; index += 1) {
const difference = (right[index] ?? -1) - (left[index] ?? -1)
if (difference !== 0) return difference
}
return 0
}
/** GPT models first by newest numeric version, followed by the remaining model names. */
export function orderModelSuggestions(models: readonly string[]): string[] {
return [...models].sort((left, right) => {
const leftVersion = gptVersion(left)
const rightVersion = gptVersion(right)
if (leftVersion && rightVersion) {
const versionOrder = compareVersionsDescending(leftVersion, rightVersion)
if (versionOrder !== 0) return versionOrder
const lengthOrder = left.length - right.length
if (lengthOrder !== 0) return lengthOrder
} else if (leftVersion) {
return -1
} else if (rightVersion) {
return 1
}
return modelNameCollator.compare(left, right)
})
}
export function preferredGPTModel(models: readonly string[]): string {
return orderModelSuggestions(models).find((model) => gptVersion(model) !== null) ?? ''
}
export function clientConfiguration(
clientID: GatewayClientID,
origin: string,
+2 -1
View File
@@ -364,7 +364,8 @@ export default {
targetApplication: 'Target application',
primaryModel: 'Primary model',
required: 'Required',
modelPlaceholder: 'Enter a model available to this access key',
modelPlaceholder: 'Select or enter a model available to this access key',
noModelMatches: 'No matching model; you can keep the current custom value',
ccSwitchModelRequired:
'This target needs an explicit model to produce a usable configuration. Enter an available model before importing',
selectClient: 'Select a client',
+3
View File
@@ -602,6 +602,9 @@ export default {
from: 'From',
to: 'To',
quickRanges: 'Quick time ranges',
calendar: 'Date range',
previousMonth: 'Previous month',
nextMonth: 'Next month',
quickDisplay: {
'1h': 'Last 1 hour',
'6h': 'Last 6 hours',
+2 -1
View File
@@ -363,7 +363,8 @@ export default {
targetApplication: '対象アプリ',
primaryModel: 'プライマリモデル',
required: '必須',
modelPlaceholder: 'このアクセスキーで利用可能なモデルを入力',
modelPlaceholder: 'このアクセスキーで利用可能なモデルを選択または入力',
noModelMatches: '一致するモデルはありません。現在の入力値をそのまま使用できます',
ccSwitchModelRequired:
'この対象で利用可能な設定を作るにはモデルの指定が必要です。利用可能なモデルを入力してからインポートしてください',
selectClient: 'クライアントを選択',
+3
View File
@@ -601,6 +601,9 @@ export default {
from: '開始時刻',
to: '終了時刻',
quickRanges: 'クイック時間範囲',
calendar: '日付範囲',
previousMonth: '前の月',
nextMonth: '次の月',
quickDisplay: {
'1h': '過去 1 時間',
'6h': '過去 6 時間',
+2 -1
View File
@@ -346,7 +346,8 @@ export default {
targetApplication: '目标应用',
primaryModel: '主模型',
required: '必填',
modelPlaceholder: '输入此访问密钥可用的模型',
modelPlaceholder: '选择或输入此访问密钥可用的模型',
noModelMatches: '没有匹配模型,可继续使用当前输入值',
ccSwitchModelRequired: '该目标需要明确模型才能生成可用配置;请先填写实际可用模型再导入',
selectClient: '选择客户端',
searchClients: '搜索客户端',
+3
View File
@@ -580,6 +580,9 @@ export default {
from: '开始时间',
to: '结束时间',
quickRanges: '快捷时间范围',
calendar: '日期范围',
previousMonth: '上一个月',
nextMonth: '下一个月',
quickDisplay: {
'1h': '最近 1 小时',
'6h': '最近 6 小时',