| 1 | import { updatePresentation } from "@/app/_actions/notebook/presentation/presentationActions"; |
| 2 | import { buildPresentationCustomization } from "@/lib/presentation/customization"; |
| 3 | import { usePresentationState } from "@/states/presentation-state"; |
| 4 | |
| 5 | const PERSIST_DELAY_MS = 500; |
| 6 | |
| 7 | let persistTimer: ReturnType<typeof setTimeout> | null = null; |
| 8 | let persistVersion = 0; |
| 9 | |
| 10 | function buildCurrentLayoutSelectionPayload() { |
| 11 | const state = usePresentationState.getState(); |
| 12 | |
| 13 | if (!state.currentPresentationId) { |
| 14 | return null; |
| 15 | } |
| 16 | |
| 17 | return { |
| 18 | id: state.currentPresentationId, |
| 19 | outline: state.outline, |
| 20 | customization: buildPresentationCustomization({ |
| 21 | customThemeData: state.customThemeData, |
| 22 | themeDataByTheme: state.themeDataByTheme, |
| 23 | generatedThemeData: state.generatedThemeData, |
| 24 | theme: state.theme, |
| 25 | pageStyle: state.pageStyle, |
| 26 | presentationStyle: state.presentationStyle, |
| 27 | generationAspectRatio: state.generationAspectRatio, |
| 28 | textContent: state.textContent, |
| 29 | tone: state.tone, |
| 30 | audience: state.audience, |
| 31 | scenario: state.scenario, |
| 32 | pageBackground: state.pageBackground, |
| 33 | selectedSlideTemplates: state.selectedSlideTemplates, |
| 34 | outlineItemIds: state.outlineItemIds, |
| 35 | outlineTemplateOverrides: state.outlineTemplateOverrides, |
| 36 | }), |
| 37 | }; |
| 38 | } |
| 39 | |
| 40 | async function persistLatestLayoutSelection(version: number): Promise<void> { |
| 41 | const payload = buildCurrentLayoutSelectionPayload(); |
| 42 | |
| 43 | if (!payload) { |
| 44 | return; |
| 45 | } |
| 46 | |
| 47 | usePresentationState.getState().setSavingStatus("saving"); |
| 48 | |
| 49 | const result = await updatePresentation(payload); |
| 50 | |
| 51 | if (version !== persistVersion) { |
| 52 | return; |
| 53 | } |
| 54 | |
| 55 | if (!result.success) { |
| 56 | console.error( |
| 57 | "Failed to persist outline layout selection:", |
| 58 | result.message, |
| 59 | ); |
| 60 | usePresentationState.getState().setSavingStatus("idle"); |
| 61 | return; |
| 62 | } |
| 63 | |
| 64 | usePresentationState.getState().setSavingStatus("saved"); |
| 65 | setTimeout(() => { |
| 66 | if (version === persistVersion) { |
| 67 | usePresentationState.getState().setSavingStatus("idle"); |
| 68 | } |
| 69 | }, 2000); |
| 70 | } |
| 71 | |
| 72 | export function persistOutlineLayoutSelection(): void { |
| 73 | persistVersion += 1; |
| 74 | const version = persistVersion; |
| 75 | |
| 76 | if (persistTimer) { |
| 77 | clearTimeout(persistTimer); |
| 78 | } |
| 79 | |
| 80 | persistTimer = setTimeout(() => { |
| 81 | persistTimer = null; |
| 82 | void persistLatestLayoutSelection(version); |
| 83 | }, PERSIST_DELAY_MS); |
| 84 | } |
| 85 |