AddExternalLinkModal.tsx 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import { useState, useEffect, useRef } from 'react';
  2. import { useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { X, Save, Loader2, Upload, Trash2 } from 'lucide-react';
  4. import { api } from '../api/client';
  5. import type { ExternalLink, ExternalLinkCreate, ExternalLinkUpdate } from '../api/client';
  6. import { Button } from './Button';
  7. import { IconPicker, getIconByName } from './IconPicker';
  8. import { useTheme } from '../contexts/ThemeContext';
  9. interface AddExternalLinkModalProps {
  10. link?: ExternalLink | null;
  11. onClose: () => void;
  12. }
  13. export function AddExternalLinkModal({ link, onClose }: AddExternalLinkModalProps) {
  14. const queryClient = useQueryClient();
  15. const { theme } = useTheme();
  16. const isEditing = !!link;
  17. const fileInputRef = useRef<HTMLInputElement>(null);
  18. const [name, setName] = useState(link?.name || '');
  19. const [url, setUrl] = useState(link?.url || '');
  20. const [icon, setIcon] = useState(link?.icon || 'link');
  21. const [useCustomIcon, setUseCustomIcon] = useState(!!link?.custom_icon);
  22. const [customIconPreview, setCustomIconPreview] = useState<string | null>(
  23. link?.custom_icon ? api.getExternalLinkIconUrl(link.id) : null
  24. );
  25. const [pendingIconFile, setPendingIconFile] = useState<File | null>(null);
  26. const [error, setError] = useState<string | null>(null);
  27. // Close on Escape key
  28. useEffect(() => {
  29. const handleKeyDown = (e: KeyboardEvent) => {
  30. if (e.key === 'Escape') onClose();
  31. };
  32. window.addEventListener('keydown', handleKeyDown);
  33. return () => window.removeEventListener('keydown', handleKeyDown);
  34. }, [onClose]);
  35. // Create mutation
  36. const createMutation = useMutation({
  37. mutationFn: async (data: ExternalLinkCreate) => {
  38. const created = await api.createExternalLink(data);
  39. // If there's a pending icon file, upload it
  40. if (pendingIconFile) {
  41. return await api.uploadExternalLinkIcon(created.id, pendingIconFile);
  42. }
  43. return created;
  44. },
  45. onSuccess: () => {
  46. queryClient.invalidateQueries({ queryKey: ['external-links'] });
  47. onClose();
  48. },
  49. onError: (err: Error) => {
  50. setError(err.message);
  51. },
  52. });
  53. // Update mutation
  54. const updateMutation = useMutation({
  55. mutationFn: async (data: ExternalLinkUpdate) => {
  56. let updated = await api.updateExternalLink(link!.id, data);
  57. // Handle icon changes
  58. if (pendingIconFile) {
  59. // Upload new icon
  60. updated = await api.uploadExternalLinkIcon(link!.id, pendingIconFile);
  61. } else if (!useCustomIcon && link?.custom_icon) {
  62. // Remove custom icon if switching to preset
  63. updated = await api.deleteExternalLinkIcon(link!.id);
  64. }
  65. return updated;
  66. },
  67. onSuccess: () => {
  68. queryClient.invalidateQueries({ queryKey: ['external-links'] });
  69. onClose();
  70. },
  71. onError: (err: Error) => {
  72. setError(err.message);
  73. },
  74. });
  75. const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
  76. const file = e.target.files?.[0];
  77. if (file) {
  78. // Validate file type
  79. const validTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml', 'image/webp', 'image/x-icon'];
  80. if (!validTypes.includes(file.type)) {
  81. setError('Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)');
  82. return;
  83. }
  84. // Validate file size (max 1MB)
  85. if (file.size > 1024 * 1024) {
  86. setError('Image file must be less than 1MB');
  87. return;
  88. }
  89. setPendingIconFile(file);
  90. setUseCustomIcon(true);
  91. // Create preview
  92. const reader = new FileReader();
  93. reader.onload = (e) => {
  94. setCustomIconPreview(e.target?.result as string);
  95. };
  96. reader.readAsDataURL(file);
  97. }
  98. };
  99. const handleRemoveCustomIcon = () => {
  100. setPendingIconFile(null);
  101. setCustomIconPreview(null);
  102. setUseCustomIcon(false);
  103. if (fileInputRef.current) {
  104. fileInputRef.current.value = '';
  105. }
  106. };
  107. const handleSubmit = (e: React.FormEvent) => {
  108. e.preventDefault();
  109. setError(null);
  110. if (!name.trim()) {
  111. setError('Name is required');
  112. return;
  113. }
  114. if (!url.trim()) {
  115. setError('URL is required');
  116. return;
  117. }
  118. // Validate URL
  119. if (!url.startsWith('http://') && !url.startsWith('https://')) {
  120. setError('URL must start with http:// or https://');
  121. return;
  122. }
  123. const data = {
  124. name: name.trim(),
  125. url: url.trim(),
  126. icon: useCustomIcon ? icon : icon, // Keep preset icon as fallback
  127. };
  128. if (isEditing) {
  129. updateMutation.mutate(data);
  130. } else {
  131. createMutation.mutate(data);
  132. }
  133. };
  134. const isPending = createMutation.isPending || updateMutation.isPending;
  135. const PresetIcon = getIconByName(icon);
  136. return (
  137. <div
  138. className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4"
  139. onClick={onClose}
  140. >
  141. <div
  142. className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md"
  143. onClick={(e) => e.stopPropagation()}
  144. >
  145. {/* Header */}
  146. <div className="flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary">
  147. <div className="flex items-center gap-3">
  148. <div className="p-2 rounded-full bg-bambu-green/20 text-bambu-green">
  149. {useCustomIcon && customIconPreview ? (
  150. <img src={customIconPreview} alt="" className={`w-5 h-5 rounded ${theme === 'dark' ? 'invert brightness-200' : ''}`} />
  151. ) : (
  152. <PresetIcon className="w-5 h-5" />
  153. )}
  154. </div>
  155. <h2 className="text-lg font-semibold text-white">
  156. {isEditing ? 'Edit Link' : 'Add External Link'}
  157. </h2>
  158. </div>
  159. <button
  160. onClick={onClose}
  161. className="text-bambu-gray hover:text-white transition-colors"
  162. >
  163. <X className="w-5 h-5" />
  164. </button>
  165. </div>
  166. {/* Form */}
  167. <form onSubmit={handleSubmit} className="p-6 space-y-4">
  168. {error && (
  169. <div className="p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400">
  170. {error}
  171. </div>
  172. )}
  173. {/* Name */}
  174. <div>
  175. <label className="block text-sm text-bambu-gray mb-1">Name *</label>
  176. <input
  177. type="text"
  178. value={name}
  179. onChange={(e) => setName(e.target.value)}
  180. placeholder="My Link"
  181. maxLength={50}
  182. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  183. />
  184. </div>
  185. {/* URL */}
  186. <div>
  187. <label className="block text-sm text-bambu-gray mb-1">URL *</label>
  188. <input
  189. type="text"
  190. value={url}
  191. onChange={(e) => setUrl(e.target.value)}
  192. placeholder="https://example.com"
  193. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  194. />
  195. </div>
  196. {/* Icon Section */}
  197. <div className="space-y-3">
  198. <label className="block text-sm text-bambu-gray">Icon</label>
  199. {/* Custom Icon Upload */}
  200. <div className="p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary">
  201. <div className="flex items-center justify-between mb-2">
  202. <span className="text-sm text-white">Custom Icon</span>
  203. <input
  204. ref={fileInputRef}
  205. type="file"
  206. accept="image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon"
  207. className="hidden"
  208. onChange={handleFileSelect}
  209. />
  210. {useCustomIcon && customIconPreview ? (
  211. <div className="flex items-center gap-2">
  212. <img src={customIconPreview} alt="Custom icon" className={`w-8 h-8 rounded border border-bambu-dark-tertiary ${theme === 'dark' ? 'invert brightness-200' : ''}`} />
  213. <button
  214. type="button"
  215. onClick={handleRemoveCustomIcon}
  216. className="p-1 text-red-400 hover:text-red-300 transition-colors"
  217. title="Remove custom icon"
  218. >
  219. <Trash2 className="w-4 h-4" />
  220. </button>
  221. </div>
  222. ) : (
  223. <Button
  224. type="button"
  225. variant="secondary"
  226. size="sm"
  227. onClick={() => fileInputRef.current?.click()}
  228. >
  229. <Upload className="w-4 h-4" />
  230. Upload
  231. </Button>
  232. )}
  233. </div>
  234. <p className="text-xs text-bambu-gray">
  235. PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB.
  236. </p>
  237. </div>
  238. {/* Preset Icon Picker */}
  239. {!useCustomIcon && (
  240. <div>
  241. <span className="text-sm text-bambu-gray block mb-2">Or choose a preset icon</span>
  242. <IconPicker value={icon} onChange={setIcon} />
  243. </div>
  244. )}
  245. </div>
  246. {/* Actions */}
  247. <div className="flex gap-3 pt-2">
  248. <Button
  249. type="button"
  250. variant="secondary"
  251. onClick={onClose}
  252. className="flex-1"
  253. >
  254. Cancel
  255. </Button>
  256. <Button
  257. type="submit"
  258. disabled={isPending}
  259. className="flex-1"
  260. >
  261. {isPending ? (
  262. <Loader2 className="w-4 h-4 animate-spin" />
  263. ) : (
  264. <Save className="w-4 h-4" />
  265. )}
  266. {isEditing ? 'Save' : 'Add'}
  267. </Button>
  268. </div>
  269. </form>
  270. </div>
  271. </div>
  272. );
  273. }