import React, { useCallback, useMemo } from "react" import { localizeString } from "../formUtils" import { Choice } from "../formDesign" import { DragDropContext, Droppable, Draggable, DropResult } from "@hello-pangea/dnd" import _ from "lodash" import { RankedAnswerValue } from "../response" type RankedQuestionProps = { /** The choices to render. */ choices: Choice[] /** The answer to the question. */ answer: RankedAnswerValue /** Locale to use */ locale?: string /** The function to call when the value changes. */ onValueChange: (value?: any) => void } const reduceAnswer = (value: any[]) => { return value.reduce((v, c, i) => { v[c.id] = i+1 return v }, {}) } /** * Renders a ranked question. Answer is a mapping of choice id to rank (1, 2, 3, etc.). */ const RankedQuestion:React.FC = ({choices, locale, answer, onValueChange}) => { const items = useMemo(() => { return _.sortBy(choices, (item) => !!answer ? (answer[item.id] ?? 0) : 0) }, [choices, answer]) const handleReorder = useCallback((result: DropResult) => { if (!result.destination) { return; } const _items = reorder( items, result.source.index, result.destination.index ); onValueChange(reduceAnswer(_items)) }, [onValueChange, items]) const moveUp = useCallback((index: number) => { const newAnswer = [...items] as Choice[] [newAnswer[index], newAnswer[index-1]] = [newAnswer[index-1], newAnswer[index]] onValueChange(reduceAnswer(newAnswer)) }, [items]) const moveDown = useCallback((index: number) => { const newAnswer = [...items] as Choice[] [newAnswer[index], newAnswer[index+1]] = [newAnswer[index+1], newAnswer[index]] onValueChange(reduceAnswer(newAnswer)) }, [items]) return ( {(provided, snapshot) => (
{items.map((item, index) => ( {(provided, snapshot) => (
{`${index+1}. `} {localizeString(item.label, locale)}
)}
))} {provided.placeholder}
)}
) } const reorder = (list: any[], startIndex: number, endIndex: number) => { const result = Array.from(list); const [removed] = result.splice(startIndex, 1); result.splice(endIndex, 0, removed); return result; }; const grid = 8; const getItemStyle = (isDragging: boolean, draggableStyle: any) => ({ // some basic styles to make the items look a bit nicer userSelect: "none", margin: `0 0 ${grid}px 0`, // change background colour if dragging background: isDragging ? "lightgreen" : "grey", borderRadius: 4, // styles we need to apply on draggables ...draggableStyle }); const getListStyle = (isDraggingOver: boolean) => ({ background: isDraggingOver ? "lightblue" : "lightgrey", }); export default RankedQuestion