MakerworldPage.tsx 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. import { useEffect, useMemo, useState } from 'react';
  2. import DOMPurify from 'dompurify';
  3. import { Link } from 'react-router-dom';
  4. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  5. import { useTranslation } from 'react-i18next';
  6. import { AlertCircle, ArrowRight, Check, ChevronLeft, ChevronRight, Download, ExternalLink, FolderOpen, Globe, Images, Loader2, Trash2, X } from 'lucide-react';
  7. import {
  8. api,
  9. type MakerworldImportResponse,
  10. type MakerworldRecentImport,
  11. type MakerworldResolvedModel,
  12. } from '../api/client';
  13. import { openInSlicer, resolveDesktopSlicer, type SlicerType } from '../utils/slicer';
  14. import { Button } from '../components/Button';
  15. import { Card, CardContent, CardHeader } from '../components/Card';
  16. import { ConfirmModal } from '../components/ConfirmModal';
  17. import { SliceModal, type SliceSource } from '../components/SliceModal';
  18. import { Cog } from 'lucide-react';
  19. import { useAuth } from '../contexts/AuthContext';
  20. import { useToast } from '../contexts/ToastContext';
  21. import { useUiSettings } from '../hooks/useUiSettings';
  22. // MakerWorld's API payloads are passed through as opaque dicts; these helpers
  23. // pull known fields out in a type-safe way so a missing/renamed field shows
  24. // up as an empty string rather than crashing the render.
  25. function pickString(obj: Record<string, unknown> | undefined, key: string): string {
  26. const value = obj?.[key];
  27. return typeof value === 'string' ? value : '';
  28. }
  29. // Rewrite MakerWorld CDN URLs inside HTML content (design summary, etc.) to
  30. // use Bambuddy's thumbnail proxy. MakerWorld summaries are authored HTML and
  31. // commonly contain ``<img src="https://makerworld.bblmw.com/...">`` tags;
  32. // Bambuddy's img-src CSP only allows ``'self' data: blob:``, so these would
  33. // otherwise be blocked. Pairs with ``proxyCdn`` below for explicit <img>
  34. // renders.
  35. function proxyCdnUrlsInHtml(html: string): string {
  36. return html.replace(
  37. /(https?:\/\/(?:makerworld|public-cdn)\.bblmw\.com\/[^\s"']+)/gi,
  38. (match) => `/api/v1/makerworld/thumbnail?url=${encodeURIComponent(match)}`,
  39. );
  40. }
  41. // MakerWorld CDN images can't be hotlinked — Bambuddy's img-src CSP blocks
  42. // external hosts. Route them through the /makerworld/thumbnail proxy.
  43. // Empty string in → empty string out so the ``{coverUrl && ...}`` checks
  44. // in the render keep short-circuiting.
  45. function proxyCdn(url: string): string {
  46. if (!url) return '';
  47. if (!/^https?:\/\/(makerworld|public-cdn)\.bblmw\.com\//i.test(url)) return url;
  48. return `/api/v1/makerworld/thumbnail?url=${encodeURIComponent(url)}`;
  49. }
  50. function pickNumber(obj: Record<string, unknown> | undefined, key: string): number | null {
  51. const value = obj?.[key];
  52. return typeof value === 'number' ? value : null;
  53. }
  54. function pickObject(obj: Record<string, unknown> | undefined, key: string): Record<string, unknown> | undefined {
  55. const value = obj?.[key];
  56. return value && typeof value === 'object' && !Array.isArray(value)
  57. ? (value as Record<string, unknown>)
  58. : undefined;
  59. }
  60. // Depth-first flatten of the library folder tree so it can be rendered in a
  61. // single <select>. Each entry carries its ``depth`` so the UI can indent the
  62. // option label.
  63. type FlatFolder = { folder: import('../api/client').LibraryFolderTree; depth: number };
  64. function flattenFolderTree(
  65. tree: import('../api/client').LibraryFolderTree,
  66. depth = 0,
  67. out: FlatFolder[] = [],
  68. ): FlatFolder[] {
  69. out.push({ folder: tree, depth });
  70. for (const child of tree.children ?? []) {
  71. flattenFolderTree(child, depth + 1, out);
  72. }
  73. return out;
  74. }
  75. // Time-based phase heuristic for the import progress indicator. The backend
  76. // does the work as one synchronous HTTP request (no streaming progress), so
  77. // we guess the phase from elapsed wall-clock time. These numbers reflect
  78. // typical 3MF downloads (5–30 s total, dominated by the S3 GET):
  79. // 0–1 s: metadata fetch (fast, just the iot-service + design lookups)
  80. // 1–<end> s: downloading the 3MF bytes
  81. // The last moment also flashes "Saving…" but we can't actually observe
  82. // the save step on the wire, so we let the download phase run until the
  83. // mutation resolves.
  84. function phaseLabelForElapsed(elapsedSec: number, t: (k: string) => string): string {
  85. if (elapsedSec < 1) return t('makerworld.phaseResolving');
  86. return t('makerworld.phaseDownloading');
  87. }
  88. function useElapsedSeconds(active: boolean): number {
  89. const [elapsed, setElapsed] = useState(0);
  90. useEffect(() => {
  91. if (!active) {
  92. setElapsed(0);
  93. return;
  94. }
  95. const start = Date.now();
  96. const tick = () => setElapsed(Math.floor((Date.now() - start) / 1000));
  97. tick();
  98. const id = window.setInterval(tick, 1000);
  99. return () => window.clearInterval(id);
  100. }, [active]);
  101. return elapsed;
  102. }
  103. /** ``embedded`` renders it as the MakerWorld tab of the Model Sources page,
  104. * which brings its own page title. */
  105. export function MakerworldPage({ embedded = false }: { embedded?: boolean } = {}) {
  106. const { t } = useTranslation();
  107. const { hasPermission } = useAuth();
  108. const { showToast } = useToast();
  109. const queryClient = useQueryClient();
  110. const canImport = hasPermission('makerworld:import');
  111. const [urlInput, setUrlInput] = useState('');
  112. const [resolved, setResolved] = useState<MakerworldResolvedModel | null>(null);
  113. // Selected target folder. ``null`` means "let the backend use the default
  114. // MakerWorld folder" (auto-created if missing). Any other value is the id
  115. // of a user-selected folder; external read-only folders are filtered out
  116. // of the picker because the backend rejects those with 403.
  117. const [selectedFolderId, setSelectedFolderId] = useState<number | null>(null);
  118. // Bulk-import progress. ``null`` when idle; ``{current, total}`` while
  119. // the "Import all" button is walking through ``instances[]``.
  120. const [bulkProgress, setBulkProgress] = useState<{ current: number; total: number } | null>(null);
  121. // Pending delete confirmation. ``null`` when no modal is open; otherwise
  122. // carries the ids/filename needed to run the delete when the user confirms.
  123. // Kept separate from the mutation state so the modal renders as soon as the
  124. // user clicks the trash icon, not only while the request is in flight.
  125. const [pendingDelete, setPendingDelete] = useState<
  126. | { libraryFileId: number; profileId: number; filename: string }
  127. | null
  128. >(null);
  129. // Lightbox state for the image gallery. When ``null`` the lightbox is closed.
  130. // ``images`` is the set of {name, url} captured at click-time (we don't mutate
  131. // it while the lightbox is open, so navigation is stable even if the underlying
  132. // instance array changes underneath).
  133. const [lightbox, setLightbox] = useState<
  134. | { images: Array<{ name: string; url: string }>; index: number }
  135. | null
  136. >(null);
  137. // Which URL the current ``resolved`` state was fetched for. When the user
  138. // edits ``urlInput`` away from this, we clear ``resolved`` — otherwise the
  139. // stale preview stays on screen and the Import button would submit the
  140. // *previous* model_id, dedupe'ing against the wrong row.
  141. const [resolvedForUrl, setResolvedForUrl] = useState<string>('');
  142. // All successful imports done during this resolved-model session, keyed
  143. // by the plate's ``profileId``. Used to render inline 'View in Library'
  144. // / 'Open in slicer' buttons directly on each imported plate row so the
  145. // user sees the follow-up actions right where they clicked (instead of
  146. // having to scroll back to a top-of-page card). Cleared when the user
  147. // resolves a fresh URL or edits the pasted URL.
  148. const [importsByProfile, setImportsByProfile] = useState<
  149. Record<number, MakerworldImportResponse>
  150. >({});
  151. const statusQuery = useQuery({
  152. queryKey: ['makerworld-status'],
  153. queryFn: () => api.getMakerworldStatus(),
  154. });
  155. const foldersQuery = useQuery({
  156. queryKey: ['library-folders'],
  157. queryFn: () => api.getLibraryFolders(),
  158. });
  159. const recentQuery = useQuery({
  160. queryKey: ['makerworld-recent-imports'],
  161. queryFn: () => api.getMakerworldRecentImports(10),
  162. });
  163. const settingsQuery = useUiSettings();
  164. // MakerWorld plates are unsliced project files — they can't be sent
  165. // directly to a printer. The "slice in slicer" action below imports the
  166. // 3MF and hands it to the user's configured slicer; from there the
  167. // slicer's own "send to printer" flow takes over.
  168. // API-sidecar slicer (in-app SliceModal) is `preferred_slicer`; desktop
  169. // "Open in Slicer" handoff respects the `open_in_slicer` override, falling
  170. // back to `preferred_slicer` when unset (#1329). The button label shows
  171. // whichever slicer this button actually drives — depends on useSlicerApi.
  172. const useSlicerApi = settingsQuery.data?.use_slicer_api ?? false;
  173. const apiSlicer: SlicerType = settingsQuery.data?.preferred_slicer || 'bambu_studio';
  174. const desktopSlicer: SlicerType = resolveDesktopSlicer(settingsQuery.data?.open_in_slicer, settingsQuery.data?.preferred_slicer);
  175. const preferredSlicer: SlicerType = useSlicerApi ? apiSlicer : desktopSlicer;
  176. const preferredSlicerName =
  177. preferredSlicer === 'orcaslicer' ? 'OrcaSlicer' : 'Bambu Studio';
  178. // Slice-via-API modal source. When set, the SliceModal is shown for the
  179. // referenced library file; it covers MakerWorld's "Slice in <Slicer>" /
  180. // "Open in Slicer" actions whenever the user has Use Slicer API enabled.
  181. const [sliceModalSource, setSliceModalSource] = useState<SliceSource | null>(null);
  182. const openSliceForLibraryFile = (libraryFileId: number, filename: string) => {
  183. setSliceModalSource({ kind: 'libraryFile', id: libraryFileId, filename });
  184. };
  185. const resolveMutation = useMutation({
  186. mutationFn: (url: string) => api.resolveMakerworldUrl(url),
  187. onSuccess: (data, url) => {
  188. setResolved(data);
  189. setResolvedForUrl(url);
  190. // Fresh resolve — clear any success card from a previous model.
  191. setImportsByProfile({});
  192. },
  193. onError: (err: Error) => showToast(err.message || t('makerworld.errors.resolveFailed'), 'error'),
  194. });
  195. // URL-change detection: if the user edits the URL input away from what
  196. // ``resolved`` was fetched for, drop the stale preview so they can't
  197. // accidentally import the previous model. Whitespace-only differences
  198. // don't count.
  199. useEffect(() => {
  200. if (resolved !== null && urlInput.trim() !== resolvedForUrl.trim()) {
  201. setResolved(null);
  202. setResolvedForUrl('');
  203. setImportsByProfile({});
  204. }
  205. }, [urlInput, resolved, resolvedForUrl]);
  206. const importMutation = useMutation({
  207. mutationFn: ({ instanceId, profileId }: { instanceId: number; profileId: number | null }) =>
  208. api.importMakerworldInstance(resolved?.model_id ?? 0, instanceId, profileId, selectedFolderId),
  209. onSuccess: (data) => {
  210. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  211. // Backend auto-creates a "MakerWorld" folder on first import; refresh
  212. // the folder tree so users see it without having to reload the page.
  213. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  214. // Track by profile_id so each plate's row can render its own inline
  215. // follow-up buttons even after multiple imports in the same session.
  216. if (data.profile_id) {
  217. setImportsByProfile((prev) => ({ ...prev, [data.profile_id!]: data }));
  218. }
  219. showToast(
  220. data.was_existing ? t('makerworld.alreadyInLibrary') : t('makerworld.importSuccess', { filename: data.filename }),
  221. 'success',
  222. );
  223. },
  224. onError: (err: Error) => showToast(err.message || t('makerworld.errors.downloadFailed'), 'error'),
  225. });
  226. // "Print Now" is a two-step mutation: import to library, then open the
  227. // existing PrintModal. We chain manually rather than composing mutations
  228. // so the modal gets the library_file_id the moment it lands.
  229. // Per-plate delete: removes a previously-imported plate from the library
  230. // (file + DB row). Used by the inline trash-icon button on imported plates
  231. // so users can quickly undo an accidental import without navigating to
  232. // File Manager. ``profileId`` is only used for local state cleanup.
  233. const deleteImportMutation = useMutation({
  234. mutationFn: ({ libraryFileId }: { libraryFileId: number; profileId: number }) =>
  235. api.deleteLibraryFile(libraryFileId),
  236. onSuccess: (_data, { profileId }) => {
  237. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  238. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  239. queryClient.invalidateQueries({ queryKey: ['makerworld-recent-imports'] });
  240. setImportsByProfile((prev) => {
  241. const next = { ...prev };
  242. delete next[profileId];
  243. return next;
  244. });
  245. setPendingDelete(null);
  246. showToast(t('makerworld.importDeleted'), 'success');
  247. },
  248. onError: (err: Error) => {
  249. setPendingDelete(null);
  250. showToast(err.message || t('makerworld.errors.deleteFailed'), 'error');
  251. },
  252. });
  253. // "Slice in BambuStudio / OrcaSlicer" — imports the plate then hands the
  254. // file off to the configured slicer. MakerWorld plates are unsliced source
  255. // files, so we can't send them straight to the printer; the slicer is the
  256. // user's actual "I want to print this" destination. Mirrors MakerWorld's
  257. // own "Download and Open" button behaviour.
  258. const sliceMutation = useMutation({
  259. mutationFn: ({ instanceId, profileId }: { instanceId: number; profileId: number | null }) =>
  260. api.importMakerworldInstance(resolved?.model_id ?? 0, instanceId, profileId, selectedFolderId),
  261. onSuccess: async (data: MakerworldImportResponse) => {
  262. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  263. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  264. queryClient.invalidateQueries({ queryKey: ['makerworld-recent-imports'] });
  265. if (data.profile_id) {
  266. setImportsByProfile((prev) => ({ ...prev, [data.profile_id!]: data }));
  267. }
  268. // After import, branch on the user's slicer-API preference: API mode
  269. // opens the in-app SliceModal; URI mode hands the file off to the
  270. // local slicer GUI (the historical behavior).
  271. if (useSlicerApi) {
  272. openSliceForLibraryFile(data.library_file_id, data.filename);
  273. } else {
  274. await handleOpenInSlicer(data.library_file_id, data.filename, preferredSlicer);
  275. }
  276. },
  277. onError: (err: Error) => showToast(err.message || t('makerworld.errors.downloadFailed'), 'error'),
  278. });
  279. // Tick while an import is in-flight so we can show "Downloading… (12 s)"
  280. // instead of a bare spinner. Only one import runs at a time (bulk is
  281. // sequential), so a single counter covers both the per-row button label
  282. // and the bulk-import progress label.
  283. const importElapsed = useElapsedSeconds(importMutation.isPending || sliceMutation.isPending);
  284. const importPhaseLabel = phaseLabelForElapsed(importElapsed, t);
  285. const handleResolve = (e?: React.FormEvent) => {
  286. e?.preventDefault();
  287. const trimmed = urlInput.trim();
  288. if (!trimmed) return;
  289. resolveMutation.mutate(trimmed);
  290. };
  291. // Keyboard navigation for the lightbox (Escape closes, arrows navigate).
  292. useEffect(() => {
  293. if (!lightbox) return;
  294. const handler = (e: KeyboardEvent) => {
  295. if (e.key === 'Escape') setLightbox(null);
  296. else if (e.key === 'ArrowLeft') {
  297. setLightbox((prev) => (prev && prev.index > 0 ? { ...prev, index: prev.index - 1 } : prev));
  298. } else if (e.key === 'ArrowRight') {
  299. setLightbox((prev) =>
  300. prev && prev.index < prev.images.length - 1 ? { ...prev, index: prev.index + 1 } : prev,
  301. );
  302. }
  303. };
  304. window.addEventListener('keydown', handler);
  305. return () => window.removeEventListener('keydown', handler);
  306. }, [lightbox]);
  307. // Extract the gallery images for a plate. MakerWorld returns an ``instance.pictures``
  308. // array of {name, url, isRealLifePhoto}; falls back to the single ``cover`` URL
  309. // when pictures is empty so the lightbox still shows something.
  310. const getInstanceImages = (inst: Record<string, unknown>): Array<{ name: string; url: string }> => {
  311. const pictures = Array.isArray(inst['pictures']) ? (inst['pictures'] as unknown[]) : [];
  312. const fromPictures = pictures
  313. .filter((p): p is Record<string, unknown> => p !== null && typeof p === 'object')
  314. .map((p) => ({ name: pickString(p, 'name') || 'image', url: pickString(p, 'url') }))
  315. .filter((p) => p.url);
  316. if (fromPictures.length > 0) return fromPictures;
  317. const cover = pickString(inst, 'cover');
  318. return cover ? [{ name: 'cover', url: cover }] : [];
  319. };
  320. // "Import all plates" — walks through ``instances[]`` sequentially (not
  321. // in parallel) so we don't hammer the Bambu API. Skips plates that have
  322. // already been imported in this session. On per-plate failure, shows the
  323. // error toast but continues with the next plate (partial success is
  324. // better than a whole-batch abort).
  325. const handleImportAll = async () => {
  326. if (!resolved) return;
  327. const plates = resolved.instances.filter((inst) => {
  328. const pid = pickNumber(inst, 'profileId');
  329. return pid !== null && !importsByProfile[pid];
  330. });
  331. if (plates.length === 0) return;
  332. setBulkProgress({ current: 0, total: plates.length });
  333. try {
  334. for (let i = 0; i < plates.length; i += 1) {
  335. const inst = plates[i];
  336. const instanceId = pickNumber(inst, 'id');
  337. const profileId = pickNumber(inst, 'profileId');
  338. if (instanceId === null || profileId === null) continue;
  339. setBulkProgress({ current: i + 1, total: plates.length });
  340. try {
  341. await importMutation.mutateAsync({ instanceId, profileId });
  342. } catch {
  343. // Per-plate failure already surfaces a toast via ``onError``; we
  344. // just continue so a flaky single profile doesn't kill the batch.
  345. }
  346. }
  347. } finally {
  348. setBulkProgress(null);
  349. }
  350. };
  351. const handleOpenInSlicer = async (
  352. fileId: number,
  353. filename: string,
  354. slicer: 'bambu_studio' | 'orcaslicer',
  355. ) => {
  356. // Slicer protocol handlers can't send Authorization headers, so we mint a
  357. // short-lived, file-bound path-embedded token and hand the slicer that URL
  358. // instead of the auth-gated /download endpoint. Mirrors ArchivesPage's
  359. // ``openInSlicerWithToken`` pattern. The token stays valid for its whole
  360. // TTL rather than for one fetch -- the slicer is a separate process and
  361. // may request the URL more than once (#3029).
  362. try {
  363. const { token } = await api.createLibrarySlicerToken(fileId);
  364. const path = api.getLibrarySlicerDownloadUrl(fileId, token, filename);
  365. openInSlicer(`${window.location.origin}${path}`, slicer);
  366. } catch {
  367. // Auth-disabled fallback — the plain download URL is already public
  368. // in that case.
  369. const path = api.getLibraryFileDownloadUrl(fileId);
  370. openInSlicer(`${window.location.origin}${path}`, slicer);
  371. }
  372. };
  373. const design = resolved?.design;
  374. const creator = pickObject(design, 'designCreator');
  375. const instances = resolved?.instances ?? [];
  376. const alreadyImported = (resolved?.already_imported_library_ids.length ?? 0) > 0;
  377. // Only block Print Now / Import actions on an import-capable login.
  378. // Browse/resolve works anonymously.
  379. const canDownload = statusQuery.data?.can_download ?? false;
  380. // A stored token Bambu has rejected downloads nothing, but it isn't "no
  381. // token" either — saying "sign in" to someone who believes they already are
  382. // is what made this so confusing. Name the actual state.
  383. const signInExpired = statusQuery.data?.sign_in_expired ?? false;
  384. const coverUrl = useMemo(() => pickString(design, 'coverUrl'), [design]);
  385. const title = pickString(design, 'title');
  386. const summaryHtml = pickString(design, 'summary');
  387. const license = pickString(design, 'license');
  388. const downloadCount = pickNumber(design, 'downloadCount');
  389. return (
  390. <div className={embedded ? 'space-y-6' : 'p-4 md:p-8 max-w-screen-2xl space-y-6'}>
  391. {embedded ? (
  392. <p className="text-bambu-gray">{t('makerworld.description')}</p>
  393. ) : (
  394. <div>
  395. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  396. <Globe className="w-7 h-7 text-bambu-green" />
  397. {t('makerworld.title')}
  398. </h1>
  399. <p className="text-bambu-gray mt-1">
  400. {t('makerworld.description')}
  401. </p>
  402. </div>
  403. )}
  404. {/* Two-column layout: main flow on the left, sticky "Recent imports"
  405. sidebar on the right at lg+. Collapses to single column on narrow
  406. screens (tablet/phone), with the sidebar tucked below the main flow. */}
  407. <div className="grid gap-6 lg:grid-cols-[1fr_20rem]">
  408. <div className="space-y-6 min-w-0">
  409. {!canDownload && (
  410. <Card className="border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-900/20">
  411. <CardContent>
  412. <div className="flex items-start gap-3 py-2">
  413. <AlertCircle className="w-5 h-5 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" />
  414. <div className="text-sm">
  415. <p className="font-medium text-amber-900 dark:text-amber-100">
  416. {signInExpired
  417. ? t('makerworld.signInExpiredTitle')
  418. : t('makerworld.signInRequiredTitle')}
  419. </p>
  420. <p className="text-amber-800 dark:text-amber-200 mt-1">
  421. {signInExpired
  422. ? t('makerworld.signInExpiredBody')
  423. : t('makerworld.signInRequiredBody')}{' '}
  424. <Link to="/profiles" className="underline">
  425. {t('makerworld.openCloudSettings')}
  426. </Link>
  427. </p>
  428. </div>
  429. </div>
  430. </CardContent>
  431. </Card>
  432. )}
  433. <Card>
  434. <CardHeader>
  435. <h2 className="text-lg font-semibold">{t('makerworld.pasteUrlHeader')}</h2>
  436. </CardHeader>
  437. <CardContent>
  438. <form onSubmit={handleResolve} className="flex gap-2">
  439. <input
  440. type="text"
  441. value={urlInput}
  442. onChange={(e) => setUrlInput(e.target.value)}
  443. placeholder={t('makerworld.pasteUrlPlaceholder')}
  444. className="flex-1 min-w-0 px-3 py-2 border rounded bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-700"
  445. autoComplete="off"
  446. />
  447. <Button
  448. type="submit"
  449. variant="primary"
  450. disabled={!urlInput.trim() || resolveMutation.isPending}
  451. >
  452. {resolveMutation.isPending ? (
  453. <Loader2 className="w-4 h-4 animate-spin" />
  454. ) : (
  455. <ArrowRight className="w-4 h-4" />
  456. )}
  457. <span className="ml-2">{t('makerworld.resolveButton')}</span>
  458. </Button>
  459. </form>
  460. </CardContent>
  461. </Card>
  462. {resolved && (
  463. <Card>
  464. <CardContent>
  465. <div className="flex gap-4 py-2">
  466. {coverUrl && (
  467. <img
  468. src={proxyCdn(coverUrl)}
  469. alt={title}
  470. className="w-32 h-32 object-cover rounded"
  471. loading="lazy"
  472. />
  473. )}
  474. <div className="flex-1 min-w-0">
  475. <h3 className="text-xl font-semibold truncate">{title || t('makerworld.untitledModel')}</h3>
  476. {creator && (
  477. <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
  478. {t('makerworld.byCreator', { name: pickString(creator, 'name') })}
  479. </p>
  480. )}
  481. <div className="flex flex-wrap gap-3 mt-2 text-xs text-gray-500 dark:text-gray-400">
  482. {downloadCount !== null && (
  483. <span>{t('makerworld.downloadsCount', { count: downloadCount })}</span>
  484. )}
  485. {license && <span>{t('makerworld.licensePrefix')}: {license}</span>}
  486. {alreadyImported && (
  487. <span className="inline-flex items-center gap-1 text-emerald-600 dark:text-emerald-400">
  488. <Check className="w-3 h-3" /> {t('makerworld.alreadyImported')}
  489. </span>
  490. )}
  491. </div>
  492. {summaryHtml && (
  493. <div
  494. className="mt-3 text-sm prose prose-sm max-w-none dark:prose-invert line-clamp-3"
  495. // Two-stage processing:
  496. // 1. ``proxyCdnUrlsInHtml`` rewrites <img src="…bblmw.com…">
  497. // so CSP allows the image load.
  498. // 2. ``DOMPurify.sanitize`` strips scripts, event handlers,
  499. // javascript: URLs, and other XSS vectors. MakerWorld
  500. // summaries are user-authored and cannot be trusted.
  501. dangerouslySetInnerHTML={{
  502. __html: DOMPurify.sanitize(proxyCdnUrlsInHtml(summaryHtml)),
  503. }}
  504. />
  505. )}
  506. {resolved && (
  507. <a
  508. href={`https://makerworld.com/models/${resolved.model_id}${resolved.profile_id ? `#profileId-${resolved.profile_id}` : ''}`}
  509. target="_blank"
  510. rel="noopener noreferrer"
  511. className="mt-3 inline-flex items-center gap-1 text-xs text-brand-500 hover:underline"
  512. >
  513. <ExternalLink className="w-3 h-3" /> {t('makerworld.openOnMakerworld')}
  514. </a>
  515. )}
  516. </div>
  517. </div>
  518. </CardContent>
  519. </Card>
  520. )}
  521. {resolved && instances.length > 0 && (
  522. <Card>
  523. <CardHeader>
  524. <div className="flex flex-wrap items-center justify-between gap-3">
  525. <h2 className="text-lg font-semibold">{t('makerworld.platesHeader', { count: instances.length })}</h2>
  526. <div className="flex flex-wrap items-center gap-2">
  527. <label className="text-xs text-gray-600 dark:text-gray-400">
  528. {t('makerworld.importTo')}
  529. </label>
  530. <select
  531. value={selectedFolderId ?? ''}
  532. onChange={(e) => setSelectedFolderId(e.target.value ? Number(e.target.value) : null)}
  533. className="text-sm px-2 py-1 border rounded bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-700"
  534. disabled={bulkProgress !== null}
  535. >
  536. <option value="">{t('makerworld.folderAuto')}</option>
  537. {(foldersQuery.data ?? [])
  538. .filter((f) => !(f.is_external && f.external_readonly))
  539. .flatMap((f) => flattenFolderTree(f))
  540. .map(({ folder, depth }) => (
  541. // Listed for the tree's shape; only own and shared folders take imports (#3201).
  542. <option key={folder.id} value={folder.id} disabled={folder.can_write === false}>
  543. {`${'— '.repeat(depth)}${folder.name}`}
  544. </option>
  545. ))}
  546. </select>
  547. <Button
  548. variant="primary"
  549. size="sm"
  550. disabled={
  551. !canImport ||
  552. !canDownload ||
  553. bulkProgress !== null ||
  554. importMutation.isPending ||
  555. sliceMutation.isPending
  556. }
  557. onClick={handleImportAll}
  558. >
  559. {bulkProgress !== null ? (
  560. <>
  561. <Loader2 className="w-4 h-4 animate-spin" />
  562. <span className="ml-2">
  563. {t('makerworld.importAllProgress', { current: bulkProgress.current, total: bulkProgress.total })}
  564. {importElapsed > 0 && ` · ${importPhaseLabel} · ${importElapsed}s`}
  565. </span>
  566. </>
  567. ) : (
  568. <>
  569. <Download className="w-4 h-4" />
  570. <span className="ml-2">{t('makerworld.importAll')}</span>
  571. </>
  572. )}
  573. </Button>
  574. </div>
  575. </div>
  576. </CardHeader>
  577. <CardContent>
  578. <div className="grid gap-3">
  579. {instances.map((inst, idx) => {
  580. const instanceId = pickNumber(inst, 'id');
  581. const profileId = pickNumber(inst, 'profileId');
  582. const instanceTitle = pickString(inst, 'title');
  583. const cover = pickString(inst, 'cover');
  584. const materialCnt = pickNumber(inst, 'materialCnt');
  585. const needAms = inst?.['needAms'] === true;
  586. const downloadsOnInstance = pickNumber(inst, 'downloadCount');
  587. // Primary printer the file was sliced for (devProductName,
  588. // e.g. "A1") + the alt-compatibility list MakerWorld marks.
  589. // Both come from the design endpoint's per-instance
  590. // extention.modelInfo, merged into the instance by the
  591. // backend resolve route. The "compat" list is informational
  592. // — Bambuddy can't actually re-slice across printers, but
  593. // the user gets to see what they're picking.
  594. const compat = (inst?.['compatibility'] as { devProductName?: string } | null) ?? null;
  595. const others = (inst?.['otherCompatibility'] as Array<{ devProductName?: string }> | null) ?? null;
  596. const primaryPrinter = compat?.devProductName ?? null;
  597. const otherPrinters: string[] = Array.isArray(others)
  598. ? others.map((o) => o?.devProductName ?? '').filter(Boolean)
  599. : [];
  600. if (instanceId == null) return null;
  601. const isImporting = importMutation.isPending && importMutation.variables?.instanceId === instanceId;
  602. const isPrinting = sliceMutation.isPending && sliceMutation.variables?.instanceId === instanceId;
  603. const imported = profileId !== null ? importsByProfile[profileId] : undefined;
  604. return (
  605. <div
  606. key={instanceId}
  607. className="flex flex-col gap-2 p-3 border rounded border-gray-200 dark:border-gray-700"
  608. >
  609. <div className="flex gap-3 items-center">
  610. {(() => {
  611. const gallery = getInstanceImages(inst);
  612. const canOpen = gallery.length > 0;
  613. return (
  614. <button
  615. type="button"
  616. disabled={!canOpen}
  617. onClick={() => canOpen && setLightbox({ images: gallery, index: 0 })}
  618. className="relative w-16 h-16 shrink-0 rounded overflow-hidden group"
  619. aria-label={t('makerworld.openGallery')}
  620. >
  621. {cover ? (
  622. <img
  623. src={proxyCdn(cover)}
  624. alt=""
  625. className="w-16 h-16 object-cover"
  626. loading="lazy"
  627. />
  628. ) : (
  629. <div className="w-16 h-16 bg-gray-100 dark:bg-gray-800" />
  630. )}
  631. {gallery.length > 1 && (
  632. <span className="absolute bottom-0.5 right-0.5 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded flex items-center gap-1">
  633. <Images className="w-2.5 h-2.5" />
  634. {gallery.length}
  635. </span>
  636. )}
  637. </button>
  638. );
  639. })()}
  640. <div className="flex-1 min-w-0">
  641. <p className="font-medium truncate">
  642. {instanceTitle || t('makerworld.plateDefaultName', { n: idx + 1 })}
  643. </p>
  644. <div className="flex flex-wrap gap-3 text-xs text-gray-500 dark:text-gray-400 mt-1">
  645. {primaryPrinter && (
  646. <span className="font-medium text-gray-700 dark:text-gray-300">
  647. {t('makerworld.slicedFor', { printer: primaryPrinter, defaultValue: 'Sliced for {{printer}}' })}
  648. </span>
  649. )}
  650. {materialCnt !== null && (
  651. <span>{t('makerworld.materialCount', { count: materialCnt })}</span>
  652. )}
  653. {needAms && <span>{t('makerworld.amsRequired')}</span>}
  654. {downloadsOnInstance !== null && (
  655. <span>{t('makerworld.downloadsCount', { count: downloadsOnInstance })}</span>
  656. )}
  657. </div>
  658. {otherPrinters.length > 0 && (
  659. <p className="text-xs text-gray-500 dark:text-gray-400 mt-1" title={otherPrinters.join(', ')}>
  660. {t('makerworld.alsoCompatible', {
  661. printers: otherPrinters.slice(0, 6).join(', ') + (otherPrinters.length > 6 ? '…' : ''),
  662. defaultValue: 'Also marked compatible: {{printers}}',
  663. })}
  664. </p>
  665. )}
  666. </div>
  667. <div className="flex gap-2 shrink-0">
  668. <Button
  669. variant="ghost"
  670. size="sm"
  671. disabled={!canImport || !canDownload || isImporting || isPrinting || bulkProgress !== null}
  672. onClick={() => importMutation.mutate({ instanceId, profileId })}
  673. title={!canDownload ? t('makerworld.signInRequiredTitle') : undefined}
  674. >
  675. {isImporting ? (
  676. <>
  677. <Loader2 className="w-4 h-4 animate-spin" />
  678. <span className="ml-2">
  679. {importPhaseLabel}
  680. {importElapsed > 0 && ` · ${importElapsed}s`}
  681. </span>
  682. </>
  683. ) : (
  684. <>
  685. <Download className="w-4 h-4" />
  686. <span className="ml-2">{t('makerworld.importToLibrary')}</span>
  687. </>
  688. )}
  689. </Button>
  690. <Button
  691. variant="primary"
  692. size="sm"
  693. disabled={!canImport || !canDownload || isImporting || isPrinting || bulkProgress !== null}
  694. onClick={() => sliceMutation.mutate({ instanceId, profileId })}
  695. title={!canDownload ? t('makerworld.signInRequiredTitle') : undefined}
  696. >
  697. {isPrinting ? (
  698. <>
  699. <Loader2 className="w-4 h-4 animate-spin" />
  700. <span className="ml-2">
  701. {importPhaseLabel}
  702. {importElapsed > 0 && ` · ${importElapsed}s`}
  703. </span>
  704. </>
  705. ) : (
  706. <>
  707. <ExternalLink className="w-4 h-4" />
  708. <span className="ml-2">
  709. {t('makerworld.sliceIn', { slicer: preferredSlicerName })}
  710. </span>
  711. </>
  712. )}
  713. </Button>
  714. </div>
  715. </div>
  716. {imported && (
  717. <div className="flex items-center gap-2 pl-20 text-xs">
  718. <Check className="w-3.5 h-3.5 text-emerald-600 dark:text-emerald-400 shrink-0" />
  719. <span className="text-emerald-700 dark:text-emerald-300">
  720. {imported.was_existing
  721. ? t('makerworld.lastImportAlreadyInLibrary')
  722. : t('makerworld.lastImportSuccess')}
  723. </span>
  724. <Button
  725. variant="ghost"
  726. size="sm"
  727. onClick={() => {
  728. const target = imported.folder_id
  729. ? `/files?folder=${imported.folder_id}`
  730. : '/files';
  731. window.location.assign(target);
  732. }}
  733. >
  734. <FolderOpen className="w-3.5 h-3.5" />
  735. <span className="ml-1.5">{t('makerworld.viewInLibrary')}</span>
  736. </Button>
  737. {useSlicerApi ? (
  738. <Button
  739. variant="ghost"
  740. size="sm"
  741. onClick={() => openSliceForLibraryFile(imported.library_file_id, imported.filename)}
  742. >
  743. <Cog className="w-3.5 h-3.5" />
  744. <span className="ml-1.5">{t('slice.action', 'Slice')}</span>
  745. </Button>
  746. ) : (
  747. <>
  748. <Button
  749. variant="ghost"
  750. size="sm"
  751. onClick={() =>
  752. handleOpenInSlicer(imported.library_file_id, imported.filename, 'bambu_studio')
  753. }
  754. >
  755. <ExternalLink className="w-3.5 h-3.5" />
  756. <span className="ml-1.5">{t('makerworld.openInBambuStudio')}</span>
  757. </Button>
  758. <Button
  759. variant="ghost"
  760. size="sm"
  761. onClick={() =>
  762. handleOpenInSlicer(imported.library_file_id, imported.filename, 'orcaslicer')
  763. }
  764. >
  765. <ExternalLink className="w-3.5 h-3.5" />
  766. <span className="ml-1.5">{t('makerworld.openInOrcaSlicer')}</span>
  767. </Button>
  768. </>
  769. )}
  770. <div className="ml-auto">
  771. <Button
  772. variant="ghost"
  773. size="sm"
  774. disabled={
  775. deleteImportMutation.isPending &&
  776. deleteImportMutation.variables?.profileId === profileId
  777. }
  778. onClick={() => {
  779. if (profileId === null) return;
  780. setPendingDelete({
  781. libraryFileId: imported.library_file_id,
  782. profileId,
  783. filename: imported.filename,
  784. });
  785. }}
  786. title={t('makerworld.deleteImport')}
  787. >
  788. {deleteImportMutation.isPending &&
  789. deleteImportMutation.variables?.profileId === profileId ? (
  790. <Loader2 className="w-3.5 h-3.5 animate-spin" />
  791. ) : (
  792. <Trash2 className="w-3.5 h-3.5 text-red-500" />
  793. )}
  794. </Button>
  795. </div>
  796. </div>
  797. )}
  798. </div>
  799. );
  800. })}
  801. </div>
  802. </CardContent>
  803. </Card>
  804. )}
  805. </div>
  806. {/* Right column — Recent imports sidebar. Sticky at lg+ so it stays
  807. reachable while browsing long plate lists. Vertical list here,
  808. not the horizontal scroll we used in the bottom-of-page layout. */}
  809. <aside className="lg:sticky lg:top-6 lg:self-start min-w-0">
  810. {recentQuery.data && recentQuery.data.length > 0 && (
  811. <Card>
  812. <CardHeader>
  813. <h2 className="text-base font-semibold">{t('makerworld.recentImportsHeader')}</h2>
  814. </CardHeader>
  815. <CardContent>
  816. <div className="flex flex-col gap-2 max-h-[28rem] overflow-y-auto -mx-2 px-2">
  817. {recentQuery.data.map((item: MakerworldRecentImport) => (
  818. <div
  819. key={item.library_file_id}
  820. className="flex gap-2 p-2 border rounded border-gray-200 dark:border-gray-700"
  821. >
  822. {item.thumbnail_path ? (
  823. <img
  824. src={api.getLibraryFileThumbnailUrl(item.library_file_id)}
  825. alt=""
  826. className="w-12 h-12 shrink-0 object-cover rounded bg-gray-100 dark:bg-gray-800"
  827. loading="lazy"
  828. />
  829. ) : (
  830. <div className="w-12 h-12 shrink-0 rounded bg-gray-100 dark:bg-gray-800" />
  831. )}
  832. <div className="flex-1 min-w-0 flex flex-col gap-1">
  833. <p className="text-xs font-medium truncate" title={item.filename}>
  834. {item.filename}
  835. </p>
  836. <div className="flex gap-0.5">
  837. <Button
  838. variant="ghost"
  839. size="sm"
  840. onClick={() => {
  841. const target = item.folder_id
  842. ? `/files?folder=${item.folder_id}`
  843. : '/files';
  844. window.location.assign(target);
  845. }}
  846. title={t('makerworld.viewInLibrary')}
  847. >
  848. <FolderOpen className="w-3.5 h-3.5" />
  849. </Button>
  850. {useSlicerApi ? (
  851. <Button
  852. variant="ghost"
  853. size="sm"
  854. onClick={() =>
  855. openSliceForLibraryFile(item.library_file_id, item.filename)
  856. }
  857. title={t('slice.action', 'Slice')}
  858. >
  859. <Cog className="w-3.5 h-3.5" />
  860. </Button>
  861. ) : (
  862. <Button
  863. variant="ghost"
  864. size="sm"
  865. onClick={() =>
  866. handleOpenInSlicer(item.library_file_id, item.filename, 'bambu_studio')
  867. }
  868. title={t('makerworld.openInBambuStudio')}
  869. >
  870. <ExternalLink className="w-3.5 h-3.5" />
  871. </Button>
  872. )}
  873. {item.source_url && (
  874. <a
  875. href={item.source_url}
  876. target="_blank"
  877. rel="noopener noreferrer"
  878. className="inline-flex items-center justify-center h-7 w-7 rounded text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
  879. title={t('makerworld.openOnMakerworld')}
  880. >
  881. <Globe className="w-3.5 h-3.5" />
  882. </a>
  883. )}
  884. </div>
  885. </div>
  886. </div>
  887. ))}
  888. </div>
  889. </CardContent>
  890. </Card>
  891. )}
  892. </aside>
  893. </div>
  894. <p className="text-xs text-gray-500 dark:text-gray-400 pt-4 border-t border-gray-200 dark:border-gray-700">
  895. {t('makerworld.disclaimer')}
  896. </p>
  897. {pendingDelete && (
  898. <ConfirmModal
  899. title={t('makerworld.deleteImport')}
  900. message={t('makerworld.confirmDelete', { filename: pendingDelete.filename })}
  901. confirmText={t('makerworld.deleteImport')}
  902. variant="danger"
  903. isLoading={deleteImportMutation.isPending}
  904. loadingText={t('makerworld.importDeleting')}
  905. onCancel={() => setPendingDelete(null)}
  906. onConfirm={() =>
  907. deleteImportMutation.mutate({
  908. libraryFileId: pendingDelete.libraryFileId,
  909. profileId: pendingDelete.profileId,
  910. })
  911. }
  912. />
  913. )}
  914. {sliceModalSource && (
  915. <SliceModal
  916. source={sliceModalSource}
  917. onClose={() => setSliceModalSource(null)}
  918. />
  919. )}
  920. {lightbox && (
  921. <div
  922. className="fixed inset-0 bg-black/90 flex items-center justify-center z-50"
  923. onClick={() => setLightbox(null)}
  924. role="dialog"
  925. aria-modal="true"
  926. >
  927. <button
  928. type="button"
  929. className="absolute top-4 right-4 p-2 bg-white/10 hover:bg-white/20 rounded-full text-white"
  930. onClick={(e) => {
  931. e.stopPropagation();
  932. setLightbox(null);
  933. }}
  934. aria-label={t('common.close', 'Close')}
  935. >
  936. <X className="w-5 h-5" />
  937. </button>
  938. {lightbox.images.length > 1 && (
  939. <>
  940. <button
  941. type="button"
  942. className="absolute left-4 p-2 bg-white/10 hover:bg-white/20 rounded-full text-white disabled:opacity-30"
  943. disabled={lightbox.index === 0}
  944. onClick={(e) => {
  945. e.stopPropagation();
  946. setLightbox((prev) => (prev ? { ...prev, index: Math.max(0, prev.index - 1) } : prev));
  947. }}
  948. aria-label={t('makerworld.galleryPrev')}
  949. >
  950. <ChevronLeft className="w-6 h-6" />
  951. </button>
  952. <button
  953. type="button"
  954. className="absolute right-4 p-2 bg-white/10 hover:bg-white/20 rounded-full text-white disabled:opacity-30"
  955. disabled={lightbox.index >= lightbox.images.length - 1}
  956. onClick={(e) => {
  957. e.stopPropagation();
  958. setLightbox((prev) =>
  959. prev ? { ...prev, index: Math.min(prev.images.length - 1, prev.index + 1) } : prev,
  960. );
  961. }}
  962. aria-label={t('makerworld.galleryNext')}
  963. >
  964. <ChevronRight className="w-6 h-6" />
  965. </button>
  966. </>
  967. )}
  968. <img
  969. src={proxyCdn(lightbox.images[lightbox.index].url)}
  970. alt={lightbox.images[lightbox.index].name}
  971. className="max-w-[90vw] max-h-[90vh] object-contain"
  972. onClick={(e) => e.stopPropagation()}
  973. />
  974. {lightbox.images.length > 1 && (
  975. <div className="absolute bottom-6 left-1/2 -translate-x-1/2 text-white bg-black/60 px-3 py-1 rounded text-xs">
  976. {lightbox.index + 1} / {lightbox.images.length}
  977. </div>
  978. )}
  979. </div>
  980. )}
  981. </div>
  982. );
  983. }