- Move the storage and model of the plugin into src/lib/features/pm/ as pure TypeScript, so the skill can still bundle them. - Move the DOM interface onto the host menus, the shared tooltip, and the host icons. - A ribbon button opens Project Management. Board tabs keep the owner runestone.pm and the board-<hex> view IDs through view patterns. - Read only .runestone/pm/. Offer the plugin migration, with backups, for legacy notes. - A save, move, or delete reads only that card again. Watcher paths reach the feature. - Add Settings → Project Management and the projectManagement section. View states move to localStorage. - Background reads the boards from workspace.json. Remove api.backgrounds and the boards service. - Add yaml 2.9.1. Use the host markdown-it. - Move 18 plugin test files to tests/unit/features/pm/ and add native tests.
3161 lines
140 KiB
TypeScript
3161 lines
140 KiB
TypeScript
import { backgroundPositions, backgroundSizes, parseBackground, backgroundOverlay, type BackgroundAppearance } from "../model/background.ts";
|
||
import { actionIcons, mountTooltips, tooltip, TOOLTIP, type ActionIcon, type ActionMenuItem, type MenuHost } from "./host.ts";
|
||
import { watchBackground, type PMBackgroundApi } from "../model/transient-background.ts";
|
||
import { mount as mountComponent, unmount as unmountComponent } from "svelte";
|
||
import ProjectManagementSettings from "../../ProjectManagementSettings.svelte";
|
||
import type { PriorityLevels } from "../model/model.ts";
|
||
import type { LegacyContent } from "../storage/legacy.ts";
|
||
import type { OriginalFile } from "../storage/catalog.ts";
|
||
import {
|
||
addDays,
|
||
validDate,
|
||
cardColors,
|
||
dayDistance,
|
||
localDay,
|
||
localInstant,
|
||
localTime,
|
||
statuses,
|
||
statusNames,
|
||
priorityNames,
|
||
type Priority,
|
||
type Status,
|
||
type Task,
|
||
type TaskFields,
|
||
} from "../model/model.ts";
|
||
import { imageReferences, imagePath, parseImage, imageTypes, maxImageBytes, saveImages, imageMarkdown } from "../storage/images.ts";
|
||
import { createSharedChoices } from "./choices-ui.ts";
|
||
import { createRelations } from "./relations-ui.ts";
|
||
import { readCatalog, writeCatalog } from "../storage/catalog.ts";
|
||
import { TaskStore } from "../model/store.ts";
|
||
import { compareCards } from "../storage/order.ts";
|
||
import { createTagInput } from "./tags.ts";
|
||
import { createCardImages } from "./images-ui.ts";
|
||
import { createDescriptionEditor } from "./description-ui.ts";
|
||
import { DescriptionDraft } from "../storage/description-draft.ts";
|
||
import { createDetailsPicker } from "./details-ui.ts";
|
||
import { createPriorityPicker, setPriorityAppearance } from "./priority-ui.ts";
|
||
import { createColorPalette } from "./colors.ts";
|
||
import {
|
||
createLabelManager,
|
||
createLabelPicker,
|
||
labelBadge,
|
||
} from "./labels-ui.ts";
|
||
import type { BoardList, BoardReference } from "../storage/board.ts";
|
||
import { allTaskColumns, allTaskGroups, type TaskColumn } from "../model/all-tasks.ts";
|
||
import { isManagedBoard } from "../storage/catalog.ts";
|
||
import { isHiddenCard } from "../storage/persistence.ts";
|
||
import { editTask } from "../storage/notes.ts";
|
||
import { markdownPaths } from "../storage/scan.ts";
|
||
import styles from "./style.css?inline";
|
||
|
||
/** The preferences of Settings → Project Management that the boards use. */
|
||
export interface Preferences {
|
||
priorityLevels: PriorityLevels;
|
||
}
|
||
|
||
type View = "kanban" | "gantt" | "calendar";
|
||
const icons = {
|
||
limit: '<path d="M4 5h16M4 19h16M8 9h8M8 15h8"/><path d="M12 9v6"/>',
|
||
warning: '<path d="m12 3 10 18H2zM12 9v5M12 17v1"/>',
|
||
scroll: '<path d="M12 3v5m-3-2 3-3 3 3M12 21v-5m-3 2 3 3 3-3M3 12h5m-2-3-3 3 3 3M21 12h-5m2-3 3 3-3 3"/><circle cx="12" cy="12" r="1"/>',
|
||
priority: '<path d="M6 21V3M6 4h13l-3 5 3 5H6"/>',
|
||
heading: actionIcons.heading,
|
||
bold: '<path d="M6 3h7a4.5 4.5 0 0 1 0 9H6zM6 12h8a4.5 4.5 0 0 1 0 9H6z"/>',
|
||
italic: '<path d="M10 3h10M4 21h10M16 3 8 21"/>',
|
||
list: '<path d="M9 6h12M9 12h12M9 18h12M3 6h1M3 12h1M3 18h1"/>',
|
||
link: '<path d="m10 13 4-4M8 16l-2 2a4 4 0 0 1-6-6l5-5a4 4 0 0 1 6 0M16 8l2-2a4 4 0 0 1 6 6l-5 5a4 4 0 0 1-6 0"/>',
|
||
code: '<path d="m8 5-6 7 6 7M16 5l6 7-6 7M14 3l-4 18"/>',
|
||
preview: '<path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/>',
|
||
expand: '<path d="M8 3H3v5M16 3h5v5M21 16v5h-5M3 16v5h5M3 3l6 6M21 3l-6 6M21 21l-6-6M3 21l6-6"/>',
|
||
image: actionIcons.image,
|
||
close: '<path d="m6 6 12 12M18 6 6 18"/>',
|
||
tag: '<path d="M3 3h8l10 10-8 8L3 11z"/><circle cx="7.5" cy="7.5" r="1"/>',
|
||
rename: '<path d="m16 3 5 5M3 21l5-1L21 7a2 2 0 0 0-5-5L3 15z"/>',
|
||
person: '<circle cx="12" cy="8" r="4"/><path d="M4 21v-2a8 8 0 0 1 16 0v2"/>',
|
||
clock: '<circle cx="12" cy="12" r="9"/><path d="M12 6v6l4 2"/>',
|
||
kanban: actionIcons.kanban,
|
||
gantt: '<path d="M4 4v16h17M8 7h7M11 12h9M8 17h4"/>',
|
||
calendar:
|
||
'<rect x="3" y="5" width="18" height="16" rx="2"/><path d="M7 3v4M17 3v4M3 10h18M7 14h2M12 14h2M7 18h2"/>',
|
||
plus: actionIcons.plus,
|
||
refresh: actionIcons.refresh,
|
||
left: '<path d="m15 5-7 7 7 7"/>',
|
||
right: '<path d="m9 5 7 7-7 7"/>',
|
||
more: '<circle cx="12" cy="5" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="12" cy="19" r="1"/>',
|
||
search: '<circle cx="10" cy="10" r="6"/><path d="m15 15 6 6"/>',
|
||
grip: '<circle cx="9" cy="5" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="19" r="1"/>',
|
||
up: actionIcons.up,
|
||
down: '<path d="m6 9 6 6 6-6"/>',
|
||
circlePlus: '<circle cx="12" cy="12" r="9"/><path d="M12 7v10M7 12h10"/>',
|
||
note: '<path d="M14 3H5v18h14V8zM14 3v5h5M8 12h8M8 16h8"/>',
|
||
check: '<path d="m5 12 4 4L19 6"/>',
|
||
select: '<path d="M8 3H4a1 1 0 0 0-1 1v4M16 3h4a1 1 0 0 1 1 1v4M21 16v4a1 1 0 0 1-1 1h-4M8 21H4a1 1 0 0 1-1-1v-4M3 11v2M21 11v2M11 3h2M11 21h2"/><rect x="8" y="8" width="8" height="8" rx="1"/>',
|
||
archive: actionIcons.archive,
|
||
trash: actionIcons.trash,
|
||
download: '<path d="M12 3v12m0 0 5-5m-5 5-5-5M5 17v4h14v-4"/>',
|
||
refresh2: actionIcons.refresh,
|
||
};
|
||
function el<K extends keyof HTMLElementTagNameMap>(
|
||
tag: K,
|
||
text = "",
|
||
className = "",
|
||
): HTMLElementTagNameMap[K] {
|
||
const node = document.createElement(tag);
|
||
node.textContent = text;
|
||
node.className = className;
|
||
return node;
|
||
}
|
||
function button(text: string, action: () => void, icon?: keyof typeof icons) {
|
||
const node = el("button", "", "pm-button");
|
||
node.type = "button";
|
||
if (icon) {
|
||
node.dataset.icon = icon;
|
||
const span = el("span", "", "pm-icon");
|
||
span.innerHTML = `<svg viewBox="0 0 24 24" aria-hidden="true">${icons[icon]}</svg>`;
|
||
node.append(span);
|
||
}
|
||
node.append(document.createTextNode(text));
|
||
node.onclick = action;
|
||
return node;
|
||
}
|
||
function applyTaskColor(node: HTMLElement, task: Task) {
|
||
if (!task.color) return;
|
||
node.style.setProperty(
|
||
"--pm-card-color",
|
||
cardColors[task.color as keyof typeof cardColors],
|
||
);
|
||
node.classList.add("pm-colored-task");
|
||
}
|
||
function iconButton(
|
||
label: string,
|
||
icon: keyof typeof icons,
|
||
action: () => void,
|
||
) {
|
||
const control = button("", action, icon);
|
||
control.classList.add("pm-icon-button");
|
||
control.setAttribute("aria-label", label);
|
||
return tooltip(control, label);
|
||
}
|
||
const shortDate = (value: string) =>
|
||
new Date(`${value}T12:00:00`).toLocaleDateString(undefined, {
|
||
month: "short",
|
||
day: "numeric",
|
||
});
|
||
|
||
export interface PMViewState {
|
||
view?: View; period?: "day" | "week" | "month"; anchor?: string; search?: string;
|
||
showArchived?: boolean; searchOpen?: boolean;
|
||
collapsedLists?: string[];
|
||
boardScroll?: { left: number; top: number }; scrollTop?: number;
|
||
}
|
||
|
||
export function parseViewState(value: unknown): PMViewState {
|
||
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
||
const raw = value as PMViewState, state: PMViewState = {};
|
||
if (["kanban", "gantt", "calendar"].includes(raw.view!)) state.view = raw.view;
|
||
if (["day", "week", "month"].includes(raw.period!)) state.period = raw.period;
|
||
if (Array.isArray(raw.collapsedLists)) state.collapsedLists = raw.collapsedLists.filter((id): id is string => typeof id === "string").slice(0, 10000);
|
||
if (validDate(raw.anchor)) state.anchor = raw.anchor;
|
||
if (typeof raw.search === "string") state.search = raw.search.slice(0, 1000);
|
||
for (const key of ["searchOpen", "showArchived"] as const) if (typeof raw[key] === "boolean") state[key] = raw[key];
|
||
if (typeof raw.scrollTop === "number" && Number.isFinite(raw.scrollTop)) state.scrollTop = Math.max(0, raw.scrollTop);
|
||
if (raw.boardScroll && Number.isFinite(raw.boardScroll.left) && Number.isFinite(raw.boardScroll.top)) state.boardScroll = { left: Math.max(0, raw.boardScroll.left), top: Math.max(0, raw.boardScroll.top) };
|
||
return state;
|
||
}
|
||
|
||
export function mountPM(
|
||
container: HTMLElement,
|
||
store: TaskStore,
|
||
options: {
|
||
/** The shared host menus. */
|
||
ui: MenuHost;
|
||
backgrounds?: PMBackgroundApi;
|
||
state?: PMViewState;
|
||
stateChanged?: () => void;
|
||
preferences: Preferences;
|
||
savePreferences?: (value: Preferences) => Promise<void>;
|
||
openBoard?: (path: string, replace?: boolean) => void | Promise<void>;
|
||
openAll?: (replace?: boolean) => void | Promise<void>;
|
||
renameBoard?: (document: BoardReference, name: string) => Promise<string>;
|
||
boardRenamed?: (name: string) => void;
|
||
boardDeleted?: () => void | Promise<void>;
|
||
/** Run `listener` after each workspace change, with the changed paths when they are known. */
|
||
watch?: (listener: (paths?: readonly string[]) => void) => () => void;
|
||
/** Data in the legacy format: the boards offer its migration. */
|
||
legacy?: {
|
||
find(): Promise<LegacyContent>;
|
||
has(content: LegacyContent): boolean;
|
||
migrate(): Promise<OriginalFile[]>;
|
||
};
|
||
},
|
||
): () => void {
|
||
const root = el("section", "", "rs-pm");
|
||
const disposeTooltips = mountTooltips(root);
|
||
let boardMenu: { close(): void } | undefined;
|
||
const background = el("div", "", "pm-background"); background.setAttribute("aria-hidden", "true");
|
||
const previousBackground = el("div", "", "pm-background-previous");
|
||
background.append(previousBackground);
|
||
let backgroundUrl: string | undefined;
|
||
let backgroundFade: Animation | undefined;
|
||
const positionBackground = () => {
|
||
if (!root.isConnected) return;
|
||
const box = container.getBoundingClientRect();
|
||
let top = Math.max(0, box.top + container.clientTop), bottom = Math.min(innerHeight, box.top + container.clientTop + container.clientHeight), left = Math.max(0, box.left + container.clientLeft), right = Math.min(innerWidth, box.left + container.clientLeft + container.clientWidth);
|
||
for (let node = container.parentElement; node; node = node.parentElement) {
|
||
const css = getComputedStyle(node), rect = node.getBoundingClientRect();
|
||
if (/(auto|scroll|hidden|clip)/.test(css.overflowY)) { top = Math.max(top, rect.top + node.clientTop); bottom = Math.min(bottom, rect.top + node.clientTop + node.clientHeight); }
|
||
if (/(auto|scroll|hidden|clip)/.test(css.overflowX)) { left = Math.max(left, rect.left + node.clientLeft); right = Math.min(right, rect.left + node.clientLeft + node.clientWidth); }
|
||
}
|
||
Object.assign(background.style, { top: `${top}px`, left: `${left}px`, width: `${Math.max(0, right - left)}px`, height: `${Math.max(0, bottom - top)}px` });
|
||
};
|
||
const style = el("style");
|
||
style.textContent = styles;
|
||
container.append(style, root);
|
||
const state = options.state ?? {};
|
||
const collapsedLists = new Set(state.collapsedLists ?? []);
|
||
const pendingCollapsedLists = new Map<string, boolean>();
|
||
const preferences = options.preferences;
|
||
let view: View = state.view ?? "kanban",
|
||
period: "day" | "week" | "month" = state.period ?? "month",
|
||
anchor = state.anchor ?? localDay(),
|
||
search = state.search ?? "",
|
||
showArchived = state.showArchived ?? false,
|
||
searchOpen = state.searchOpen ?? false;
|
||
let selectionMode = false;
|
||
const selectedCards = new Set<string>();
|
||
let restoring = true;
|
||
let renderPending = false;
|
||
const remember = () => {
|
||
Object.assign(state, { view, period, anchor, search, showArchived, searchOpen });
|
||
options.stateChanged?.();
|
||
if (!root.getClientRects().length) return;
|
||
const board = root.querySelector<HTMLElement>(".pm-board");
|
||
if (board) state.boardScroll = { left: board.scrollLeft, top: board.scrollTop };
|
||
const scroller = scrollContainer();
|
||
state.scrollTop = scroller.scrollTop;
|
||
};
|
||
const scrollContainer = () => {
|
||
for (let node = root.parentElement; node; node = node.parentElement)
|
||
if (/(auto|scroll)/.test(getComputedStyle(node).overflowY)) return node;
|
||
return document.scrollingElement as HTMLElement;
|
||
};
|
||
let closed = false,
|
||
busy = false,
|
||
message = "",
|
||
failed = false,
|
||
activeDialog: HTMLDialogElement | undefined;
|
||
let restoreFocus: HTMLElement | undefined;
|
||
let disposeEditor: (() => void) | undefined;
|
||
let closePopup: (() => void) | undefined;
|
||
let cardDraft: { listId: string | null; status: Status; title: string } | undefined;
|
||
const cardDrafts = new Map<string | null, NonNullable<typeof cardDraft>>();
|
||
let drag:
|
||
| {
|
||
kind: "list" | "task";
|
||
id: string;
|
||
source: HTMLElement;
|
||
preview: HTMLElement;
|
||
}
|
||
| undefined;
|
||
const clearDrag = () => {
|
||
drag?.source.classList.remove("pm-drag-source");
|
||
drag?.preview.remove();
|
||
drag = undefined;
|
||
root.classList.remove("pm-dragging");
|
||
root
|
||
.querySelectorAll(".pm-drop-target")
|
||
.forEach((node) => node.classList.remove("pm-drop-target"));
|
||
root
|
||
.querySelectorAll<HTMLElement>(".pm-list-insertion,.pm-card-insertion")
|
||
.forEach((node) => {
|
||
node.hidden = true;
|
||
});
|
||
};
|
||
const movePreview = (event: DragEvent) => {
|
||
if (!drag) return;
|
||
const rect = drag.preview.getBoundingClientRect();
|
||
drag.preview.style.left =
|
||
Math.max(
|
||
8,
|
||
Math.min(event.clientX + 16, window.innerWidth - rect.width - 8),
|
||
) + "px";
|
||
drag.preview.style.top =
|
||
Math.max(
|
||
8,
|
||
Math.min(event.clientY + 16, window.innerHeight - rect.height - 8),
|
||
) + "px";
|
||
};
|
||
const beginDrag = (
|
||
event: DragEvent,
|
||
kind: "list" | "task",
|
||
id: string,
|
||
source: HTMLElement,
|
||
name: string,
|
||
) => {
|
||
if (!event.dataTransfer || busy) {
|
||
event.preventDefault();
|
||
return;
|
||
}
|
||
clearDrag();
|
||
closePopup?.();
|
||
event.stopPropagation();
|
||
event.dataTransfer.setData(`application/x-runestone-pm-${kind}`, id);
|
||
event.dataTransfer.effectAllowed = "move";
|
||
const preview = el("div", "", "pm-drag-preview");
|
||
preview.setAttribute("aria-hidden", "true");
|
||
preview.inert = true;
|
||
preview.style.width =
|
||
Math.min(source.getBoundingClientRect().width, 340) + "px";
|
||
const clone = source.cloneNode(true) as HTMLElement;
|
||
clone.removeAttribute("aria-label");
|
||
for (const node of [clone, ...clone.querySelectorAll<HTMLElement>(`[${TOOLTIP}]`)]) node.removeAttribute(TOOLTIP);
|
||
const content = el("div", "", "pm-drag-preview-content");
|
||
content.append(clone);
|
||
preview.append(el("div", "Move " + name, "pm-drag-preview-label"), content);
|
||
const blank = el("canvas");
|
||
blank.width = blank.height = 1;
|
||
preview.append(blank);
|
||
root.append(preview);
|
||
event.dataTransfer.setDragImage(blank, 0, 0);
|
||
drag = { kind, id, source, preview };
|
||
source.classList.add("pm-drag-source");
|
||
root.classList.add("pm-dragging");
|
||
movePreview(event);
|
||
};
|
||
document.addEventListener("dragover", movePreview);
|
||
document.addEventListener("dragend", clearDrag);
|
||
document.addEventListener("drop", clearDrag);
|
||
function popup(
|
||
trigger: HTMLElement,
|
||
name: string,
|
||
fill: (panel: HTMLDivElement, close: () => void) => void | (() => void),
|
||
) {
|
||
closePopup?.();
|
||
const panel = el("div", "", "pm-popup");
|
||
let disposePanel: (() => void) | undefined;
|
||
panel.setAttribute("role", "dialog");
|
||
panel.setAttribute("aria-label", name);
|
||
const close = () => {
|
||
disposePanel?.();
|
||
sharedChoices.close();
|
||
panel.remove();
|
||
document.removeEventListener("pointerdown", outside, true);
|
||
window.removeEventListener("keydown", key, true);
|
||
if (closePopup === close) closePopup = undefined;
|
||
if (trigger.isConnected) trigger.focus({ preventScroll: true });
|
||
};
|
||
const outside = (event: PointerEvent) => {
|
||
if (
|
||
!busy &&
|
||
!(event.target instanceof Element && event.target.closest(".rs-menu")) &&
|
||
!panel.contains(event.target as Node) &&
|
||
!trigger.contains(event.target as Node)
|
||
)
|
||
close();
|
||
};
|
||
const key = (event: KeyboardEvent) => {
|
||
if (event.key === "Escape" && !busy && !(event.target instanceof Element && event.target.closest(".rs-menu"))) {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
close();
|
||
}
|
||
};
|
||
disposePanel = fill(panel, close) || undefined;
|
||
if (panel.classList.contains("pm-menu")) {
|
||
boardMenu?.close();
|
||
trigger.focus({ preventScroll: true });
|
||
const hostIcons: Record<string, ActionIcon> = { kanban: "kanban", up: "up", down: "down", rename: "rename", left: "arrow-left", right: "arrow-right", archive: "archive", trash: "trash", image: "image", list: "settings", circlePlus: "kanban", note: "file-plus", link: "link", refresh: "refresh" };
|
||
const items: ActionMenuItem[] = [];
|
||
for (const child of panel.children) {
|
||
if (child instanceof HTMLButtonElement) items.push({ label: child.textContent ?? "", icon: hostIcons[child.dataset.icon ?? ""], disabled: child.disabled, run: () => child.click() });
|
||
else if (child instanceof HTMLLabelElement) {
|
||
const select = child.querySelector("select");
|
||
if (select) items.push({ label: child.firstChild?.textContent ?? "Choose", icon: "kanban", children: Array.from(select.options).map(option => ({ label: option.textContent ?? "", checked: option.selected, radio: true, disabled: option.disabled,
|
||
run: () => { select.value = option.value; select.dispatchEvent(new Event("change")); } })) });
|
||
}
|
||
}
|
||
const bounds = trigger.getBoundingClientRect();
|
||
boardMenu = options.ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: name, items });
|
||
return;
|
||
}
|
||
for (const select of panel.querySelectorAll<HTMLSelectElement>("select:not([hidden])")) sharedChoice(select);
|
||
panel.setAttribute("popover", "manual");
|
||
root.append(panel);
|
||
panel.showPopover();
|
||
const anchor = trigger.getBoundingClientRect(),
|
||
bounds = panel.getBoundingClientRect();
|
||
panel.style.left =
|
||
Math.max(
|
||
8,
|
||
Math.min(
|
||
anchor.right - bounds.width,
|
||
window.innerWidth - bounds.width - 8,
|
||
),
|
||
) + "px";
|
||
panel.style.top =
|
||
Math.max(
|
||
8,
|
||
Math.min(anchor.bottom + 6, window.innerHeight - bounds.height - 8),
|
||
) + "px";
|
||
document.addEventListener("pointerdown", outside, true);
|
||
window.addEventListener("keydown", key, true);
|
||
closePopup = close;
|
||
panel.querySelector<HTMLElement>("input:not([hidden]):not(:disabled),button:not([hidden]):not(:disabled),select:not([hidden]):not(:disabled)")?.focus();
|
||
}
|
||
root.classList.add("pm-shared-menus");
|
||
const sharedChoices = createSharedChoices(root, options.ui);
|
||
const sharedChoice = sharedChoices.use;
|
||
const imageCache = new Map<string, Promise<string>>();
|
||
const loadImage = (id: string) => {
|
||
if (!imageCache.has(id)) imageCache.set(id, store.workspace.read(imagePath(id)).then(parseImage));
|
||
return imageCache.get(id)!;
|
||
};
|
||
const backgroundWatcher = watchBackground(
|
||
store.board.reference ? `pm-board:${store.board.reference.id}` : "pm-all",
|
||
options.backgrounds,
|
||
async () => {
|
||
const saved = store.board.reference ? store.board.value : (await readCatalog(store.workspace)).value;
|
||
const id = saved.backgroundImage;
|
||
const appearance = parseBackground(saved.backgroundAppearance);
|
||
const data = typeof id === "string" ? await loadImage(id) : "";
|
||
return data ? { ...appearance, url: data } : null;
|
||
},
|
||
frame => {
|
||
const appearance = parseBackground(frame);
|
||
const fade = !!backgroundUrl && backgroundUrl !== frame?.url && !!frame?.previous && !!frame.transitionMs && !matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||
backgroundFade?.cancel();
|
||
previousBackground.style.backgroundImage = fade ? `${backgroundOverlay(frame!.previous!.overlay)}, url(${JSON.stringify(frame!.previous!.url)})${frame?.previous?.blurredUrl ? `, url(${JSON.stringify(frame.previous.blurredUrl)})` : ""}` : "none";
|
||
previousBackground.style.backgroundPosition = frame?.previous?.blurredUrl ? `center, ${frame.previous.position}, center` : frame?.previous?.position ?? "center";
|
||
previousBackground.style.backgroundSize = `100% 100%, ${frame?.previous?.size ?? "cover"}${frame?.previous?.blurredUrl ? ", cover" : ""}`;
|
||
previousBackground.hidden = !fade;
|
||
background.style.backgroundImage = frame ? `${backgroundOverlay(appearance.overlay)}, url(${JSON.stringify(frame.url)})${frame.blurredUrl ? `, url(${JSON.stringify(frame.blurredUrl)})` : ""}` : "none";
|
||
background.style.backgroundPosition = frame?.blurredUrl ? `center, ${appearance.position}, center` : appearance.position;
|
||
background.style.backgroundSize = `100% 100%, ${appearance.size}${frame?.blurredUrl ? ", cover" : ""}`;
|
||
background.style.backgroundRepeat = "no-repeat";
|
||
backgroundUrl = frame?.url;
|
||
if (fade) {
|
||
backgroundFade = previousBackground.animate([{ opacity: 1 }, { opacity: 0 }], { duration: frame!.transitionMs, fill: "forwards" });
|
||
backgroundFade.onfinish = () => { previousBackground.hidden = true; };
|
||
}
|
||
root.classList.toggle("pm-has-background", !!frame);
|
||
positionBackground();
|
||
},
|
||
);
|
||
const applyBackground = backgroundWatcher.refresh;
|
||
function customizeBackground(trigger: HTMLElement) {
|
||
popup(trigger, "Customize background", (panel, close) => {
|
||
panel.append(el("h3", "Customize background"), el("p", "Choose a PNG, JPEG, GIF, or WebP image up to 50 MiB.", "pm-muted"));
|
||
const file = el("input"); file.type = "file"; file.accept = imageTypes.join(","); file.setAttribute("aria-label", "Background image");
|
||
const saveBackground = async (id: string | null) => {
|
||
if (store.board.reference) await store.changeBoard(() => store.board.update(board => { board.backgroundImage = id; }));
|
||
else { const catalog = await readCatalog(store.workspace); catalog.value.backgroundImage = id; await writeCatalog(store.workspace, catalog.value, catalog.source); }
|
||
};
|
||
file.onchange = () => {
|
||
const image = file.files?.[0]; if (!image) return;
|
||
void perform(async () => {
|
||
if (!imageTypes.includes(image.type) || image.size > maxImageBytes) throw new Error("Choose a supported image no larger than 50 MiB.");
|
||
const data = await new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result)); reader.onerror = () => reject(new Error("Cannot read this image.")); reader.readAsDataURL(image); });
|
||
const id = crypto.randomUUID();
|
||
await saveImages(store.workspace, imageMarkdown(image.name, id), new Map([[id, data]]));
|
||
await saveBackground(id); close();
|
||
}, "Background saved.");
|
||
};
|
||
const saveAppearance = async (appearance: BackgroundAppearance) => {
|
||
if (store.board.reference) await store.changeBoard(() => store.board.update(board => { board.backgroundAppearance = appearance; }));
|
||
else { const catalog = await readCatalog(store.workspace); catalog.value.backgroundAppearance = appearance; await writeCatalog(store.workspace, catalog.value, catalog.source); }
|
||
await applyBackground();
|
||
};
|
||
const controls = el("div");
|
||
void (async () => {
|
||
await Promise.resolve();
|
||
const saved = store.board.reference ? store.board.value : (await readCatalog(store.workspace)).value;
|
||
let appearance = parseBackground(saved.backgroundAppearance);
|
||
if (!panel.isConnected) return;
|
||
controls.classList.add("pm-background-settings");
|
||
const error = el("p", "", "pm-error"); error.setAttribute("role", "alert");
|
||
let saveQueue = Promise.resolve();
|
||
const save = async (next: BackgroundAppearance) => { appearance = next; error.textContent = ""; try { saveQueue = saveQueue.catch(() => {}).then(() => saveAppearance(next)); await saveQueue; } catch (reason) { error.textContent = reason instanceof Error ? reason.message : String(reason); } };
|
||
const positionRow = el("label", "Image position", "pm-background-row"), position = el("select"); position.setAttribute("aria-label", "Image position");
|
||
const positionLabels = ["Center", "Top left", "Top center", "Top right", "Center left", "Center right", "Bottom left", "Bottom center", "Bottom right"];
|
||
for (const [index, value] of backgroundPositions.entries()) { const option = el("option", positionLabels[index]); option.value = value; position.append(option); }
|
||
position.value = appearance.position; position.onchange = () => { void save({ ...appearance, position: position.value as BackgroundAppearance["position"] }); };
|
||
positionRow.append(position); controls.append(positionRow); sharedChoice(position);
|
||
const sizeRow = el("label", "Image size", "pm-background-row"), size = el("select"); size.setAttribute("aria-label", "Image size");
|
||
for (const [index, value] of backgroundSizes.entries()) { const option = el("option", ["Fill", "Fit", "Actual size"][index]); option.value = value; size.append(option); }
|
||
size.value = appearance.size; size.onchange = () => { void save({ ...appearance, size: size.value as BackgroundAppearance["size"] }); };
|
||
sizeRow.append(size); controls.append(sizeRow); sharedChoice(size);
|
||
const overlay = el("input"); overlay.type = "range"; overlay.min = "-100"; overlay.max = "100"; overlay.step = "1"; overlay.value = String(Math.round(appearance.overlay * 100)); overlay.setAttribute("aria-label", "Image overlay");
|
||
const percent = el("input"); percent.type = "number"; percent.min = "-100"; percent.max = "100"; percent.step = "1"; percent.value = overlay.value; percent.setAttribute("aria-label", "Image overlay percentage");
|
||
const changeOverlay = (input: HTMLInputElement) => {
|
||
if (!Number.isFinite(input.valueAsNumber)) return;
|
||
const value = Math.round(Math.max(-100, Math.min(100, input.valueAsNumber)));
|
||
overlay.value = String(value);
|
||
if (input === overlay) percent.value = overlay.value;
|
||
void save({ ...appearance, overlay: value / 100 });
|
||
};
|
||
overlay.oninput = () => changeOverlay(overlay); percent.oninput = () => changeOverlay(percent);
|
||
percent.onblur = () => { percent.value = String(Math.round(appearance.overlay * 100)); };
|
||
const overlayRow = el("div", "", "pm-background-row"), overlayControls = el("div", "", "pm-overlay-controls"), percentLabel = el("label", "", "pm-overlay-value");
|
||
percentLabel.append(percent, el("span", "%")); overlayControls.append(overlay, percentLabel);
|
||
overlayRow.append(el("span", "Image overlay"), overlayControls); controls.append(overlayRow, el("p", "Move left to lighten the image or right to darken it.", "pm-muted"));
|
||
controls.append(error);
|
||
})().catch(reason => { controls.textContent = String(reason); });
|
||
panel.append(file, controls, button("Remove background", () => { void perform(async () => { await saveBackground(null); close(); }, "Background removed."); }, "trash"));
|
||
});
|
||
}
|
||
root.addEventListener("contextmenu", event => {
|
||
const target = event.target as HTMLElement;
|
||
if (target.closest(".pm-card,button,input,textarea,select,dialog,.pm-popup,.pm-toolbar")) return;
|
||
event.preventDefault();
|
||
const anchor = el("span"); anchor.style.cssText = `position:fixed;left:${event.clientX}px;top:${event.clientY}px;width:1px;height:1px`;
|
||
root.append(anchor);
|
||
popup(anchor, "Background actions", (panel, close) => { panel.classList.add("pm-menu"); panel.append(button("Customize background", () => { close(); customizeBackground(root.querySelector<HTMLElement>(".pm-toolbar")!); }, "image")); });
|
||
anchor.remove();
|
||
});
|
||
function renameBoardForm(trigger: HTMLElement, create = false) {
|
||
const action = create ? "Create board" : "Rename board";
|
||
popup(trigger, action, (panel, close) => {
|
||
const form = el("form"),
|
||
label = el("label", "Board name", "pm-field"),
|
||
name = el("input"),
|
||
error = el("p", "", "pm-error"),
|
||
actions = el("div", "", "pm-popup-actions"),
|
||
save = button(action, () => {});
|
||
name.value = create ? "" : store.board.name;
|
||
name.required = true;
|
||
label.append(name);
|
||
error.role = "alert";
|
||
save.type = "submit";
|
||
save.classList.add("pm-primary");
|
||
actions.append(
|
||
save,
|
||
button("Cancel", () => {
|
||
if (!busy) close();
|
||
}),
|
||
);
|
||
form.append(label, error, actions);
|
||
panel.append(form);
|
||
name.select();
|
||
form.onsubmit = async (event) => {
|
||
event.preventDefault();
|
||
if (busy) return;
|
||
save.disabled = true;
|
||
const ok = await perform(
|
||
async () => {
|
||
if (create) {
|
||
const reference = await store.createBoard(name.value);
|
||
close();
|
||
await options.openBoard?.(reference.path);
|
||
} else {
|
||
await store.renameBoard(name.value, options.renameBoard);
|
||
options.boardRenamed?.(store.board.name);
|
||
}
|
||
},
|
||
create ? "Board created." : "Board renamed.",
|
||
);
|
||
save.disabled = false;
|
||
if (ok) {
|
||
close();
|
||
render();
|
||
if (!create)
|
||
root.querySelector<HTMLElement>(
|
||
trigger.classList.contains("pm-board-rename")
|
||
? ".pm-board-rename"
|
||
: '[aria-label="More actions"]',
|
||
)?.focus({ preventScroll: true });
|
||
} else error.textContent = message;
|
||
};
|
||
});
|
||
}
|
||
function deleteBoardForm(trigger: HTMLElement) {
|
||
if (activeDialog || busy) return;
|
||
closePopup?.();
|
||
const dialog = el("dialog", "", "pm-editor"),
|
||
error = el("p", "", "pm-error"),
|
||
actions = el("div", "", "pm-editor-actions"),
|
||
cancel = button("Cancel", () => { if (!busy) dialog.close(); }),
|
||
remove = button("Delete board", () => { void removeBoard(); }, "trash");
|
||
activeDialog = dialog;
|
||
dialog.setAttribute("aria-label", "Delete board");
|
||
const description = el("p", "Cards stay in All tasks. Notes, backups, and memberships on other boards stay unchanged. This action has no undo.");
|
||
description.id = "pm-delete-board-description";
|
||
dialog.setAttribute("aria-describedby", description.id);
|
||
error.role = "alert";
|
||
actions.append(cancel, remove);
|
||
dialog.append(el("h2", `Delete “${store.board.name}”?`), description,
|
||
el("p", "Original board files stay on disk, but Project Management no longer lists this board."), error, actions);
|
||
root.append(dialog);
|
||
dialog.oncancel = (event) => { if (busy) event.preventDefault(); };
|
||
dialog.onclose = () => {
|
||
activeDialog = undefined;
|
||
dialog.remove();
|
||
render();
|
||
if (trigger.isConnected) trigger.focus({ preventScroll: true });
|
||
else root.querySelector<HTMLElement>('[aria-label="More actions"]')?.focus({ preventScroll: true });
|
||
};
|
||
dialog.showModal();
|
||
cancel.focus();
|
||
async function removeBoard() {
|
||
if (busy) return;
|
||
remove.disabled = cancel.disabled = true;
|
||
const ok = await perform(
|
||
() => store.changeBoard(() => store.board.deleteBoard()),
|
||
"Board deleted. Cards remain in All tasks.",
|
||
);
|
||
remove.disabled = cancel.disabled = false;
|
||
if (!ok) { error.textContent = message; return; }
|
||
dialog.close();
|
||
await perform(async () => {
|
||
await options.openAll?.(true);
|
||
await options.boardDeleted?.();
|
||
}, "Board deleted. Cards remain in All tasks.");
|
||
}
|
||
}
|
||
function deleteCardForm(task: Task, trigger: HTMLElement) {
|
||
if (activeDialog || busy) return;
|
||
closePopup?.();
|
||
const dialog = el("dialog", "", "pm-editor"),
|
||
error = el("p", "", "pm-error"),
|
||
actions = el("div", "", "pm-editor-actions"),
|
||
cancel = button("Cancel", () => { if (!busy) dialog.close(); }),
|
||
remove = button("Delete card", () => { void removeCard(); }, "trash");
|
||
activeDialog = dialog;
|
||
dialog.setAttribute("aria-label", "Delete card");
|
||
const description = el("p", "This removes the card from all boards, All tasks, and the archive. This action has no undo.");
|
||
description.id = `pm-delete-card-${crypto.randomUUID()}`;
|
||
dialog.setAttribute("aria-describedby", description.id);
|
||
error.role = "alert";
|
||
actions.append(cancel, remove);
|
||
dialog.append(el("h2", `Delete “${task.title}”?`), description,
|
||
el("p", "Stored notes and images remain on disk for recovery. Linked cards and subtasks remain separate cards."), error, actions);
|
||
root.append(dialog);
|
||
dialog.oncancel = event => { if (busy) event.preventDefault(); };
|
||
dialog.onclose = () => {
|
||
activeDialog = undefined;
|
||
dialog.remove();
|
||
render();
|
||
const card = Array.from(root.querySelectorAll<HTMLElement>(".pm-card-menu")).find(item => item.getAttribute("aria-label") === trigger.getAttribute("aria-label"));
|
||
(card ?? root.querySelector<HTMLElement>('[aria-label="More actions"]'))?.focus({ preventScroll: true });
|
||
};
|
||
dialog.showModal();
|
||
cancel.focus();
|
||
async function removeCard() {
|
||
if (busy) return;
|
||
remove.disabled = cancel.disabled = true;
|
||
const ok = await perform(() => store.deleteCard(task), "Card deleted.");
|
||
remove.disabled = cancel.disabled = false;
|
||
if (!ok) { error.textContent = message; return; }
|
||
dialog.close();
|
||
}
|
||
}
|
||
function listForm(trigger: HTMLElement, list?: BoardList) {
|
||
popup(trigger, list ? "Edit list" : "Add list", (panel, close) => {
|
||
const form = el("form"),
|
||
name = el("input");
|
||
name.setAttribute("aria-label", "List name");
|
||
name.placeholder = "List name";
|
||
name.required = true;
|
||
name.maxLength = 80;
|
||
name.value = list?.name ?? "";
|
||
const label = el(
|
||
"label",
|
||
"Status when a card enters this list",
|
||
"pm-field",
|
||
),
|
||
status = el("select");
|
||
status.setAttribute("aria-label", "Status on move");
|
||
const unchanged = el("option", "Do not change status");
|
||
unchanged.value = "";
|
||
status.append(unchanged);
|
||
for (const value of statuses) {
|
||
const option = el("option", statusNames[value]);
|
||
option.value = value;
|
||
status.append(option);
|
||
}
|
||
status.value = list?.status ?? "";
|
||
label.append(status);
|
||
const error = el("p", "", "pm-error");
|
||
error.role = "alert";
|
||
const add = button(list ? "Save list" : "Add list", () => {});
|
||
add.type = "submit";
|
||
add.classList.add("pm-primary");
|
||
const actions = el("div", "", "pm-popup-actions");
|
||
actions.append(
|
||
add,
|
||
button("Cancel", () => {
|
||
if (!busy) close();
|
||
}),
|
||
);
|
||
form.append(name, label, error, actions);
|
||
panel.append(form);
|
||
sharedChoice(status);
|
||
form.onsubmit = async (event) => {
|
||
event.preventDefault();
|
||
if (busy) return;
|
||
add.disabled = true;
|
||
const ok = await perform(
|
||
() =>
|
||
store.changeBoard(() =>
|
||
list
|
||
? store.board.edit(
|
||
list.id,
|
||
name.value,
|
||
(status.value || null) as Status | null,
|
||
)
|
||
: store.board.add(
|
||
name.value,
|
||
(status.value || null) as Status | null,
|
||
),
|
||
),
|
||
list ? "List saved." : "List added.",
|
||
);
|
||
add.disabled = false;
|
||
if (ok) {
|
||
close();
|
||
render();
|
||
} else error.textContent = message;
|
||
};
|
||
});
|
||
}
|
||
function listLimitForm(trigger: HTMLElement, list: BoardList) {
|
||
popup(trigger, "Set list limit", (panel, close) => {
|
||
const form = el("form");
|
||
const field = el("label", "Maximum cards", "pm-field");
|
||
const maximum = el("input");
|
||
maximum.type = "number";
|
||
maximum.min = "1";
|
||
maximum.max = String(Number.MAX_SAFE_INTEGER);
|
||
maximum.step = "1";
|
||
maximum.placeholder = "No limit";
|
||
maximum.value = list.maxCards === undefined ? "" : String(list.maxCards);
|
||
field.append(maximum);
|
||
const hint = el("p", "Leave blank for no limit. A warning appears at the maximum. Cards can still enter this list.");
|
||
const error = el("p", "", "pm-error");
|
||
error.role = "alert";
|
||
const save = button("Save limit", () => {}, "check");
|
||
save.type = "submit";
|
||
save.classList.add("pm-primary");
|
||
const actions = el("div", "", "pm-popup-actions");
|
||
actions.append(button("Cancel", () => { if (!busy) close(); }), save);
|
||
form.append(field, hint, error, actions);
|
||
panel.append(form);
|
||
form.onsubmit = async event => {
|
||
event.preventDefault();
|
||
if (busy) return;
|
||
save.disabled = true;
|
||
const ok = await perform(() => store.changeBoard(() => store.board.setLimit(list.id, maximum.value === "" ? undefined : Number(maximum.value))), "List limit saved.");
|
||
save.disabled = false;
|
||
if (ok) { close(); render(); }
|
||
else error.textContent = message;
|
||
};
|
||
});
|
||
}
|
||
function listMenu(trigger: HTMLElement, list: BoardList) {
|
||
const fill = (panel: HTMLDivElement, close: () => void) => {
|
||
panel.classList.add("pm-menu");
|
||
panel.append(
|
||
button("Edit list", () => {
|
||
close();
|
||
listForm(trigger, list);
|
||
}, "rename"),
|
||
button("Set list limit", () => {
|
||
close();
|
||
listLimitForm(trigger, list);
|
||
}, "limit"),
|
||
);
|
||
const index = store.board.value.lists.findIndex(
|
||
(item) => item.id === list.id,
|
||
);
|
||
for (const [label, delta] of [
|
||
["Move left", -1],
|
||
["Move right", 1],
|
||
] as const) {
|
||
const move = button(label, () => {
|
||
close();
|
||
void perform(
|
||
() =>
|
||
store.changeBoard(() => store.board.move(list.id, index + delta)),
|
||
"List moved.",
|
||
);
|
||
}, delta < 0 ? "left" : "right");
|
||
move.disabled =
|
||
index + delta < 0 || index + delta >= store.board.value.lists.length;
|
||
panel.append(move);
|
||
}
|
||
const archive = button("Archive all cards", () => {
|
||
close();
|
||
void perform(() => store.archiveList(list.id), "Cards archived.");
|
||
}, "archive");
|
||
archive.disabled = !store.cardsInList(list.id).length;
|
||
panel.append(archive);
|
||
panel.append(
|
||
button("Delete list", () => {
|
||
close();
|
||
popup(trigger, "Delete list", (confirmation, done) => {
|
||
const count = store.tasks.filter(
|
||
(task) => store.board.listFor(task)?.id === list.id,
|
||
).length;
|
||
confirmation.append(
|
||
el("strong", "Delete “" + list.name + "”?"),
|
||
el(
|
||
"p",
|
||
count
|
||
? count +
|
||
" cards will move to Unlisted. Their notes and status will stay unchanged."
|
||
: "This removes the empty list.",
|
||
),
|
||
);
|
||
const error = el("p", "", "pm-error");
|
||
error.role = "alert";
|
||
const actions = el("div", "", "pm-popup-actions");
|
||
actions.append(
|
||
button("Cancel", () => {
|
||
if (!busy) done();
|
||
}),
|
||
button("Delete list", async () => {
|
||
const ok = await perform(
|
||
() => store.changeBoard(() => store.board.remove(list.id)),
|
||
"List deleted. Task notes were kept.",
|
||
);
|
||
if (ok) {
|
||
done();
|
||
render();
|
||
} else error.textContent = message;
|
||
}),
|
||
);
|
||
confirmation.append(error, actions);
|
||
});
|
||
}, "trash"),
|
||
);
|
||
};
|
||
closePopup?.();
|
||
boardMenu?.close();
|
||
trigger.focus({ preventScroll: true });
|
||
const panel = el("div");
|
||
fill(panel, () => { boardMenu?.close(); boardMenu = undefined; });
|
||
const bounds = trigger.getBoundingClientRect();
|
||
const hostIcons = { limit: "settings", kanban: "kanban", up: "up", down: "down", rename: "rename", left: "arrow-left", right: "arrow-right", archive: "archive", trash: "trash" } as const;
|
||
boardMenu = options.ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: "List actions", items: Array.from(panel.querySelectorAll<HTMLButtonElement>(":scope > button")).map(control => ({
|
||
label: control.textContent ?? "", icon: hostIcons[control.dataset.icon as keyof typeof hostIcons], disabled: control.disabled, run: () => control.click(),
|
||
})) });
|
||
}
|
||
const notify = (text: string, error = false) => {
|
||
message = text;
|
||
failed = error;
|
||
};
|
||
async function perform(
|
||
action: () => Promise<void>,
|
||
success: string,
|
||
): Promise<boolean> {
|
||
if (busy || closed) return false;
|
||
busy = true;
|
||
root.setAttribute("aria-busy", "true");
|
||
try {
|
||
await action();
|
||
if (!closed) notify(success);
|
||
return true;
|
||
} catch (error) {
|
||
if (!closed)
|
||
notify(error instanceof Error ? error.message : String(error), true);
|
||
return false;
|
||
} finally {
|
||
busy = false;
|
||
if (!closed) {
|
||
root.removeAttribute("aria-busy");
|
||
if (!activeDialog && !closePopup) render();
|
||
}
|
||
}
|
||
}
|
||
const filtered = () =>
|
||
store.scopedTasks.filter(
|
||
(task) =>
|
||
task.archived === showArchived &&
|
||
`${task.title} ${task.body} ${task.tags.join(" ")} ${(task.labels ?? []).map((id) => store.labels.value.find((label) => label.id === id)?.name ?? "").join(" ")} ${(task.assignees ?? []).join(" ")} ${(task.customFields ?? []).map((field) => `${field.name} ${field.value}`).join(" ")}`
|
||
.toLocaleLowerCase()
|
||
.includes(search.toLocaleLowerCase()),
|
||
);
|
||
function manageLabels(updated?: () => void) {
|
||
if (busy || store.labels.source === undefined) return;
|
||
closePopup?.();
|
||
const parent = activeDialog;
|
||
const focus = document.activeElement as HTMLElement | null;
|
||
const dialog = createLabelManager(
|
||
store.labels,
|
||
async (labels, expected) => {
|
||
const ok = await perform(
|
||
() => store.saveLabels(labels, expected),
|
||
"Labels saved.",
|
||
);
|
||
if (!ok) throw new Error(message);
|
||
},
|
||
() => {
|
||
activeDialog = parent;
|
||
if (closed) return;
|
||
render();
|
||
if (focus?.isConnected) focus.focus({ preventScroll: true });
|
||
else
|
||
root
|
||
.querySelector<HTMLButtonElement>('[aria-label="Manage labels"]')
|
||
?.focus({ preventScroll: true });
|
||
updated?.();
|
||
},
|
||
);
|
||
activeDialog = dialog;
|
||
root.append(dialog);
|
||
dialog.showModal();
|
||
}
|
||
function openEditor(task?: Task, initial: Partial<TaskFields> = {}) {
|
||
if (activeDialog || busy) return;
|
||
closePopup?.();
|
||
restoreFocus =
|
||
document.activeElement instanceof HTMLElement
|
||
? document.activeElement
|
||
: undefined;
|
||
const restoreTaskId = restoreFocus?.closest<HTMLElement>(".pm-card")?.dataset.taskId;
|
||
const dialog = el("dialog", "", "pm-editor pm-card-editor");
|
||
activeDialog = dialog;
|
||
const form = el("form");
|
||
form.method = "dialog";
|
||
const heading = el("h2", task ? task.title : "New card");
|
||
heading.id = "pm-editor-title";
|
||
dialog.setAttribute("aria-labelledby", heading.id);
|
||
const intro = el(
|
||
"p",
|
||
task
|
||
? isHiddenCard(task.path)
|
||
? "Private workspace card"
|
||
: `Linked note: ${task.path}`
|
||
: "Creates a private workspace card.",
|
||
"pm-muted",
|
||
);
|
||
heading.classList.add("pm-visually-hidden");
|
||
intro.classList.add("pm-card-context");
|
||
form.append(heading, intro);
|
||
const grid = el("div", "", "pm-form-grid");
|
||
form.append(grid);
|
||
const field = (
|
||
label: string,
|
||
type: string,
|
||
value: string,
|
||
wide = false,
|
||
) => {
|
||
const wrap = el("label", label, wide ? "pm-field pm-wide" : "pm-field");
|
||
const input = el("input");
|
||
input.type = type;
|
||
input.value = value;
|
||
wrap.append(input);
|
||
grid.append(wrap);
|
||
return input;
|
||
};
|
||
const title = field("Title", "text", task?.title ?? "", true);
|
||
title.parentElement!.classList.add("pm-editor-card-title");
|
||
title.placeholder = "Card title";
|
||
title.required = true;
|
||
title.maxLength = 100;
|
||
const values: TaskFields = task ?? {
|
||
status: "todo",
|
||
listId: store.board.value.defaults.todo,
|
||
tags: [],
|
||
archived: false,
|
||
sessions: [],
|
||
...initial,
|
||
};
|
||
const statusWrap = el("label", "Status", "pm-field pm-wide"),
|
||
status = el("select");
|
||
status.setAttribute("aria-label", "Status");
|
||
statuses.forEach((value) => {
|
||
const option = el("option", statusNames[value]);
|
||
option.value = value;
|
||
status.append(option);
|
||
});
|
||
status.value = values.status;
|
||
statusWrap.append(status);
|
||
grid.append(statusWrap);
|
||
const listWrap = el("label", "List", "pm-field pm-wide"),
|
||
listSelect = el("select");
|
||
const activeBoards = store.boards.filter(board => !board.archived);
|
||
let originalBoardId = store.board.reference?.id ??
|
||
(task ? activeBoards.find(board => Object.hasOwn(task?.placements ?? {}, board.id))?.id : undefined) ?? "";
|
||
const editorBoard = activeBoards.find(board => board.id === originalBoardId)?.value ?? store.board.value;
|
||
listSelect.setAttribute("aria-label", "List");
|
||
const unlisted = el("option", "Unlisted");
|
||
unlisted.value = "";
|
||
listSelect.append(unlisted);
|
||
for (const list of editorBoard.lists) {
|
||
const option = el("option", list.name);
|
||
option.value = list.id;
|
||
listSelect.append(option);
|
||
}
|
||
let originalListId = originalBoardId && task
|
||
? task.placements?.[originalBoardId]?.listId ?? ""
|
||
: store.board.listFor(values)?.id ?? "";
|
||
listSelect.value = originalListId;
|
||
if (listSelect.selectedIndex < 0) listSelect.value = "";
|
||
listWrap.append(listSelect);
|
||
grid.append(listWrap);
|
||
const due = field("Deadline", "date", values.due?.date ?? "");
|
||
const start = field("Planned start", "date", values.plan?.start ?? "");
|
||
const end = field(
|
||
"Planned last day",
|
||
"date",
|
||
values.plan ? addDays(values.plan.end, -1) : "",
|
||
);
|
||
const tags = createTagInput(
|
||
values.tags,
|
||
store.tasks.flatMap((task) => task.tags),
|
||
);
|
||
const first = values.sessions[0];
|
||
const sessionStart = field(
|
||
"Work session start",
|
||
"datetime-local",
|
||
first ? localTime(first.start) : "",
|
||
);
|
||
const sessionEnd = field(
|
||
"Work session end",
|
||
"datetime-local",
|
||
first ? localTime(first.end) : "",
|
||
);
|
||
const sessionHint = el(
|
||
"p",
|
||
`Session times use ${Intl.DateTimeFormat().resolvedOptions().timeZone}. This editor changes the first session only.`,
|
||
"pm-muted pm-wide",
|
||
);
|
||
const description = el("textarea");
|
||
description.rows = 3;
|
||
description.spellcheck = true;
|
||
description.value = task?.body ?? "";
|
||
const labels = createLabelPicker(store.labels, values.labels ?? [], () =>
|
||
manageLabels(() => {
|
||
if (task) {
|
||
const current = store.tasks.find((current) => current.id === task!.id);
|
||
if (current && current.source === editTask(task, { labels: current.labels })) task = current;
|
||
}
|
||
labels.refresh();
|
||
labels.open();
|
||
}),
|
||
true,
|
||
);
|
||
const images = createCardImages(
|
||
store.workspace,
|
||
description,
|
||
(name, action) => button(name, action, name === "Actual size" ? "expand" : "image"),
|
||
(name, action) => iconButton(name, "close", action),
|
||
(loading) => { save.disabled = loading || busy || !title.value.trim(); descriptionEditor.updateLoading(); },
|
||
task?.attachments,
|
||
);
|
||
const formattingIcons: Record<string, keyof typeof icons> = {
|
||
Heading: "heading", Bold: "bold", Italic: "italic", "Bullet list": "list", Link: "link", Code: "code",
|
||
Preview: "preview", Save: "check", Cancel: "close",
|
||
};
|
||
const draft = task ? new DescriptionDraft(store.workspace, task.id) : undefined;
|
||
let descriptionSaving = false;
|
||
let draftTimer: ReturnType<typeof setTimeout> | undefined;
|
||
let draftEdited = false;
|
||
const draftReady = draft?.load().then(body => {
|
||
if (body !== null && !draftEdited && dialog.isConnected) {
|
||
descriptionEditor.restoreDraft(body);
|
||
updateDescriptionBadge(task!.id, body !== task!.body);
|
||
}
|
||
});
|
||
const flushDraft = async () => {
|
||
clearTimeout(draftTimer);
|
||
await draftReady;
|
||
if (!draft || !task) return;
|
||
await images.save(description.value);
|
||
await draft.save(description.value === task.body ? null : description.value);
|
||
};
|
||
const reportDraftError = (reason: unknown) => { error.textContent = reason instanceof Error ? reason.message : String(reason); };
|
||
void draftReady?.catch(reportDraftError);
|
||
const descriptionEditor = createDescriptionEditor(description, images,
|
||
(name, action) => button(name, action, name === "Edit" ? "rename" : formattingIcons[name]), task ? {
|
||
async save() {
|
||
if (busy) throw new Error("Wait for the card to finish saving.");
|
||
descriptionSaving = true;
|
||
const body = description.value;
|
||
description.readOnly = true;
|
||
for (const control of [boardSelect, listSelect, status, save, cancel, closeEditor]) control.disabled = true;
|
||
clearTimeout(draftTimer);
|
||
try {
|
||
await draftReady;
|
||
await placementQueue;
|
||
await images.save(body);
|
||
await store.save(task!, { body, attachments: images.value() });
|
||
task = store.tasks.find(item => item.id === task!.id)!;
|
||
await draft!.save(null);
|
||
updateDescriptionBadge(task!.id, false);
|
||
error.textContent = "";
|
||
} catch (reason) { reportDraftError(reason); throw reason; }
|
||
finally {
|
||
descriptionSaving = false; description.readOnly = false;
|
||
for (const control of [boardSelect, listSelect, status, cancel, closeEditor]) control.disabled = false;
|
||
save.disabled = !title.value.trim() || images.isLoading();
|
||
}
|
||
},
|
||
async cancel() {
|
||
clearTimeout(draftTimer);
|
||
try { await draftReady; await draft!.save(null); updateDescriptionBadge(task!.id, false); error.textContent = ""; return task!.body; }
|
||
catch (reason) { reportDraftError(reason); throw reason; }
|
||
},
|
||
} : undefined);
|
||
description.addEventListener("input", () => {
|
||
draftEdited = true;
|
||
if (task) updateDescriptionBadge(task.id, description.value !== task.body);
|
||
clearTimeout(draftTimer);
|
||
if (draft && !images.isLoading()) draftTimer = setTimeout(() => { void flushDraft().catch(reportDraftError); }, 300);
|
||
});
|
||
const useSharedChoices = sharedChoice;
|
||
const updateChoice = sharedChoices.update;
|
||
const header = el("div", "", "pm-card-editor-header");
|
||
const closeEditor = iconButton("Close card", "close", () => {
|
||
if (!busy) requestClose();
|
||
});
|
||
listWrap.hidden = !originalBoardId;
|
||
statusWrap.hidden = !!originalBoardId;
|
||
header.append(listWrap);
|
||
if (!store.board.reference) header.append(statusWrap);
|
||
const boardSelect = el("select"); boardSelect.setAttribute("aria-label", "Board");
|
||
const needsBoard = !task && !store.board.reference;
|
||
if (task || needsBoard) {
|
||
const boardWrap = el("label", "Board", "pm-field");
|
||
if (!originalBoardId) { const none = el("option", needsBoard ? "Choose a board" : "No active board"); none.value = ""; boardSelect.append(none); }
|
||
for (const board of activeBoards) { const option = el("option", board.name); option.value = board.id; boardSelect.append(option); }
|
||
boardSelect.value = originalBoardId;
|
||
boardSelect.onchange = () => {
|
||
const board = store.boards.find(item => item.id === boardSelect.value);
|
||
listSelect.replaceChildren(el("option", "Unlisted")); listSelect.options[0].value = "";
|
||
for (const list of (board?.value ?? store.board.value).lists) { const option = el("option", list.name); option.value = list.id; listSelect.append(option); }
|
||
const placement = task?.placements?.[boardSelect.value];
|
||
const matchingList = needsBoard ? board?.value.lists.find(list => `list:${list.name.trim().toLowerCase()}` === initial.listId) : undefined;
|
||
listSelect.value = placement ? placement.listId ?? "" : matchingList?.id ?? board?.value.defaults[values.status] ?? "";
|
||
if (listSelect.selectedIndex < 0) listSelect.value = "";
|
||
listWrap.hidden = !boardSelect.value; statusWrap.hidden = !!boardSelect.value;
|
||
updateChoice(listSelect);
|
||
error.textContent = "";
|
||
};
|
||
boardWrap.append(boardSelect); header.prepend(boardWrap);
|
||
}
|
||
header.append(closeEditor);
|
||
for (const select of [status, listSelect, boardSelect]) if (select.isConnected || select.parentElement) useSharedChoices(select);
|
||
form.insertBefore(header, heading);
|
||
let relatedTarget: { taskId?: string; subtaskId?: string } | undefined;
|
||
let nextCard: Task | undefined;
|
||
const relations = createRelations(task, store.tasks, (name, action) => button(name, action, "plus"), (name, action) => iconButton(name, "trash", action), store.boards, target => {
|
||
if (busy || images.isLoading()) return;
|
||
relatedTarget = target;
|
||
form.requestSubmit(save);
|
||
}, useSharedChoices);
|
||
grid.replaceChildren(title.parentElement!, labels.element, descriptionEditor.element);
|
||
const optional = el("div", "", "pm-optional-fields pm-wide");
|
||
const choices = el("div", "", "pm-field-choices pm-wide");
|
||
choices.setAttribute("role", "group");
|
||
choices.setAttribute("aria-label", "Card details");
|
||
const addDetails = button("Add details", () => {}, "plus");
|
||
const details = createDetailsPicker(addDetails);
|
||
choices.append(addDetails, labels.trigger, details.element);
|
||
details.add(button("Subtasks and linked cards", () => { relations.element.hidden = false; relations.focus(); }, "link"), "Track smaller tasks and card dependencies.");
|
||
relations.element.hidden = !(task?.links?.length || task?.subtasks?.length || (task && store.tasks.some(item => item.links?.some(link => link.taskId === task?.id) || item.subtasks?.some(subtask => subtask.taskId === task?.id))));
|
||
grid.append(images.attachmentsElement, relations.element);
|
||
const coverWrap = el("label", "Card cover", "pm-field pm-wide");
|
||
const cover = el("select"); cover.setAttribute("aria-label", "Card cover");
|
||
let coverInitialized = false;
|
||
const drawCovers = () => {
|
||
const selected = coverInitialized ? cover.value : task?.coverImage || "";
|
||
coverInitialized = true;
|
||
cover.replaceChildren(el("option", "No cover")); cover.options[0].value = "";
|
||
for (const ref of images.references()) { const option = el("option", ref.name); option.value = ref.id; cover.append(option); }
|
||
cover.value = [...cover.options].some(item => item.value === selected) ? selected : "";
|
||
};
|
||
drawCovers(); description.addEventListener("input", drawCovers); coverWrap.append(cover);
|
||
const coverChoice = useSharedChoices(cover);
|
||
coverWrap.hidden = !task?.coverImage; grid.append(coverWrap);
|
||
details.add(button("Card cover", () => { drawCovers(); coverWrap.hidden = false; coverChoice.focus(); }, "image"), "Choose an image from this card.");
|
||
details.add(button("Labels", () => labels.open(), "tag"), "Organize cards with saved labels.");
|
||
disposeEditor = () => { clearTimeout(draftTimer); sharedChoices.close(); descriptionEditor.dispose(); details.dispose(); priority.dispose(); labels.dispose(); images.dispose(); };
|
||
const group = (
|
||
name: string,
|
||
icon: keyof typeof icons,
|
||
nodes: HTMLElement[],
|
||
visible: boolean,
|
||
clear?: () => void,
|
||
) => {
|
||
const section = el("section", "", "pm-optional-group");
|
||
section.setAttribute("aria-label", name + " fields");
|
||
const header = el("div", "", "pm-optional-heading");
|
||
const content = el("div", "", "pm-optional-content");
|
||
content.append(...nodes);
|
||
const show = () => {
|
||
section.hidden = false;
|
||
section.querySelector<HTMLElement>("input,select,textarea")?.focus();
|
||
};
|
||
const choice = button(
|
||
name,
|
||
show,
|
||
icon,
|
||
);
|
||
const remove = iconButton(
|
||
(clear ? "Remove " : "Hide ") + name,
|
||
"close",
|
||
() => {
|
||
clear?.();
|
||
section.hidden = true;
|
||
(quickChoice ?? addDetails).focus();
|
||
},
|
||
);
|
||
header.append(el("h3", name), remove);
|
||
section.append(header, content);
|
||
section.hidden = !visible;
|
||
const quickChoice = ["Deadline", "Assignments", "Priority"].includes(name) ? button(name, show, icon) : undefined;
|
||
if (quickChoice) choices.append(quickChoice);
|
||
details.add(choice, name === "Priority" ? "Set urgency without changing labels." : `Add or edit ${name.toLocaleLowerCase()}.`);
|
||
optional.append(section);
|
||
};
|
||
group("Deadline", "calendar", [due.parentElement!], !!values.due, () => {
|
||
due.value = "";
|
||
});
|
||
group(
|
||
"Planned dates",
|
||
"gantt",
|
||
[start.parentElement!, end.parentElement!],
|
||
!!values.plan,
|
||
() => {
|
||
start.value = end.value = "";
|
||
},
|
||
);
|
||
group("Tags", "tag", [tags.element], !!values.tags.length, tags.clear);
|
||
group(
|
||
"Work session",
|
||
"clock",
|
||
[sessionStart.parentElement!, sessionEnd.parentElement!, sessionHint],
|
||
!!first,
|
||
() => {
|
||
sessionStart.value = sessionEnd.value = "";
|
||
},
|
||
);
|
||
const color = createColorPalette(
|
||
"Card color",
|
||
values.color ?? "",
|
||
() => updateColor(),
|
||
true,
|
||
);
|
||
const colorSample = el("div", "Card preview", "pm-color-sample pm-wide");
|
||
const updateColor = () => {
|
||
colorSample.style.setProperty(
|
||
"--pm-card-color",
|
||
cardColors[color.value() as keyof typeof cardColors] ?? "transparent",
|
||
);
|
||
};
|
||
updateColor();
|
||
group("Color", "tag", [color.element, colorSample], !!values.color, () => {
|
||
color.set("");
|
||
updateColor();
|
||
});
|
||
const assignees = field(
|
||
"Names (comma separated)",
|
||
"text",
|
||
(values.assignees ?? []).join(", "),
|
||
true,
|
||
);
|
||
assignees.placeholder = "People, teams, or customers";
|
||
group(
|
||
"Assignments",
|
||
"person",
|
||
[assignees.parentElement!],
|
||
!!values.assignees?.length,
|
||
() => {
|
||
assignees.value = "";
|
||
},
|
||
);
|
||
const priorityTrigger = button("Priority", () => {}, "priority");
|
||
const priority = createPriorityPicker(priorityTrigger, values.priority ?? null, preferences.priorityLevels, options.ui);
|
||
choices.append(priorityTrigger);
|
||
details.add(button("Priority", () => priority.open(), "priority"), "Set urgency without changing labels.");
|
||
const customRows: { name: HTMLInputElement; value: HTMLInputElement }[] =
|
||
[];
|
||
const addCustomField = (name = "", value = "") => {
|
||
const section = el("section", "", "pm-optional-group");
|
||
const header = el("div", "", "pm-optional-heading");
|
||
const content = el("div", "", "pm-optional-content");
|
||
const nameInput = field("Field name", "text", name);
|
||
const valueInput = field("Field value", "text", value);
|
||
nameInput.required = true;
|
||
nameInput.maxLength = 80;
|
||
const row = { name: nameInput, value: valueInput };
|
||
customRows.push(row);
|
||
header.append(
|
||
el("h3", "Custom field"),
|
||
iconButton("Remove custom field", "close", () => {
|
||
customRows.splice(customRows.indexOf(row), 1);
|
||
section.remove();
|
||
addDetails.focus();
|
||
}),
|
||
);
|
||
content.append(nameInput.parentElement!, valueInput.parentElement!);
|
||
section.append(header, content);
|
||
optional.append(section);
|
||
return nameInput;
|
||
};
|
||
for (const field of values.customFields ?? [])
|
||
addCustomField(field.name, field.value);
|
||
const customChoice = button(
|
||
"Custom field",
|
||
() => addCustomField().focus(),
|
||
"plus",
|
||
);
|
||
details.add(customChoice, "Store a named value on this card.");
|
||
grid.insertBefore(choices, labels.element);
|
||
grid.insertBefore(optional, descriptionEditor.element);
|
||
const placement = store.board.listFor(values)?.name ?? "Unlisted";
|
||
intro.textContent = task
|
||
? isHiddenCard(task.path)
|
||
? "Private workspace card"
|
||
: `Linked note: ${task.path}`
|
||
: needsBoard ? "Choose a board for this card." : `New card in ${placement}`;
|
||
const error = el("p", needsBoard && !activeBoards.length ? "Create a board before adding cards." : "", "pm-error");
|
||
error.setAttribute("role", "alert");
|
||
form.append(error);
|
||
if (task) {
|
||
const created = el("p", `Created: ${task.createdAt ? new Date(task.createdAt).toLocaleString() : "Unknown"}`, "pm-created-at");
|
||
if (task.createdAt) created.title = task.createdAt;
|
||
form.append(created);
|
||
}
|
||
const actions = el("div", "", "pm-editor-actions");
|
||
const cancel = button("Cancel", () => { if (!busy && !descriptionSaving) void placementQueue.then(flushDraft).then(() => dialog.close()).catch(reportDraftError); });
|
||
const save = button(task ? "Save card" : "Create card", () => {});
|
||
save.type = "submit";
|
||
save.classList.add("pm-primary");
|
||
actions.append(cancel, save);
|
||
form.append(actions);
|
||
dialog.append(form);
|
||
root.append(dialog);
|
||
dialog.showModal();
|
||
let titleEntered = !!task;
|
||
const titleFirst = () => {
|
||
if (title.value.trim()) titleEntered = true;
|
||
for (const item of [choices, labels.element, optional, descriptionEditor.element, images.attachmentsElement])
|
||
item.hidden = !titleEntered;
|
||
save.disabled = images.isLoading() || !title.value.trim() || (needsBoard && !activeBoards.length);
|
||
descriptionEditor.resize();
|
||
};
|
||
title.addEventListener("input", titleFirst);
|
||
titleFirst();
|
||
const initialDraft = () => JSON.stringify({
|
||
title: title.value.trim(), body: description.value.trim(), status: status.value,
|
||
board: boardSelect.value, list: listSelect.value, due: due.value, start: start.value, end: end.value,
|
||
tags: tags.value(), labels: labels.value(), color: color.value(),
|
||
priority: priority.value(), cover: cover.value, relations: relations.value(), removedIncoming: relations.removedIncoming().map(task => task.id), assignees: assignees.value.trim(),
|
||
attachments: images.value(),
|
||
sessionStart: sessionStart.value, sessionEnd: sessionEnd.value,
|
||
custom: customRows.map((row) => [row.name.value, row.value.value]),
|
||
});
|
||
const emptyDraft = initialDraft();
|
||
let placementQueue: Promise<void> = Promise.resolve();
|
||
const persistPlacement = () => {
|
||
if (!task || descriptionSaving) return;
|
||
const boardId = boardSelect.value;
|
||
const listId = listSelect.value;
|
||
const nextStatus = status.value as Status;
|
||
placementQueue = placementQueue.catch(() => {}).then(async () => {
|
||
try {
|
||
if (boardId) await store.saveToBoard(task!, boardId, listId || null, {});
|
||
else await store.save(task!, { status: nextStatus });
|
||
task = store.tasks.find(item => item.id === task!.id)!;
|
||
originalBoardId = boardId;
|
||
originalListId = listId;
|
||
status.value = task.status;
|
||
updateChoice(status);
|
||
error.textContent = "";
|
||
} catch (reason) {
|
||
reportDraftError(reason);
|
||
throw reason;
|
||
}
|
||
});
|
||
void placementQueue.catch(() => {});
|
||
};
|
||
for (const control of [boardSelect, listSelect, status]) control.addEventListener("change", persistPlacement);
|
||
title.focus();
|
||
dialog.oncancel = (event) => {
|
||
event.preventDefault();
|
||
if (!busy) requestClose();
|
||
};
|
||
dialog.onclose = () => {
|
||
activeDialog = undefined;
|
||
disposeEditor?.();
|
||
disposeEditor = undefined;
|
||
dialog.remove();
|
||
if (nextCard && !closed) { openEditor(nextCard); return; }
|
||
if (!closed) {
|
||
render();
|
||
const restoredCard = restoreTaskId
|
||
? Array.from(root.querySelectorAll<HTMLElement>(".pm-card"))
|
||
.find((card) => card.dataset.taskId === restoreTaskId)
|
||
?.querySelector<HTMLButtonElement>(".pm-card-title")
|
||
: undefined;
|
||
const focus = restoreFocus?.isConnected ? restoreFocus : restoredCard;
|
||
if (focus) focus.focus({ preventScroll: true });
|
||
else
|
||
root
|
||
.querySelector<HTMLButtonElement>('.pm-tabs [aria-pressed="true"]')
|
||
?.focus({ preventScroll: true });
|
||
}
|
||
};
|
||
// A backdrop click must start and end outside the card. Child dialogs and
|
||
// popovers consume their own dismissal without saving the parent draft.
|
||
let outsidePointer: number | undefined;
|
||
let outsideClick = false;
|
||
let outsideChildSurface = false;
|
||
const onBackdrop = (event: MouseEvent) => {
|
||
const target = event.target;
|
||
if (!(target instanceof HTMLElement) ||
|
||
(target !== dialog && !target.matches(":popover-open"))) return false;
|
||
const bounds = target.getBoundingClientRect();
|
||
return event.clientX < bounds.left || event.clientX > bounds.right ||
|
||
event.clientY < bounds.top || event.clientY > bounds.bottom;
|
||
};
|
||
const hasChildSurface = () => activeDialog !== dialog ||
|
||
!!dialog.querySelector('dialog[open], :popover-open');
|
||
dialog.addEventListener("pointerdown", (event) => {
|
||
outsideClick = false;
|
||
outsideChildSurface = hasChildSurface();
|
||
outsidePointer = event.isPrimary && event.button === 0 &&
|
||
onBackdrop(event) ? event.pointerId : undefined;
|
||
}, true);
|
||
dialog.addEventListener("pointerup", (event) => {
|
||
outsideClick = outsidePointer === event.pointerId && onBackdrop(event);
|
||
outsidePointer = undefined;
|
||
}, true);
|
||
dialog.addEventListener("pointercancel", () => {
|
||
outsidePointer = undefined;
|
||
outsideClick = false;
|
||
});
|
||
dialog.addEventListener("click", (event) => {
|
||
const dismiss = outsideClick && onBackdrop(event);
|
||
outsideClick = false;
|
||
if (!dismiss || busy || !dialog.open) return;
|
||
if (outsideChildSurface || hasChildSurface()) {
|
||
for (const panel of dialog.querySelectorAll<HTMLElement>(":popover-open"))
|
||
panel.hidePopover();
|
||
return;
|
||
}
|
||
requestClose();
|
||
});
|
||
function requestClose() {
|
||
if (descriptionSaving) return;
|
||
if (images.isLoading()) {
|
||
error.textContent = "Wait for images to finish loading, then try again.";
|
||
return;
|
||
}
|
||
if (!task && initialDraft() === emptyDraft) {
|
||
dialog.close();
|
||
return;
|
||
}
|
||
if (!title.value.trim()) {
|
||
title.focus();
|
||
error.textContent = "Enter a card title to save this draft.";
|
||
return;
|
||
}
|
||
form.requestSubmit(save);
|
||
}
|
||
form.addEventListener("invalid", (event) => {
|
||
const control = event.target as HTMLInputElement;
|
||
error.textContent = control.validationMessage;
|
||
}, true);
|
||
form.onsubmit = async (event) => {
|
||
event.preventDefault();
|
||
if (busy || descriptionSaving || images.isLoading()) return;
|
||
error.textContent = "";
|
||
if (needsBoard && !boardSelect.value) { error.textContent = "Choose a board for this card."; sharedChoice(boardSelect).focus(); return; }
|
||
try {
|
||
await placementQueue;
|
||
if (!!start.value !== !!end.value)
|
||
throw new Error("Enter both planned dates, or clear both fields.");
|
||
if (!!sessionStart.value !== !!sessionEnd.value)
|
||
throw new Error("Enter both session times, or clear both fields.");
|
||
const sessions = [...values.sessions.slice(1)];
|
||
if (sessionStart.value)
|
||
sessions.unshift({
|
||
id: first?.id ?? crypto.randomUUID(),
|
||
start: localInstant(sessionStart.value),
|
||
end: localInstant(sessionEnd.value),
|
||
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||
});
|
||
const selectedList = (boardSelect.value ? activeBoards.find(board => board.id === boardSelect.value)?.value : store.board.value)?.lists.find(
|
||
(list) => list.id === listSelect.value,
|
||
);
|
||
const listChanged = listSelect.value !== originalListId;
|
||
const fields: TaskFields = {
|
||
...(task && title.value.trim() !== task.title
|
||
? { title: title.value.trim() }
|
||
: {}),
|
||
color: color.value() || undefined,
|
||
coverImage: cover.value || null,
|
||
attachments: images.value(),
|
||
...relations.value(),
|
||
...(priority.changed() ? { priority: priority.value() } : {}),
|
||
assignees: assignees.value
|
||
.split(",")
|
||
.map((name) => name.trim())
|
||
.filter(Boolean),
|
||
customFields: customRows.map((row) => ({
|
||
name: row.name.value.trim(),
|
||
value: row.value.value,
|
||
})),
|
||
status: boardSelect.value || store.board.reference || needsBoard
|
||
? ((!task || listChanged ? selectedList?.status : null) ??
|
||
task?.status ?? values.status)
|
||
: (status.value as Status),
|
||
...((store.board.reference && originalBoardId === store.board.reference.id) || needsBoard
|
||
? { listId: listSelect.value || null }
|
||
: {}),
|
||
tags: tags.value(),
|
||
labels:
|
||
labels.value().length || values.labels !== undefined
|
||
? labels.value()
|
||
: undefined,
|
||
due: due.value ? { date: due.value } : undefined,
|
||
plan: start.value
|
||
? { start: start.value, end: addDays(end.value, 1) }
|
||
: undefined,
|
||
sessions,
|
||
archived: values.archived,
|
||
};
|
||
save.disabled = cancel.disabled = true;
|
||
images.setSaving(true);
|
||
const body = task ? task.body : description.value;
|
||
const ok = await perform(
|
||
async () => {
|
||
await flushDraft();
|
||
await images.save(body);
|
||
const existingIds = new Set(store.tasks.map(candidate => candidate.id));
|
||
await (task && boardSelect.value && (boardSelect.value !== originalBoardId || (!store.board.reference && listChanged))
|
||
? store.saveToBoard(task, boardSelect.value, listSelect.value || null, { ...fields, body })
|
||
: task
|
||
? store.save(
|
||
task,
|
||
{ ...fields, body },
|
||
!!store.board.reference && listChanged,
|
||
)
|
||
: store.create(title.value, fields, body, needsBoard ? boardSelect.value : undefined));
|
||
task = store.tasks.find(candidate => task ? candidate.id === task.id : !existingIds.has(candidate.id));
|
||
if (!task) throw new Error("The saved card is unavailable. Refresh the board.");
|
||
await store.unlinkIncoming(task.id, relations.removedIncoming());
|
||
save.textContent = "Save card";
|
||
if (relatedTarget?.subtaskId) {
|
||
nextCard = await store.openSubtask(task.id, relatedTarget.subtaskId);
|
||
} else if (relatedTarget?.taskId) {
|
||
nextCard = store.tasks.find(candidate => candidate.id === relatedTarget!.taskId);
|
||
if (!nextCard) throw new Error("The linked card is unavailable. Refresh the board.");
|
||
}
|
||
},
|
||
"Card saved.",
|
||
);
|
||
if (closed) return;
|
||
if (ok) dialog.close();
|
||
else error.textContent = message;
|
||
} catch (reason) {
|
||
error.textContent =
|
||
reason instanceof Error ? reason.message : String(reason);
|
||
} finally {
|
||
relatedTarget = undefined;
|
||
save.disabled = cancel.disabled = false;
|
||
images.setSaving(false);
|
||
}
|
||
};
|
||
}
|
||
function transferCard(task: Task) {
|
||
if (activeDialog || busy) return;
|
||
closePopup?.();
|
||
const dialog = el("dialog", "", "pm-editor"),
|
||
form = el("form"),
|
||
grid = el("div", "", "pm-form-grid"),
|
||
boardLabel = el("label", "Destination board", "pm-field"),
|
||
boardSelect = el("select"),
|
||
listLabel = el("label", "Destination list", "pm-field"),
|
||
listSelect = el("select"),
|
||
hint = el("p", "", "pm-muted"),
|
||
error = el("p", "", "pm-error"),
|
||
actions = el("div", "", "pm-editor-actions"),
|
||
cancel = button("Cancel", () => { if (!busy) dialog.close(); }),
|
||
move = button("Move card", () => {}, "right");
|
||
activeDialog = dialog;
|
||
dialog.setAttribute("aria-label", "Move card to board");
|
||
boardSelect.required = true;
|
||
boardLabel.append(boardSelect);
|
||
listLabel.append(listSelect);
|
||
error.role = "alert";
|
||
move.type = "submit";
|
||
move.classList.add("pm-primary");
|
||
actions.append(cancel, move);
|
||
grid.append(boardLabel, listLabel);
|
||
form.append(el("h2", `Move “${task.title}”`),
|
||
el("p", `Remove this card from ${store.board.name} and place it on the selected board. Card details, status, and other board memberships stay unchanged.`),
|
||
grid, hint, error, actions);
|
||
dialog.append(form);
|
||
root.append(dialog);
|
||
const fillLists = (preferred?: string) => {
|
||
listSelect.replaceChildren();
|
||
const destination = store.boards.find((board) => board.id === boardSelect.value);
|
||
if (destination) {
|
||
const unlisted = el("option", "Unlisted");
|
||
unlisted.value = "";
|
||
listSelect.append(unlisted);
|
||
for (const list of destination.value.lists) {
|
||
const option = el("option", list.name);
|
||
option.value = list.id;
|
||
listSelect.append(option);
|
||
}
|
||
const placement = task.placements?.[destination.id];
|
||
listSelect.value = preferred ??
|
||
(placement ? placement.listId : destination.value.defaults[task.status]) ?? "";
|
||
if (listSelect.selectedIndex < 0) listSelect.value = "";
|
||
hint.textContent = placement
|
||
? "This card already belongs to that board. The selected list replaces its current placement."
|
||
: "The card will appear at the end of the selected list.";
|
||
}
|
||
listSelect.disabled = move.disabled = !destination;
|
||
};
|
||
const fillBoards = () => {
|
||
const previousBoard = boardSelect.value, previousList = listSelect.value;
|
||
const boards = store.boards.filter((board) =>
|
||
board.id !== store.board.reference?.id && !board.archived);
|
||
const placeholder = el("option", boards.length ? "Choose a board" : "No other active boards");
|
||
placeholder.value = "";
|
||
boardSelect.replaceChildren(placeholder);
|
||
for (const board of boards) {
|
||
const option = el("option", board.name);
|
||
option.value = board.id;
|
||
boardSelect.append(option);
|
||
}
|
||
boardSelect.value = boards.some((board) => board.id === previousBoard) ? previousBoard : "";
|
||
boardSelect.disabled = !boards.length;
|
||
hint.textContent = boards.length ? "Choose the board that should contain this card." : "Create another board before moving this card.";
|
||
fillLists(previousList);
|
||
};
|
||
fillBoards();
|
||
const boardChoice = sharedChoice(boardSelect);
|
||
sharedChoice(listSelect);
|
||
boardSelect.onchange = () => fillLists();
|
||
dialog.oncancel = (event) => { if (busy) event.preventDefault(); };
|
||
dialog.onclose = () => {
|
||
activeDialog = undefined;
|
||
dialog.remove();
|
||
if (closed) return;
|
||
render();
|
||
const card = Array.from(root.querySelectorAll<HTMLElement>(".pm-card"))
|
||
.find((item) => item.dataset.taskId === task.id);
|
||
(card?.querySelector<HTMLButtonElement>(".pm-card-menu") ??
|
||
root.querySelector<HTMLButtonElement>('.pm-tabs [aria-pressed="true"]'))
|
||
?.focus({ preventScroll: true });
|
||
};
|
||
form.onsubmit = async (event) => {
|
||
event.preventDefault();
|
||
if (busy || !boardSelect.value) return;
|
||
error.textContent = "";
|
||
boardSelect.disabled = listSelect.disabled = move.disabled = cancel.disabled = true;
|
||
const ok = await perform(
|
||
() => store.transferTask(task, boardSelect.value, listSelect.value || null),
|
||
"Card moved to the selected board.",
|
||
);
|
||
if (closed) return;
|
||
if (ok) dialog.close();
|
||
else {
|
||
cancel.disabled = false;
|
||
fillBoards();
|
||
error.textContent = message;
|
||
}
|
||
};
|
||
dialog.showModal();
|
||
(boardSelect.disabled ? cancel : boardChoice).focus();
|
||
}
|
||
function updateDescriptionBadge(id: string, dirty: boolean) {
|
||
for (const badge of root.querySelectorAll<HTMLElement>(`.pm-card[data-task-id="${CSS.escape(id)}"] .pm-card-unsaved`)) {
|
||
badge.dataset.edited = "true";
|
||
badge.hidden = !dirty;
|
||
}
|
||
}
|
||
function card(task: Task): HTMLElement {
|
||
const item = el("article", "", "pm-card");
|
||
const toggleSelection = () => {
|
||
if (selectedCards.has(task.id)) selectedCards.delete(task.id); else selectedCards.add(task.id);
|
||
render(); root.querySelector<HTMLInputElement>(`.pm-card[data-task-id="${CSS.escape(task.id)}"] .pm-card-select`)?.focus();
|
||
};
|
||
if (selectionMode) {
|
||
item.classList.toggle("pm-card-selected", selectedCards.has(task.id));
|
||
const checkbox = el("input", "", "pm-card-select"); checkbox.type = "checkbox"; checkbox.checked = selectedCards.has(task.id); checkbox.setAttribute("aria-label", `Select ${task.title}`); checkbox.onchange = toggleSelection; item.append(checkbox);
|
||
}
|
||
item.dataset.taskId = task.id;
|
||
applyTaskColor(item, task);
|
||
if (task.coverImage && [...imageReferences(task.body), ...(task.attachments ?? [])].some(ref => ref.id === task.coverImage)) {
|
||
const cover = el("img", "", "pm-card-cover"); cover.alt = ""; cover.loading = "lazy";
|
||
const coverButton = button("", () => openEditor(task)); coverButton.className = "pm-card-cover-button";
|
||
coverButton.setAttribute("aria-label", `Open ${task.title}`); coverButton.append(cover); item.append(coverButton);
|
||
void loadImage(task.coverImage).then(data => { if (!closed) cover.src = data; }).catch(() => coverButton.remove());
|
||
cover.onerror = () => coverButton.remove();
|
||
}
|
||
if (task.color) {
|
||
item.classList.add("pm-colored-card");
|
||
item.setAttribute("aria-label", task.title + ", " + task.color);
|
||
}
|
||
const line = el("div", "", "pm-card-line"),
|
||
open = button(task.title, () => openEditor(task));
|
||
open.className = "pm-card-title";
|
||
if (task.status === "done") open.classList.add("pm-complete");
|
||
const menu = iconButton("Actions for " + task.title, "more", () =>
|
||
popup(menu, "Card actions", (panel, close) => {
|
||
panel.classList.add("pm-menu");
|
||
panel.append(
|
||
button("Edit card", () => {
|
||
close();
|
||
openEditor(task);
|
||
}, "rename"),
|
||
);
|
||
const label = el("label", "Move to list", "pm-field"),
|
||
select = el("select");
|
||
select.setAttribute("aria-label", "Move " + task.title + " to list");
|
||
const unlisted = el("option", "Unlisted");
|
||
unlisted.value = "";
|
||
select.append(unlisted);
|
||
for (const list of store.board.value.lists) {
|
||
const option = el("option", list.name);
|
||
option.value = list.id;
|
||
select.append(option);
|
||
}
|
||
select.value = store.board.listFor(task)?.id ?? "";
|
||
select.onchange = () => {
|
||
close();
|
||
void perform(
|
||
() => store.moveTask(task, select.value || null),
|
||
"Card moved.",
|
||
);
|
||
};
|
||
label.append(select);
|
||
if (store.board.reference) panel.append(label);
|
||
if (store.board.reference) {
|
||
const transfer = button("Move to board", () => {
|
||
close();
|
||
transferCard(task);
|
||
}, "right");
|
||
transfer.disabled = store.board.archived;
|
||
panel.append(transfer);
|
||
}
|
||
if (store.board.reference && !task.archived) {
|
||
const listId = store.board.listFor(task)?.id ?? null;
|
||
const cards = store.cardsInList(listId);
|
||
const index = cards.findIndex((card) => card.id === task.id);
|
||
for (const [name, delta] of [
|
||
["Move up", -1],
|
||
["Move down", 1],
|
||
] as const) {
|
||
const move = button(name, () => {
|
||
close();
|
||
const beforeId =
|
||
delta < 0
|
||
? cards[index - 1].id
|
||
: (cards[index + 2]?.id ?? null);
|
||
void perform(
|
||
() => store.moveTask(task, listId, beforeId),
|
||
"Card moved.",
|
||
);
|
||
}, delta < 0 ? "up" : "down");
|
||
move.disabled = index + delta < 0 || index + delta >= cards.length;
|
||
panel.append(move);
|
||
}
|
||
}
|
||
if (store.board.reference)
|
||
panel.append(
|
||
button("Remove from board", () => {
|
||
close();
|
||
void perform(
|
||
() => store.removeFromBoard(task),
|
||
"Card removed from this board. The task note remains.",
|
||
);
|
||
}, "kanban"),
|
||
);
|
||
panel.append(
|
||
button(task.archived ? "Restore" : "Archive", () => {
|
||
close();
|
||
void perform(
|
||
() => store.save(task, { archived: !task.archived }),
|
||
task.archived ? "Task restored." : "Task archived.",
|
||
);
|
||
}, "archive"),
|
||
button("Delete card", () => { close(); deleteCardForm(task, menu); }, "trash"),
|
||
);
|
||
}),
|
||
);
|
||
menu.classList.add("pm-card-menu");
|
||
menu.setAttribute("aria-haspopup", "menu");
|
||
menu.onkeydown = event => { if (["ArrowDown", "ArrowUp"].includes(event.key)) { event.preventDefault(); menu.click(); } };
|
||
line.append(open, menu);
|
||
item.append(line);
|
||
const unsaved = el("span", "Unsaved description", "pm-card-unsaved");
|
||
const draftIcon = el("span", "", "pm-icon");
|
||
draftIcon.innerHTML = `<svg viewBox="0 0 24 24" aria-hidden="true">${icons.rename}</svg>`;
|
||
unsaved.prepend(draftIcon);
|
||
unsaved.title = "Open this card and save or cancel the description changes.";
|
||
unsaved.hidden = true;
|
||
item.append(unsaved);
|
||
void new DescriptionDraft(store.workspace, task.id).load().then(body => {
|
||
if (!closed && !unsaved.dataset.edited) unsaved.hidden = body === null || body === task.body;
|
||
}).catch(() => {
|
||
if (!closed && !unsaved.dataset.edited) {
|
||
unsaved.textContent = "Description draft needs recovery";
|
||
unsaved.hidden = false;
|
||
}
|
||
});
|
||
if (
|
||
task.tags.length ||
|
||
task.labels?.length ||
|
||
task.priority ||
|
||
task.due ||
|
||
task.assignees?.length
|
||
) {
|
||
const badges = el("div", "", "pm-badges");
|
||
if (task.priority) {
|
||
const priority = el("span", `${priorityNames[task.priority]} priority`, "pm-priority");
|
||
const icon = el("span", "", "pm-icon");
|
||
icon.innerHTML = `<svg viewBox="0 0 24 24" aria-hidden="true">${icons.priority}</svg>`;
|
||
priority.prepend(icon);
|
||
setPriorityAppearance(priority, task.priority);
|
||
badges.append(priority);
|
||
}
|
||
for (const id of task.labels ?? [])
|
||
badges.append(
|
||
labelBadge(
|
||
store.labels.value.find((label) => label.id === id),
|
||
id,
|
||
),
|
||
);
|
||
for (const tag of task.tags) badges.append(el("span", tag, "pm-tag"));
|
||
for (const name of task.assignees ?? []) {
|
||
const person = el("span", name, "pm-assignee");
|
||
person.setAttribute("aria-label", "Assigned to " + name);
|
||
badges.append(person);
|
||
}
|
||
if (task.due)
|
||
badges.append(
|
||
el(
|
||
"span",
|
||
shortDate(task.due.date),
|
||
task.status !== "done" && task.due.date < localDay()
|
||
? "pm-due pm-overdue"
|
||
: "pm-due",
|
||
),
|
||
);
|
||
item.append(badges);
|
||
}
|
||
let dragged = false;
|
||
item.onpointerdown = () => { dragged = false; };
|
||
item.addEventListener("click", (event) => {
|
||
if (selectionMode && event.target instanceof Element && !event.target.closest(".pm-card-select")) {
|
||
event.preventDefault(); event.stopImmediatePropagation(); toggleSelection(); return;
|
||
}
|
||
if (dragged && event.detail !== 0) {
|
||
event.preventDefault();
|
||
event.stopImmediatePropagation();
|
||
return;
|
||
}
|
||
if (event.defaultPrevented || drag || !(event.target instanceof Element)) return;
|
||
if (event.target.closest("button,a,input,select,textarea,label,summary,[role=button],[contenteditable=true]")) return;
|
||
open.focus({ preventScroll: true });
|
||
openEditor(task);
|
||
}, true);
|
||
item.draggable = !!store.board.reference && !task.archived && !selectionMode;
|
||
item.ondragstart = (event) => {
|
||
if (!item.draggable) { event.preventDefault(); return; }
|
||
dragged = true;
|
||
beginDrag(event, "task", task.id, item, task.title);
|
||
};
|
||
return item;
|
||
}
|
||
function bulkForm(trigger: HTMLElement, action: "delete" | "list" | "board") {
|
||
const tasks = filtered().filter(task => selectedCards.has(task.id));
|
||
if (!tasks.length || busy) return;
|
||
const title = action === "delete" ? "Delete selected cards" : action === "list" ? "Move selected cards to list" : "Move selected cards to board";
|
||
popup(trigger, title, (panel, close) => {
|
||
panel.append(el("h3", title), el("p", `${tasks.length} cards selected.`));
|
||
const boards = el("select"); boards.setAttribute("aria-label", "Destination board");
|
||
const lists = el("select"); lists.setAttribute("aria-label", "Destination list");
|
||
const destinations = store.boards.filter(board => !board.archived && board.id !== store.board.reference?.id);
|
||
for (const board of destinations) { const option = el("option", board.name); option.value = board.id; boards.append(option); }
|
||
const updateLists = () => {
|
||
lists.replaceChildren(); const unlisted = el("option", "Unlisted"); unlisted.value = ""; lists.append(unlisted);
|
||
const board = action === "board" ? destinations.find(board => board.id === boards.value)?.value : store.board.value;
|
||
for (const list of board?.lists ?? []) { const option = el("option", list.name); option.value = list.id; lists.append(option); }
|
||
};
|
||
boards.onchange = updateLists; updateLists();
|
||
if (action === "board") { const field = el("label", "Destination board", "pm-field"); field.append(boards); panel.append(field); }
|
||
if (action !== "delete") { const field = el("label", "Destination list", "pm-field"); field.append(lists); panel.append(field); }
|
||
else panel.append(el("p", "Delete these cards from all boards. Saved source notes and images remain in the workspace."));
|
||
const error = el("p", "", "pm-error"); error.setAttribute("role", "alert"); panel.append(error);
|
||
const actions = el("div", "", "pm-popup-actions");
|
||
const apply = button(action === "delete" ? "Delete cards" : "Move cards", async () => {
|
||
let completed = 0;
|
||
apply.disabled = true;
|
||
const ok = await perform(async () => {
|
||
await store.reload();
|
||
for (const task of tasks) if (!store.tasks.some(current => current.id === task.id && current.source === task.source))
|
||
throw new Error("A selected card changed. Refresh and select the cards again.");
|
||
for (const task of tasks) {
|
||
if (action === "delete") await store.deleteCard(task);
|
||
else if (action === "list") await store.moveTask(task, lists.value || null);
|
||
else await store.transferTask(task, boards.value, lists.value || null);
|
||
selectedCards.delete(task.id); completed++;
|
||
}
|
||
}, `${tasks.length} cards ${action === "delete" ? "deleted" : "moved"}.`);
|
||
apply.disabled = false;
|
||
if (ok) { close(); render(); }
|
||
else { error.textContent = `${completed} of ${tasks.length} cards changed. ${message}`; apply.disabled = true; }
|
||
}, action === "delete" ? "trash" : "right");
|
||
apply.disabled = action === "board" && !destinations.length;
|
||
actions.append(button("Cancel", () => { if (!busy) { close(); render(); } }), apply); panel.append(actions);
|
||
});
|
||
}
|
||
root.addEventListener("keydown", event => {
|
||
if (event.key === "Escape" && selectionMode && !activeDialog && !closePopup && !busy) {
|
||
event.preventDefault(); selectionMode = false; selectedCards.clear(); render(); root.querySelector<HTMLButtonElement>(".pm-select-mode")?.focus();
|
||
}
|
||
});
|
||
function selectionToolbar() {
|
||
const bar = el("div", "", "pm-selection-toolbar"); bar.setAttribute("role", "group"); bar.setAttribute("aria-label", "Selected cards");
|
||
bar.append(el("span", `${selectedCards.size} selected`, "pm-selection-count"));
|
||
bar.append(button("Select all cards", () => { for (const task of filtered()) selectedCards.add(task.id); render(); root.querySelector<HTMLButtonElement>(".pm-selection-toolbar button")?.focus(); }, "check"));
|
||
const clear = button("Clear selection", () => { selectedCards.clear(); render(); root.querySelector<HTMLButtonElement>(".pm-selection-toolbar button")?.focus(); }, "close"); clear.disabled = !selectedCards.size; bar.append(clear);
|
||
for (const [label, action, icon] of [["Move to list", "list", "kanban"], ["Move to board", "board", "right"], ["Delete selected", "delete", "trash"]] as const) {
|
||
const control = button(label, () => bulkForm(control, action), icon);
|
||
control.disabled = !selectedCards.size || (action !== "delete" && (!store.board.editable || !store.board.reference)); bar.append(control);
|
||
}
|
||
return bar;
|
||
}
|
||
let autoScroll: { x: number; y: number; pointerX: number; pointerY: number; moved: boolean; frame: number; time: number; marker: HTMLElement } | undefined;
|
||
function stopAutoScroll() {
|
||
if (!autoScroll) return;
|
||
cancelAnimationFrame(autoScroll.frame); autoScroll.marker.remove(); autoScroll = undefined;
|
||
root.classList.remove("pm-auto-scrolling");
|
||
}
|
||
function autoScrollFrame(time: number) {
|
||
const state = autoScroll;
|
||
if (!state) return;
|
||
const board = root.querySelector<HTMLElement>(".pm-board");
|
||
if (!board || !root.getClientRects().length || activeDialog || closePopup || closed) { stopAutoScroll(); return; }
|
||
const elapsed = Math.min(40, time - state.time || 16) / 16;
|
||
state.time = time;
|
||
const speed = (distance: number) => Math.abs(distance) <= 8 ? 0 : Math.sign(distance) * Math.min(40, (Math.abs(distance) - 8) / 6);
|
||
board.scrollLeft += speed(state.pointerX - state.x) * elapsed;
|
||
scrollContainer().scrollTop += speed(state.pointerY - state.y) * elapsed;
|
||
state.frame = requestAnimationFrame(autoScrollFrame);
|
||
}
|
||
function startAutoScroll(event: MouseEvent) {
|
||
if (autoScroll) { event.preventDefault(); stopAutoScroll(); return; }
|
||
if (event.button !== 1 || activeDialog || closePopup || drag || !root.querySelector(".pm-board") ||
|
||
!(event.target instanceof Element) || event.target.closest("button,a,input,textarea,select,dialog,.pm-popup,.rs-menu,[contenteditable=true]")) return;
|
||
const board = root.querySelector<HTMLElement>(".pm-board")!, vertical = scrollContainer();
|
||
if (board.scrollWidth <= board.clientWidth && vertical.scrollHeight <= vertical.clientHeight) return;
|
||
event.preventDefault();
|
||
const marker = el("div", "", "pm-autoscroll-marker"); marker.setAttribute("aria-hidden", "true");
|
||
const glyph = el("span", "", "pm-icon");
|
||
glyph.innerHTML = `<svg viewBox="0 0 24 24" aria-hidden="true">${icons.scroll}</svg>`;
|
||
marker.append(glyph); marker.style.left = `${event.clientX}px`; marker.style.top = `${event.clientY}px`;
|
||
root.append(marker); root.classList.add("pm-auto-scrolling");
|
||
autoScroll = { x: event.clientX, y: event.clientY, pointerX: event.clientX, pointerY: event.clientY, moved: false, frame: requestAnimationFrame(autoScrollFrame), time: performance.now(), marker };
|
||
}
|
||
function moveAutoScroll(event: MouseEvent) {
|
||
if (!autoScroll) return;
|
||
autoScroll.pointerX = event.clientX; autoScroll.pointerY = event.clientY;
|
||
if (Math.hypot(event.clientX - autoScroll.x, event.clientY - autoScroll.y) > 8) autoScroll.moved = true;
|
||
}
|
||
function releaseAutoScroll(event: MouseEvent) { if (event.button === 1 && autoScroll?.moved) stopAutoScroll(); }
|
||
function dismissAutoScroll(event: KeyboardEvent) { if (event.key === "Escape" && autoScroll) { event.preventDefault(); stopAutoScroll(); } }
|
||
function outsideAutoScroll(event: MouseEvent) { if (autoScroll && !root.contains(event.target as Node)) { event.preventDefault(); stopAutoScroll(); } }
|
||
function preventAutoScrollClick(event: MouseEvent) { if (event.button === 1 && event.target instanceof Element && !event.target.closest("a,button,input")) event.preventDefault(); }
|
||
function scrollBoard(event: WheelEvent) {
|
||
if (
|
||
activeDialog ||
|
||
closePopup ||
|
||
drag ||
|
||
event.defaultPrevented ||
|
||
!event.cancelable ||
|
||
event.ctrlKey ||
|
||
event.metaKey ||
|
||
event.shiftKey ||
|
||
event.altKey ||
|
||
event.deltaX !== 0 ||
|
||
event.deltaY === 0
|
||
)
|
||
return;
|
||
const board = root.querySelector<HTMLElement>(".pm-board");
|
||
if (
|
||
!board ||
|
||
(event.target !== board &&
|
||
event.target !== root &&
|
||
event.target !== root.querySelector(".pm-toolbar"))
|
||
)
|
||
return;
|
||
const unit =
|
||
event.deltaMode === WheelEvent.DOM_DELTA_LINE
|
||
? parseFloat(getComputedStyle(board).lineHeight) || 16
|
||
: event.deltaMode === WheelEvent.DOM_DELTA_PAGE
|
||
? board.clientWidth
|
||
: 1;
|
||
const previous = board.scrollLeft;
|
||
board.scrollLeft += event.deltaY * unit;
|
||
if (board.scrollLeft !== previous) event.preventDefault();
|
||
}
|
||
function kanban(tasks: Task[]) {
|
||
const board = el("div", "", "pm-board");
|
||
const insertion = el("div", "", "pm-list-insertion");
|
||
insertion.hidden = true;
|
||
insertion.setAttribute("aria-hidden", "true");
|
||
const cardInsertion = el("div", "", "pm-card-insertion");
|
||
cardInsertion.hidden = true;
|
||
cardInsertion.setAttribute("aria-hidden", "true");
|
||
const columns: { node: HTMLElement; id: string | null }[] = [];
|
||
const targetAt = (x: number) => {
|
||
const remaining = columns.filter(
|
||
(column) => column.id !== null && column.id !== drag?.id,
|
||
);
|
||
const index = remaining.findIndex(({ node }) => {
|
||
const rect = node.getBoundingClientRect();
|
||
return x < rect.left + rect.width / 2;
|
||
});
|
||
return { remaining, index: index < 0 ? remaining.length : index };
|
||
};
|
||
const cardTarget = (column: (typeof columns)[number], y: number) => {
|
||
const cards = [
|
||
...column.node.querySelectorAll<HTMLElement>(
|
||
".pm-card-stack > .pm-card",
|
||
),
|
||
].filter((card) => card.dataset.taskId !== drag?.id);
|
||
const before = cards.find((card) => {
|
||
const rect = card.getBoundingClientRect();
|
||
return y < rect.top + rect.height / 2;
|
||
});
|
||
const top = before
|
||
? before.getBoundingClientRect().top - 4
|
||
: cards.length
|
||
? cards.at(-1)!.getBoundingClientRect().bottom + 4
|
||
: column.node
|
||
.querySelector(".pm-column-heading")!
|
||
.getBoundingClientRect().bottom + 6;
|
||
return { beforeId: before?.dataset.taskId ?? null, top };
|
||
};
|
||
const showTarget = (x: number, y: number) => {
|
||
columns.forEach(({ node }) => node.classList.remove("pm-drop-target"));
|
||
if (drag?.kind === "list") {
|
||
const { remaining, index } = targetAt(x);
|
||
const target = remaining[index] ?? remaining.at(-1);
|
||
if (!target) return;
|
||
const rect = target.node.getBoundingClientRect();
|
||
const bounds = board.getBoundingClientRect();
|
||
insertion.hidden = false;
|
||
insertion.style.left =
|
||
(index < remaining.length ? rect.left - 7 : rect.right + 5) -
|
||
bounds.left +
|
||
board.scrollLeft +
|
||
"px";
|
||
insertion.style.height = Math.max(160, rect.height) + "px";
|
||
} else if (drag?.kind === "task") {
|
||
const column = nearestColumn(x);
|
||
if (!column) return;
|
||
column.node.classList.add("pm-drop-target");
|
||
const target = cardTarget(column, y);
|
||
const rect = column.node.getBoundingClientRect();
|
||
const bounds = board.getBoundingClientRect();
|
||
cardInsertion.hidden = false;
|
||
cardInsertion.style.left =
|
||
rect.left - bounds.left + board.scrollLeft + 8 + "px";
|
||
cardInsertion.style.top =
|
||
target.top - bounds.top + board.scrollTop + "px";
|
||
cardInsertion.style.width = rect.width - 16 + "px";
|
||
}
|
||
};
|
||
const nearestColumn = (x: number) =>
|
||
columns.reduce<(typeof columns)[number] | undefined>(
|
||
(nearest, column) => {
|
||
const distance = (node: HTMLElement) => {
|
||
const rect = node.getBoundingClientRect();
|
||
return Math.abs(x - (rect.left + rect.width / 2));
|
||
};
|
||
return !nearest || distance(column.node) < distance(nearest.node)
|
||
? column
|
||
: nearest;
|
||
},
|
||
undefined,
|
||
);
|
||
board.ondragover = (event) => {
|
||
if (!store.board.reference || !drag || busy) return;
|
||
event.preventDefault();
|
||
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
|
||
const bounds = board.getBoundingClientRect();
|
||
if (event.clientX < bounds.left + 40) board.scrollLeft -= 24;
|
||
else if (event.clientX > bounds.right - 40) board.scrollLeft += 24;
|
||
if (event.clientY < bounds.top + 40) board.scrollTop -= 24;
|
||
else if (event.clientY > bounds.bottom - 40) board.scrollTop += 24;
|
||
showTarget(event.clientX, event.clientY);
|
||
};
|
||
board.ondragleave = (event) => {
|
||
if (!board.contains(event.relatedTarget as Node)) {
|
||
insertion.hidden = true;
|
||
cardInsertion.hidden = true;
|
||
columns.forEach(({ node }) => node.classList.remove("pm-drop-target"));
|
||
}
|
||
};
|
||
board.ondrop = (event) => {
|
||
if (!store.board.reference || !drag || busy) return;
|
||
event.preventDefault();
|
||
const { kind, id } = drag;
|
||
if (kind === "list") {
|
||
const { index } = targetAt(event.clientX);
|
||
const source = store.board.value.lists.findIndex(
|
||
(list) => list.id === id,
|
||
);
|
||
clearDrag();
|
||
if (source !== index)
|
||
void perform(
|
||
() => store.changeBoard(() => store.board.move(id, index)),
|
||
"List moved.",
|
||
);
|
||
} else {
|
||
const target = nearestColumn(event.clientX);
|
||
const task = store.tasks.find((task) => task.id === id);
|
||
const position = target ? cardTarget(target, event.clientY) : undefined;
|
||
clearDrag();
|
||
if (task && target && position)
|
||
void perform(
|
||
() => store.moveTask(task, target.id, position.beforeId),
|
||
"Card moved.",
|
||
);
|
||
}
|
||
};
|
||
const lists: TaskColumn[] = store.board.reference
|
||
? store.board.value.lists.map(list => ({ list, tasks: tasks.filter(task => store.board.listFor(task)?.id === list.id) }))
|
||
: allTaskColumns(store.boards, tasks);
|
||
if (store.board.reference && tasks.some(task => !store.board.listFor(task)))
|
||
lists.push({ tasks: tasks.filter(task => !store.board.listFor(task)) });
|
||
for (const column of lists) {
|
||
const data = column.list;
|
||
const name = data?.name ?? "Unlisted",
|
||
id = data?.id ?? null;
|
||
const list = el("section", "", "pm-column");
|
||
list.setAttribute("aria-label", name);
|
||
list.dataset.listId = id ?? "unlisted";
|
||
const collapsed = store.board.reference ? pendingCollapsedLists.get(id ?? "unlisted") ?? !!data?.collapsed : collapsedLists.has(id ?? "unlisted");
|
||
list.classList.toggle("pm-column-collapsed", collapsed);
|
||
const members = column.tasks.sort((a, b) => compareCards(a, b, store.board.reference?.id));
|
||
const heading = el("div", "", "pm-column-heading");
|
||
if (data && store.board.editable) {
|
||
const grip = iconButton("Move list " + name, "grip", () =>
|
||
listMenu(grip, data),
|
||
);
|
||
grip.classList.add("pm-list-grip");
|
||
grip.draggable = true;
|
||
grip.ondragstart = (event) => {
|
||
beginDrag(event, "list", data.id, list, name);
|
||
};
|
||
heading.append(grip);
|
||
}
|
||
if (!store.board.reference || (data && store.board.editable)) {
|
||
const collapse = iconButton(
|
||
(collapsed ? "Expand " : "Collapse ") + name,
|
||
collapsed ? "right" : "down",
|
||
async () => {
|
||
if (store.board.reference && data) {
|
||
pendingCollapsedLists.set(data.id, !collapsed);
|
||
render();
|
||
await perform(() => store.changeBoard(() => store.board.collapse(data.id), false), "List updated.");
|
||
pendingCollapsedLists.delete(data.id);
|
||
render();
|
||
} else {
|
||
const key = id ?? "unlisted";
|
||
if (collapsedLists.has(key)) collapsedLists.delete(key); else collapsedLists.add(key);
|
||
state.collapsedLists = [...collapsedLists];
|
||
render();
|
||
}
|
||
Array.from(root.querySelectorAll<HTMLElement>(".pm-column"))
|
||
.find(column => column.dataset.listId === (id ?? "unlisted"))
|
||
?.querySelector<HTMLButtonElement>("[aria-expanded]")?.focus({ preventScroll: true });
|
||
},
|
||
);
|
||
collapse.setAttribute("aria-expanded", String(!collapsed));
|
||
heading.append(collapse);
|
||
}
|
||
heading.append(
|
||
el("h2", name),
|
||
);
|
||
const activeCount = store.cardsInList(id).length;
|
||
const maximum = data?.maxCards;
|
||
const count = el("span", maximum === undefined ? String(members.length) : `${activeCount}/${maximum}`, "pm-count");
|
||
heading.append(count);
|
||
if (maximum !== undefined) {
|
||
const reached = activeCount >= maximum;
|
||
const description = `${activeCount} active cards in ${name}. Maximum is ${maximum}.${reached ? activeCount > maximum ? " Limit exceeded." : " Limit reached." : ""}`;
|
||
count.setAttribute("aria-label", description);
|
||
const indicator = iconButton(description, reached ? "warning" : "limit", () => { if (data && store.board.editable) listLimitForm(indicator, data); });
|
||
indicator.classList.add("pm-list-limit");
|
||
if (reached) indicator.classList.add("pm-list-limit-reached");
|
||
heading.append(indicator);
|
||
}
|
||
if (data && store.board.editable) {
|
||
const more = iconButton("List actions for " + name, "more", () =>
|
||
listMenu(more, data),
|
||
);
|
||
more.classList.add("pm-list-actions");
|
||
heading.append(more);
|
||
}
|
||
list.append(heading);
|
||
if (!collapsed) {
|
||
const cards = el("div", "", "pm-card-stack");
|
||
if (store.board.reference) members.forEach((task) => cards.append(card(task)));
|
||
else for (const group of allTaskGroups(store.boards, column)) {
|
||
const section = el("section", "", "pm-board-group");
|
||
section.setAttribute("aria-label", group.name);
|
||
section.append(el("h3", group.name, "pm-board-group-heading"));
|
||
group.tasks.forEach(task => section.append(card(task)));
|
||
cards.append(section);
|
||
}
|
||
list.append(cards);
|
||
if ((store.board.reference || store.boards.some(board => !board.archived)) && !showArchived && cardDraft?.listId === id) {
|
||
list.append(cardComposer());
|
||
} else if ((store.board.reference || store.boards.some(board => !board.archived)) && !showArchived) {
|
||
list.append(addCardButton(id, data?.status ?? "todo"));
|
||
}
|
||
}
|
||
board.append(list);
|
||
columns.push({ node: list, id });
|
||
}
|
||
if (!lists.length) {
|
||
const empty = el("div", "", "pm-board-empty");
|
||
const add = button("Add a list", () => listForm(add), "plus");
|
||
empty.append(add);
|
||
board.append(empty);
|
||
}
|
||
board.append(insertion, cardInsertion);
|
||
return board;
|
||
}
|
||
function addCardButton(listId: string | null, status: Status) {
|
||
const add = button("Add a card", () => {
|
||
if (!store.board.reference) { openEditor(undefined, { listId, status }); return; }
|
||
cardDraft = cardDrafts.get(listId) ?? { listId, status, title: "" };
|
||
cardDraft.status = status;
|
||
cardDrafts.set(listId, cardDraft);
|
||
render();
|
||
root.querySelector<HTMLTextAreaElement>(".pm-card-composer textarea")?.focus({ preventScroll: true });
|
||
}, "plus");
|
||
add.classList.add("pm-add-card");
|
||
return add;
|
||
}
|
||
function hideCardComposer() {
|
||
if (!cardDraft || busy) return;
|
||
const draft = cardDraft;
|
||
cardDraft = undefined;
|
||
// Replace only the composer, so the outside control keeps its focus and click.
|
||
root.querySelector(".pm-card-composer")?.replaceWith(addCardButton(draft.listId, draft.status));
|
||
}
|
||
function outsideCardComposer(event: Event) {
|
||
const form = root.querySelector(".pm-card-composer");
|
||
if (form && event.target instanceof Node && !form.contains(event.target)) hideCardComposer();
|
||
}
|
||
function cardComposer() {
|
||
const draft = cardDraft!;
|
||
const form = el("form", "", "pm-card-composer");
|
||
form.setAttribute("aria-label", "New card");
|
||
const title = el("textarea");
|
||
title.setAttribute("aria-label", "Card title");
|
||
title.placeholder = "Enter a title for this card";
|
||
title.rows = 3;
|
||
title.maxLength = 100;
|
||
title.required = true;
|
||
title.value = draft.title;
|
||
const actions = el("div", "", "pm-composer-actions");
|
||
const save = button("Add card", () => {}, "plus");
|
||
save.type = "submit";
|
||
save.classList.add("pm-primary");
|
||
save.disabled = busy || !draft.title.trim();
|
||
const cancel = iconButton("Cancel new card", "close", () => {
|
||
if (busy) return;
|
||
cardDrafts.delete(draft.listId);
|
||
cardDraft = undefined;
|
||
render();
|
||
Array.from(root.querySelectorAll<HTMLElement>(".pm-column"))
|
||
.find(column => column.dataset.listId === (draft.listId ?? "unlisted"))
|
||
?.querySelector<HTMLButtonElement>(".pm-add-card")?.focus({ preventScroll: true });
|
||
});
|
||
cancel.disabled = title.disabled = busy;
|
||
title.oninput = () => {
|
||
draft.title = title.value;
|
||
save.disabled = busy || !draft.title.trim();
|
||
};
|
||
form.onkeydown = event => {
|
||
if (event.key === "Escape") {
|
||
event.preventDefault();
|
||
cancel.click();
|
||
} else if (event.target === title && event.key === "Enter" && !event.shiftKey && !event.isComposing) {
|
||
event.preventDefault();
|
||
if (!save.disabled) form.requestSubmit();
|
||
}
|
||
};
|
||
form.onsubmit = async event => {
|
||
event.preventDefault();
|
||
if (busy || !draft.title.trim()) return;
|
||
save.disabled = cancel.disabled = title.disabled = true;
|
||
form.setAttribute("aria-busy", "true");
|
||
await perform(async () => {
|
||
await store.createOrLink(draft.title.trim().replace(/\s*\n\s*/g, " "), {
|
||
listId: draft.listId, status: draft.status, tags: [], sessions: [], archived: false,
|
||
});
|
||
cardDrafts.delete(draft.listId);
|
||
cardDraft = undefined;
|
||
}, "Card saved.");
|
||
if (closed) return;
|
||
const column = Array.from(root.querySelectorAll<HTMLElement>(".pm-column"))
|
||
.find(column => column.dataset.listId === (draft.listId ?? "unlisted"));
|
||
column?.querySelector<HTMLElement>(".pm-card-composer textarea, .pm-add-card")?.focus({ preventScroll: true });
|
||
};
|
||
actions.append(save, cancel);
|
||
form.append(title, actions);
|
||
return form;
|
||
}
|
||
function dateNav() {
|
||
const toolbar = el("div", "", "pm-date-nav");
|
||
const move = (direction: number) => {
|
||
if (view === "calendar" && period === "month") {
|
||
const date = new Date(`${anchor.slice(0, 7)}-01T12:00:00`);
|
||
date.setMonth(date.getMonth() + direction);
|
||
anchor = localDay(date);
|
||
} else
|
||
anchor = addDays(
|
||
anchor,
|
||
direction * (view === "gantt" ? 14 : period === "week" ? 7 : 1),
|
||
);
|
||
render();
|
||
};
|
||
toolbar.append(
|
||
iconButton("Previous", "left", () => move(-1)),
|
||
button("Today", () => {
|
||
anchor = localDay();
|
||
render();
|
||
}),
|
||
iconButton("Next", "right", () => move(1)),
|
||
);
|
||
const date = el("input");
|
||
date.type = "date";
|
||
date.value = anchor;
|
||
date.setAttribute("aria-label", "Visible date");
|
||
date.onchange = () => {
|
||
if (date.value) {
|
||
anchor = date.value;
|
||
render();
|
||
}
|
||
};
|
||
toolbar.append(date);
|
||
return toolbar;
|
||
}
|
||
function gantt(tasks: Task[]) {
|
||
const wrap = el("div");
|
||
wrap.className = "pm-view";
|
||
wrap.append(dateNav());
|
||
const scroll = el("div", "", "pm-gantt-scroll"),
|
||
table = el("div", "", "pm-gantt");
|
||
table.setAttribute("role", "table");
|
||
table.setAttribute("aria-label", "Task timeline");
|
||
const days = 28;
|
||
const header = el("div", "", "pm-gantt-row");
|
||
header.setAttribute("role", "row");
|
||
header.append(el("div", "Task / planned range", "pm-gantt-name"));
|
||
const dates = el("div", "", "pm-gantt-dates");
|
||
for (let i = 0; i < days; i++) {
|
||
const day = addDays(anchor, i);
|
||
const cell = el(
|
||
"span",
|
||
day.slice(-2),
|
||
day === localDay() ? "pm-today" : "",
|
||
);
|
||
cell.title = day;
|
||
dates.append(cell);
|
||
}
|
||
header.append(dates);
|
||
table.append(header);
|
||
for (const task of tasks) {
|
||
const row = el("div", "", "pm-gantt-row");
|
||
row.setAttribute("role", "row");
|
||
const name = button(task.title, () => openEditor(task));
|
||
name.className = "pm-gantt-name";
|
||
applyTaskColor(name, task);
|
||
name.append(
|
||
el(
|
||
"small",
|
||
task.plan
|
||
? `${shortDate(task.plan.start)} – ${shortDate(addDays(task.plan.end, -1))}`
|
||
: "Unscheduled",
|
||
),
|
||
);
|
||
row.append(name);
|
||
const track = el("div", "", "pm-gantt-track");
|
||
if (task.plan) {
|
||
const left = Math.max(0, dayDistance(anchor, task.plan.start)),
|
||
right = Math.min(days, dayDistance(anchor, task.plan.end));
|
||
if (right > left) {
|
||
const bar = button(task.title, () => openEditor(task));
|
||
bar.className = `pm-gantt-bar pm-status-${task.status}`;
|
||
applyTaskColor(bar, task);
|
||
bar.style.left = `${(left / days) * 100}%`;
|
||
bar.style.width = `${((right - left) / days) * 100}%`;
|
||
bar.title = `${task.title}: ${task.plan.start} through ${addDays(task.plan.end, -1)}`;
|
||
track.append(bar);
|
||
}
|
||
}
|
||
if (task.due) {
|
||
const offset = dayDistance(anchor, task.due.date);
|
||
if (offset >= 0 && offset < days) {
|
||
const marker = button("◆", () => openEditor(task));
|
||
marker.className = "pm-deadline";
|
||
applyTaskColor(marker, task);
|
||
marker.style.left = `${((offset + 0.5) / days) * 100}%`;
|
||
marker.setAttribute(
|
||
"aria-label",
|
||
`${task.title}, deadline ${task.due.date}`,
|
||
);
|
||
track.append(marker);
|
||
}
|
||
}
|
||
row.append(track);
|
||
table.append(row);
|
||
}
|
||
scroll.append(table);
|
||
wrap.append(scroll);
|
||
return wrap;
|
||
}
|
||
function calendar(tasks: Task[]) {
|
||
const wrap = el("div"),
|
||
toolbar = dateNav();
|
||
for (const value of ["day", "week", "month"] as const) {
|
||
const tab = button(value[0].toUpperCase() + value.slice(1), () => {
|
||
period = value;
|
||
render();
|
||
});
|
||
tab.setAttribute("aria-pressed", String(period === value));
|
||
toolbar.append(tab);
|
||
}
|
||
wrap.className = "pm-view";
|
||
toolbar.append(
|
||
el("span", Intl.DateTimeFormat().resolvedOptions().timeZone, "pm-zone"),
|
||
);
|
||
wrap.append(toolbar);
|
||
const entries = (day: string, timedOnly = false) => {
|
||
const list = el("div", "", "pm-calendar-entries");
|
||
for (const task of tasks) {
|
||
if (!timedOnly && task.due?.date === day) {
|
||
const event = button(`◆ Due: ${task.title}`, () => openEditor(task));
|
||
event.className = "pm-calendar-event pm-deadline-event";
|
||
applyTaskColor(event, task);
|
||
list.append(event);
|
||
}
|
||
for (const session of task.sessions) {
|
||
const start = new Date(session.start),
|
||
end = new Date(session.end);
|
||
const dayStart = new Date(`${day}T00:00:00`),
|
||
dayEnd = new Date(`${addDays(day, 1)}T00:00:00`);
|
||
if (start >= dayEnd || end <= dayStart) continue;
|
||
const event = button(
|
||
`${start.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })} ${task.title}`,
|
||
() => openEditor(task),
|
||
);
|
||
event.className = "pm-calendar-event";
|
||
applyTaskColor(event, task);
|
||
event.title = `${task.title}: ${start.toLocaleString()} – ${end.toLocaleString()}`;
|
||
if (timedOnly) {
|
||
const clippedStart = start < dayStart ? dayStart : start,
|
||
clippedEnd = end > dayEnd ? dayEnd : end;
|
||
const minuteStart =
|
||
clippedStart.getHours() * 60 + clippedStart.getMinutes();
|
||
const minuteEnd =
|
||
clippedEnd.getTime() === dayEnd.getTime()
|
||
? 1440
|
||
: clippedEnd.getHours() * 60 + clippedEnd.getMinutes();
|
||
event.style.top = `${(minuteStart / 60) * 52}px`;
|
||
event.style.minHeight = `${Math.max(24, ((minuteEnd - minuteStart) / 60) * 52)}px`;
|
||
event.classList.add("pm-timed-event");
|
||
}
|
||
list.append(event);
|
||
}
|
||
}
|
||
return list;
|
||
};
|
||
if (period === "month") {
|
||
const first = `${anchor.slice(0, 7)}-01`,
|
||
start = addDays(first, -new Date(`${first}T12:00:00`).getDay());
|
||
wrap.append(
|
||
el(
|
||
"h2",
|
||
new Date(`${first}T12:00:00`).toLocaleDateString(undefined, {
|
||
month: "long",
|
||
year: "numeric",
|
||
}),
|
||
),
|
||
);
|
||
const month = el("div", "", "pm-month");
|
||
for (const label of ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"])
|
||
month.append(el("div", label, "pm-day-heading"));
|
||
for (let i = 0; i < 42; i++) {
|
||
const day = addDays(start, i),
|
||
cell = el(
|
||
"div",
|
||
"",
|
||
`pm-month-day${day.slice(0, 7) !== anchor.slice(0, 7) ? " pm-outside" : ""}`,
|
||
);
|
||
const add = button(day.slice(-2), () =>
|
||
openEditor(undefined, { due: { date: day } }),
|
||
);
|
||
add.title = `Create task due ${day}`;
|
||
add.setAttribute("aria-label", add.title);
|
||
if (day === localDay()) add.classList.add("pm-today");
|
||
cell.append(add, entries(day));
|
||
month.append(cell);
|
||
}
|
||
wrap.append(month);
|
||
} else {
|
||
const count = period === "week" ? 7 : 1,
|
||
start =
|
||
count === 7
|
||
? addDays(anchor, -new Date(`${anchor}T12:00:00`).getDay())
|
||
: anchor;
|
||
const scroller = el("div", "", "pm-hours-scroll"),
|
||
hours = el("div", "", "pm-hours");
|
||
hours.style.setProperty("--days", String(count));
|
||
const labels = el("div", "", "pm-hour-labels");
|
||
labels.append(el("div", "Time", "pm-hour-heading"));
|
||
for (let hour = 0; hour < 24; hour++)
|
||
labels.append(
|
||
el("div", `${String(hour).padStart(2, "0")}:00`, "pm-hour-label"),
|
||
);
|
||
hours.append(labels);
|
||
for (let i = 0; i < count; i++) {
|
||
const day = addDays(start, i),
|
||
column = el("div", "", "pm-hour-day"),
|
||
heading = el("div", "", "pm-hour-heading");
|
||
heading.append(el("strong", shortDate(day)));
|
||
for (const task of tasks.filter((task) => task.due?.date === day)) {
|
||
const event = button(`◆ ${task.title}`, () => openEditor(task));
|
||
applyTaskColor(event, task);
|
||
heading.append(event);
|
||
}
|
||
const grid = el("div", "", "pm-hour-grid");
|
||
for (let hour = 0; hour < 24; hour++) {
|
||
const slot = button("", () => {
|
||
const from = new Date(
|
||
`${day}T${String(hour).padStart(2, "0")}:00:00`,
|
||
);
|
||
openEditor(undefined, {
|
||
sessions: [
|
||
{
|
||
id: crypto.randomUUID(),
|
||
start: from.toISOString(),
|
||
end: new Date(from.getTime() + 3_600_000).toISOString(),
|
||
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||
},
|
||
],
|
||
});
|
||
});
|
||
slot.className = "pm-hour-slot";
|
||
slot.setAttribute("aria-label", `Create session ${day} ${hour}:00`);
|
||
grid.append(slot);
|
||
}
|
||
const events = entries(day, true);
|
||
grid.append(events);
|
||
if (day === localDay()) {
|
||
const now = new Date(),
|
||
line = el("div", "", "pm-now");
|
||
line.style.top = `${(now.getHours() + now.getMinutes() / 60) * 52}px`;
|
||
grid.append(line);
|
||
}
|
||
column.append(heading, grid);
|
||
hours.append(column);
|
||
}
|
||
scroller.append(hours);
|
||
wrap.append(scroller);
|
||
}
|
||
return wrap;
|
||
}
|
||
function addExisting() {
|
||
if (activeDialog || busy) return;
|
||
closePopup?.();
|
||
const dialog = el("dialog", "", "pm-editor pm-note-picker");
|
||
activeDialog = dialog;
|
||
dialog.setAttribute("aria-label", "Add existing note");
|
||
const form = el("form"),
|
||
searchLabel = el("label", "Find a note or card", "pm-field"),
|
||
searchInput = el("input"),
|
||
results = el("div", "", "pm-note-results rs-picker"),
|
||
summary = el("p", "Loading notes…", "pm-note-summary"),
|
||
label = el("label", "Workspace note path", "pm-field"),
|
||
input = el("input");
|
||
searchInput.type = "search";
|
||
searchInput.placeholder = "Search by title or path";
|
||
searchLabel.append(searchInput);
|
||
summary.setAttribute("aria-live", "polite");
|
||
results.setAttribute("role", "group");
|
||
results.setAttribute("aria-label", "Matching notes and cards");
|
||
input.placeholder = "Notes/My task.md";
|
||
input.required = true;
|
||
label.append(input);
|
||
let candidates: { path: string; title: string }[] = [];
|
||
let loading = true;
|
||
let scanError = "";
|
||
const updateSelection = () => {
|
||
submit.disabled = busy || !input.value.trim();
|
||
for (const row of results.querySelectorAll<HTMLButtonElement>("button"))
|
||
{ const selected = String(row.dataset.path === input.value.trim()); row.setAttribute("aria-pressed", selected); row.setAttribute("aria-current", selected); }
|
||
};
|
||
const showResults = () => {
|
||
const query = searchInput.value.trim().toLocaleLowerCase();
|
||
const matches = candidates.filter(({ title, path }) =>
|
||
`${title} ${path}`.toLocaleLowerCase().includes(query),
|
||
);
|
||
results.replaceChildren();
|
||
for (const note of matches.slice(0, 100)) {
|
||
const row = button("", () => {
|
||
input.value = note.path;
|
||
error.textContent = "";
|
||
updateSelection();
|
||
}, "note");
|
||
row.className = "pm-note-result rs-picker-row";
|
||
row.querySelector(".pm-icon")?.classList.add("rs-picker-icon");
|
||
row.disabled = busy;
|
||
row.dataset.path = note.path;
|
||
const text = el("span", "", "pm-note-result-text");
|
||
text.append(el("span", note.title), el("span",
|
||
isHiddenCard(note.path) ? "Private card" : note.path,
|
||
"pm-note-path rs-picker-hint"));
|
||
row.append(text);
|
||
results.append(row);
|
||
}
|
||
summary.textContent = loading ? "Loading notes…" : scanError ||
|
||
(matches.length > 100 ? `${matches.length} matches. First 100 shown. Refine your search.` :
|
||
matches.length ? `${matches.length} ${matches.length === 1 ? "match" : "matches"}. Choose a note, then select Add note.` :
|
||
query ? "No matching notes. Change the search or enter a path below." :
|
||
"No notes found. Enter a workspace note path below.");
|
||
updateSelection();
|
||
};
|
||
searchInput.oninput = showResults;
|
||
input.oninput = () => { error.textContent = ""; updateSelection(); };
|
||
searchInput.onkeydown = (event) => {
|
||
if (event.key === "ArrowDown") {
|
||
event.preventDefault();
|
||
results.querySelector<HTMLButtonElement>("button")?.focus();
|
||
}
|
||
if (event.key === "Enter") event.preventDefault();
|
||
};
|
||
results.onkeydown = (event) => {
|
||
const rows = [...results.querySelectorAll<HTMLButtonElement>("button")];
|
||
const index = rows.indexOf(document.activeElement as HTMLButtonElement);
|
||
if (index < 0) return;
|
||
const next = event.key === "ArrowDown" ? Math.min(index + 1, rows.length - 1) :
|
||
event.key === "ArrowUp" ? Math.max(index - 1, 0) :
|
||
event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : -1;
|
||
if (next >= 0) { event.preventDefault(); rows[next].focus(); }
|
||
};
|
||
const error = el("p", "", "pm-error");
|
||
error.role = "alert";
|
||
const submit = button("Add note", () => {}, "plus"),
|
||
cancel = button("Cancel", () => { if (!busy) dialog.close(); }),
|
||
actions = el("div", "", "pm-editor-actions");
|
||
submit.type = "submit";
|
||
submit.classList.add("pm-primary");
|
||
submit.disabled = true;
|
||
actions.append(cancel, submit);
|
||
form.append(
|
||
el("h2", "Add an existing note"),
|
||
searchLabel,
|
||
summary,
|
||
results,
|
||
label,
|
||
error,
|
||
actions,
|
||
);
|
||
dialog.append(form);
|
||
root.append(dialog);
|
||
dialog.showModal();
|
||
searchInput.focus();
|
||
dialog.oncancel = (event) => {
|
||
if (busy) event.preventDefault();
|
||
};
|
||
dialog.onclose = () => {
|
||
activeDialog = undefined;
|
||
dialog.remove();
|
||
render();
|
||
root.querySelector<HTMLElement>('[aria-label="More actions"]')?.focus({ preventScroll: true });
|
||
};
|
||
void markdownPaths(store.workspace, () => {
|
||
if (closed || !dialog.isConnected) throw new Error("The note picker is closed.");
|
||
}).then((paths) => {
|
||
const tasks = new Map(store.tasks.map((task) => [task.path, task.title]));
|
||
const boards = new Set([...store.boards, ...store.legacyBoards].map((board) => board.path));
|
||
candidates = [...new Set([...paths, ...tasks.keys()])]
|
||
.filter((path) => !boards.has(path))
|
||
.map((path) => ({ path, title: tasks.get(path) ?? path.split("/").at(-1)!.replace(/\.(md|markdown|mdown)$/i, "") }))
|
||
.sort((a, b) => a.title.localeCompare(b.title) || a.path.localeCompare(b.path));
|
||
}).catch(() => {
|
||
scanError = "Could not list notes. Enter a workspace note path below.";
|
||
}).finally(() => {
|
||
loading = false;
|
||
if (!closed && dialog.isConnected) showResults();
|
||
});
|
||
form.onsubmit = async (event) => {
|
||
event.preventDefault();
|
||
if (busy || !input.value.trim()) return;
|
||
error.textContent = "";
|
||
for (const control of form.querySelectorAll<HTMLInputElement | HTMLButtonElement>("input, button")) control.disabled = true;
|
||
form.setAttribute("aria-busy", "true");
|
||
const ok = await perform(
|
||
async () => { await store.adopt(input.value.trim()); },
|
||
"Note added.",
|
||
);
|
||
if (closed || !dialog.isConnected) return;
|
||
form.removeAttribute("aria-busy");
|
||
for (const control of form.querySelectorAll<HTMLInputElement | HTMLButtonElement>("input, button")) control.disabled = false;
|
||
updateSelection();
|
||
if (ok) dialog.close();
|
||
else error.textContent = message;
|
||
};
|
||
}
|
||
/** The legacy data of the workspace, when the migration has data to copy. */
|
||
let legacyOffer: LegacyContent | undefined;
|
||
let legacyDismissed = false;
|
||
/** The original files after a migration. The user removes them after a check. */
|
||
let migrated: OriginalFile[] | undefined;
|
||
function legacyNotice() {
|
||
const section = el("section", "", "pm-onboarding pm-migration");
|
||
if (migrated) {
|
||
section.setAttribute("aria-label", "Migration complete");
|
||
section.append(el("h2", "Migration complete"), el("p", migrated.length
|
||
? "Project Management copied the data to hidden storage. The original files stay unchanged. Check the boards, then remove these originals:"
|
||
: "Project Management copied the data to hidden storage."));
|
||
if (migrated.length) {
|
||
const list = el("ul");
|
||
for (const file of migrated) list.append(el("li", file.path));
|
||
section.append(list);
|
||
}
|
||
section.append(button("Done", () => { migrated = undefined; legacyOffer = undefined; render(); }, "check"));
|
||
return section;
|
||
}
|
||
const content = legacyOffer!;
|
||
const parts = [
|
||
...content.boards.length ? [content.boards.length === 1 ? "1 board" : `${content.boards.length} boards`] : [],
|
||
...content.cards.length ? [content.cards.length === 1 ? "1 task note" : `${content.cards.length} task notes`] : [],
|
||
...content.labels ? ["the label file runestone-pm-labels.json"] : [],
|
||
];
|
||
section.setAttribute("aria-label", "Migrate Project Management data");
|
||
section.append(el("h2", "Migrate Project Management data"),
|
||
el("p", `This workspace has Project Management data in visible files${parts.length ? `: ${parts.join(", ")}` : ""}. Project Management now reads only hidden storage in .runestone/pm. The migration copies the data there with exact backups. The original files stay unchanged.`));
|
||
if (content.invalid.length)
|
||
section.append(el("p", `${content.invalid.length === 1 ? "1 note has" : `${content.invalid.length} notes have`} invalid Project Management properties: ${content.invalid.join(", ")}. Repair them before the migration.`));
|
||
const actions = el("div", "", "pm-popup-actions");
|
||
const migrate = button("Migrate", () => {
|
||
void perform(async () => {
|
||
migrated = await options.legacy!.migrate();
|
||
legacyOffer = undefined;
|
||
await store.reload();
|
||
}, "Migration complete.");
|
||
});
|
||
migrate.classList.add("pm-primary");
|
||
actions.append(migrate, button("Not now", () => { legacyDismissed = true; render(); }));
|
||
section.append(actions);
|
||
return section;
|
||
}
|
||
function render() {
|
||
Object.assign(state, { view, period, anchor, search, showArchived, searchOpen });
|
||
options.stateChanged?.();
|
||
if (closed || activeDialog || closePopup) return;
|
||
stopAutoScroll();
|
||
// Host tabs retain their mounts while hidden. Replacing hidden scroll nodes loses their position.
|
||
if (!root.getClientRects().length) {
|
||
renderPending = true;
|
||
return;
|
||
}
|
||
renderPending = false;
|
||
const focusedDraft = document.activeElement instanceof HTMLTextAreaElement &&
|
||
document.activeElement.closest(".pm-card-composer")?.parentElement?.closest(".rs-pm") === root
|
||
? { start: document.activeElement.selectionStart, end: document.activeElement.selectionEnd }
|
||
: undefined;
|
||
const previousBoard =
|
||
view === "kanban" ? root.querySelector<HTMLElement>(".pm-board") : null;
|
||
const boardScroll = previousBoard
|
||
? { left: previousBoard.scrollLeft, top: previousBoard.scrollTop }
|
||
: undefined;
|
||
const scrollParents: { node: HTMLElement; left: number; top: number }[] =
|
||
[];
|
||
if (boardScroll)
|
||
for (let node: HTMLElement | null = root; node; node = node.parentElement)
|
||
scrollParents.push({
|
||
node,
|
||
left: node.scrollLeft,
|
||
top: node.scrollTop,
|
||
});
|
||
const visibleIds = new Set(filtered().map(task => task.id));
|
||
for (const id of selectedCards) if (!visibleIds.has(id)) selectedCards.delete(id);
|
||
root.replaceChildren(background);
|
||
const header = el("header", "", "pm-toolbar"),
|
||
tabs = el("nav", "", "pm-tabs");
|
||
tabs.setAttribute("aria-label", "Project Management views");
|
||
for (const tab of ["kanban", "gantt", "calendar"] as const) {
|
||
const control = iconButton(
|
||
tab[0].toUpperCase() + tab.slice(1), tab,
|
||
() => {
|
||
if (view !== tab) {
|
||
cardDraft = undefined;
|
||
cardDrafts.clear();
|
||
}
|
||
selectionMode = false; selectedCards.clear();
|
||
view = tab;
|
||
remember();
|
||
render();
|
||
},
|
||
);
|
||
control.setAttribute("aria-pressed", String(view === tab));
|
||
tabs.append(control);
|
||
}
|
||
header.append(tabs);
|
||
const canRenameBoard = store.board.editable &&
|
||
Boolean(options.renameBoard || isManagedBoard(store.board.reference!.path));
|
||
const titleArea = el("div", "", "pm-title-area");
|
||
const title = el(
|
||
"span",
|
||
store.board.name + (showArchived ? " · Archived" : ""),
|
||
"pm-view-title",
|
||
);
|
||
if (canRenameBoard) {
|
||
const rename = button("", () => renameBoardForm(rename), "rename");
|
||
rename.classList.add("pm-board-rename");
|
||
rename.setAttribute("aria-label", `Rename board: ${store.board.name}`);
|
||
rename.setAttribute("aria-haspopup", "dialog");
|
||
tooltip(rename, "Rename board");
|
||
if (!options.openBoard && !options.openAll) rename.prepend(title);
|
||
titleArea.append(rename);
|
||
} else if (!options.openBoard && !options.openAll) titleArea.append(title);
|
||
header.append(titleArea);
|
||
if (options.openBoard || options.openAll) {
|
||
const scope = button("", () => {
|
||
boardMenu?.close();
|
||
const bounds = scope.getBoundingClientRect();
|
||
const open = (path: string) => void perform(async () => {
|
||
if (path) await options.openBoard?.(path, true);
|
||
else await options.openAll?.(true);
|
||
}, "View opened.");
|
||
boardMenu = options.ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: "Board scope", items: [
|
||
{ label: "All tasks", checked: !store.board.reference, radio: true, run: () => open("") },
|
||
...store.boards.map(board => ({ label: board.name + (board.archived ? " (archived)" : "") + (isManagedBoard(board.path) ? "" : " · " + board.path), checked: board.path === store.board.reference?.path, radio: true, run: () => open(board.path) })),
|
||
] });
|
||
}, "down");
|
||
scope.classList.add("pm-scope");
|
||
scope.append(el("span", store.board.name, "pm-scope-label"));
|
||
scope.setAttribute("aria-label", `Board scope: ${store.board.name}`);
|
||
scope.setAttribute("aria-haspopup", "menu");
|
||
scope.onkeydown = event => { if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); scope.click(); } };
|
||
titleArea.prepend(scope);
|
||
}
|
||
const actions = el("div", "", "pm-toolbar-actions");
|
||
if (view === "kanban") {
|
||
const select = iconButton(selectionMode ? "Finish selection" : "Select cards", "select", () => { selectionMode = !selectionMode; selectedCards.clear(); render(); root.querySelector<HTMLButtonElement>(".pm-select-mode")?.focus(); });
|
||
select.classList.add("pm-select-mode"); select.setAttribute("aria-pressed", String(selectionMode)); actions.append(select);
|
||
}
|
||
const labels = iconButton("Manage labels", "tag", () => manageLabels());
|
||
labels.disabled = store.labels.source === undefined;
|
||
actions.append(labels);
|
||
if (view === "kanban" && store.board.editable) {
|
||
const add = iconButton("Add a list", "circlePlus", () => listForm(add));
|
||
actions.append(add);
|
||
} else if (view !== "kanban")
|
||
actions.append(iconButton("New card", "note", () => openEditor()));
|
||
const searchButton = iconButton("Search tasks", "search", () => {
|
||
searchOpen = !searchOpen;
|
||
render();
|
||
if (searchOpen)
|
||
root.querySelector<HTMLInputElement>("input[type=search]")?.focus();
|
||
});
|
||
searchButton.setAttribute("aria-pressed", String(searchOpen));
|
||
actions.append(searchButton);
|
||
const more = iconButton("More actions", "more", () =>
|
||
popup(more, "More actions", (panel, close) => {
|
||
panel.classList.add("pm-menu");
|
||
if (options.openBoard && store.workspace.create)
|
||
panel.append(
|
||
button("New board", () => {
|
||
close();
|
||
renameBoardForm(more, true);
|
||
}, "circlePlus"),
|
||
);
|
||
if (
|
||
store.board.reference &&
|
||
isManagedBoard(store.board.reference.path) &&
|
||
store.board.available
|
||
)
|
||
panel.append(
|
||
button(
|
||
store.board.archived ? "Restore board" : "Archive board",
|
||
() => {
|
||
close();
|
||
void perform(
|
||
() =>
|
||
store.changeBoard(() =>
|
||
store.board.manage({ archived: !store.board.archived }),
|
||
),
|
||
"Board archive state saved.",
|
||
);
|
||
},
|
||
"archive",
|
||
),
|
||
);
|
||
if (store.board.reference && store.board.available)
|
||
panel.append(
|
||
button("Delete board", () => {
|
||
close();
|
||
deleteBoardForm(more);
|
||
}, "trash"),
|
||
);
|
||
if (canRenameBoard)
|
||
panel.append(
|
||
button("Rename board", () => {
|
||
close();
|
||
renameBoardForm(more);
|
||
}, "rename"),
|
||
);
|
||
panel.append(
|
||
button("New card", () => {
|
||
close();
|
||
openEditor();
|
||
}, "note"),
|
||
button("Add existing note", () => {
|
||
close();
|
||
addExisting();
|
||
}, "link"),
|
||
button(showArchived ? "Show active" : "Show archived", () => {
|
||
close();
|
||
showArchived = !showArchived;
|
||
render();
|
||
}, "archive"),
|
||
button("Refresh", () => {
|
||
close();
|
||
void perform(() => store.reload(), "Tasks reloaded.");
|
||
}, "refresh"),
|
||
);
|
||
panel.append(button("Customize background", () => { close(); customizeBackground(more); }, "image"));
|
||
panel.append(button("Project Management settings", () => {
|
||
close(); popup(more, "Project Management settings", panel => {
|
||
// The same component as Settings → Project Management.
|
||
panel.classList.add("pm-settings-popup");
|
||
const component = mountComponent(ProjectManagementSettings, { target: panel, props: { compact: true } });
|
||
return () => { void unmountComponent(component); };
|
||
});
|
||
}, "list"));
|
||
}),
|
||
);
|
||
actions.append(more);
|
||
header.append(actions);
|
||
root.append(header);
|
||
if (!store.board.reference && !store.boards.some(board => !board.archived) && options.openBoard && store.workspace.create) {
|
||
const welcome = el("section", "", "pm-onboarding");
|
||
welcome.setAttribute("aria-label", "Create your first board");
|
||
const create = button("Create your first board", () => renameBoardForm(create, true), "circlePlus");
|
||
welcome.append(el("h2", "Create your first board"), el("p", "Use a board to organize cards and move them between lists."), create);
|
||
root.append(welcome);
|
||
}
|
||
if (migrated || (legacyOffer && !legacyDismissed)) root.append(legacyNotice());
|
||
if (selectionMode) root.append(selectionToolbar());
|
||
if (searchOpen || search) {
|
||
const field = el("div", "", "pm-search-row"),
|
||
find = el("input");
|
||
find.type = "search";
|
||
find.placeholder = "Search tasks, labels, and tags";
|
||
find.setAttribute("aria-label", "Search tasks");
|
||
find.value = search;
|
||
find.oninput = () => {
|
||
search = find.value;
|
||
render();
|
||
root.querySelector<HTMLInputElement>("input[type=search]")?.focus();
|
||
};
|
||
field.append(find);
|
||
root.append(field);
|
||
}
|
||
const notice = el(
|
||
"div",
|
||
message,
|
||
failed ? "pm-error pm-notice" : "pm-sr-only",
|
||
);
|
||
notice.setAttribute("role", failed ? "alert" : "status");
|
||
root.append(notice);
|
||
if (store.issues.length) {
|
||
const details = el("details", "", "pm-issues");
|
||
details.append(
|
||
el("summary", store.issues.length + " notes need attention"),
|
||
);
|
||
for (const issue of store.issues) details.append(el("p", issue));
|
||
root.append(details);
|
||
}
|
||
void applyBackground();
|
||
const tasks = filtered();
|
||
if (search && !tasks.length)
|
||
root.append(el("p", "No tasks match this search.", "pm-muted pm-empty"));
|
||
root.append(
|
||
view === "kanban"
|
||
? kanban(tasks)
|
||
: view === "gantt"
|
||
? gantt(tasks)
|
||
: calendar(tasks),
|
||
);
|
||
if (restoring && message === "Workspace loaded.") {
|
||
restoring = false;
|
||
root.querySelector<HTMLElement>(".pm-board")?.scrollTo({ ...state.boardScroll, behavior: "instant" });
|
||
scrollContainer().scrollTop = state.scrollTop ?? 0;
|
||
} else if (boardScroll) {
|
||
root.querySelector<HTMLElement>(".pm-board")?.scrollTo({
|
||
...boardScroll,
|
||
behavior: "instant",
|
||
});
|
||
for (const { node, left, top } of scrollParents)
|
||
node.scrollTo({ left, top, behavior: "instant" });
|
||
}
|
||
if (focusedDraft) {
|
||
const title = root.querySelector<HTMLTextAreaElement>(".pm-card-composer textarea");
|
||
title?.focus({ preventScroll: true });
|
||
title?.setSelectionRange(focusedDraft.start, focusedDraft.end);
|
||
}
|
||
}
|
||
root.addEventListener("mousedown", startAutoScroll);
|
||
root.addEventListener("auxclick", preventAutoScrollClick);
|
||
document.addEventListener("mousedown", outsideAutoScroll);
|
||
document.addEventListener("mousemove", moveAutoScroll);
|
||
document.addEventListener("mouseup", releaseAutoScroll);
|
||
window.addEventListener("keydown", dismissAutoScroll);
|
||
window.addEventListener("blur", stopAutoScroll);
|
||
root.addEventListener("wheel", scrollBoard, { passive: false });
|
||
root.addEventListener("scroll", remember, true);
|
||
document.addEventListener("pointerdown", outsideCardComposer, true);
|
||
document.addEventListener("focusin", outsideCardComposer);
|
||
window.addEventListener("blur", hideCardComposer);
|
||
let composerFocusTimer: ReturnType<typeof setTimeout> | undefined;
|
||
const composerFocusOut = (event: FocusEvent) => {
|
||
if (event.relatedTarget) return;
|
||
clearTimeout(composerFocusTimer);
|
||
// Wait for the full focus transition, including controls inside the form.
|
||
composerFocusTimer = setTimeout(() => {
|
||
const form = root.querySelector(".pm-card-composer");
|
||
if (!closed && form && !form.contains(document.activeElement)) hideCardComposer();
|
||
}, 0);
|
||
};
|
||
root.addEventListener("focusout", composerFocusOut);
|
||
const visibilityObserver = new ResizeObserver(() => {
|
||
positionBackground();
|
||
if (!root.getClientRects().length) hideCardComposer();
|
||
if (renderPending && root.getClientRects().length) render();
|
||
});
|
||
visibilityObserver.observe(root);
|
||
visibilityObserver.observe(container);
|
||
document.addEventListener("scroll", positionBackground, true);
|
||
window.addEventListener("resize", positionBackground);
|
||
render();
|
||
void perform(() => store.reload(), "Workspace loaded.");
|
||
// Offer the migration when the workspace still has data in the legacy format. Nothing migrates without a choice.
|
||
void options.legacy?.find().then(content => {
|
||
if (closed || !options.legacy!.has(content)) return;
|
||
legacyOffer = content;
|
||
if (!busy) render();
|
||
}, () => undefined);
|
||
let refreshTimer: ReturnType<typeof setTimeout> | undefined;
|
||
let refreshing = false;
|
||
const sameDocuments = (
|
||
before: { path: string; source: string }[],
|
||
after: { path: string; source: string }[],
|
||
) =>
|
||
before.length === after.length &&
|
||
before.every(
|
||
(document, index) =>
|
||
document.path === after[index].path &&
|
||
document.source === after[index].source,
|
||
);
|
||
/** The changed paths since the last refresh. Null when a change had no paths, so everything reads again. */
|
||
let pendingPaths: Set<string> | null = new Set();
|
||
const refresh = (paths?: readonly string[]) => {
|
||
if (!paths) pendingPaths = null;
|
||
else if (pendingPaths) for (const path of paths) pendingPaths.add(path);
|
||
clearTimeout(refreshTimer);
|
||
refreshTimer = setTimeout(async () => {
|
||
if (closed) return;
|
||
if (busy || refreshing || activeDialog || closePopup || drag) {
|
||
refresh([]);
|
||
return;
|
||
}
|
||
const changedPaths = pendingPaths;
|
||
pendingPaths = new Set();
|
||
refreshing = true;
|
||
const before = {
|
||
tasks: store.tasks,
|
||
boards: store.boards,
|
||
issues: store.issues,
|
||
labels: store.labels.source,
|
||
labelError: store.labels.error,
|
||
boardAvailable: store.board.available,
|
||
};
|
||
let changed = false;
|
||
try {
|
||
await store.reloadPaths(changedPaths ? [...changedPaths] : undefined);
|
||
changed =
|
||
!sameDocuments(before.tasks, store.tasks) ||
|
||
!sameDocuments(before.boards, store.boards) ||
|
||
before.labels !== store.labels.source ||
|
||
before.labelError !== store.labels.error ||
|
||
before.boardAvailable !== store.board.available ||
|
||
before.issues.length !== store.issues.length ||
|
||
before.issues.some((issue, index) => issue !== store.issues[index]);
|
||
} catch (error) {
|
||
changed = true;
|
||
if (!closed)
|
||
notify(error instanceof Error ? error.message : String(error), true);
|
||
} finally {
|
||
refreshing = false;
|
||
if (changed && !busy && !drag) render();
|
||
}
|
||
}, 150);
|
||
};
|
||
// The host watcher reports the changed files of `.runestone/pm/`, also from other windows and programs.
|
||
const unsubscribe = options.watch ? options.watch(refresh) : store.workspace.subscribe?.(() => refresh());
|
||
return () => {
|
||
if (closed) return;
|
||
remember();
|
||
closed = true;
|
||
disposeTooltips();
|
||
backgroundWatcher.dispose();
|
||
backgroundFade?.cancel();
|
||
clearTimeout(refreshTimer);
|
||
clearTimeout(composerFocusTimer);
|
||
unsubscribe?.();
|
||
window.removeEventListener("blur", hideCardComposer);
|
||
document.removeEventListener("pointerdown", outsideCardComposer, true);
|
||
document.removeEventListener("focusin", outsideCardComposer);
|
||
root.removeEventListener("focusout", composerFocusOut);
|
||
visibilityObserver.disconnect();
|
||
document.removeEventListener("scroll", positionBackground, true);
|
||
window.removeEventListener("resize", positionBackground);
|
||
root.removeEventListener("scroll", remember, true);
|
||
stopAutoScroll();
|
||
root.removeEventListener("mousedown", startAutoScroll);
|
||
root.removeEventListener("auxclick", preventAutoScrollClick);
|
||
document.removeEventListener("mousedown", outsideAutoScroll);
|
||
document.removeEventListener("mousemove", moveAutoScroll);
|
||
document.removeEventListener("mouseup", releaseAutoScroll);
|
||
window.removeEventListener("keydown", dismissAutoScroll);
|
||
window.removeEventListener("blur", stopAutoScroll);
|
||
root.removeEventListener("wheel", scrollBoard);
|
||
clearDrag();
|
||
document.removeEventListener("dragover", movePreview);
|
||
document.removeEventListener("dragend", clearDrag);
|
||
document.removeEventListener("drop", clearDrag);
|
||
closePopup?.();
|
||
boardMenu?.close();
|
||
sharedChoices.dispose();
|
||
disposeEditor?.();
|
||
store.dispose();
|
||
activeDialog?.remove();
|
||
root.remove();
|
||
style.remove();
|
||
};
|
||
}
|