Closed3
MUI Datagridでドラッグドロップかつセルを直接編集できるようにしたい
ドラッグドロップできて、セルの編集もできるように、それでいて金も払いたくないというワガママな要求ではあるが、下記のStackOverflowを見て解決した
要はdnd-kitのPointerSensorを改造して、セル編集のところにはドラッグドロップを効かないようにすれば良いらしい以下ざっくりとしたコード
editablePointerSensor.ts
// @ts-nocheck
import { PointerSensor } from '@dnd-kit/core'
class EditablePointerSensor extends PointerSensor {
static activators = [
{
eventName: 'onPointerDown' as 'onPointerDown',
handler: ({ nativeEvent: event }) => {
if (!event.isPrimary || event.button !== 0 || isInteractiveElement(event.target)) {
return false
}
return true
},
},
]
}
function isInteractiveElement(element: Element) {
const child = element.firstChild
const mago = child ? (child.firstChild as Element) : null
if (!mago || !mago.tagName) return true
return mago.tagName.toLowerCase() === 'svg' && element.tagName.toLowerCase() === 'svg' // svgだけはドラッグ可能にする
}
export default EditablePointerSensor
table.tsx
import DraggableGridRow from '@/components/commons/draggableGridRow'
import EditablePointerSensor from '@/utils/editablePointerSensor'
import DragHandleIcon from '@mui/icons-material/DragHandle'
const Table = () => {
const sensors = useSensors(useSensor(EditablePointerSensor))
// ドラッグ終了時の処理
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event
if (over) {
const oldIndex = processes.findIndex((row) => row.id === active.id)
const newIndex = processes.findIndex((row) => row.id === over.id)
//適宜mutation
}
}
const columnsWithDelete: GridColDef<ProcessOperationType>[] = [
{
headerName: 'ドラッグ',
field: 'drag',
type: 'actions',
getActions: (_params: any) => [
<DragHandleIcon
color="primary"
sx={{ pointerEvents: 'none', zIndex: -1 }}
key={_params.id + 'drag'}
/>,
],
},
]
if (isLoading) return <p>hoge</p>
return (
<>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
autoScroll={false}
>
<SortableContext
items={processes.map((row) => row.id)}
strategy={verticalListSortingStrategy}
>
<DataGrid
columns={columnsWithDelete}
slots={{ row: DraggableGridRow }}
rows={processes}
hideFooter={true}
hideFooterPagination={true}
/>
</SortableContext>
</DndContext>
</>
)
}
export default Table
mutationの処理は書いてないので元に戻るが、大体できることがわかった。
このスクラップは2023/09/14にクローズされました