Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/3114-scheduled-task-time-zone.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A scheduled task's form now names the time zone its rule runs in: "Every day at 09:00" carries the zone it was saved with instead of silently meaning this device's zone, a Once task's date and time are read in that zone, and the row and the edit form name the same one ([#3114](https://github.com/ThinkFlowLab/FlyBot/issues/3114)).
89 changes: 78 additions & 11 deletions core/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -1258,6 +1258,7 @@ var ZH = {
"What for": "用途",
Activity: "活跃度",
"Time range": "时间范围",
"Time zone": "时区",
"All usage": "全部用量",
"Group usage by": "用量分组",
"By Bot": "按 Bot",
Expand Down Expand Up @@ -3943,6 +3944,59 @@ function useSchedules(actions) {
}
var schedulesReadFailure = (failure) => typeof failure === "string" && failure !== "" ? t("The scheduled tasks could not be read: {reason}", { reason: failure }) : null;
var localZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
function timeZoneOptions(current) {
const supported = typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : [];
const zone = String(current ?? "").trim();
const list = supported.length > 0 ? ["UTC", ...supported] : ["UTC", "Asia/Shanghai"];
if (zone !== "") list.unshift(zone);
return [...new Set(list.filter(Boolean))];
}
function zoneParts(ms, timeZone) {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: timeZone || "UTC",
hourCycle: "h23",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
}).formatToParts(new Date(ms));
const value = (type) => Number(parts.find((part) => part.type === type)?.value);
return Date.UTC(value("year"), value("month") - 1, value("day"), value("hour"), value("minute"), value("second"));
}
function wallClockInput(ms, timeZone) {
const at = Number(ms);
if (!Number.isFinite(at)) return "";
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: String(timeZone ?? "").trim() || localZone(),
hourCycle: "h23",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit"
}).formatToParts(new Date(at));
const value = (type) => parts.find((part) => part.type === type)?.value;
return value("year") ? `${value("year")}-${value("month")}-${value("day")}T${value("hour")}:${value("minute")}` : "";
}
function instantFromWallClock(wall, timeZone) {
const match = String(wall ?? "").match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/);
if (!match) throw new Error("Pick a date and time");
const asUtc = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), Number(match[6] ?? 0));
const zone = String(timeZone ?? "").trim() || "UTC";
let instant2 = asUtc;
for (let pass = 0; pass < 3; pass += 1) {
const shown = zoneParts(instant2, zone);
if (shown === asUtc) break;
instant2 -= shown - asUtc;
}
if (zoneParts(instant2, zone) === asUtc) return new Date(instant2).toISOString();
for (const probe of [instant2 - 36e5, instant2 + 36e5, instant2 - 72e5, instant2 + 72e5]) {
if (zoneParts(probe, zone) === asUtc) return new Date(probe).toISOString();
}
throw new Error("Pick a date and time");
}
var clock2 = (time) => String(time ?? "").slice(0, 5);
var when = (ms, options) => new Intl.DateTimeFormat(dateLocale(), options).format(ms);
function dayAndTime(ms) {
Expand Down Expand Up @@ -4117,10 +4171,6 @@ function inAnHour() {
}
var KINDS = [["at", "Once"], ["daily", "Every day"], ["weekly", "Every week"], ["every", "Repeat"]];
var UNITS = [["seconds", 1, "second", "seconds"], ["minutes", 60, "minute", "minutes"], ["hours", 3600, "hour", "hours"], ["days", 86400, "day", "days"]];
function localInput(ms) {
const date = new Date(ms);
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
function formStart(task) {
const seconds = task?.kind === "every" ? Number(task.everySeconds) : 3600;
const [unit, size] = seconds % 86400 === 0 ? ["days", 86400] : seconds % 3600 === 0 ? ["hours", 3600] : seconds % 60 === 0 ? ["minutes", 60] : ["seconds", 1];
Expand All @@ -4129,14 +4179,21 @@ function formStart(task) {
title: task?.title ?? "",
prompt: task?.prompt ?? "",
kind: once ? "at" : task?.kind ?? "daily",
at: once && !Number.isNaN(Date.parse(task.scheduledAt)) ? localInput(Date.parse(task.scheduledAt)) : inAnHour(),
at: once && !Number.isNaN(Date.parse(task.scheduledAt)) ? wallClockInput(Date.parse(task.scheduledAt), task?.timeZone || localZone()) : inAnHour(),
time: task?.time ? clock2(task.time) : "09:00",
weekdays: task?.kind === "weekly" && Array.isArray(task.weekdays) ? task.weekdays : [1, 2, 3, 4, 5],
count: Math.max(1, Math.round(seconds / size)),
unit,
timeZone: task?.timeZone || localZone()
};
}
function whenFromForm({ kind, at, time, weekdays, timeZone, count, unit } = {}) {
const zone = String(timeZone ?? "").trim() || localZone();
if (kind === "cron") return { kind: "keep" };
if (kind === "at") return { kind, at: instantFromWallClock(at, zone), timeZone: zone };
if (kind === "every") return { kind, seconds: Math.round(Number(count) * UNITS.find(([id]) => id === unit)[1]) };
return { kind, time, timeZone: zone, ...kind === "weekly" ? { weekdays } : {} };
}
function TaskForm({ roster, actions, start, task, onDone, onCancel }) {
const first = formStart(task);
const [target, setTarget] = (0, import_react4.useState)(task ? task.botId ?? task.roomId : start ?? "");
Expand All @@ -4148,14 +4205,10 @@ function TaskForm({ roster, actions, start, task, onDone, onCancel }) {
const [weekdays, setWeekdays] = (0, import_react4.useState)(first.weekdays);
const [count, setCount] = (0, import_react4.useState)(first.count);
const [unit, setUnit] = (0, import_react4.useState)(first.unit);
const [timeZone, setTimeZone] = (0, import_react4.useState)(first.timeZone);
const [busy, setBusy] = (0, import_react4.useState)(false);
const [error, setError] = (0, import_react4.useState)("");
const timing = () => {
if (kind === "cron") return { kind: "keep" };
if (kind === "at") return { kind, at: new Date(at).toISOString(), timeZone: first.timeZone };
if (kind === "every") return { kind, seconds: Math.round(Number(count) * UNITS.find(([id]) => id === unit)[1]) };
return { kind, time, timeZone: first.timeZone, ...kind === "weekly" ? { weekdays } : {} };
};
const timing = () => whenFromForm({ kind, at, time, weekdays, timeZone, count, unit });
const submit = (event) => {
event.preventDefault();
if (busy || target === "") return;
Expand Down Expand Up @@ -4234,6 +4287,20 @@ function TaskForm({ roster, actions, start, task, onDone, onCancel }) {
) : null
)
),
// Which 09:00 this is: only the rules DSH keeps a zone for show it — a repeat interval has
// none, and a cron rule is kept as stored unless the kind changes (#3110).
kind === "at" || kind === "daily" || kind === "weekly" ? (0, import_react4.createElement)(
"label",
{ className: "bt-set-row bt-bs-row" },
(0, import_react4.createElement)("span", { className: "bt-set-copy" }, (0, import_react4.createElement)("span", { className: "bt-bs-label" }, t("Time zone"))),
(0, import_react4.createElement)("select", {
className: "bt-select bt-task-timezone",
"data-flybot": "task-timezone",
value: timeZone,
"aria-label": t("Time zone"),
onChange: (event) => setTimeZone(event.target.value)
}, timeZoneOptions(timeZone).map((zone) => (0, import_react4.createElement)("option", { key: zone, value: zone }, zone)))
) : null,
error ? (0, import_react4.createElement)("div", { className: "bt-set-row" }, (0, import_react4.createElement)("span", { className: "bt-danger bt-set-hint", role: "alert" }, error)) : null,
(0, import_react4.createElement)(
"div",
Expand Down
1 change: 1 addition & 0 deletions core/src/client/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -1212,6 +1212,7 @@ const ZH = {
'What for': '用途',
Activity: '活跃度',
'Time range': '时间范围',
'Time zone': '时区',
'All usage': '全部用量',
'Group usage by': '用量分组',
'By Bot': '按 Bot',
Expand Down
101 changes: 84 additions & 17 deletions core/src/client/schedules.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,63 @@ export const schedulesReadFailure = failure => (typeof failure === 'string' && f
: null)

const localZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone

// The form sends an IANA zone with the rules that carry one (#3110). This runtime's own list is
// the choices; a zone already on the task stays listed even when the runtime omits it.
export function timeZoneOptions(current) {
const supported = typeof Intl.supportedValuesOf === 'function' ? Intl.supportedValuesOf('timeZone') : []
const zone = String(current ?? '').trim()
const list = supported.length > 0 ? ['UTC', ...supported] : ['UTC', 'Asia/Shanghai']
if (zone !== '') list.unshift(zone)
return [...new Set(list.filter(Boolean))]
}

// The wall clock a zone shows for an instant, as the parts of a datetime-local value.
function zoneParts(ms, timeZone) {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone: timeZone || 'UTC', hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
}).formatToParts(new Date(ms))
const value = type => Number(parts.find(part => part.type === type)?.value)
return Date.UTC(value('year'), value('month') - 1, value('day'), value('hour'), value('minute'), value('second'))
}

// A stored instant as a datetime-local value in the zone the task keeps (#3110), not this device's.
export function wallClockInput(ms, timeZone) {
const at = Number(ms)
if (!Number.isFinite(at)) return ''
const parts = new Intl.DateTimeFormat('en-US', {
timeZone: String(timeZone ?? '').trim() || localZone(), hourCycle: 'h23',
year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit',
}).formatToParts(new Date(at))
const value = type => parts.find(part => part.type === type)?.value
return value('year') ? `${value('year')}-${value('month')}-${value('day')}T${value('hour')}:${value('minute')}` : ''
}

// The instant a wall clock names in a zone (#3110). DSH stores the instant; a wall clock the zone
// skips (a DST gap) is refused rather than moved to another hour.
export function instantFromWallClock(wall, timeZone) {
const match = String(wall ?? '').match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/)
if (!match) throw new Error('Pick a date and time')
const asUtc = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), Number(match[6] ?? 0))
const zone = String(timeZone ?? '').trim() || 'UTC'
let instant = asUtc
// Two passes settle the offset: the first guess is read back in the zone, and the difference
// between what it shows and what we meant is the offset to remove.
for (let pass = 0; pass < 3; pass += 1) {
const shown = zoneParts(instant, zone)
if (shown === asUtc) break
instant -= shown - asUtc
}
if (zoneParts(instant, zone) === asUtc) return new Date(instant).toISOString()
// A clock the zone gains (a DST gap) has no instant: refuse it, as the host refuses a time it
// cannot run.
for (const probe of [instant - 3_600_000, instant + 3_600_000, instant - 7_200_000, instant + 7_200_000]) {
if (zoneParts(probe, zone) === asUtc) return new Date(probe).toISOString()
}
throw new Error('Pick a date and time')
}

const clock = time => String(time ?? '').slice(0, 5)
const when = (ms, options) => new Intl.DateTimeFormat(dateLocale(), options).format(ms)
function dayAndTime(ms) {
Expand Down Expand Up @@ -221,11 +278,6 @@ const KINDS = [['at', 'Once'], ['daily', 'Every day'], ['weekly', 'Every week'],
// The form says one unit with one count ("1 minute"), so each unit carries both words.
const UNITS = [['seconds', 1, 'second', 'seconds'], ['minutes', 60, 'minute', 'minutes'], ['hours', 3600, 'hour', 'hours'], ['days', 86400, 'day', 'days']]

// A stored instant as the value of a datetime-local input, in this browser's zone.
function localInput(ms) {
const date = new Date(ms)
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`
}
// What the form starts with: a new task's defaults, or the edited task's own values.
// A cron rule has no control here, so it is kept unless another kind is picked.
export function formStart(task) {
Expand All @@ -236,7 +288,7 @@ export function formStart(task) {
title: task?.title ?? '',
prompt: task?.prompt ?? '',
kind: once ? 'at' : task?.kind ?? 'daily',
at: once && !Number.isNaN(Date.parse(task.scheduledAt)) ? localInput(Date.parse(task.scheduledAt)) : inAnHour(),
at: once && !Number.isNaN(Date.parse(task.scheduledAt)) ? wallClockInput(Date.parse(task.scheduledAt), task?.timeZone || localZone()) : inAnHour(),
time: task?.time ? clock(task.time) : '09:00',
weekdays: task?.kind === 'weekly' && Array.isArray(task.weekdays) ? task.weekdays : [1, 2, 3, 4, 5],
count: Math.max(1, Math.round(seconds / size)),
Expand All @@ -245,6 +297,17 @@ export function formStart(task) {
}
}

// The form's timing as the host takes it (#3110): the zone the form shows is the one a daily or
// weekly rule carries, and the one a Once task's wall clock is read in. A repeat interval is a
// duration, so it carries no zone at all.
export function whenFromForm({ kind, at, time, weekdays, timeZone, count, unit } = {}) {
const zone = String(timeZone ?? '').trim() || localZone()
if (kind === 'cron') return { kind: 'keep' }
if (kind === 'at') return { kind, at: instantFromWallClock(at, zone), timeZone: zone }
if (kind === 'every') return { kind, seconds: Math.round(Number(count) * UNITS.find(([id]) => id === unit)[1]) }
return { kind, time, timeZone: zone, ...(kind === 'weekly' ? { weekdays } : {}) }
}

function TaskForm({ roster, actions, start, task, onDone, onCancel }) {
// A task goes to a Bot's chat or to a group chat, where it reads as your message.
const first = formStart(task)
Expand All @@ -259,19 +322,10 @@ function TaskForm({ roster, actions, start, task, onDone, onCancel }) {
const [weekdays, setWeekdays] = useState(first.weekdays)
const [count, setCount] = useState(first.count)
const [unit, setUnit] = useState(first.unit)
const [timeZone, setTimeZone] = useState(first.timeZone)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const timing = () => {
if (kind === 'cron') return { kind: 'keep' }
// A once task is an instant; the host reads its wall clock in this zone when quiet
// hours are on (#1166). The others carry their zone with the time itself.
if (kind === 'at') return { kind, at: new Date(at).toISOString(), timeZone: first.timeZone }
// Seconds, not minutes: DSH takes any interval of 60s or more, so a 90s repeat must
// survive the form instead of being rounded to two minutes (#1651).
if (kind === 'every') return { kind, seconds: Math.round(Number(count) * UNITS.find(([id]) => id === unit)[1]) }
// An edited task keeps its own time zone; a new one takes this browser's.
return { kind, time, timeZone: first.timeZone, ...(kind === 'weekly' ? { weekdays } : {}) }
}
const timing = () => whenFromForm({ kind, at, time, weekdays, timeZone, count, unit })
const submit = (event) => {
event.preventDefault()
if (busy || target === '') return
Expand Down Expand Up @@ -313,6 +367,19 @@ function TaskForm({ roster, actions, start, task, onDone, onCancel }) {
h('input', { className: 'bt-input bt-task-count', type: 'number', min: 1, value: count, 'aria-label': t('How many'), onChange: event => setCount(event.target.value) }),
h('select', { className: 'bt-select bt-task-unit', value: unit, 'aria-label': t('Unit'), onChange: event => setUnit(event.target.value) },
UNITS.map(([id, , one, many]) => h('option', { key: id, value: id }, t(Number(count) === 1 ? one : many))))) : null)),
// Which 09:00 this is: only the rules DSH keeps a zone for show it — a repeat interval has
// none, and a cron rule is kept as stored unless the kind changes (#3110).
kind === 'at' || kind === 'daily' || kind === 'weekly'
? h('label', { className: 'bt-set-row bt-bs-row' },
h('span', { className: 'bt-set-copy' }, h('span', { className: 'bt-bs-label' }, t('Time zone'))),
h('select', {
className: 'bt-select bt-task-timezone',
'data-flybot': 'task-timezone',
value: timeZone,
'aria-label': t('Time zone'),
onChange: event => setTimeZone(event.target.value),
}, timeZoneOptions(timeZone).map(zone => h('option', { key: zone, value: zone }, zone))))
: null,
error ? h('div', { className: 'bt-set-row' }, h('span', { className: 'bt-danger bt-set-hint', role: 'alert' }, error)) : null,
h('div', { className: 'bt-set-row bt-task-foot' },
h('button', { type: 'button', className: 'bt-soft bt-soft-sm', onClick: onCancel }, t('Cancel')),
Expand Down
2 changes: 1 addition & 1 deletion core/test/schedules-client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -791,7 +791,7 @@ test('#2232: Quiet hours and the form announce a refusal, not only print it', as
const start = formStart(ACTIVE)
seeded.push(
{ available: true, tasks: [] }, true, null, false, '', '22:00', '07:00',
'b1', start.title, start.prompt, start.kind, start.at, start.time, start.weekdays, start.count, start.unit, false, sentence,
'b1', start.title, start.prompt, start.kind, start.at, start.time, start.weekdays, start.count, start.unit, start.timeZone, false, sentence,
)
const formShown = render(SchedulesPage({ roster: ROSTER, actions: formActions, start: 'b1' }))
const formAlerts = alertsOf(formShown)
Expand Down
Loading
Loading