import { useEffect, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { FeatherArrowUpDown, FeatherCalendarRange, FeatherChevronDown, FeatherChevronLeft, FeatherChevronRight, FeatherColumns, FeatherEdit2, FeatherList, FeatherPlus, FeatherUser, } from "@subframe/core"; import * as SubframeCore from "@subframe/core"; import { addDaysIso, buildPlantafelDetailDraft, buildPlantafelWeek, scheduleStatusTone, sortPlantafelEntries, parsePlantafelSort, PLANTAFEL_SORTS, type PlantafelSort, type PlantafelDetailDraft, type PlantafelEntryVM, type PlantafelScreenVM, type PlantafelWeekEntry, type PlantafelWeekGrid, } from "@hivegrid/view-models"; import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell"; import { FacetFilterBar, type ClientFacet } from "../shared/FacetFilterBar"; import { Alert } from "~/ui/components/Alert"; import { BadgeFeedback } from "~/ui/components/BadgeFeedback"; import { Button } from "~/ui/components/Button"; import { Card } from "~/ui/components/Card"; import { Checkbox } from "~/ui/components/Checkbox"; import { Dialog } from "~/ui/components/Dialog"; import { DropdownMenu } from "~/ui/components/DropdownMenu"; import { DropdownMenuMultiSelect } from "~/ui/components/DropdownMenuMultiSelect"; import { FilterBar } from "~/ui/components/FilterBar"; import { IconButton } from "~/ui/components/IconButton"; import { ToggleGroup } from "~/ui/components/ToggleGroup"; import { EmptyState } from "~/ui/components/EmptyState"; import { Select } from "~/ui/components/Select"; import { Table } from "~/ui/components/Table"; import { TextArea } from "~/ui/components/TextArea"; import { TextInput } from "~/ui/components/TextInput"; import { APP_TIME_ZONE } from "~/locale/format"; export type PlantafelSubmit = (intent: string, fields?: Record) => void; export type PlantafelOption = { id: string; label: string }; export type PlantafelActionResult = { intent: string | null; ok?: boolean; error?: string }; /** * What the loader should fetch. `assignedUserId: null` = everybody the user may * see; `includePast` widens the table window backwards over finished jobs; * `sort` orders the table rows. */ export type PlantafelFilter = { assignedUserId: string | null; includePast: boolean; sort: PlantafelSort }; export type PlantafelViewMode = "table" | "calendar"; export type PlantafelPageProps = { vm: PlantafelScreenVM; projectLabels: readonly PlantafelOption[]; editableProjectIds: readonly string[]; projectOptions: readonly PlantafelOption[]; projectOptionsHasMore: boolean; projectPickerLoading: boolean; assigneeOptions: readonly PlantafelOption[]; canWrite: boolean; canBulkReassign: boolean; filter: PlantafelFilter; /** Table or Monday-first working week. GET-driven, so the loader resolves the matching window. */ view: PlantafelViewMode; /** ISO calendar date (`YYYY-MM-DD`) inside the rendered week, resolved by the loader. */ anchorIso: string; todayIso: string; submitting: boolean; actionResult?: PlantafelActionResult | null; actions: { onSubmit: PlantafelSubmit; onProjectSearch: (query: string) => void; onFilterChange: (next: PlantafelFilter) => void; onViewChange: (view: PlantafelViewMode) => void; onAnchorChange: (anchorIso: string) => void; }; }; const DATETIME_INPUT_TYPE = "datetime-local" as const; const SCHEDULE_STATUSES = ["planned", "confirmed", "in_progress", "done", "cancelled"] as const; const headingText = "text-body-large-0 font-body-large-0 text-text-neutral-primary"; const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary"; /** The table sits in the page chrome now instead of a card - same framing as the forms list. */ const tableFrame = "flex w-full min-w-0 flex-col items-start overflow-hidden overflow-x-auto rounded-lg border border-solid border-border-default shadow-sm"; function formatDateTime(value: string | null, language: string): string { if (!value) return "—"; return new Intl.DateTimeFormat(language, { timeZone: APP_TIME_ZONE, dateStyle: "medium", timeStyle: "short" }).format(new Date(value)); } /** * Render a plain calendar date. Anchoring at noon UTC keeps the displayed date * stable, so a Monday cell never labels itself as the Sunday before it. */ function formatCalendarDate(dateIso: string, language: string, options: Intl.DateTimeFormatOptions): string { return new Intl.DateTimeFormat(language, { timeZone: APP_TIME_ZONE, ...options }).format(new Date(`${dateIso}T12:00:00Z`)); } function statusTone(statusTone: string): "subtle-neutral" | "subtle-information" | "subtle-positive" | "subtle-warning" | "subtle-negative" { if (statusTone === "positive") return "subtle-positive"; if (statusTone === "information") return "subtle-information"; if (statusTone === "warning") return "subtle-warning"; if (statusTone === "negative") return "subtle-negative"; return "subtle-neutral"; } function newCreateMutationId(): string { return globalThis.crypto?.randomUUID?.() ?? `plantafel-${Date.now()}-${Math.random().toString(36).slice(2)}`; } /** * Rows per table page. The plantafel window is loaded whole (the calendar needs * every entry of its week), so paging is a reading aid over the loaded set, not * a second query. */ const PLANTAFEL_PAGE_SIZE = 25; /** One hour of the time axis, in pixels. Sets how deep the whole week gets. */ const HOUR_ROW_PX = 84; /** Narrower than this and a block cannot hold readable text. */ const DAY_COLUMN_MIN_PX = 240; const TIME_GUTTER_PX = 64; /** Below this height a block only has room for its time and title. */ const COMPACT_BLOCK_MINUTES = 60; /** From here on a block can also carry the project and the status badge. */ const ROOMY_BLOCK_MINUTES = 120; function minuteLabel(minute: number): string { return `${String(Math.floor(minute / 60)).padStart(2, "0")}:${String(minute % 60).padStart(2, "0")}`; } /** * One appointment as a block on the day's time axis. How much it shows depends * on how much room it has: a two-hour job carries project and status, a short * one only its time and title, so nothing gets clipped mid-word. */ function WeekEntry({ placed, projectLabel, assigneeLabel, startHour, endHour, onOpen, }: { placed: PlantafelWeekEntry; projectLabel?: string; assigneeLabel: string; startHour: number; endHour: number; onOpen: () => void; }) { const { t } = useTranslation(); const { entry } = placed; const minutes = placed.endMinute - placed.startMinute; // Clamp into the rendered window: the night stretch of a multi-day job can // fall outside it and still has to appear as a strip at the edge instead of // vanishing. const windowStart = startHour * 60; const windowEnd = endHour * 60; const visibleStart = Math.min(Math.max(placed.startMinute, windowStart), windowEnd - 15); const visibleEnd = Math.max(Math.min(placed.endMinute, windowEnd), visibleStart + 15); const top = ((visibleStart - windowStart) / 60) * HOUR_ROW_PX; // Keep a floor so a 15-minute call-out stays clickable and legible. const height = Math.max(((visibleEnd - visibleStart) / 60) * HOUR_ROW_PX, 34); const width = 100 / placed.laneCount; const showAssignee = minutes >= COMPACT_BLOCK_MINUTES; const showDetails = minutes >= ROOMY_BLOCK_MINUTES; return (
{ if (event.key !== "Enter" && event.key !== " ") return; event.preventDefault(); onOpen(); }} title={`${minuteLabel(placed.startMinute)} – ${minuteLabel(placed.endMinute)} · ${entry.title}${projectLabel ? ` · ${projectLabel}` : ""}`} data-ui-id={`ui.projects.plantafel.week.entry.${entry.id}`} data-entry-id={entry.id} data-lane={placed.lane} data-lane-count={placed.laneCount} >
{placed.continuesBefore ? "↑ " : ""} {minuteLabel(placed.startMinute)} – {minuteLabel(placed.endMinute)} {placed.continuesAfter ? " ↓" : ""} {entry.title} {showAssignee ? ( {assigneeLabel} ) : null} {showDetails && projectLabel ? ( {projectLabel} ) : null} {showDetails ? (
{t(entry.statusLabelKey)} {entry.conflictCount > 0 ? ( 0 ? "subtle-negative" : "subtle-warning"} size="small"> {t("projects.plantafel.conflicts", { count: entry.conflictCount })} ) : null}
) : null}
); } /** * Monday-Sunday week as a time grid: hours down the left, one column per day, * appointments placed at their actual time and side by side where they overlap. * The columns keep a readable minimum width, so the grid scrolls sideways on a * narrow screen rather than squeezing seven days into it. */ function PlantafelWeek({ grid, projectLabels, assigneeLabels, onOpenEntry, }: { grid: PlantafelWeekGrid; projectLabels: ReadonlyMap; assigneeLabels: ReadonlyMap; onOpenEntry: (entryId: string) => void; }) { const { t, i18n } = useTranslation(); const hours = Array.from({ length: grid.endHour - grid.startHour }, (_, index) => grid.startHour + index); const bodyHeight = hours.length * HOUR_ROW_PX; const columns = `${TIME_GUTTER_PX}px repeat(7, minmax(${DAY_COLUMN_MIN_PX}px, 1fr))`; return (
{/* Day header row. The gutter cell above the hours stays empty. */}
{grid.days.map((day) => (
{formatCalendarDate(day.dateIso, i18n.language, { weekday: "short" })} {day.dayOfMonth}
))}
{/* Time axis. Labels sit on their hour line, hence the -0.5 line shift. */}
{hours.map((hour, index) => ( {minuteLabel(hour * 60)} ))}
{grid.days.map((day) => (
{/* Hour lines, drawn behind the blocks. */} {hours.map((hour, index) => index === 0 ? null : (
) )} {day.entries.map((placed) => ( onOpenEntry(placed.entry.id)} /> ))}
))}
); } export function PlantafelPage(props: PlantafelPageProps) { const { t, i18n } = useTranslation(); const [search, setSearch] = useState(""); const [createOpen, setCreateOpen] = useState(false); const [draft, setDraft] = useState({ projektId: props.projectOptions[0]?.id ?? "", assignedUserId: props.assigneeOptions[0]?.id ?? "", title: "", startAt: "", endAt: "", status: "planned", }); const [projectQuery, setProjectQuery] = useState(""); // Detail popup: which entry, and whether it has been unlocked for editing. // It always opens read-only - looking something up must not risk changing it. const [detailEntryId, setDetailEntryId] = useState(null); const [detailEditing, setDetailEditing] = useState(false); const [detailDraft, setDetailDraft] = useState(null); const [detailOverrideReason, setDetailOverrideReason] = useState(""); const [detailSubmitted, setDetailSubmitted] = useState(false); const [detailResultAtSubmission, setDetailResultAtSubmission] = useState(null); const [conflictOverrideReason, setConflictOverrideReason] = useState(""); const [createMutationId, setCreateMutationId] = useState(""); const [createSubmitted, setCreateSubmitted] = useState(false); const [actionResultAtSubmission, setActionResultAtSubmission] = useState(null); const [selectedEntryIds, setSelectedEntryIds] = useState([]); // Which page of the table is on screen. Kept local because search and sorting // are evaluated on the loaded window too - a page number in the URL would // outlive the result set it counted into. const [page, setPage] = useState(1); const [bulkAssignee, setBulkAssignee] = useState(props.assigneeOptions[0]?.id ?? ""); const [bulkOverrideReason, setBulkOverrideReason] = useState(""); const [offlinePayload, setOfflinePayload] = useState({ clientMutationId: "", operation: "schedule_upsert", payload: "{}" }); const [localSubmitting, setLocalSubmitting] = useState(false); const [localProjectSearchLoading, setLocalProjectSearchLoading] = useState(false); const submitLockedRef = useRef(false); const projectSearchLockedRef = useRef(false); const sawSubmittingRef = useRef(false); const sawProjectPickerLoadingRef = useRef(false); const previousActionResultRef = useRef(props.actionResult); const previousProjectOptionsRef = useRef(props.projectOptions); // Anything that reshuffles the result set sends the reader back to page one - // otherwise a narrowed search lands on a page that no longer exists. useEffect(() => { setPage(1); }, [search, props.filter.assignedUserId, props.filter.includePast, props.filter.sort, props.view]); useEffect(() => { if (props.projectOptions.some(({ id }) => id === draft.projektId)) return; setDraft((current) => ({ ...current, projektId: props.projectOptions[0]?.id ?? "" })); }, [draft.projektId, props.projectOptions]); useEffect(() => { if (props.submitting) { sawSubmittingRef.current = true; return; } if (!sawSubmittingRef.current) return; sawSubmittingRef.current = false; submitLockedRef.current = false; setLocalSubmitting(false); }, [props.submitting]); useEffect(() => { if (previousActionResultRef.current === props.actionResult) return; previousActionResultRef.current = props.actionResult; submitLockedRef.current = false; setLocalSubmitting(false); }, [props.actionResult]); useEffect(() => { const optionsChanged = previousProjectOptionsRef.current !== props.projectOptions; previousProjectOptionsRef.current = props.projectOptions; if (props.projectPickerLoading) { sawProjectPickerLoadingRef.current = true; return; } if (!sawProjectPickerLoadingRef.current && !optionsChanged) return; sawProjectPickerLoadingRef.current = false; projectSearchLockedRef.current = false; setLocalProjectSearchLoading(false); }, [props.projectOptions, props.projectPickerLoading]); const createActionResult = createSubmitted && props.actionResult !== actionResultAtSubmission && props.actionResult?.intent === "upsertSchedule" ? props.actionResult : null; useEffect(() => { if (!createActionResult?.ok) return; setCreateOpen(false); setCreateSubmitted(false); setActionResultAtSubmission(createActionResult); setConflictOverrideReason(""); setCreateMutationId(""); }, [createActionResult]); // Both dialogs save through `upsertSchedule`; the submitted flags keep their // results apart, so a create result never closes the detail popup. const detailActionResult = detailSubmitted && props.actionResult !== detailResultAtSubmission && props.actionResult?.intent === "upsertSchedule" ? props.actionResult : null; useEffect(() => { if (!detailActionResult?.ok) return; setDetailResultAtSubmission(detailActionResult); setDetailSubmitted(false); setDetailEditing(false); setDetailDraft(null); setDetailOverrideReason(""); setDetailEntryId(null); }, [detailActionResult]); const bulkActionResult = props.actionResult?.intent === "bulkReassign" ? props.actionResult : null; const bulkNeedsOverride = bulkActionResult?.error === "projects.error.scheduleConflictOverrideRequired"; useEffect(() => { if (!bulkActionResult?.ok) return; setSelectedEntryIds([]); setBulkOverrideReason(""); }, [bulkActionResult]); if (props.vm.status !== "ready") return null; const data = props.vm.data; const projectLabels = new Map(props.projectLabels.map((option) => [option.id, option.label])); const editableProjectIds = new Set(props.editableProjectIds); const assigneeLabels = new Map(props.assigneeOptions.map((option) => [option.id, option.label])); // The search matches what the row shows - appointment, monteur, project - // so a hit is always explainable by something visible on screen. It belongs // to the table: the week grid navigates by date, not by term. const searchTerm = props.view === "table" ? search.trim().toLocaleLowerCase() : ""; const matchedEntries = searchTerm ? data.entries.filter((entry) => [entry.title, assigneeLabels.get(entry.assignedUserId) ?? "", projectLabels.get(entry.projectId) ?? ""] .join(" ") .toLocaleLowerCase() .includes(searchTerm) ) : data.entries; // The calendar places entries by time, so only the table takes the order. const visibleEntries = props.view === "table" ? sortPlantafelEntries(matchedEntries, props.filter.sort, assigneeLabels) : matchedEntries; const visibleConflictCount = visibleEntries.reduce((sum, entry) => sum + entry.conflictCount, 0); // The page is clamped rather than corrected in state: a rerender with fewer // rows must not need a second render pass before it shows something. const pageCount = Math.max(1, Math.ceil(visibleEntries.length / PLANTAFEL_PAGE_SIZE)); const currentPage = Math.min(Math.max(page, 1), pageCount); const pagedEntries = props.view === "table" ? visibleEntries.slice((currentPage - 1) * PLANTAFEL_PAGE_SIZE, currentPage * PLANTAFEL_PAGE_SIZE) : visibleEntries; const pageSelectableIds = pagedEntries.filter((entry) => editableProjectIds.has(entry.projectId)).map((entry) => entry.id); const pageFullySelected = pageSelectableIds.length > 0 && pageSelectableIds.every((id) => selectedEntryIds.includes(id)); const weekGrid = props.view === "calendar" ? buildPlantafelWeek({ entries: visibleEntries, anchorIso: props.anchorIso, todayIso: props.todayIso }) : null; const weekDays = weekGrid?.days ?? []; const weekRangeLabel = weekDays.length ? `${formatCalendarDate(weekDays[0]!.dateIso, i18n.language, { day: "2-digit", month: "2-digit" })} – ${formatCalendarDate(weekDays[6]!.dateIso, i18n.language, { day: "2-digit", month: "2-digit", year: "numeric" })}` : ""; // The picked monteur reads back off the facet button, so a shared link never // looks unfiltered; the chip below the bar is the way back out. const assigneeFacet: ClientFacet = { key: "assignee", label: props.filter.assignedUserId ? (assigneeLabels.get(props.filter.assignedUserId) ?? t("projects.plantafel.unknownAssignee")) : t("projects.plantafel.filterAssignee"), icon: , tone: "sky-subtle", options: props.assigneeOptions.map((option) => ({ value: option.id, label: option.label })), selected: new Set(props.filter.assignedUserId ? [props.filter.assignedUserId] : []), }; /** Back to the default window and order, and with an empty search box. */ const resetFilter = () => { setSearch(""); props.actions.onFilterChange({ assignedUserId: null, includePast: false, sort: "start_asc" }); }; const formBusy = props.submitting || localSubmitting; const projectSearchBusy = props.projectPickerLoading || localProjectSearchLoading; const needsConflictOverride = createActionResult?.error === "projects.error.scheduleConflictOverrideRequired"; const canSubmitDraft = Boolean( createMutationId && draft.projektId && draft.assignedUserId && draft.title.trim() && draft.startAt && draft.endAt && (!needsConflictOverride || conflictOverrideReason.trim()) ); const submitOnce: PlantafelSubmit = (intent, fields) => { if (submitLockedRef.current || props.submitting) return; submitLockedRef.current = true; setLocalSubmitting(true); try { props.actions.onSubmit(intent, fields); } catch (error) { submitLockedRef.current = false; setLocalSubmitting(false); throw error; } }; const searchProjectsOnce = (query: string) => { if (projectSearchLockedRef.current || projectSearchBusy || formBusy) return; projectSearchLockedRef.current = true; setLocalProjectSearchLoading(true); try { props.actions.onProjectSearch(query); } catch (error) { projectSearchLockedRef.current = false; setLocalProjectSearchLoading(false); throw error; } }; // The popup follows the loaded rows: once an entry leaves the window (a // reassignment, a changed filter), the popup closes instead of showing stale // data. const detailEntry = detailEntryId ? (data.entries.find((entry) => entry.id === detailEntryId) ?? null) : null; const detailCanEdit = Boolean(detailEntry && props.canWrite && editableProjectIds.has(detailEntry.projectId)); const detailNeedsOverride = detailActionResult?.error === "projects.error.scheduleConflictOverrideRequired"; // The entry's own project is not necessarily in the picker's page, so it is // seeded in - otherwise the select would open on a different project. const detailProjectOptions: PlantafelOption[] = detailEntry ? [ ...(props.projectOptions.some((option) => option.id === detailEntry.projectId) ? [] : [{ id: detailEntry.projectId, label: projectLabels.get(detailEntry.projectId) ?? detailEntry.projectId }]), ...props.projectOptions, ] : []; const canSubmitDetail = Boolean( detailDraft && detailDraft.projektId && detailDraft.assignedUserId && detailDraft.title.trim() && detailDraft.startAt && detailDraft.endAt && (!detailNeedsOverride || detailOverrideReason.trim()) ); const openDetail = (entryId: string) => { setDetailEntryId(entryId); setDetailEditing(false); setDetailDraft(null); setDetailOverrideReason(""); setDetailSubmitted(false); setDetailResultAtSubmission(props.actionResult ?? null); }; const startDetailEdit = (entry: PlantafelEntryVM) => { setDetailDraft(buildPlantafelDetailDraft(entry, APP_TIME_ZONE)); setDetailResultAtSubmission(props.actionResult ?? null); setDetailEditing(true); }; const closeDetail = () => { if (formBusy) return; setDetailEntryId(null); setDetailEditing(false); setDetailDraft(null); setDetailOverrideReason(""); setDetailSubmitted(false); }; const closeCreateDialog = () => { if (formBusy) return; setCreateSubmitted(false); setConflictOverrideReason(""); setCreateMutationId(""); setCreateOpen(false); }; return ( } title={t("projects.plantafel.title")} subtitle={t("projects.plantafel.subtitle")} actions={
{t("projects.plantafel.entries", { count: visibleEntries.length })} 0 ? "subtle-warning" : "subtle-positive"}> {t("projects.plantafel.conflicts", { count: visibleConflictCount })} {t("projects.plantafel.absences", { count: data.absencesCount })} {/* Labelled table/calendar switch, same place and shape as the leads list. */} { if (value === "table" || value === "calendar") props.actions.onViewChange(value); }} data-ui-id="ui.projects.plantafel.viewToggle" > } value="table" aria-label={t("projects.plantafel.viewMode.table")} data-ui-id="ui.projects.plantafel.viewToggle.table" > {t("projects.plantafel.viewMode.table")} } value="calendar" aria-label={t("projects.plantafel.viewMode.calendar")} data-ui-id="ui.projects.plantafel.viewToggle.calendar" > {t("projects.plantafel.viewMode.calendar")} {props.canWrite ? ( ) : null}
} /> {/* --- Filter bar: the same strip the files browser and the boards wear - free-text box, facet buttons, chips for what is active and one reset. The monteur facet is a loader roundtrip (`assignedUserId`); the search narrows the loaded window in place, because that window is one day or one week, not a paged list. Sorting follows the monteur facet directly; the past switch sits at the trailing edge, and the week view puts its Mon-Sun navigation there instead. --- */} props.actions.onFilterChange({ ...props.filter, assignedUserId: props.filter.assignedUserId === value ? null : value }) } search={search} onSearchChange={setSearch} searchPlaceholder={t("projects.plantafel.filterSearchPlaceholder")} onReset={resetFilter} labels={{ reset: t("projects.plantafel.filterReset"), removeChip: t("projects.plantafel.filterRemoveChip") }} // Sorting is a table concern - the calendar puts every entry on its own // time slot. It sits right behind the monteur facet, because it orders // exactly the rows that facet narrows. The button carries the active // criterion as its label, so the bar states the order without being // opened. afterFacets={ props.view === "table" ? ( } label={t(`projects.plantafel.sortOption.${props.filter.sort}`)} count="" data-ui-id="ui.projects.plantafel.filter.sort" dropdown={ {PLANTAFEL_SORTS.map((sort) => ( props.actions.onFilterChange({ ...props.filter, sort: parsePlantafelSort(sort) })} data-ui-id={`ui.projects.plantafel.filter.sort.${sort}`} > {t(`projects.plantafel.sortOption.${sort}`)} ))} } /> ) : null } trailing={ <> {/* Only the table needs this switch: the calendar reaches the past by paging back a week, so a second control there would say the same thing twice. */} {props.view === "table" ? ( props.actions.onFilterChange({ ...props.filter, includePast: checked })} data-ui-id="ui.projects.plantafel.filter.past" /> ) : null} {/* Week navigation takes the same trailing slot: the range reads first, the controls stay at the edge. */} {props.view === "calendar" ? (
{weekRangeLabel} } aria-label={t("projects.plantafel.week.previous")} disabled={formBusy} onClick={() => props.actions.onAnchorChange(addDaysIso(weekDays[0]?.dateIso ?? props.anchorIso, -7))} data-ui-id="ui.projects.plantafel.weekNav.previous" /> } aria-label={t("projects.plantafel.week.next")} disabled={formBusy} onClick={() => props.actions.onAnchorChange(addDaysIso(weekDays[0]?.dateIso ?? props.anchorIso, 7))} data-ui-id="ui.projects.plantafel.weekNav.next" />
) : null} } /> {props.actionResult?.error && !(createOpen && props.actionResult.intent === "upsertSchedule") ? ( ) : null} {/* --- Bulk bar: the flat strip the project list wears - a count badge, the action, and the way out of the selection. It appears above the table only while something is selected, so it never takes room from the rows it acts on. --- */} {props.canBulkReassign && selectedEntryIds.length > 0 ? (
{t("projects.plantafel.bulkSelected", { count: selectedEntryIds.length })}
{bulkNeedsOverride ? ( setBulkOverrideReason(event.target.value)} /> ) : null}
) : null} {/* Section heading over the bare table - no card around it, same as the other list screens. */}
{t("projects.plantafel.entriesTitle")} {props.view === "calendar" ? ( <> {/* An empty week keeps the grid and gains a slim hint - a search that matched nothing says so, instead of reading as "nothing planned". */} {visibleEntries.length === 0 ? ( {searchTerm ? t("projects.plantafel.filterNoMatches") : t("projects.plantafel.week.empty")} ) : null} {weekGrid ? ( ) : null} ) : visibleEntries.length === 0 ? ( ) : (
{/* Select-all covers the rows on screen and only those the reader may actually reassign - a box that also picked up rows on other pages would promise more than the action delivers. */} {props.canBulkReassign ? ( {pageSelectableIds.length > 0 ? ( setSelectedEntryIds((current) => checked ? [...new Set([...current, ...pageSelectableIds])] : current.filter((id) => !pageSelectableIds.includes(id)) ) } hideLabel label={t("projects.plantafel.selectAll")} data-ui-id="ui.projects.plantafel.selectAll" /> ) : null} ) : null} {t("projects.plantafel.columns.entry")}{t("projects.plantafel.columns.assignee")}{t("projects.plantafel.columns.period")}{t("projects.plantafel.columns.status")} } > {pagedEntries.map((entry) => ( // Double-click opens the details, same gesture as in the week // grid. Single click stays free for the row's own controls // (selection checkbox, status flyout). openDetail(entry.id)}> {props.canBulkReassign ? ( {editableProjectIds.has(entry.projectId) ? ( setSelectedEntryIds((current) => (checked ? [...current, entry.id] : current.filter((id) => id !== entry.id))) } aria-label={`${t("projects.plantafel.selectEntry")}: ${entry.title}`} data-ui-id={`ui.projects.plantafel.select.${entry.id}`} /> ) : null} ) : null}
{/* The title is the keyboard-reachable door to the same popup - a double-click-only affordance would leave keyboard users without one. It carries the link colour every other list uses for an openable row, so the row reads as clickable before it is tried. */} {/* Entries whose title is just the project label (the demo seed does exactly that) would otherwise print the same string twice. */} {projectLabels.get(entry.projectId) && projectLabels.get(entry.projectId) !== entry.title ? ( {projectLabels.get(entry.projectId)} ) : null}
{assigneeLabels.get(entry.assignedUserId) ?? t("projects.plantafel.unknownAssignee")}
{formatDateTime(entry.startAtIso, i18n.language)} {formatDateTime(entry.endAtIso, i18n.language)}
{/* The status badge is the control: opening it lists the statuses and picking one saves right away. That replaced the separate select-plus-save column, which cost two clicks and a column width for every row. */} {props.canWrite && editableProjectIds.has(entry.projectId) ? ( {SCHEDULE_STATUSES.map((status) => ( status !== entry.status && submitOnce("updateStatus", { entryId: entry.id, status })} data-ui-id={`ui.projects.plantafel.status.${entry.id}.${status}`} > {/* Each option carries its own status colour, so the list reads like the column it changes. */} {t(`projects.scheduleStatus.${status}`)} ))} ) : ( {t(entry.statusLabelKey)} )} {entry.conflictCount > 0 ? ( 0 ? "subtle-negative" : "subtle-warning"}> {t("projects.plantafel.conflicts", { count: entry.conflictCount })} ) : null}
))}
)} {/* Table footer: how fresh the data is on the left, the way through the pages on the right. The "Stand" line used to sit above the table, where it pushed the rows down for a detail that is only read after them. */}
{t("projects.plantafel.generatedAt", { value: formatDateTime(data.generatedAt, i18n.language) })} {props.view === "table" && visibleEntries.length > 0 ? (
{t("projects.plantafel.pagination.position", { page: currentPage, pageCount })}
) : null}
{t("projects.plantafel.offlineTitle")} setOfflinePayload((current) => ({ ...current, clientMutationId: event.target.value }))} />
{/* --- Detail popup. Opens read-only on a double-click in either view; "Bearbeiten" top right unlocks the same fields as a form, and only then does the footer offer "Speichern" instead of "Schließen". --- */} { if (!open) closeDetail(); }} > {detailEntry ? (
{/* Title and the edit switch share the top line - the switch sits in the corner where a dialog's controls are expected. */}
{detailEntry.title} {detailEditing ? {t("projects.plantafel.detail.editHint")} : null}
{detailCanEdit && !detailEditing ? ( ) : null}
{detailActionResult?.error ? ( ) : null} {detailEditing && detailDraft ? ( <> setDetailDraft((current) => (current ? { ...current, title: event.target.value } : current))} data-ui-id="ui.projects.plantafel.detailDialog.title" />
setDetailDraft((current) => (current ? { ...current, startAt: event.target.value } : current))} data-ui-id="ui.projects.plantafel.detailDialog.start" /> setDetailDraft((current) => (current ? { ...current, endAt: event.target.value } : current))} data-ui-id="ui.projects.plantafel.detailDialog.end" />
{detailNeedsOverride ? ( ) : null} ) : (
{t("projects.plantafel.fields.project")}
{projectLabels.get(detailEntry.projectId) ?? "—"}
{t("projects.plantafel.columns.assignee")}
{assigneeLabels.get(detailEntry.assignedUserId) ?? t("projects.plantafel.unknownAssignee")}
{t("projects.fields.startDate")}
{formatDateTime(detailEntry.startAtIso, i18n.language)}
{t("projects.fields.deadline")}
{formatDateTime(detailEntry.endAtIso, i18n.language)}
{t("projects.plantafel.columns.status")}
{t(detailEntry.statusLabelKey)}
{t("projects.plantafel.detail.conflicts")}
0 ? "subtle-negative" : "subtle-warning" } > {t("projects.plantafel.conflicts", { count: detailEntry.conflictCount })}
)}
{detailEditing ? ( <> ) : ( )}
) : null}
{props.canWrite ? ( { if (open) { setCreateOpen(true); return; } closeCreateDialog(); }} >
{t("projects.plantafel.newEntry")} {createActionResult?.error ? ( ) : null}
setProjectQuery(event.target.value)} onKeyDown={(event) => { if (event.key !== "Enter") return; event.preventDefault(); searchProjectsOnce(projectQuery); }} data-ui-id="ui.projects.plantafel.createDialog.projectSearch" />
{projectSearchBusy ? {t("projects.plantafel.projectPickerLoading")} : null} {!projectSearchBusy && props.projectOptionsHasMore ? ( {t("projects.plantafel.projectPickerLimited")} ) : null} {!projectSearchBusy && props.projectOptions.length === 0 ? ( {t("projects.plantafel.projectPickerEmpty")} ) : null}
setDraft((current) => ({ ...current, title: event.target.value }))} data-ui-id="ui.projects.plantafel.createDialog.title" />
setDraft((current) => ({ ...current, startAt: event.target.value }))} data-ui-id="ui.projects.plantafel.createDialog.start" /> setDraft((current) => ({ ...current, endAt: event.target.value }))} data-ui-id="ui.projects.plantafel.createDialog.end" />
{needsConflictOverride ? ( ) : null}
) : null}
); }