Files
Docwell/Packages/editor/src/dates.ts
T
tajniak81andClaude Opus 5.5 84043ba05b Add date mentions with reminders
- "@today", "@friday", "@2026-12-01" insert a date; "@remind friday"
  or the date's popover adds a reminder for the person who set it.
- docwell-server keeps a reminders row per person, date and time zone
  in step with each page and sends a "reminder" notification at 9:00
  on the day in that time zone (job notify.reminders). Dates already
  past when added do not notify.
- Exports write dates out; the web and phone inboxes show reminders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 14:55:46 +01:00

337 lines
11 KiB
TypeScript

// SPDX-License-Identifier: AGPL-3.0-or-later
import { autoUpdate, computePosition, flip, offset, shift } from "@floating-ui/dom";
import { mergeAttributes, Node, type Editor } from "@tiptap/core";
import type { Node as PMNode } from "@tiptap/pm/model";
import type { EditorLabels } from "./labels";
import { svgIcon } from "./suggestion";
/** A date offered in the "@" list; remind asks for a reminder on that day. */
export interface DateChoice {
date: string;
remind: boolean;
}
const isoPattern = /^(\d{4})-(\d{2})-(\d{2})$/;
/** The calendar date of d in local time, as YYYY-MM-DD. */
export function isoDate(d: Date): string {
const p = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
}
/** Midnight local time of a YYYY-MM-DD date, or null when it is not one. */
export function parseIso(s: string): Date | null {
const m = isoPattern.exec(s);
if (!m) return null;
const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
return isoDate(d) === s ? d : null;
}
function addDays(d: Date, n: number): Date {
return new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
}
function daysBetween(from: Date, to: Date): number {
// Rounded, so a daylight saving change in between does not matter.
return Math.round((to.getTime() - from.getTime()) / 86_400_000);
}
/** How a date reads in the page: "Today", "Tomorrow", "Nov 20" or "Nov 20, 2027". */
export function formatDate(iso: string, labels: EditorLabels, now = new Date()): string {
const d = parseIso(iso);
if (!d) return iso;
const w = labels.dates;
const diff = daysBetween(addDays(now, 0), d);
if (diff === 0) return w.today;
if (diff === 1) return w.tomorrow;
if (diff === -1) return w.yesterday;
return new Intl.DateTimeFormat(labels.locale, {
month: "short",
day: "numeric",
year: d.getFullYear() === now.getFullYear() ? undefined : "numeric",
}).format(d);
}
/** The date in full, e.g. "Friday, November 20, 2026". */
export function longDate(iso: string, labels: EditorLabels): string {
const d = parseIso(iso);
return d ? new Intl.DateTimeFormat(labels.locale, { dateStyle: "full" }).format(d) : iso;
}
/**
* The dates an "@" query could mean: today, tomorrow, yesterday, next week,
* a weekday (the next one), or a YYYY-MM-DD date, in the labels' language
* or English. A query starting with "remind" asks for reminders, which
* canRemind allows. An empty query offers today, and a reminder tomorrow.
*/
export function dateChoices(query: string, labels: EditorLabels, canRemind: boolean, now = new Date()): DateChoice[] {
const w = labels.dates;
let q = query.trim().toLowerCase();
let remind = false;
for (const word of new Set([w.remindWord.toLowerCase(), "remind"])) {
if (q.startsWith(word)) {
remind = true;
q = q.slice(word.length).trim();
break;
}
// Part of the word is enough to see where it is going.
if (q.length >= 3 && word.startsWith(q)) {
remind = true;
q = "";
break;
}
}
if (remind && !canRemind) return [];
const today = addDays(now, 0);
if (!q) {
if (remind) return [1, 0, 7].map((n) => ({ date: isoDate(addDays(today, n)), remind }));
return [
{ date: isoDate(today), remind: false },
...(canRemind ? [{ date: isoDate(addDays(today, 1)), remind: true }] : []),
];
}
const named: { words: string[]; date: Date }[] = [
{ words: [w.today, "today"], date: today },
{ words: [w.tomorrow, "tomorrow"], date: addDays(today, 1) },
{ words: [w.nextWeek, "next week"], date: addDays(today, 7) },
];
if (!remind) named.push({ words: [w.yesterday, "yesterday"], date: addDays(today, -1) });
const weekday = (locale: string | undefined) => new Intl.DateTimeFormat(locale, { weekday: "long" });
for (let n = 1; n <= 7; n++) {
const d = addDays(today, n);
named.push({ words: [weekday(labels.locale).format(d), weekday("en").format(d)], date: d });
}
const out: DateChoice[] = [];
const iso = parseIso(q);
if (iso) out.push({ date: q, remind });
for (const c of named) {
if (c.words.some((word) => word.toLowerCase().startsWith(q))) out.push({ date: isoDate(c.date), remind });
}
return out.filter((c, i) => out.findIndex((o) => o.date === c.date) === i).slice(0, 5);
}
/** Whether an "@" query with spaces in it is still a date ("remind next friday", "next week"). */
export function spacedDate(query: string, labels: EditorLabels): boolean {
const words = query.toLowerCase().split(" ");
const starts = [labels.dates.remindWord, "remind", labels.dates.nextWeek.split(" ")[0] ?? "", "next"];
return words.length > 1 && words.length <= 3 && starts.some((w) => w && w.toLowerCase() === words[0]);
}
export interface DateMentionOptions {
labels: EditorLabels;
/** The signed-in person's id; without one dates cannot get reminders. */
me: () => string | undefined;
}
/**
* A date in the text ("@today", "@remind friday"). With remind set to a
* person's id, docwell-server reminds them at 9:00 on the day in their time
* zone (tz). Clicking a date while editing opens a small popover to change
* it or turn the reminder on and off.
*/
export const DateMention = Node.create<DateMentionOptions>({
name: "dateMention",
group: "inline",
inline: true,
atom: true,
selectable: true,
addOptions() {
return { labels: undefined as unknown as EditorLabels, me: () => undefined };
},
addAttributes() {
return {
date: {
default: "",
parseHTML: (el) => el.getAttribute("data-date") ?? "",
renderHTML: (a) => ({ "data-date": a.date }),
},
remind: {
default: "",
parseHTML: (el) => el.getAttribute("data-remind") ?? "",
renderHTML: (a) => (a.remind ? { "data-remind": a.remind } : {}),
},
tz: {
default: "",
parseHTML: (el) => el.getAttribute("data-tz") ?? "",
renderHTML: (a) => (a.tz ? { "data-tz": a.tz } : {}),
},
};
},
parseHTML() {
return [{ tag: 'span[data-type="date"]' }];
},
renderHTML({ node, HTMLAttributes }) {
return [
"span",
mergeAttributes({ "data-type": "date", class: "dw-date" }, HTMLAttributes),
formatDate(node.attrs.date as string, this.options.labels),
];
},
renderText({ node }) {
return formatDate(node.attrs.date as string, this.options.labels);
},
addNodeView() {
const { labels, me } = this.options;
return ({ node: initial, editor, getPos }) => {
let node = initial;
const dom = document.createElement("span");
dom.dataset.type = "date";
dom.className = "dw-date";
dom.contentEditable = "false";
let closePopover: (() => void) | null = null;
const draw = () => {
const date = node.attrs.date as string;
const remind = node.attrs.remind as string;
const past = !!parseIso(date) && date < isoDate(new Date());
dom.classList.toggle("is-reminder", !!remind);
dom.classList.toggle("is-past", remind !== "" && past);
dom.title = remind ? `${longDate(date, labels)} · ${labels.dates.reminderAt}` : longDate(date, labels);
dom.replaceChildren(
svgIcon(remind ? "bell" : "calendar", 14),
document.createTextNode(formatDate(date, labels)),
);
};
draw();
const set = (patch: Record<string, string>) => {
const pos = typeof getPos === "function" ? getPos() : undefined;
if (pos === undefined) return;
editor
.chain()
.command(({ tr }) => {
tr.setNodeMarkup(pos, undefined, { ...node.attrs, ...patch });
return true;
})
.run();
};
dom.addEventListener("mousedown", (e) => {
if (!editor.isEditable || closePopover) return;
e.preventDefault();
closePopover = openPopover(dom, editor, node, labels, me(), set, () => (closePopover = null));
});
return {
dom,
update(next: PMNode) {
if (next.type !== node.type) return false;
node = next;
draw();
return true;
},
ignoreMutation: () => true,
stopEvent: (e: Event) => dom.contains(e.target as globalThis.Node) && e.type !== "mousedown",
destroy() {
closePopover?.();
},
};
};
},
});
/** The time zone reminders are set in. */
function timeZone(): string {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone ?? "";
} catch {
return "";
}
}
/** Inserts a date at range, as the "@" list does. */
export function insertDate(editor: Editor, range: { from: number; to: number }, c: DateChoice, me?: string) {
const attrs = { date: c.date, remind: c.remind && me ? me : "", tz: c.remind && me ? timeZone() : "" };
editor
.chain()
.focus()
.insertContentAt(range, [
{ type: "dateMention", attrs },
{ type: "text", text: " " },
])
.run();
}
function openPopover(
anchor: HTMLElement,
editor: Editor,
node: PMNode,
labels: EditorLabels,
me: string | undefined,
set: (patch: Record<string, string>) => void,
onClose: () => void,
): () => void {
const w = labels.dates;
const box = document.createElement("div");
box.className = "dw-date-pop";
box.setAttribute("role", "dialog");
box.setAttribute("aria-label", w.edit);
const input = document.createElement("input");
input.type = "date";
input.className = "dw-input";
input.value = node.attrs.date as string;
input.setAttribute("aria-label", w.edit);
input.addEventListener("change", () => {
if (parseIso(input.value)) set({ date: input.value });
});
box.append(input);
const remind = node.attrs.remind as string;
if (remind && remind !== me) {
const note = document.createElement("p");
note.className = "dw-date-pop__note";
note.textContent = w.someoneElse;
box.append(note);
} else if (me) {
const label = document.createElement("label");
label.className = "dw-date-pop__check";
const box2 = document.createElement("input");
box2.type = "checkbox";
box2.checked = remind === me;
box2.addEventListener("change", () => set(box2.checked ? { remind: me, tz: timeZone() } : { remind: "", tz: "" }));
label.append(box2, document.createTextNode(w.remindMe));
const hint = document.createElement("span");
hint.className = "dw-date-pop__note";
hint.textContent = w.reminderAt;
box.append(label, hint);
}
document.body.append(box);
const stop = autoUpdate(anchor, box, () => {
void computePosition(anchor, box, {
placement: "bottom-start",
strategy: "fixed",
middleware: [offset(6), flip(), shift({ padding: 8 })],
}).then(({ x, y }) => Object.assign(box.style, { left: `${x}px`, top: `${y}px` }));
});
const onDown = (e: MouseEvent) => {
if (!box.contains(e.target as globalThis.Node) && !anchor.contains(e.target as globalThis.Node)) close();
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
close();
editor.commands.focus();
}
};
function close() {
stop();
box.remove();
document.removeEventListener("mousedown", onDown, true);
document.removeEventListener("keydown", onKey, true);
onClose();
}
document.addEventListener("mousedown", onDown, true);
document.addEventListener("keydown", onKey, true);
input.focus();
return close;
}