NotificationTemplateEditor.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import { useState, useEffect, useRef } from 'react';
  2. import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
  3. import { X, Save, Loader2, RotateCcw, Plus, Eye } from 'lucide-react';
  4. import { api } from '../api/client';
  5. import type { NotificationTemplate, NotificationTemplateUpdate } from '../api/client';
  6. import { Button } from './Button';
  7. interface NotificationTemplateEditorProps {
  8. template: NotificationTemplate;
  9. onClose: () => void;
  10. }
  11. export function NotificationTemplateEditor({ template, onClose }: NotificationTemplateEditorProps) {
  12. const queryClient = useQueryClient();
  13. const bodyRef = useRef<HTMLTextAreaElement>(null);
  14. const [titleTemplate, setTitleTemplate] = useState(template.title_template);
  15. const [bodyTemplate, setBodyTemplate] = useState(template.body_template);
  16. const [error, setError] = useState<string | null>(null);
  17. const [showPreview, setShowPreview] = useState(true);
  18. // Fetch variables for this event type
  19. const { data: variablesData } = useQuery({
  20. queryKey: ['template-variables'],
  21. queryFn: api.getTemplateVariables,
  22. });
  23. // Get variables for this template's event type
  24. const eventVariables = variablesData?.find(v => v.event_type === template.event_type);
  25. // Live preview
  26. const { data: preview, isLoading: previewLoading } = useQuery({
  27. queryKey: ['template-preview', template.event_type, titleTemplate, bodyTemplate],
  28. queryFn: () => api.previewTemplate({
  29. event_type: template.event_type,
  30. title_template: titleTemplate,
  31. body_template: bodyTemplate,
  32. }),
  33. enabled: showPreview && titleTemplate.length > 0 && bodyTemplate.length > 0,
  34. });
  35. // Close on Escape key
  36. useEffect(() => {
  37. const handleKeyDown = (e: KeyboardEvent) => {
  38. if (e.key === 'Escape') onClose();
  39. };
  40. window.addEventListener('keydown', handleKeyDown);
  41. return () => window.removeEventListener('keydown', handleKeyDown);
  42. }, [onClose]);
  43. // Update mutation
  44. const updateMutation = useMutation({
  45. mutationFn: (data: NotificationTemplateUpdate) => api.updateNotificationTemplate(template.id, data),
  46. onSuccess: () => {
  47. queryClient.invalidateQueries({ queryKey: ['notification-templates'] });
  48. onClose();
  49. },
  50. onError: (err: Error) => {
  51. setError(err.message);
  52. },
  53. });
  54. // Reset mutation
  55. const resetMutation = useMutation({
  56. mutationFn: () => api.resetNotificationTemplate(template.id),
  57. onSuccess: (resetTemplate) => {
  58. setTitleTemplate(resetTemplate.title_template);
  59. setBodyTemplate(resetTemplate.body_template);
  60. queryClient.invalidateQueries({ queryKey: ['notification-templates'] });
  61. },
  62. onError: (err: Error) => {
  63. setError(err.message);
  64. },
  65. });
  66. const handleSubmit = (e: React.FormEvent) => {
  67. e.preventDefault();
  68. setError(null);
  69. if (!titleTemplate.trim()) {
  70. setError('Title is required');
  71. return;
  72. }
  73. if (!bodyTemplate.trim()) {
  74. setError('Body is required');
  75. return;
  76. }
  77. updateMutation.mutate({
  78. title_template: titleTemplate,
  79. body_template: bodyTemplate,
  80. });
  81. };
  82. const insertVariable = (variable: string) => {
  83. const textarea = bodyRef.current;
  84. if (!textarea) return;
  85. const start = textarea.selectionStart;
  86. const end = textarea.selectionEnd;
  87. const text = bodyTemplate;
  88. const before = text.substring(0, start);
  89. const after = text.substring(end);
  90. const newValue = before + `{${variable}}` + after;
  91. setBodyTemplate(newValue);
  92. // Restore focus and cursor position
  93. setTimeout(() => {
  94. textarea.focus();
  95. const newCursor = start + variable.length + 2;
  96. textarea.setSelectionRange(newCursor, newCursor);
  97. }, 0);
  98. };
  99. const hasChanges = titleTemplate !== template.title_template || bodyTemplate !== template.body_template;
  100. return (
  101. <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4">
  102. <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col">
  103. {/* Header */}
  104. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0">
  105. <h2 className="text-lg font-semibold text-white">
  106. Edit Template: {template.name}
  107. </h2>
  108. <button
  109. onClick={onClose}
  110. className="p-1 hover:bg-bambu-dark-tertiary rounded transition-colors"
  111. >
  112. <X className="w-5 h-5 text-bambu-gray" />
  113. </button>
  114. </div>
  115. {/* Content */}
  116. <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-4 space-y-4">
  117. {error && (
  118. <div className="p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm">
  119. {error}
  120. </div>
  121. )}
  122. {/* Title */}
  123. <div>
  124. <label className="block text-sm font-medium text-bambu-gray mb-1">
  125. Title
  126. </label>
  127. <input
  128. type="text"
  129. value={titleTemplate}
  130. onChange={(e) => setTitleTemplate(e.target.value)}
  131. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green"
  132. placeholder="Notification title..."
  133. />
  134. </div>
  135. {/* Body */}
  136. <div>
  137. <label className="block text-sm font-medium text-bambu-gray mb-1">
  138. Body
  139. </label>
  140. <textarea
  141. ref={bodyRef}
  142. value={bodyTemplate}
  143. onChange={(e) => setBodyTemplate(e.target.value)}
  144. rows={4}
  145. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green font-mono text-sm resize-none"
  146. placeholder="Notification body..."
  147. />
  148. </div>
  149. {/* Available Variables */}
  150. {eventVariables && (
  151. <div>
  152. <label className="block text-sm font-medium text-bambu-gray mb-2">
  153. Available Variables
  154. </label>
  155. <div className="flex flex-wrap gap-2">
  156. {eventVariables.variables.map((variable) => (
  157. <button
  158. key={variable}
  159. type="button"
  160. onClick={() => insertVariable(variable)}
  161. className="inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs text-bambu-gray hover:text-white transition-colors"
  162. >
  163. <Plus className="w-3 h-3" />
  164. {variable}
  165. </button>
  166. ))}
  167. </div>
  168. <p className="text-xs text-bambu-gray/60 mt-1">
  169. Click to insert at cursor position in body
  170. </p>
  171. </div>
  172. )}
  173. {/* Preview */}
  174. <div>
  175. <div className="flex items-center justify-between mb-2">
  176. <label className="text-sm font-medium text-bambu-gray flex items-center gap-2">
  177. <Eye className="w-4 h-4" />
  178. Live Preview
  179. </label>
  180. <button
  181. type="button"
  182. onClick={() => setShowPreview(!showPreview)}
  183. className="text-xs text-bambu-green hover:text-bambu-green-light"
  184. >
  185. {showPreview ? 'Hide' : 'Show'}
  186. </button>
  187. </div>
  188. {showPreview && (
  189. <div className="bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2">
  190. {previewLoading ? (
  191. <div className="flex items-center gap-2 text-bambu-gray text-sm">
  192. <Loader2 className="w-4 h-4 animate-spin" />
  193. Loading preview...
  194. </div>
  195. ) : preview ? (
  196. <>
  197. <div>
  198. <span className="text-xs text-bambu-gray">Title:</span>
  199. <div className="text-white font-medium">{preview.title}</div>
  200. </div>
  201. <div>
  202. <span className="text-xs text-bambu-gray">Body:</span>
  203. <div className="text-white whitespace-pre-wrap text-sm">{preview.body}</div>
  204. </div>
  205. </>
  206. ) : (
  207. <div className="text-bambu-gray text-sm">
  208. Enter template content to see preview
  209. </div>
  210. )}
  211. </div>
  212. )}
  213. </div>
  214. </form>
  215. {/* Footer */}
  216. <div className="flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0">
  217. <Button
  218. type="button"
  219. variant="ghost"
  220. onClick={() => resetMutation.mutate()}
  221. disabled={resetMutation.isPending}
  222. className="text-orange-400 hover:text-orange-300"
  223. >
  224. {resetMutation.isPending ? (
  225. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  226. ) : (
  227. <RotateCcw className="w-4 h-4 mr-2" />
  228. )}
  229. Reset to Default
  230. </Button>
  231. <div className="flex gap-2">
  232. <Button type="button" variant="secondary" onClick={onClose}>
  233. Cancel
  234. </Button>
  235. <Button
  236. onClick={handleSubmit}
  237. disabled={updateMutation.isPending || !hasChanges}
  238. >
  239. {updateMutation.isPending ? (
  240. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  241. ) : (
  242. <Save className="w-4 h-4 mr-2" />
  243. )}
  244. Save
  245. </Button>
  246. </div>
  247. </div>
  248. </div>
  249. </div>
  250. );
  251. }