feat: tasks manual reordering

This commit is contained in:
wpetit 2023-09-02 11:22:01 -06:00
parent 1c2b0bb9d9
commit d44959f91e
8 changed files with 219 additions and 88 deletions

View File

@ -9,7 +9,6 @@ export interface FooterProps {
} }
const Footer: FunctionComponent<FooterProps> = ({ ...props}) => { const Footer: FunctionComponent<FooterProps> = ({ ...props}) => {
console.log(__BUILD__)
return ( return (
<div className={`container ${style.footer} ${props.class ? props.class : ''}`}> <div className={`container ${style.footer} ${props.class ? props.class : ''}`}>
<div className="columns"> <div className="columns">

View File

@ -1,4 +1,4 @@
import { Project } from "../models/project"; import { Project, sanitize } from "../models/project";
import { Task, TaskID, EstimationConfidence, TaskCategoryID, TaskCategory } from "../models/task"; import { Task, TaskID, EstimationConfidence, TaskCategoryID, TaskCategory } from "../models/task";
import { useReducer } from "react"; import { useReducer } from "react";
import { generate as diff } from "json-merge-patch"; import { generate as diff } from "json-merge-patch";
@ -27,7 +27,7 @@ export function useProjectReducer(project: Project) {
} }
export function projectReducer(project: Project, action: ProjectReducerActions): Project { export function projectReducer(project: Project, action: ProjectReducerActions): Project {
console.log(action); console.log('action', action);
switch(action.type) { switch(action.type) {
case ADD_TASK: case ADD_TASK:
return handleAddTask(project, action as AddTask); return handleAddTask(project, action as AddTask);
@ -43,6 +43,9 @@ export function projectReducer(project: Project, action: ProjectReducerActions):
case UPDATE_TASK_LABEL: case UPDATE_TASK_LABEL:
return handleUpdateTaskLabel(project, action as UpdateTaskLabel); return handleUpdateTaskLabel(project, action as UpdateTaskLabel);
case MOVE_TASK:
return handleMoveTask(project, action as MoveTask);
case UPDATE_PARAM: case UPDATE_PARAM:
return handleUpdateParam(project, action as UpdateParam); return handleUpdateParam(project, action as UpdateParam);
@ -84,6 +87,10 @@ export function handleAddTask(project: Project, action: AddTask): Project {
...project.tasks, ...project.tasks,
[task.id]: task, [task.id]: task,
}, },
ordering: [
...project.ordering,
task.id
],
updatedAt: new Date(), updatedAt: new Date(),
}; };
} }
@ -101,9 +108,17 @@ export function removeTask(id: TaskID): RemoveTask {
export function handleRemoveTask(project: Project, action: RemoveTask): Project { export function handleRemoveTask(project: Project, action: RemoveTask): Project {
const tasks = { ...project.tasks }; const tasks = { ...project.tasks };
delete tasks[action.id]; delete tasks[action.id];
const ordering = [ ...(project.ordering ?? []) ]
const taskIndex = ordering.findIndex(taskId => taskId === action.id)
if (taskIndex !== -1) {
ordering.splice(taskIndex, 1)
}
return { return {
...project, ...project,
tasks, tasks,
ordering,
updatedAt: new Date(), updatedAt: new Date(),
}; };
} }
@ -183,6 +198,43 @@ export function handleUpdateTaskLabel(project: Project, action: UpdateTaskLabel)
}; };
} }
export const MOVE_TASK = "MOVE_TASK";
export interface MoveTask extends Action {
id: TaskID
move: number
}
export function moveTask(id: TaskID, move: number): MoveTask {
return { type: MOVE_TASK, id, move };
}
export function handleMoveTask(project: Project, action: MoveTask): Project {
let ordering = [
...(project.ordering ?? []),
]
if (ordering.length === 0) {
ordering = Object.keys(project.tasks)
}
const taskIndex = ordering.findIndex(taskId => action.id === taskId)
if (taskIndex+action.move < 0 || taskIndex+action.move > ordering.length-1 ) {
return project
}
ordering.splice(taskIndex, 1)
ordering.splice(taskIndex+action.move, 0, action.id)
return {
...project,
ordering,
updatedAt: new Date(),
}
}
export interface UpdateParam extends Action { export interface UpdateParam extends Action {
name: string name: string
value: any value: any
@ -324,7 +376,8 @@ export function handlePatchProject(project: Project, action: PatchProject): Proj
console.log('patch to apply', p); console.log('patch to apply', p);
if (!p) return project; if (!p) return project;
const patched: Project = applyPatch(project, p) as Project const patched: Project = applyPatch(project, p) as Project
if (typeof patched.createdAt === 'string') patched.createdAt = new Date(patched.createdAt)
if (typeof patched.updatedAt === 'string') patched.updatedAt = new Date(patched.updatedAt) sanitize(patched)
return patched; return patched;
} }

View File

@ -1,35 +1,38 @@
import {Project} from "../models/project"; import { Project, sanitize } from "../models/project";
import { useState } from "react"; import { useState } from "react";
import { ProjectStorageKeyPrefix } from "../util/storage"; import { ProjectStorageKeyPrefix } from "../util/storage";
export function loadStoredProjects(): Project[] { export function loadStoredProjects(): Project[] {
const projects: Project[] = []; const projects: Project[] = [];
Object.keys(window.localStorage).forEach(key => { Object.keys(window.localStorage).forEach(key => {
if (key.startsWith(ProjectStorageKeyPrefix)) { if (key.startsWith(ProjectStorageKeyPrefix)) {
try { try {
const data = window.localStorage.getItem(key); const data = window.localStorage.getItem(key);
if (data) { if (data) {
const project = JSON.parse(data); const project: Project = JSON.parse(data);
projects.push(project);
} sanitize(project)
} catch(err) {
console.error(err); projects.push(project);
}
} }
}); } catch (err) {
console.error(err);
}
}
});
return projects return projects
} }
export function useStoredProjectList(): [Project[], () => void] { export function useStoredProjectList(): [Project[], () => void] {
const [ projects, setProjects ] = useState(() => { const [projects, setProjects] = useState(() => {
return loadStoredProjects(); return loadStoredProjects();
}); });
const refresh = () => { const refresh = () => {
setProjects(loadStoredProjects()); setProjects(loadStoredProjects());
}; };
return [ projects, refresh]; return [projects, refresh];
} }

View File

@ -1,4 +1,4 @@
import { Task } from './task'; import { Task, TaskID } from './task';
import { Params, defaults } from "./params"; import { Params, defaults } from "./params";
import { uuidV4 } from "../util/uuid"; import { uuidV4 } from "../util/uuid";
@ -12,6 +12,7 @@ export interface Project {
params: Params params: Params
createdAt: Date createdAt: Date
updatedAt: Date updatedAt: Date
ordering: TaskID[]
} }
export interface Tasks { export interface Tasks {
@ -29,5 +30,22 @@ export function newProject(id?: string): Project {
}, },
createdAt: new Date(), createdAt: new Date(),
updatedAt: new Date(), updatedAt: new Date(),
ordering: [],
}; };
}
export function sanitize(project: Project): Project {
if (!Array.isArray(project.ordering)) {
project.ordering = Object.keys(project.tasks)
}
if (typeof project.updatedAt === 'string') {
project.updatedAt = new Date(project.updatedAt)
}
if (typeof project.createdAt === 'string') {
project.createdAt = new Date(project.createdAt)
}
return project
} }

View File

@ -1,58 +1,63 @@
import React, { FunctionComponent, Fragment } from "react"; import React, { FunctionComponent, Fragment, useCallback } from "react";
import { Project } from "../../models/project"; import { Project } from "../../models/project";
import TaskTable from "./tasks-table"; import TaskTable from "./tasks-table";
import TimePreview from "./time-preview"; import TimePreview from "./time-preview";
import FinancialPreview from "./financial-preview"; import FinancialPreview from "./financial-preview";
import { addTask, updateTaskEstimation, removeTask, updateTaskLabel, ProjectReducerActions } from "../../hooks/use-project-reducer"; import { addTask, updateTaskEstimation, removeTask, updateTaskLabel, ProjectReducerActions, moveTask } from "../../hooks/use-project-reducer";
import { Task, TaskID, EstimationConfidence } from "../../models/task"; import { Task, TaskID, EstimationConfidence } from "../../models/task";
import RepartitionPreview from "./repartition-preview"; import RepartitionPreview from "./repartition-preview";
import { getHideFinancialPreviewOnPrint } from "../../models/params"; import { getHideFinancialPreviewOnPrint } from "../../models/params";
export interface EstimationTabProps { export interface EstimationTabProps {
project: Project project: Project
dispatch: (action: ProjectReducerActions) => void dispatch: (action: ProjectReducerActions) => void
} }
const EstimationTab: FunctionComponent<EstimationTabProps> = ({ project, dispatch }) => { const EstimationTab: FunctionComponent<EstimationTabProps> = ({ project, dispatch }) => {
const onTaskAdd = (task: Task) => { const onTaskAdd = (task: Task) => {
dispatch(addTask(task)); dispatch(addTask(task));
}; };
const onTaskRemove = (taskId: TaskID) => { const onTaskRemove = (taskId: TaskID) => {
dispatch(removeTask(taskId)); dispatch(removeTask(taskId));
} }
const onTaskLabelUpdate = (taskId: TaskID, label: string) => { const onTaskLabelUpdate = (taskId: TaskID, label: string) => {
dispatch(updateTaskLabel(taskId, label)); dispatch(updateTaskLabel(taskId, label));
} }
const onEstimationChange = (taskId: TaskID, confidence: EstimationConfidence, value: number) => { const onEstimationChange = (taskId: TaskID, confidence: EstimationConfidence, value: number) => {
dispatch(updateTaskEstimation(taskId, confidence, value)); dispatch(updateTaskEstimation(taskId, confidence, value));
}; };
return ( const onTaskMove = useCallback((taskId: TaskID, move: number) => {
<Fragment> dispatch(moveTask(taskId, move))
<div className="columns"> }, [dispatch])
<div className="column is-9">
<TaskTable return (
project={project} <Fragment>
onTaskAdd={onTaskAdd} <div className="columns">
onTaskRemove={onTaskRemove} <div className="column is-9">
onTaskLabelUpdate={onTaskLabelUpdate} <TaskTable
onEstimationChange={onEstimationChange} /> project={project}
</div> onTaskMove={onTaskMove}
<div className="column is-3"> onTaskAdd={onTaskAdd}
<TimePreview project={project} /> onTaskRemove={onTaskRemove}
<RepartitionPreview project={project} /> onTaskLabelUpdate={onTaskLabelUpdate}
</div> onEstimationChange={onEstimationChange} />
</div> </div>
<div className="columns"> <div className="column is-3">
<div className={`column ${getHideFinancialPreviewOnPrint(project) ? 'noPrint': ''}`}> <TimePreview project={project} />
<FinancialPreview project={project} /> <RepartitionPreview project={project} />
</div>
</div> </div>
{ </div>
Object.keys(project.tasks).length <= 20 ? <div className="columns">
<div className={`column ${getHideFinancialPreviewOnPrint(project) ? 'noPrint' : ''}`}>
<FinancialPreview project={project} />
</div>
</div>
{
Object.keys(project.tasks).length <= 20 ?
<div className="message noPrint"> <div className="message noPrint">
<div className="message-body"> <div className="message-body">
<p><strong> Attention</strong></p> <p><strong> Attention</strong></p>
@ -60,10 +65,10 @@ const EstimationTab: FunctionComponent<EstimationTabProps> = ({ project, dispatc
</div> </div>
</div> : </div> :
null null
} }
<hr /> <hr />
</Fragment> </Fragment>
); );
}; };
export default EstimationTab; export default EstimationTab;

View File

@ -1,6 +1,6 @@
import React, { FunctionComponent, useEffect } from "react"; import React, { FunctionComponent, useEffect } from "react";
import style from "./style.module.css"; import style from "./style.module.css";
import { newProject, Project } from "../../models/project"; import { newProject, Project, sanitize } from "../../models/project";
import { useProjectReducer, updateProjectLabel, patchProject } from "../../hooks/use-project-reducer"; import { useProjectReducer, updateProjectLabel, patchProject } from "../../hooks/use-project-reducer";
import { getProjectStorageKey } from "../../util/storage"; import { getProjectStorageKey } from "../../util/storage";
import { useLocalStorage } from "../../hooks/use-local-storage"; import { useLocalStorage } from "../../hooks/use-local-storage";
@ -21,9 +21,10 @@ const Project: FunctionComponent<ProjectProps> = () => {
const { projectId } = useParams<{ projectId: string }>(); const { projectId } = useParams<{ projectId: string }>();
const projectStorageKey = getProjectStorageKey(projectId); const projectStorageKey = getProjectStorageKey(projectId);
const [ storedProject, storeProject ] = useLocalStorage(projectStorageKey, newProject(projectId)); const [ storedProject, storeProject ] = useLocalStorage(projectStorageKey, newProject(projectId));
const [ project, dispatch ] = useProjectReducer(storedProject); const [ project, dispatch ] = useProjectReducer(sanitize(storedProject));
useServerSync(project, (project: Project) => { useServerSync(project, (project: Project) => {
sanitize(project)
dispatch(patchProject(project)); dispatch(patchProject(project));
}); });

View File

@ -1,11 +1,11 @@
import React, { FunctionComponent, useState, useEffect, ChangeEvent, MouseEvent } from "react"; import React, { FunctionComponent, useState, useEffect, ChangeEvent, MouseEvent, useCallback } from "react";
import style from "./style.module.css"; import style from "./style.module.css";
import { Project } from "../../models/project"; import { Project } from "../../models/project";
import { newTask, Task, TaskID, EstimationConfidence } from "../../models/task"; import { newTask, Task, TaskID, EstimationConfidence } from "../../models/task";
import EditableText from "../../components/editable-text"; import EditableText from "../../components/editable-text";
import { usePrintMediaQuery } from "../../hooks/use-media-query"; import { usePrintMediaQuery } from "../../hooks/use-media-query";
import { defaults, getTimeUnit } from "../../models/params";
import ProjectTimeUnit from "../../components/project-time-unit"; import ProjectTimeUnit from "../../components/project-time-unit";
import { useSort } from "../../hooks/useSort";
export interface TaskTableProps { export interface TaskTableProps {
project: Project project: Project
@ -13,11 +13,12 @@ export interface TaskTableProps {
onTaskRemove: (taskId: TaskID) => void onTaskRemove: (taskId: TaskID) => void
onEstimationChange: (taskId: TaskID, confidence: EstimationConfidence, value: number) => void onEstimationChange: (taskId: TaskID, confidence: EstimationConfidence, value: number) => void
onTaskLabelUpdate: (taskId: TaskID, label: string) => void onTaskLabelUpdate: (taskId: TaskID, label: string) => void
onTaskMove: (taskId: TaskID, move: number) => void
} }
export type EstimationTotals = { [confidence in EstimationConfidence]: number } export type EstimationTotals = { [confidence in EstimationConfidence]: number }
const TaskTable: FunctionComponent<TaskTableProps> = ({ project, onTaskAdd, onEstimationChange, onTaskRemove, onTaskLabelUpdate }) => { const TaskTable: FunctionComponent<TaskTableProps> = ({ project, onTaskAdd, onEstimationChange, onTaskRemove, onTaskLabelUpdate, onTaskMove }) => {
const defaultTaskCategory = Object.keys(project.params.taskCategories)[0]; const defaultTaskCategory = Object.keys(project.params.taskCategories)[0];
const [task, setTask] = useState(newTask("", defaultTaskCategory)); const [task, setTask] = useState(newTask("", defaultTaskCategory));
@ -27,6 +28,21 @@ const TaskTable: FunctionComponent<TaskTableProps> = ({ project, onTaskAdd, onEs
[EstimationConfidence.Pessimistic]: 0, [EstimationConfidence.Pessimistic]: 0,
} as EstimationTotals); } as EstimationTotals);
const [tasks, setTasks] = useState<Task[]>([])
useEffect(() => {
setTasks(Object.values(project.tasks))
}, [project.tasks])
const sortTask = useCallback((a: Task, b: Task) => {
const aIndex = (project.ordering ?? []).findIndex(taskId => a.id === taskId)
const bIndex = (project.ordering ?? []).findIndex(taskId => b.id === taskId)
return aIndex - bIndex;
}, [project.ordering])
const sorted = useSort(tasks, sortTask)
const [ activeTaskActions, setActiveTaskActions ] = useState<string|null>(null);
const isPrint = usePrintMediaQuery(); const isPrint = usePrintMediaQuery();
useEffect(() => { useEffect(() => {
@ -43,6 +59,12 @@ const TaskTable: FunctionComponent<TaskTableProps> = ({ project, onTaskAdd, onEs
setTotals({ optimistic, likely, pessimistic }); setTotals({ optimistic, likely, pessimistic });
}, [project.tasks]); }, [project.tasks]);
const toggleActiveTaskAction = useCallback((evt: MouseEvent<HTMLButtonElement>) => {
const taskId = evt.currentTarget.dataset.taskId;
if (!taskId) return
setActiveTaskActions(activeTaskActions === taskId ? null : taskId)
}, [activeTaskActions])
const onNewTaskLabelChange = (evt: ChangeEvent) => { const onNewTaskLabelChange = (evt: ChangeEvent) => {
const value = (evt.currentTarget as HTMLInputElement).value; const value = (evt.currentTarget as HTMLInputElement).value;
setTask({ ...task, label: value }); setTask({ ...task, label: value });
@ -62,9 +84,23 @@ const TaskTable: FunctionComponent<TaskTableProps> = ({ project, onTaskAdd, onEs
setTask(newTask("", defaultTaskCategory)); setTask(newTask("", defaultTaskCategory));
}; };
const onTaskRemoveClick = (taskId: TaskID, evt: MouseEvent) => { const onTaskRemoveClick = useCallback((evt: MouseEvent<HTMLAnchorElement>) => {
const taskId = evt.currentTarget.dataset.taskId;
if (!taskId) return
onTaskRemove(taskId); onTaskRemove(taskId);
}; }, []);
const onTaskMoveUpClick = useCallback((evt: MouseEvent<HTMLAnchorElement>) => {
const taskId = evt.currentTarget.dataset.taskId;
if (!taskId) return
onTaskMove(taskId, -1);
}, []);
const onTaskMoveDownClick = useCallback((evt: MouseEvent<HTMLAnchorElement>) => {
const taskId = evt.currentTarget.dataset.taskId;
if (!taskId) return
onTaskMove(taskId, +1);
}, []);
const withEstimationChange = (confidence: EstimationConfidence, taskID: TaskID, evt: ChangeEvent) => { const withEstimationChange = (confidence: EstimationConfidence, taskID: TaskID, evt: ChangeEvent) => {
const textValue = (evt.currentTarget as HTMLInputElement).value; const textValue = (evt.currentTarget as HTMLInputElement).value;
@ -94,17 +130,32 @@ const TaskTable: FunctionComponent<TaskTableProps> = ({ project, onTaskAdd, onEs
</thead> </thead>
<tbody> <tbody>
{ {
Object.values(project.tasks).map(t => { sorted.map(t => {
const category = project.params.taskCategories[t.category]; const category = project.params.taskCategories[t.category];
const categoryLabel = category ? category.label : '???'; const categoryLabel = category ? category.label : '???';
return ( return (
<tr key={`taks-${t.id}`}> <tr key={`taks-${t.id}`}>
<td className={`is-narrow noPrint`}> <td className={`is-narrow noPrint`}>
<button <div className={`dropdown ${activeTaskActions === t.id ? 'is-active' : ''}`}>
onClick={onTaskRemoveClick.bind(null, t.id)} <div className="dropdown-trigger">
className="button is-danger is-small is-outlined"> <button onClick={toggleActiveTaskAction} data-task-id={t.id} className={`button is-small is-outlined ${activeTaskActions === t.id ? 'is-active' : ''}`} aria-haspopup="true" aria-controls="dropdown-menu">
🗑 <span></span>
</button> </button>
</div>
<div className="dropdown-menu" id="dropdown-menu" role="menu">
<div className="dropdown-content">
<a className="dropdown-item" data-task-id={t.id} onClick={onTaskMoveUpClick}>
Monter
</a>
<a href="#" className="dropdown-item" data-task-id={t.id} onClick={onTaskMoveDownClick}>
Descendre
</a>
<a className="dropdown-item" onClick={onTaskRemoveClick} data-task-id={t.id}>
<span className="has-text-danger">🗑 Supprimer</span>
</a>
</div>
</div>
</div>
</td> </td>
<td className={style.mainColumn}> <td className={style.mainColumn}>
<EditableText <EditableText
@ -128,9 +179,9 @@ const TaskTable: FunctionComponent<TaskTableProps> = ({ project, onTaskAdd, onEs
{ {
isPrint ? isPrint ?
<span>{t.estimations.likely}</span> : <span>{t.estimations.likely}</span> :
<input <input
className={`input ${t.estimations.likely < t.estimations.optimistic ? 'is-danger' : ''}`} className={`input ${t.estimations.likely < t.estimations.optimistic ? 'is-danger' : ''}`}
type="number" type="number"
value={t.estimations.likely} value={t.estimations.likely}
min={0} min={0}
onChange={onLikelyChange.bind(null, t.id)} /> onChange={onLikelyChange.bind(null, t.id)} />
@ -140,9 +191,9 @@ const TaskTable: FunctionComponent<TaskTableProps> = ({ project, onTaskAdd, onEs
{ {
isPrint ? isPrint ?
<span>{t.estimations.pessimistic}</span> : <span>{t.estimations.pessimistic}</span> :
<input <input
className={`input ${t.estimations.pessimistic < t.estimations.likely ? 'is-danger' : ''}`} className={`input ${t.estimations.pessimistic < t.estimations.likely ? 'is-danger' : ''}`}
type="number" type="number"
value={t.estimations.pessimistic} value={t.estimations.pessimistic}
min={0} min={0}
onChange={onPessimisticChange.bind(null, t.id)} /> onChange={onPessimisticChange.bind(null, t.id)} />

View File

@ -15,6 +15,7 @@ type Project struct {
Label string `json:"label"` Label string `json:"label"`
Description string `json:"description"` Description string `json:"description"`
Tasks map[TaskID]Task `json:"tasks"` Tasks map[TaskID]Task `json:"tasks"`
Ordering []TaskID `json:"ordering"`
Params Params `json:"params"` Params Params `json:"params"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"` UpdatedAt time.Time `json:"updatedAt"`