draganddrop.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from __future__ import annotations
  2. from typing import Callable, Optional, Protocol
  3. from nicegui import ui
  4. class Item(Protocol):
  5. title: str
  6. dragged: Optional[card] = None
  7. class column(ui.column):
  8. def __init__(self, name: str, on_drop: Optional[Callable[[Item, str], None]] = None) -> None:
  9. super().__init__()
  10. with self.classes('bg-blue-grey-2 w-60 p-4 rounded shadow-2'):
  11. ui.label(name).classes('text-bold ml-1')
  12. self.name = name
  13. self.on('dragover.prevent', self.highlight)
  14. self.on('dragleave', self.unhighlight)
  15. self.on('drop', self.move_card)
  16. self.on_drop = on_drop
  17. def highlight(self) -> None:
  18. self.classes(remove='bg-blue-grey-2', add='bg-blue-grey-3')
  19. def unhighlight(self) -> None:
  20. self.classes(remove='bg-blue-grey-3', add='bg-blue-grey-2')
  21. def move_card(self) -> None:
  22. global dragged # pylint: disable=global-statement # noqa: PLW0603
  23. self.unhighlight()
  24. dragged.parent_slot.parent.remove(dragged)
  25. with self:
  26. card(dragged.item)
  27. self.on_drop(dragged.item, self.name)
  28. dragged = None
  29. class card(ui.card):
  30. def __init__(self, item: Item) -> None:
  31. super().__init__()
  32. self.item = item
  33. with self.props('draggable').classes('w-full cursor-pointer bg-grey-1'):
  34. ui.label(item.title)
  35. self.on('dragstart', self.handle_dragstart)
  36. def handle_dragstart(self) -> None:
  37. global dragged # pylint: disable=global-statement # noqa: PLW0603
  38. dragged = self