ProjectPageModal.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. import { useState, useEffect } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import {
  4. X,
  5. User,
  6. Calendar,
  7. FileText,
  8. Image,
  9. Edit3,
  10. Save,
  11. ExternalLink,
  12. ChevronLeft,
  13. ChevronRight,
  14. } from 'lucide-react';
  15. import { api } from '../api/client';
  16. import { Button } from './Button';
  17. import { RichTextEditor } from './RichTextEditor';
  18. interface ProjectPageModalProps {
  19. archiveId: number;
  20. archiveName?: string;
  21. onClose: () => void;
  22. }
  23. export function ProjectPageModal({ archiveId, archiveName, onClose }: ProjectPageModalProps) {
  24. const queryClient = useQueryClient();
  25. const [isEditing, setIsEditing] = useState(false);
  26. const [selectedImageIndex, setSelectedImageIndex] = useState<number | null>(null);
  27. const [editData, setEditData] = useState<{
  28. title?: string;
  29. description?: string;
  30. designer?: string;
  31. license?: string;
  32. profile_title?: string;
  33. profile_description?: string;
  34. }>({});
  35. const { data: projectPage, isLoading, error } = useQuery({
  36. queryKey: ['archive-project-page', archiveId],
  37. queryFn: () => api.getArchiveProjectPage(archiveId),
  38. });
  39. const updateMutation = useMutation({
  40. mutationFn: (data: typeof editData) => api.updateArchiveProjectPage(archiveId, data),
  41. onSuccess: () => {
  42. queryClient.invalidateQueries({ queryKey: ['archive-project-page', archiveId] });
  43. setIsEditing(false);
  44. setEditData({});
  45. },
  46. });
  47. // Handle escape key to close modal
  48. useEffect(() => {
  49. const handleKeyDown = (e: KeyboardEvent) => {
  50. if (e.key === 'Escape') {
  51. if (selectedImageIndex !== null) {
  52. setSelectedImageIndex(null);
  53. } else if (isEditing) {
  54. handleCancelEdit();
  55. } else {
  56. onClose();
  57. }
  58. }
  59. };
  60. document.addEventListener('keydown', handleKeyDown);
  61. return () => document.removeEventListener('keydown', handleKeyDown);
  62. }, [selectedImageIndex, isEditing, onClose]);
  63. // Combine all images for gallery
  64. const allImages = [
  65. ...(projectPage?.model_pictures || []),
  66. ...(projectPage?.profile_pictures || []),
  67. ];
  68. const handleStartEdit = () => {
  69. setEditData({
  70. title: projectPage?.title || '',
  71. description: projectPage?.description || '',
  72. designer: projectPage?.designer || '',
  73. license: projectPage?.license || '',
  74. profile_title: projectPage?.profile_title || '',
  75. profile_description: projectPage?.profile_description || '',
  76. });
  77. setIsEditing(true);
  78. };
  79. const handleSave = () => {
  80. updateMutation.mutate(editData);
  81. };
  82. const handleCancelEdit = () => {
  83. setIsEditing(false);
  84. setEditData({});
  85. };
  86. // Sanitize HTML content (basic XSS prevention)
  87. const sanitizeHtml = (html: string) => {
  88. // Allow basic formatting tags only
  89. const allowed = ['p', 'br', 'b', 'strong', 'i', 'em', 'u', 'a', 'ul', 'ol', 'li', 'figure', 'img'];
  90. const doc = new DOMParser().parseFromString(html, 'text/html');
  91. const clean = (node: Node): string => {
  92. if (node.nodeType === Node.TEXT_NODE) {
  93. return node.textContent || '';
  94. }
  95. if (node.nodeType === Node.ELEMENT_NODE) {
  96. const el = node as Element;
  97. const tag = el.tagName.toLowerCase();
  98. if (!allowed.includes(tag)) {
  99. // Return children content without the tag
  100. return Array.from(el.childNodes).map(clean).join('');
  101. }
  102. // Build allowed attributes
  103. let attrs = '';
  104. if (tag === 'a' && el.getAttribute('href')) {
  105. const href = el.getAttribute('href');
  106. if (href?.toLowerCase().startsWith('http')) {
  107. attrs = ` href="${href}" target="_blank" rel="noopener noreferrer"`;
  108. }
  109. }
  110. if (tag === 'img') {
  111. const src = el.getAttribute('src');
  112. // Only render img if it has a valid http(s) URL, otherwise skip entirely
  113. if (!src?.toLowerCase().startsWith('http')) {
  114. return ''; // Skip images without valid URLs
  115. }
  116. attrs = ` src="${src}" style="max-width: 100%; height: auto;"`;
  117. }
  118. const children = Array.from(el.childNodes).map(clean).join('');
  119. if (['br', 'img'].includes(tag)) {
  120. return `<${tag}${attrs} />`;
  121. }
  122. return `<${tag}${attrs}>${children}</${tag}>`;
  123. }
  124. return '';
  125. };
  126. return Array.from(doc.body.childNodes).map(clean).join('');
  127. };
  128. const hasContent = projectPage && (
  129. projectPage.title ||
  130. projectPage.description ||
  131. projectPage.designer ||
  132. projectPage.profile_title ||
  133. allImages.length > 0
  134. );
  135. // Handle backdrop click to close modal
  136. const handleBackdropClick = (e: React.MouseEvent) => {
  137. if (e.target === e.currentTarget) {
  138. onClose();
  139. }
  140. };
  141. return (
  142. <div
  143. className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4"
  144. onClick={handleBackdropClick}
  145. >
  146. <div className="bg-bambu-dark-secondary rounded-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
  147. {/* Header */}
  148. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  149. <div className="flex items-center gap-3">
  150. <FileText className="w-5 h-5 text-bambu-green" />
  151. <h2 className="text-lg font-semibold text-white">
  152. Project Page
  153. {archiveName && <span className="text-bambu-gray ml-2">- {archiveName}</span>}
  154. </h2>
  155. </div>
  156. <div className="flex items-center gap-2">
  157. {!isEditing && hasContent && (
  158. <Button variant="ghost" size="sm" onClick={handleStartEdit}>
  159. <Edit3 className="w-4 h-4 mr-1" />
  160. Edit
  161. </Button>
  162. )}
  163. {isEditing && (
  164. <>
  165. <Button variant="ghost" size="sm" onClick={handleCancelEdit}>
  166. Cancel
  167. </Button>
  168. <Button
  169. variant="primary"
  170. size="sm"
  171. onClick={handleSave}
  172. disabled={updateMutation.isPending}
  173. >
  174. <Save className="w-4 h-4 mr-1" />
  175. Save
  176. </Button>
  177. </>
  178. )}
  179. <button
  180. onClick={onClose}
  181. className="p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors"
  182. >
  183. <X className="w-5 h-5 text-bambu-gray" />
  184. </button>
  185. </div>
  186. </div>
  187. {/* Content */}
  188. <div className="flex-1 overflow-y-auto p-6">
  189. {isLoading && (
  190. <div className="flex items-center justify-center py-12">
  191. <div className="animate-spin rounded-full h-8 w-8 border-2 border-bambu-green border-t-transparent" />
  192. </div>
  193. )}
  194. {error && (
  195. <div className="text-red-400 text-center py-12">
  196. Failed to load project page data
  197. </div>
  198. )}
  199. {projectPage && !hasContent && (
  200. <div className="text-bambu-gray text-center py-12">
  201. <FileText className="w-12 h-12 mx-auto mb-4 opacity-50" />
  202. <p>No project page data found in this 3MF file.</p>
  203. <p className="text-sm mt-2">
  204. Project pages are typically included in files downloaded from MakerWorld.
  205. </p>
  206. </div>
  207. )}
  208. {projectPage && hasContent && (
  209. <div className="space-y-6">
  210. {/* Title & Designer */}
  211. <div className="space-y-4">
  212. {isEditing ? (
  213. <input
  214. type="text"
  215. value={editData.title || ''}
  216. onChange={(e) => setEditData({ ...editData, title: e.target.value })}
  217. placeholder="Title"
  218. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-4 py-2 text-white text-xl font-semibold"
  219. />
  220. ) : (
  221. projectPage.title && (
  222. <h3 className="text-xl font-semibold text-white">{projectPage.title}</h3>
  223. )
  224. )}
  225. <div className="flex flex-wrap gap-4 text-sm">
  226. {isEditing ? (
  227. <div className="flex items-center gap-2">
  228. <User className="w-4 h-4 text-bambu-gray" />
  229. <input
  230. type="text"
  231. value={editData.designer || ''}
  232. onChange={(e) => setEditData({ ...editData, designer: e.target.value })}
  233. placeholder="Designer"
  234. className="bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"
  235. />
  236. </div>
  237. ) : (
  238. projectPage.designer && (
  239. <div className="flex items-center gap-2 text-bambu-gray">
  240. <User className="w-4 h-4" />
  241. <span>{projectPage.designer}</span>
  242. {projectPage.designer_user_id && (
  243. <a
  244. href={`https://makerworld.com/en/@${projectPage.designer_user_id}`}
  245. target="_blank"
  246. rel="noopener noreferrer"
  247. className="text-bambu-green hover:underline"
  248. >
  249. <ExternalLink className="w-3 h-3" />
  250. </a>
  251. )}
  252. </div>
  253. )
  254. )}
  255. {projectPage.creation_date && (
  256. <div className="flex items-center gap-2 text-bambu-gray">
  257. <Calendar className="w-4 h-4" />
  258. <span>{projectPage.creation_date}</span>
  259. </div>
  260. )}
  261. {isEditing ? (
  262. <div className="flex items-center gap-2">
  263. <FileText className="w-4 h-4 text-bambu-gray" />
  264. <input
  265. type="text"
  266. value={editData.license || ''}
  267. onChange={(e) => setEditData({ ...editData, license: e.target.value })}
  268. placeholder="License"
  269. className="bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"
  270. />
  271. </div>
  272. ) : (
  273. projectPage.license && (
  274. <div className="flex items-center gap-2 text-bambu-gray">
  275. <FileText className="w-4 h-4" />
  276. <span>{projectPage.license}</span>
  277. </div>
  278. )
  279. )}
  280. {projectPage.origin && (
  281. <span className="px-2 py-0.5 bg-bambu-dark rounded text-bambu-gray">
  282. {projectPage.origin}
  283. </span>
  284. )}
  285. </div>
  286. </div>
  287. {/* Description */}
  288. {(projectPage.description || isEditing) && (
  289. <div className="space-y-2">
  290. <h4 className="text-sm font-medium text-bambu-gray uppercase tracking-wide">
  291. Description
  292. </h4>
  293. {isEditing ? (
  294. <RichTextEditor
  295. content={editData.description || ''}
  296. onChange={(html) => setEditData({ ...editData, description: html })}
  297. placeholder="Enter description..."
  298. />
  299. ) : (
  300. <div
  301. className="prose prose-invert prose-sm max-w-none text-bambu-gray-light"
  302. dangerouslySetInnerHTML={{
  303. __html: sanitizeHtml(projectPage.description || ''),
  304. }}
  305. />
  306. )}
  307. </div>
  308. )}
  309. {/* Profile Info */}
  310. {(projectPage.profile_title || projectPage.profile_description || isEditing) && (
  311. <div className="space-y-2 p-4 bg-bambu-dark rounded-lg">
  312. <h4 className="text-sm font-medium text-bambu-gray uppercase tracking-wide">
  313. Print Profile
  314. </h4>
  315. {isEditing ? (
  316. <div className="space-y-2">
  317. <input
  318. type="text"
  319. value={editData.profile_title || ''}
  320. onChange={(e) => setEditData({ ...editData, profile_title: e.target.value })}
  321. placeholder="Profile Title"
  322. className="w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-white"
  323. />
  324. <RichTextEditor
  325. content={editData.profile_description || ''}
  326. onChange={(html) => setEditData({ ...editData, profile_description: html })}
  327. placeholder="Profile description..."
  328. />
  329. </div>
  330. ) : (
  331. <>
  332. {projectPage.profile_title && (
  333. <p className="text-white font-medium">{projectPage.profile_title}</p>
  334. )}
  335. {projectPage.profile_description && (
  336. <div
  337. className="prose prose-invert prose-sm max-w-none text-bambu-gray-light"
  338. dangerouslySetInnerHTML={{
  339. __html: sanitizeHtml(projectPage.profile_description),
  340. }}
  341. />
  342. )}
  343. {projectPage.profile_user_name && (
  344. <p className="text-sm text-bambu-gray">
  345. by {projectPage.profile_user_name}
  346. </p>
  347. )}
  348. </>
  349. )}
  350. </div>
  351. )}
  352. {/* Image Gallery */}
  353. {allImages.length > 0 && (
  354. <div className="space-y-2">
  355. <h4 className="text-sm font-medium text-bambu-gray uppercase tracking-wide flex items-center gap-2">
  356. <Image className="w-4 h-4" />
  357. Images ({allImages.length})
  358. </h4>
  359. <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2">
  360. {allImages.map((img, index) => (
  361. <button
  362. key={img.path}
  363. onClick={() => setSelectedImageIndex(index)}
  364. className="aspect-square rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors"
  365. >
  366. <img
  367. src={img.url}
  368. alt={img.name}
  369. className="w-full h-full object-cover"
  370. />
  371. </button>
  372. ))}
  373. </div>
  374. </div>
  375. )}
  376. {/* MakerWorld Link */}
  377. {projectPage.design_model_id && (
  378. <div className="pt-4 border-t border-bambu-dark-tertiary">
  379. <a
  380. href={`https://makerworld.com/en/models/${projectPage.design_model_id}`}
  381. target="_blank"
  382. rel="noopener noreferrer"
  383. className="inline-flex items-center gap-2 text-bambu-green hover:underline"
  384. >
  385. <ExternalLink className="w-4 h-4" />
  386. View on MakerWorld
  387. </a>
  388. </div>
  389. )}
  390. </div>
  391. )}
  392. </div>
  393. </div>
  394. {/* Image Lightbox */}
  395. {selectedImageIndex !== null && allImages[selectedImageIndex] && (
  396. <div
  397. className="fixed inset-0 bg-black/90 flex items-center justify-center z-60"
  398. onClick={() => setSelectedImageIndex(null)}
  399. >
  400. <button
  401. onClick={(e) => {
  402. e.stopPropagation();
  403. setSelectedImageIndex(Math.max(0, selectedImageIndex - 1));
  404. }}
  405. disabled={selectedImageIndex === 0}
  406. className="absolute left-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary disabled:opacity-30"
  407. >
  408. <ChevronLeft className="w-6 h-6 text-white" />
  409. </button>
  410. <img
  411. src={allImages[selectedImageIndex].url}
  412. alt={allImages[selectedImageIndex].name}
  413. className="max-w-[90vw] max-h-[90vh] object-contain"
  414. onClick={(e) => e.stopPropagation()}
  415. />
  416. <button
  417. onClick={(e) => {
  418. e.stopPropagation();
  419. setSelectedImageIndex(Math.min(allImages.length - 1, selectedImageIndex + 1));
  420. }}
  421. disabled={selectedImageIndex === allImages.length - 1}
  422. className="absolute right-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary disabled:opacity-30"
  423. >
  424. <ChevronRight className="w-6 h-6 text-white" />
  425. </button>
  426. <button
  427. onClick={() => setSelectedImageIndex(null)}
  428. className="absolute top-4 right-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary"
  429. >
  430. <X className="w-6 h-6 text-white" />
  431. </button>
  432. <div className="absolute bottom-4 text-white text-sm">
  433. {selectedImageIndex + 1} / {allImages.length}
  434. </div>
  435. </div>
  436. )}
  437. </div>
  438. );
  439. }