LocationsModal.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import { useState, useEffect, useCallback } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { MapPin, Plus, Loader2, Pencil, Trash2, X } from 'lucide-react';
  5. import { api, type StorageLocation } from '../api/client';
  6. import { Button } from './Button';
  7. import { ConfirmModal } from './ConfirmModal';
  8. import { useToast } from '../contexts/ToastContext';
  9. import { inventoryLocationsQueryKey, invalidateInventoryLocations } from '../utils/inventoryQueries';
  10. interface LocationsModalProps {
  11. open: boolean;
  12. onClose: () => void;
  13. onPickLocation?: (locationId: number) => void;
  14. }
  15. export function LocationsModal({ open, onClose, onPickLocation }: LocationsModalProps) {
  16. const { t } = useTranslation();
  17. const queryClient = useQueryClient();
  18. const { showToast } = useToast();
  19. const [editorOpen, setEditorOpen] = useState(false);
  20. const [editing, setEditing] = useState<StorageLocation | null>(null);
  21. const [name, setName] = useState('');
  22. const [deleteTarget, setDeleteTarget] = useState<StorageLocation | null>(null);
  23. const { data: locations = [], isLoading } = useQuery({
  24. queryKey: inventoryLocationsQueryKey,
  25. queryFn: api.getLocations,
  26. enabled: open,
  27. });
  28. const invalidate = () => {
  29. invalidateInventoryLocations(queryClient);
  30. queryClient.invalidateQueries({ queryKey: ['inventory-spools'] });
  31. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  32. };
  33. const saveMutation = useMutation({
  34. mutationFn: async () => {
  35. const trimmed = name.trim();
  36. if (!trimmed) throw new Error(t('locations.nameRequired'));
  37. if (editing) {
  38. return api.updateLocation(editing.id, { name: trimmed });
  39. }
  40. return api.createLocation({ name: trimmed });
  41. },
  42. onSuccess: () => {
  43. showToast(t(editing ? 'locations.updated' : 'locations.created'), 'success');
  44. setEditorOpen(false);
  45. setEditing(null);
  46. setName('');
  47. invalidate();
  48. },
  49. onError: (err: Error) => {
  50. showToast(err.message || t('locations.saveFailed'), 'error');
  51. },
  52. });
  53. const deleteMutation = useMutation({
  54. mutationFn: (id: number) => api.deleteLocation(id),
  55. onSuccess: () => {
  56. showToast(t('locations.deleted'), 'success');
  57. setDeleteTarget(null);
  58. invalidate();
  59. },
  60. onError: (err: Error) => {
  61. showToast(err.message || t('locations.deleteFailed'), 'error');
  62. },
  63. });
  64. const openCreate = () => {
  65. setEditing(null);
  66. setName('');
  67. setEditorOpen(true);
  68. };
  69. const openEdit = (location: StorageLocation) => {
  70. setEditing(location);
  71. setName(location.name);
  72. setEditorOpen(true);
  73. };
  74. const closeEditor = useCallback(() => {
  75. if (saveMutation.isPending) return;
  76. setEditorOpen(false);
  77. setEditing(null);
  78. setName('');
  79. }, [saveMutation.isPending]);
  80. // Esc closes the inner editor first; if it's closed, Esc closes the outer
  81. // modal — but only when neither save nor delete is mid-flight, so a stray
  82. // keypress during a network round-trip doesn't drop the user back into the
  83. // inventory page with an orphaned spinner.
  84. useEffect(() => {
  85. if (!open) return;
  86. const handleKeyDown = (e: KeyboardEvent) => {
  87. if (e.key !== 'Escape') return;
  88. if (saveMutation.isPending || deleteMutation.isPending) return;
  89. if (editorOpen) {
  90. closeEditor();
  91. } else if (!deleteTarget) {
  92. onClose();
  93. }
  94. };
  95. document.addEventListener('keydown', handleKeyDown);
  96. return () => document.removeEventListener('keydown', handleKeyDown);
  97. }, [open, editorOpen, deleteTarget, saveMutation.isPending, deleteMutation.isPending, closeEditor, onClose]);
  98. const handleSave = (e: React.FormEvent) => {
  99. e.preventDefault();
  100. saveMutation.mutate();
  101. };
  102. if (!open) return null;
  103. const modalTitleId = 'locations-modal-title';
  104. const editorTitleId = 'location-editor-title';
  105. return (
  106. <div className="fixed inset-0 z-50 flex items-center justify-center">
  107. <div
  108. className="absolute inset-0 bg-black/60"
  109. onClick={() => {
  110. if (saveMutation.isPending || deleteMutation.isPending) return;
  111. onClose();
  112. }}
  113. />
  114. <div
  115. className="relative w-full max-w-2xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col"
  116. role="dialog"
  117. aria-modal="true"
  118. aria-labelledby={modalTitleId}
  119. >
  120. <div className="flex items-center justify-between gap-4 px-6 py-4 border-b border-bambu-dark-tertiary">
  121. <div>
  122. <h2 id={modalTitleId} className="text-lg font-semibold text-white flex items-center gap-2">
  123. <MapPin className="w-5 h-5 text-bambu-green" />
  124. {t('locations.title')}
  125. </h2>
  126. <p className="text-bambu-gray text-sm mt-0.5">{t('locations.subtitle')}</p>
  127. </div>
  128. <div className="flex items-center gap-2">
  129. <Button onClick={openCreate}>
  130. <Plus className="w-4 h-4" />
  131. {t('locations.add')}
  132. </Button>
  133. <button
  134. type="button"
  135. className="p-1.5 text-bambu-gray hover:text-white rounded"
  136. onClick={onClose}
  137. aria-label={t('common.close')}
  138. >
  139. <X className="w-5 h-5" />
  140. </button>
  141. </div>
  142. </div>
  143. <div className="overflow-y-auto">
  144. {isLoading ? (
  145. <div className="flex items-center justify-center py-16 text-bambu-gray">
  146. <Loader2 className="w-6 h-6 animate-spin mr-2" />
  147. {t('common.loading')}
  148. </div>
  149. ) : locations.length === 0 ? (
  150. <div className="py-16 text-center text-bambu-gray">{t('locations.empty')}</div>
  151. ) : (
  152. <table className="w-full text-sm">
  153. <thead>
  154. <tr className="border-b border-bambu-dark-tertiary text-left text-bambu-gray">
  155. <th className="px-4 py-3 font-medium">{t('locations.name')}</th>
  156. <th className="px-4 py-3 font-medium text-right">{t('locations.spools')}</th>
  157. <th className="px-4 py-3 font-medium text-right w-32">{t('common.actions')}</th>
  158. </tr>
  159. </thead>
  160. <tbody>
  161. {locations.map((loc) => (
  162. <tr
  163. key={loc.id}
  164. className="border-b border-bambu-dark-tertiary/60 hover:bg-bambu-dark-tertiary/30 cursor-pointer"
  165. onClick={() => {
  166. if (onPickLocation) {
  167. onPickLocation(loc.id);
  168. onClose();
  169. }
  170. }}
  171. >
  172. <td className="px-4 py-3 text-white font-medium">{loc.name}</td>
  173. <td className="px-4 py-3 text-right text-bambu-gray">{loc.spool_count}</td>
  174. <td className="px-4 py-3 text-right" onClick={(e) => e.stopPropagation()}>
  175. <div className="flex items-center justify-end gap-1">
  176. <button
  177. type="button"
  178. className="p-1.5 text-bambu-gray hover:text-bambu-green rounded"
  179. onClick={() => openEdit(loc)}
  180. title={t('common.edit')}
  181. aria-label={t('locations.editAria', { name: loc.name, defaultValue: `Edit ${loc.name}` })}
  182. >
  183. <Pencil className="w-4 h-4" />
  184. </button>
  185. <button
  186. type="button"
  187. className="p-1.5 text-bambu-gray hover:text-red-600 dark:hover:text-red-400 rounded disabled:opacity-40"
  188. disabled={loc.spool_count > 0}
  189. onClick={() => setDeleteTarget(loc)}
  190. title={loc.spool_count > 0 ? t('locations.deleteBlocked') : t('common.delete')}
  191. aria-label={t('locations.deleteAria', { name: loc.name, defaultValue: `Delete ${loc.name}` })}
  192. >
  193. <Trash2 className="w-4 h-4" />
  194. </button>
  195. </div>
  196. </td>
  197. </tr>
  198. ))}
  199. </tbody>
  200. </table>
  201. )}
  202. </div>
  203. </div>
  204. {editorOpen && (
  205. <div className="fixed inset-0 z-[60] flex items-center justify-center">
  206. <div className="absolute inset-0 bg-black/60" onClick={closeEditor} />
  207. <div
  208. className="relative w-full max-w-md mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-6 shadow-2xl"
  209. role="dialog"
  210. aria-modal="true"
  211. aria-labelledby={editorTitleId}
  212. >
  213. <h3 id={editorTitleId} className="text-lg font-semibold text-white mb-4">
  214. {editing ? t('locations.edit') : t('locations.add')}
  215. </h3>
  216. <form onSubmit={handleSave}>
  217. <label className="block text-sm font-medium text-bambu-gray mb-1" htmlFor="location-name">
  218. {t('locations.name')}
  219. </label>
  220. <input
  221. id="location-name"
  222. type="text"
  223. maxLength={255}
  224. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green mb-4"
  225. placeholder={t('locations.createPlaceholder')}
  226. value={name}
  227. onChange={(e) => setName(e.target.value)}
  228. autoFocus
  229. />
  230. <div className="flex justify-end gap-2">
  231. <Button type="button" variant="secondary" onClick={closeEditor}>
  232. {t('common.cancel')}
  233. </Button>
  234. <Button type="submit" disabled={saveMutation.isPending || !name.trim()}>
  235. {saveMutation.isPending && <Loader2 className="w-4 h-4 animate-spin" />}
  236. {t('common.save')}
  237. </Button>
  238. </div>
  239. </form>
  240. </div>
  241. </div>
  242. )}
  243. {deleteTarget && (
  244. <ConfirmModal
  245. title={t('locations.confirmDelete', { name: deleteTarget.name })}
  246. message={t('locations.confirmDeleteMessage')}
  247. confirmText={t('common.delete')}
  248. variant="danger"
  249. isLoading={deleteMutation.isPending}
  250. onConfirm={() => deleteMutation.mutate(deleteTarget.id)}
  251. onCancel={() => setDeleteTarget(null)}
  252. />
  253. )}
  254. </div>
  255. );
  256. }