NotificationTemplateEditor.tsx 10 KB

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