mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-05 20:59:38 +08:00
264 lines
8.4 KiB
TypeScript
264 lines
8.4 KiB
TypeScript
'use client'
|
|
|
|
import { useEffect, useState } from 'react'
|
|
import { useTranslation } from 'react-i18next'
|
|
import { Button } from '@/shared/ui/Button'
|
|
import { NumberField } from '@/shared/ui/number-field/number-field'
|
|
import { Field } from '@/shared/ui/Field'
|
|
import { Dialog } from '@/shared/ui/Dialog'
|
|
import { getPartnerTask, savePartnerTask, type PartnerTask } from '@/lib/partners-api'
|
|
|
|
const control = 'rounded-lg focus:outline-none focus-visible:bg-[var(--secondary)]'
|
|
const field = `w-full rounded-xl border border-border bg-transparent px-4 py-3 ${control}`
|
|
const row = 'flex flex-wrap items-center justify-between gap-3 px-4 py-3'
|
|
|
|
function TaskChoices<T extends string | number>({
|
|
label,
|
|
options,
|
|
value,
|
|
onChange,
|
|
}: {
|
|
label: string
|
|
options: ReadonlyArray<readonly [T, string]>
|
|
value: T
|
|
onChange: (choice: T) => void
|
|
}) {
|
|
return (
|
|
<div role="group" aria-label={label} className="inline-flex gap-1 rounded-xl bg-muted/60 p-1">
|
|
{options.map(([choice, text]) => (
|
|
<button
|
|
key={choice}
|
|
type="button"
|
|
aria-pressed={value === choice}
|
|
onClick={() => onChange(choice)}
|
|
className={`rounded-lg px-3 py-1.5 text-sm transition-colors focus:outline-none focus-visible:underline ${value === choice ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}
|
|
>
|
|
{text}
|
|
</button>
|
|
))}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function localTime(ms?: number | null) {
|
|
if (!ms) return ''
|
|
const date = new Date(ms)
|
|
return new Date(ms - date.getTimezoneOffset() * 60000).toISOString().slice(0, 19)
|
|
}
|
|
|
|
export function PartnerTaskEditor({
|
|
partnerId,
|
|
partnerName,
|
|
sessionKey,
|
|
jobId,
|
|
messageTime,
|
|
description,
|
|
onClose,
|
|
onSaved,
|
|
}: {
|
|
partnerId: string
|
|
partnerName: string
|
|
sessionKey: string
|
|
jobId?: string
|
|
messageTime?: string
|
|
description: string
|
|
onClose: () => void
|
|
onSaved: (id: string) => void
|
|
}) {
|
|
const { t } = useTranslation()
|
|
const [original, setOriginal] = useState<PartnerTask | null>(null)
|
|
const [loading, setLoading] = useState(Boolean(jobId))
|
|
const [ready, setReady] = useState(!jobId)
|
|
const [saving, setSaving] = useState(false)
|
|
const [error, setError] = useState('')
|
|
const [name, setName] = useState(description.split('\n')[0].slice(0, 48))
|
|
const [message, setMessage] = useState(description)
|
|
const [kind, setKind] = useState<PartnerTask['schedule']['kind']>('at')
|
|
const [when, setWhen] = useState('')
|
|
const [amount, setAmount] = useState(1)
|
|
const [unit, setUnit] = useState(3600)
|
|
|
|
useEffect(() => {
|
|
if (!jobId) return
|
|
let active = true
|
|
getPartnerTask(partnerId, sessionKey, jobId)
|
|
.then(task => {
|
|
if (!active) return
|
|
if (task) {
|
|
setOriginal(task)
|
|
setName(task.name)
|
|
setMessage(task.message)
|
|
setKind(task.schedule.kind)
|
|
setWhen(localTime(task.schedule.at_ms))
|
|
const seconds = task.schedule.every_seconds ?? 3600
|
|
const scale = seconds % 3600 === 0 ? 3600 : seconds % 60 === 0 ? 60 : 1
|
|
setUnit(scale)
|
|
setAmount(seconds / scale)
|
|
}
|
|
setReady(true)
|
|
})
|
|
.catch(e => {
|
|
if (active) setError(String(e.message ?? e))
|
|
})
|
|
.finally(() => {
|
|
if (active) setLoading(false)
|
|
})
|
|
return () => {
|
|
active = false
|
|
}
|
|
}, [jobId, partnerId, sessionKey])
|
|
|
|
const recorded = messageTime ? new Date(messageTime) : null
|
|
const seconds = amount * unit
|
|
const at =
|
|
original?.schedule.kind === 'at' && when === localTime(original.schedule.at_ms)
|
|
? original.schedule.at_ms
|
|
: new Date(when).getTime()
|
|
const schedule: PartnerTask['schedule'] =
|
|
kind === 'at'
|
|
? { kind, at_ms: at }
|
|
: kind === 'every'
|
|
? { kind, every_seconds: seconds }
|
|
: original!.schedule
|
|
const unchanged =
|
|
original &&
|
|
original.name === name.trim() &&
|
|
original.message === message.trim() &&
|
|
Object.entries(schedule).every(
|
|
([key, value]) => original.schedule[key as keyof typeof schedule] === value
|
|
)
|
|
const valid =
|
|
name.trim() &&
|
|
message.trim() &&
|
|
(kind === 'at'
|
|
? at && at > Date.now()
|
|
: kind === 'every'
|
|
? Number.isSafeInteger(seconds) && seconds >= 30
|
|
: original?.schedule.kind === 'cron')
|
|
|
|
async function save() {
|
|
if (!ready || saving || !valid || unchanged) return
|
|
setSaving(true)
|
|
setError('')
|
|
try {
|
|
const result = await savePartnerTask(
|
|
partnerId,
|
|
sessionKey,
|
|
{ name: name.trim(), message: message.trim(), schedule },
|
|
original ? jobId : undefined
|
|
)
|
|
onSaved(result.id)
|
|
} catch (e) {
|
|
setError(e instanceof Error ? e.message : String(e))
|
|
setSaving(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Dialog
|
|
open
|
|
onClose={onClose}
|
|
title={t('Edit task')}
|
|
closeLabel={t('Close')}
|
|
size="lg"
|
|
busy={saving}
|
|
footer={
|
|
<>
|
|
<Button variant="ghost" disabled={saving} onClick={onClose}>
|
|
{t('Cancel')}
|
|
</Button>
|
|
<Button loading={saving} disabled={!ready || !valid || Boolean(unchanged)} onClick={save}>
|
|
{t(original || loading ? 'Save' : 'Schedule again')}
|
|
</Button>
|
|
</>
|
|
}
|
|
>
|
|
{loading && <p>{t('Loading...')}</p>}
|
|
{ready && (
|
|
<fieldset disabled={saving} className="space-y-4 text-sm">
|
|
<Field label={t('Task name')}>
|
|
<input className={field} value={name} onChange={e => setName(e.target.value)} />
|
|
</Field>
|
|
<Field label={t('Task description')}>
|
|
<textarea
|
|
className={`${field} min-h-32 resize-y leading-relaxed`}
|
|
value={message}
|
|
onChange={e => setMessage(e.target.value)}
|
|
/>
|
|
</Field>
|
|
<div className="divide-y divide-border rounded-xl border border-border">
|
|
{recorded && Number.isFinite(recorded.getTime()) && (
|
|
<div className={row}>
|
|
<span>{t('Reminder message time')}</span>
|
|
<time dateTime={messageTime}>{recorded.toLocaleString()}</time>
|
|
</div>
|
|
)}
|
|
<div className={row}>
|
|
<span>{t('Repeat')}</span>
|
|
<TaskChoices
|
|
label={t('Repeat')}
|
|
value={kind}
|
|
onChange={setKind}
|
|
options={[
|
|
...(original?.schedule.kind === 'cron'
|
|
? [['cron', t('Keep existing schedule')] as const]
|
|
: []),
|
|
['at', t('Once')],
|
|
['every', t('Fixed interval')],
|
|
]}
|
|
/>
|
|
</div>
|
|
{kind === 'every' ? (
|
|
<div className={row}>
|
|
<NumberField label={t('Every')} size="sm" value={amount}
|
|
min={unit === 1 ? 30 : 1} max={Math.floor(Number.MAX_SAFE_INTEGER / unit)}
|
|
onValueChange={setAmount} disabled={saving} limitHint={false} />
|
|
<TaskChoices
|
|
label={t('Interval unit')}
|
|
value={unit}
|
|
onChange={next => {
|
|
setUnit(next)
|
|
setAmount(value => Math.min(Math.floor(Number.MAX_SAFE_INTEGER / next), Math.max(next === 1 ? 30 : 1, value)))
|
|
}}
|
|
options={[
|
|
[1, t('Seconds')],
|
|
[60, t('Minutes')],
|
|
[3600, t('Hours')],
|
|
]}
|
|
/>
|
|
</div>
|
|
) : kind === 'at' ? (
|
|
<label className={row}>
|
|
{t(original ? 'Run at' : 'New run time')}
|
|
<input
|
|
type="datetime-local"
|
|
step="1"
|
|
className={control}
|
|
value={when}
|
|
onChange={e => setWhen(e.target.value)}
|
|
/>
|
|
</label>
|
|
) : null}
|
|
</div>
|
|
<details>
|
|
<summary className={`w-fit cursor-pointer text-muted-foreground ${control}`}>
|
|
{t('Advanced')}
|
|
</summary>
|
|
<div className="mt-2 divide-y divide-border rounded-xl border border-border">
|
|
<div className={row}>
|
|
<span>{t('Runs in')}</span>
|
|
<span>{partnerName}</span>
|
|
</div>
|
|
</div>
|
|
</details>
|
|
</fieldset>
|
|
)}
|
|
{error && (
|
|
<p role="alert" className="mt-2 text-destructive">
|
|
{error}
|
|
</p>
|
|
)}
|
|
</Dialog>
|
|
)
|
|
}
|