File size: 11,236 Bytes
20df2a6
610e126
20df2a6
 
 
 
 
b00cff7
20df2a6
 
b00cff7
 
20df2a6
 
74fb13d
20df2a6
 
 
 
 
 
 
eed056f
20df2a6
 
 
c62e893
a141ee7
c62e893
eed056f
74fb13d
 
eed056f
 
 
 
 
20df2a6
b00cff7
20df2a6
 
 
 
 
 
 
 
 
 
 
a141ee7
 
eed056f
 
74fb13d
 
eed056f
 
 
 
 
20df2a6
b00cff7
20df2a6
 
74fb13d
610e126
20df2a6
 
 
 
 
a141ee7
20df2a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a141ee7
 
 
 
 
 
 
 
 
74fb13d
610e126
74fb13d
eed056f
 
 
 
74fb13d
 
610e126
 
 
 
 
 
 
 
20df2a6
 
 
43462bc
610e126
20df2a6
 
 
 
 
 
 
 
 
 
 
 
 
 
610e126
 
 
 
 
 
 
 
 
 
 
 
20df2a6
 
 
a141ee7
20df2a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b00cff7
11d3514
 
 
 
 
 
 
 
 
 
74fb13d
11d3514
74fb13d
20df2a6
 
11d3514
20df2a6
 
74fb13d
43462bc
74fb13d
 
 
 
 
 
 
 
b00cff7
 
 
11d3514
b00cff7
74fb13d
 
 
 
 
 
 
11d3514
74fb13d
 
 
 
 
 
 
 
 
 
 
 
 
 
11d3514
 
20df2a6
 
 
 
 
c62e893
a141ee7
20df2a6
 
 
 
 
 
a141ee7
 
 
c62e893
a141ee7
 
 
 
c62e893
 
 
 
 
 
 
 
 
 
 
20df2a6
 
a141ee7
 
 
 
 
 
 
 
20df2a6
 
 
 
 
eed056f
 
74fb13d
eed056f
74fb13d
eed056f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20df2a6
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import { format } from "date-fns";
import { useRef, useState } from "react";

import {
  buildAllocationBarSegment,
  dateStringsFromDayIndices,
  dayIndexFromPointer,
  formatAllocationEffort,
  projectBarStyle,
  roundToHalfHour,
  visibleWeekdayCount,
  type EffortDisplayMode,
} from "../../planner/allocationTimeline";
import type { Allocation, Person } from "../../types";
import { AllocationBarMenuTrigger } from "./AllocationBarMenu";
import { AllocationCreatePopover, type AllocationDragDraft } from "./AllocationCreatePopover";

interface AllocationDragTimelineProps {
  dayDates: Date[];
  color: string;
  fixedPerson?: Person;
  candidatePeople?: Person[];
  transferPeople?: Person[];
  allocation?: Allocation;
  weeklyCapacityHrs?: number;
  allocationPct?: number;
  onSave: (draft: AllocationDragDraft) => Promise<Allocation | undefined> | Allocation | undefined;
  onUpdate?: (draft: AllocationDragDraft) => void;
  onDelete?: (allocation: Allocation) => void;
  onTransfer?: (personId: number) => void;
  onStartClone?: () => void;
  cloneSourceId?: number;
  onSelectAllToRight?: () => void;
  onToggleMultiSelect?: () => void;
  multiSelectActive?: boolean;
  selected?: boolean;
  onToggleSelect?: () => void;
  isSaving?: boolean;
  effortMode?: EffortDisplayMode;
}

export function AllocationDragTimeline({
  dayDates,
  color,
  fixedPerson,
  candidatePeople = [],
  allocation,
  weeklyCapacityHrs,
  allocationPct,
  onSave,
  onUpdate,
  onDelete,
  transferPeople = [],
  onTransfer,
  onStartClone,
  cloneSourceId,
  onSelectAllToRight,
  onToggleMultiSelect,
  multiSelectActive = false,
  selected = false,
  onToggleSelect,
  isSaving = false,
  effortMode = "hours",
}: AllocationDragTimelineProps) {
  const trackRef = useRef<HTMLDivElement>(null);
  const barHostRef = useRef<HTMLDivElement>(null);
  const dragPointerRef = useRef<{ x: number; y: number } | null>(null);
  const [dragRange, setDragRange] = useState<{ start: number; end: number } | null>(null);
  const [popover, setPopover] = useState<{
    startDate: string;
    endDate: string;
    anchor: { top: number; left: number };
    allocation?: Allocation;
  } | null>(null);

  const totalDays = dayDates.length;
  const existingSegment =
    allocation && weeklyCapacityHrs !== undefined && allocationPct !== undefined
      ? buildAllocationBarSegment(dayDates, allocation.start_date, allocation.end_date)
      : null;

  const previewSegment =
    dragRange && totalDays > 0
      ? {
          startIndex: Math.min(dragRange.start, dragRange.end),
          endIndex: Math.max(dragRange.start, dragRange.end),
        }
      : null;

  const openPopoverAt = (startDate: string, endDate: string, clientX: number, clientY: number, edit?: Allocation) => {
    setPopover({
      startDate,
      endDate,
      anchor: { top: clientY + 8, left: clientX - 180 },
      allocation: edit,
    });
  };

  const openEditPopover = (event?: React.MouseEvent<HTMLButtonElement>) => {
    if (!allocation) return;
    event?.stopPropagation();
    if (multiSelectActive && onToggleSelect) {
      onToggleSelect();
      return;
    }
    const rect = event?.currentTarget.getBoundingClientRect() ?? barHostRef.current?.getBoundingClientRect();
    if (!rect) return;
    openPopoverAt(
      allocation.start_date,
      allocation.end_date,
      rect.left + rect.width / 2,
      rect.bottom,
      allocation,
    );
  };

  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
    if (!trackRef.current || event.button !== 0) return;
    if ((event.target as HTMLElement).closest(".allocation-bar-host, .allocation-bar")) return;
    dragPointerRef.current = { x: event.clientX, y: event.clientY };
    const index = dayIndexFromPointer(event.clientX, trackRef.current.getBoundingClientRect(), totalDays);
    setDragRange({ start: index, end: index });
    trackRef.current.setPointerCapture(event.pointerId);
  };

  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
    if (!dragRange || !trackRef.current) return;
    const index = dayIndexFromPointer(event.clientX, trackRef.current.getBoundingClientRect(), totalDays);
    setDragRange((prev) => (prev ? { ...prev, end: index } : null));
  };

  const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
    if (!trackRef.current?.hasPointerCapture(event.pointerId)) return;
    trackRef.current.releasePointerCapture(event.pointerId);
    const pointerStart = dragPointerRef.current;
    dragPointerRef.current = null;
    const range = dragRange;
    setDragRange(null);
    if (!range) return;
    const movedPx = pointerStart
      ? Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y)
      : 0;
    const didDrag = range.start !== range.end || movedPx > 6;
    if (!didDrag) return;
    const { start_date, end_date } = dateStringsFromDayIndices(dayDates, range.start, range.end);
    openPopoverAt(start_date, end_date, event.clientX, event.clientY);
  };

  const pickerPeople = fixedPerson ? [fixedPerson] : candidatePeople;
  const editingAllocation = popover?.allocation;

  return (
    <>
      <div
        className={`planner-timeline planner-drag-timeline${dragRange ? " is-dragging" : ""}`}
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={onPointerUp}
        ref={trackRef}
      >
        <div className="planner-day-grid" />
        {dayDates.map((day, index) => (
          <div
            className={`planner-day-hit${format(day, "yyyy-MM-dd") === format(new Date(), "yyyy-MM-dd") ? " is-today" : ""}`}
            key={day.toISOString()}
            style={{
              left: `${(index / totalDays) * 100}%`,
              width: `${(1 / totalDays) * 100}%`,
            }}
          />
        ))}
        {previewSegment ? (
          <div
            className="planner-drag-preview"
            style={{
              ...projectBarStyle(
                {
                  startIndex: previewSegment.startIndex,
                  endIndex: previewSegment.endIndex,
                  className: "project-bar allocation-bar preview",
                  label: "",
                },
                totalDays,
              ),
              background: color,
              borderTopColor: color,
            }}
          />
        ) : null}
        {existingSegment && weeklyCapacityHrs !== undefined && allocationPct !== undefined && allocation ? (
          (() => {
            const weekdayCount = visibleWeekdayCount(
              dayDates,
              allocation.start_date,
              allocation.end_date,
            );
            const daySpan = existingSegment.endIndex - existingSegment.startIndex + 1;
            const widthPct = totalDays > 0 ? (daySpan / totalDays) * 100 : 100;
            const isCompact = weekdayCount <= 1 || widthPct <= 18;
            return (
          <div
            className={`allocation-bar-host project-bar${isCompact ? " is-compact" : " is-span"}${selected ? " is-selected" : ""}${cloneSourceId === allocation.id ? " is-clone-source" : ""}`}
            ref={barHostRef}
            style={{
              ...projectBarStyle(existingSegment, totalDays),
              minWidth: 76,
            }}
          >
            <button
              className="allocation-bar-main project-bar allocation-bar"
              onClick={openEditPopover}
              onPointerDown={(event) => event.stopPropagation()}
              onPointerUp={(event) => event.stopPropagation()}
              style={{
                background: color,
                borderTopColor: color,
              }}
              title={formatAllocationEffort(
                effortMode,
                allocationPct,
                weeklyCapacityHrs,
                weekdayCount,
              )}
              type="button"
            >
              <span className="planner-bar-label">
                {formatAllocationEffort(
                  effortMode,
                  allocationPct,
                  weeklyCapacityHrs,
                  weekdayCount,
                )}
              </span>
            </button>
            <AllocationBarMenuTrigger
              multiSelectActive={multiSelectActive}
              onClone={() => onStartClone?.()}
              onDelete={onDelete ? () => onDelete(allocation) : undefined}
              onEdit={() => openEditPopover()}
              onSelectAllToRight={onSelectAllToRight}
              onToggleMultiSelect={onToggleMultiSelect}
              onTransferPerson={onTransfer}
              transferPeople={transferPeople}
            />
          </div>
            );
          })()
        ) : null}
      </div>

      {popover && pickerPeople.length > 0 ? (
        <AllocationCreatePopover
          key={`${popover.startDate}-${popover.endDate}-${editingAllocation?.id ?? "new"}`}
          allocation={editingAllocation}
          anchor={popover.anchor}
          dayDates={dayDates}
          endDate={popover.endDate}
          fixedPerson={fixedPerson}
          isSaving={isSaving}
          onCancel={() => setPopover(null)}
          onDelete={
            editingAllocation && onDelete
              ? () => {
                  onDelete(editingAllocation);
                  setPopover(null);
                }
              : undefined
          }
          onSave={async (draft) => {
            const created = await onSave(draft);
            if (created) {
              setPopover({
                startDate: created.start_date,
                endDate: created.end_date,
                anchor: popover.anchor,
                allocation: created,
              });
              return;
            }
            setPopover(null);
          }}
          onUpdate={
            editingAllocation && onUpdate
              ? (draft) => {
                  onUpdate(draft);
                  setPopover(null);
                }
              : undefined
          }
          people={pickerPeople}
          startDate={popover.startDate}
          defaultHoursPerDay={
            fixedPerson ? roundToHalfHour(fixedPerson.weekly_capacity_hrs / 5) : undefined
          }
          multiSelectActive={multiSelectActive}
          onClone={
            editingAllocation && onStartClone
              ? () => {
                  onStartClone();
                  setPopover(null);
                }
              : undefined
          }
          onSelectAllToRight={
            editingAllocation && onSelectAllToRight
              ? () => {
                  onSelectAllToRight();
                  setPopover(null);
                }
              : undefined
          }
          onToggleMultiSelect={
            onToggleMultiSelect
              ? () => {
                  onToggleMultiSelect();
                  setPopover(null);
                }
              : undefined
          }
          onTransfer={
            editingAllocation && onTransfer
              ? (personId) => {
                  onTransfer(personId);
                  setPopover(null);
                }
              : undefined
          }
          transferPeople={transferPeople}
        />
      ) : null}
    </>
  );
}