/* # Slideshow Converts the active Excalidraw drawing into a slideshow presentation. [![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/logo-slideshow-v4.png)](https://community.sketch-your-mind.com/slideshow) To get the most out of the Slideshow script check out the [Slideshow mini-course](https://community.sketch-your-mind.com/slideshow) on the Sketch Your Mind Community. ![](https://youtu.be/7DDY8rRDzdU) [Also watch the Excalidraw 2.27.0 update video](https://youtu.be/am2HOlbYsxI?t=272) ![Slideshow example](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-slideshow-2.jpg) [Slideshow mini-course](https://community.sketch-your-mind.com/slideshow) ## Launch behavior - Slideshow requests Excalidraw Automate autostart permission. Its autostart pass only registers the view-local **Edit slideshow** element action; it never starts a presentation. - Select a frame or line/arrow carrying slideshow metadata and use its Lucide presentation action to open/focus the **Slideshow** sidepanel for that element's frame or line deck. - After a view is registered, invoking the script from its toolbar icon, Obsidian command, or hotkey starts that view's presentation. A normal invocation starts fullscreen; whether presenter notes open follows the persisted sidepanel setting. Shift resumes saved progress, Alt/Option starts windowed, and Cmd/Ctrl opens/focuses the Slideshow sidepanel instead of presenting. A selected frame or line/arrow overrides the saved source; with no relevant selection, the exact presentation source last chosen in the sidepanel for that drawing is used. A normal invocation while a presentation is active advances the existing controller. Shift re-resolves the selected or saved source and resumes that source's own continuation point. - Slideshow uses `utils.executionSource` so autostart remains registration-only while the very first manual toolbar, command, or hotkey invocation can start presenting immediately. - The presentation toolbar's settings button ends the active presentation and opens the sidepanel. Presentation-source switching and presenter-view launch are intentionally configured from the sidepanel rather than duplicated on the compact presentation toolbar. - The sidepanel is a single non-persistent instance. It follows the most recently focused Excalidraw drawing across main-window/popout contexts and shows an empty state for Markdown notes. ## Presentation sources and slide order A drawing can contain one frame presentation plus any number of independent line/arrow presentations. The sidepanel keeps an explicit presentation-source selection; selecting ordinary canvas elements never changes which deck the sorter is editing. - Frames form one presentation source when the drawing contains frames. - A line/arrow becomes a presentation source only after slideshow metadata is created for it. Merely selecting an ordinary line does not replace the sidepanel deck, but manually launching Slideshow with that line selected creates the presentation metadata and uses that line for the launch. - When an ordinary line/arrow with at least one complete point pair is selected, the sidepanel shows a contextual **Create line presentation** action in the top toolbar. - Every persisted line presentation has its own optional name. Use its ellipsis/settings action beside the deck summary to rename it or remove only its slideshow metadata. Removing presentation metadata never deletes the line itself and restores its original styling if the path had been persistently hidden. - If presentation names collide, the selector disambiguates them only in the UI as `Name (1)`, `Name (2)`, and so on; element ids remain the stable identity. Unnamed paths use `Line presentation` with the same duplicate-numbering rule. - When multiple sources exist, the presentation selector lists `Frames` plus every named line presentation independently. The selected source is persisted per drawing and becomes the manual-launch default whenever no frame or line/arrow is selected on the canvas. A selected frame or line/arrow overrides that default for the invocation. - Frames without slideshow metadata retain alphabetical ordering. - The first sorter mutation writes explicit normalized `order` metadata; after that, frame renames do not change presentation order. - Excluded frame and line slides remain visible and editable in the sorter. Presentations omit them; PDF setup lets you choose visible slides or all slides. ## Slide sorter The sidepanel shows a title, thumbnail, and controls for every slide. Titles occupy their own top row so long frame names remain readable. - Desktop: drag rows to reorder them. - All platforms: use the up/down buttons or `Alt+Arrow Up/Down`. - `Arrow Up/Down`: move sorter focus. - `Enter`: zoom the drawing editor to the focused slide. - `Space`: toggle inclusion for frame or line slides. - `N`: expand and focus presenter notes for the selected slide. - `A`: open the animation editor for a frame slide. Line slides reorder consecutive point pairs in absolute scene coordinates and normalize the line origin afterward. Stable line-slide metadata records are reordered in the same transaction so presenter notes and inclusion state remain attached to the correct slide. Reordering is disabled when the presentation line/arrow has an active start or end binding. ## Appearance sequence and animation Frame slides support a build sequence stored on the frame's slideshow metadata. Open the sorter, choose a frame, and use the sparkles action (or `A`) to expand the animation editor directly beneath that slide. The frame is selected and zoomed to fit when editing starts. Select elements or groups in the drawing, then add or update steps with these effects: - **Appear:** restore the target instantly. - **Fade:** animate from transparent to the element's original opacity. - **Slide in:** animate an SVG overlay from the chosen direction. - **Zoom in:** animate an SVG overlay from approximately 5% scale at the target center. Choose effects and slide directions with the editor's buttons. After **Add step**, the form is ready to add another animation and retains your effect, direction, and timing choices for the editing session. Selecting a different element or group opens its first animation, or prepares a new step if it has none. Use **New step** to animate the same selection again; select any sequence row to edit a later animation. Sequence rows include thumbnails of their targets. Steps can trigger on presenter advance or sequentially after a delay. Fade, slide, and zoom default to 350 ms; timed steps default to a 1000 ms delay. Steps can be reordered with drag/drop, buttons, or `Alt+Arrow Up/Down`, previewed, edited, and deleted. Editor previews position SVG motion overlays in the drawing host coordinate space, matching presentation geometry even when the Excalidraw leaf is offset by sidepanels or other workspace chrome. Motion overlays remain in place while the canvas paints the completed animation, avoiding a blank frame at the handoff. Groups are stored by group ID and resolved dynamically when the presentation runs. Bound text and its container are treated as one visual unit. Marker frames do not own their contents, so animation eligibility is determined by geometric overlap between each element rectangle and the marker-frame rectangle rather than by `frameId`. A target can appear in multiple steps, including repeated entrances and exits. Adding or editing a step preserves the target's other animations. Presentation navigation is hierarchical: Forward reveals the next pending build before advancing the slide; Backward reverses the most recently completed build before moving to the previous slide. Previous slides entered while navigating backward start fully built, while direct jumps enter the destination in its initial build state. Timed callbacks and animation frames are invalidated on navigation and exit. Temporary scene changes use `captureUpdate: "NEVER"`; real elements are changed only through opacity, while slide/zoom motion uses disposable SVG overlays. Any interruption or presentation exit explicitly restores every animated target to its final/original visibility before cleanup. Animation editing remains frame-only because frames provide stable geometric slide boundaries. Line slides support ordering, notes, and inclusion/exclusion but not element animation. ## Presenter notes Each sorter row can own Markdown presenter notes. Use the notes icon on that row to expand/collapse its editor directly beneath the slide instead of using a shared editor at the bottom of the sorter. - Frame notes are stored in `frame.customData.slideshow.notes`. - Line-slide notes are stored in the corresponding stable record on the presentation-path element. - Notes save after a short debounce and are flushed on blur, slide changes, panel close, and presentation start. - Empty notes are removed rather than persisted as empty strings. - Each persisted notes edit is followed by an immediate drawing `forceSave(true)` so the metadata is written to disk, not merely left dirty in memory. On desktop, presenter view runs in a script-owned Obsidian popout. The presenter window shows the current slide, rendered Markdown notes, live animation progress, and the **next navigation state**. When another animation is pending, the large next preview shows that next animation state on the current slide; only after the slide is fully built does it preview the next visible slide. A layout toggle can devote approximately 85% of the window width to presenter notes, leaving a compact current/next preview rail for teleprompter-style use. Its Previous/Next controls and keyboard shortcuts call the same `SlideshowController` state machine as the floating presentation toolbar. Keyboard handling is scoped to the window that actually has focus and ignores repeated/default-prevented keydown events, preventing one key press from being interpreted twice. Closing only the presenter popout leaves the presentation running; ending the presentation closes the presenter popout as part of cleanup. Presenter view is disabled on mobile because Obsidian does not support popout windows there. ## Thumbnails `SlidePreviewService` calculates each slide's configured `printSlideWidth` × `printSlideHeight` navigation rectangle and exports only elements intersecting that viewport. Sorter and presenter previews are bounded-resolution PNG blobs rather than full-scene SVG clones, so off-slide embedded images are not repeated in every thumbnail. Sorter previews are requested lazily with `IntersectionObserver` and rendered through a serialized queue. A byte-budgeted LRU cache owns object URLs and revokes them on eviction or drawing changes. Slideshow metadata-only changes do not invalidate visual previews. PDF slides use area selection clipped to each slide's own rectangle through `ea.createViewSVG({ exportArea })`, but remain vector SVGs. Each page is self-contained and includes only image files referenced by elements intersecting that page instead of retaining the complete drawing behind a changed `viewBox`. ## Slideshow settings The sidepanel cog opens a script-owned settings modal for transition timing, edit zoom, fade level, print/presentation dimensions, and maximum zoom. Values are persisted through Excalidraw Automate script settings, with the historical configuration values used as defaults. The sidepanel preview aspect ratio updates to match the configured print width and height. The sidepanel also includes a small support link to [Ko-fi](https://ko-fi.com/zsolt). ## Presentation launch, displays, and PDF behavior The sidepanel has one compact **Play** button. Launch behavior is configured independently through dropdowns instead of overloading the play action: **Start / Resume / Current**, **Fullscreen / Windowed**, and **Slides only / With Notes**. If multiple presentation sources exist, a separate presentation selector is shown. Changing a dropdown never starts the presentation; pressing Play uses the currently selected combination. These choices are persisted in script settings. The launch/display controls live in a collapsible **Presentation settings** section so the sorter can use most of the panel height. Launches hide the docked Excalidraw sidepanel and wait for both the drawing layout and Excalidraw viewport dimensions to settle before framing the first slide. A sidepanel in a separate popout stays open. On desktop, display selectors are shown only when **With Notes** is selected. The default keeps the presentation on the current/primary display and chooses another display for presenter notes when available. Presentation and notes display selections are persisted in script settings under a stable local device key, allowing different machines that share the script settings to keep independent monitor choices. Presenter placement is deliberately fail-safe. The host native-window placement is captured **before** a presenter popout is opened. After `openPopoutLeaf()`, Slideshow waits until Obsidian has actually migrated the presenter leaf into a DOM `Window` distinct from the host, then verifies that the two DOM windows resolve to different native Electron `BrowserWindow`s before moving either presenter window. If identity cannot be established unambiguously, presenter movement is skipped instead of risking moving the main Obsidian window. The host is then moved to the requested presentation display and fullscreen is requested only after Electron confirms the display transition. Native restoration uses Electron's `BrowserWindow.id`, waits for macOS native fullscreen to finish exiting, and briefly monitors the captured host for a late Sidecar/Spaces drift; only a window that moves off its original display or fully off-screen is repaired. Display handling remains best-effort because Obsidian does not expose a first-class presentation-display API to scripts. On Obsidian Mobile, presentations always use fullscreen mode, presenter view is unavailable, and the docked mobile navbar is hidden for the duration of the presentation. The presentation toolbar is centered and uses a compact slide picker on narrow screens. Presentation navigation and the toolbar slide picker consume the canonical visible deck. The presentation slide picker labels entries as `Title (current/total)`. Starting from the sidepanel returns focus to the drawing leaf before keyboard handlers are installed, so arrow-key navigation is immediately active. PDF pages use the final fully built scene state: all animation targets are restored to their original opacity and no animation overlays are included. ## PDF printing and handouts Select **Print slideshow to PDF** in the sidepanel or presentation toolbar to open floating print setup. Choose any available frame or named line/arrow slideshow; the current deck is selected initially. Printing preserves the sorter's slide order. - **Print theme** offers **Light** and **Dark** for slides and handouts. Each time setup opens, it defaults to the drawing's current scene theme. - Choose slides only, one slide with notes below it, or two/three slides with notes beside each slide per page. - The **Print only visible slides** toggle is on by default. Turn it off to include excluded slides, including decks whose slides are all excluded. - Choose the configured slide size, **A4**, **Letter**, **16:9**, or **Custom**, then select **Landscape** or **Portrait**. Width and height are editable in pixels (96 pixels per inch), from 320 to 14400 pixels. Holding Shift while opening setup starts with the current viewport dimensions. - Each slide is clipped to its own rectangle and fitted intact inside its page or handout slot. Changing paper aspect ratio never pulls neighboring slides into the printout or splits a slide across pages. Handout slots retain the configured presentation aspect ratio. - **Include frames around slides** adds a border using the configured slide aspect ratio in notes and handout layouts, including notes continuations. It is off by default and hidden for **Slides only**, which always prints without added frames. - **Margins** offers **None** (default, edge-to-edge slides), **Minimal** (10 px), and **Normal** (60 px). Margins apply to slides and handouts without adding a second inset in the PDF exporter. - Notes use Obsidian's Markdown renderer, preserving headings, emphasis, links, lists, tables, and code as formatted HTML. Long notes continue in another slot with the slide repeated. - **Page ranges** accepts output-page selections such as `1-3;5;9-`; leave it blank for all pages. Ranges count final pages, including notes continuation pages, and preserve their original order. - Confirmed print preferences (layout, visibility, handout frames, page size, orientation/dimensions, margins, and page ranges) are saved in script settings and restored the next time print setup opens. The slideshow source initially follows the current drawing. PDF creation uses Excalidraw's existing desktop PDF export and its normal save dialog. ## Export frame slides to Markdown For frame decks, select the **Export frame slides to Markdown** file-down button beside Print. Enter a filename to create a note in the drawing's folder and open it in a new tab. Existing notes are never overwritten; cancelling creates nothing. The note includes every frame slide in sorter order, including excluded slides. Each section contains the frame title, an embed such as `![[Folder/Drawing.excalidraw.md#^frame=Opening]]`, and the slide's original Markdown notes. Duplicate, unnamed, or unlinkable frame names use the frame ID in the same `#^frame=` syntax to keep the reference unambiguous. Line/arrow decks do not offer Markdown export. ## Keyboard shortcuts and modifier keys during presentation - **Forward:** Arrow Down, Arrow Right, or Space - **Backward:** Arrow Up or Arrow Left - **Finish:** Backspace or Escape - **Edit current line-path slide:** E - **Toggle fullscreen:** F - **Return to the current slide:** Home - **Go to the final slide:** End - **Normal script invocation:** start fullscreen. Slides-only vs presenter notes follows the sidepanel setting. - **Run in a window:** Hold Alt/Option while launching the script. - **Resume from the last slide:** Hold Shift while launching the script. Progress is held only in temporary runtime memory and is tracked independently for each presentation source in each concrete Excalidraw view, even when two views show the same file. It can be combined with Alt/Option. - **Open the Slideshow sidepanel:** Hold Cmd on macOS or Ctrl on Windows/Linux while invoking the script. Build version: 2026-11-16T17:57:13.580Z ```javascript */ // Script bundle /* EA Script — slideshow | ea-scripts v1.0.0 */ (() => { // src/sharedUtils/i18n.ts function interpolateTranslation(template, params = {}) { return Object.entries(params).reduce( (result, [key, value]) => result.split(`{${key}}`).join(String(value)), template ); } function createTranslator(requestedLocale, catalogs, fallbackLocale = "en") { const locale = requestedLocale.toLowerCase().replaceAll("_", "-"); const baseLocale = locale.split("-")[0] ?? locale; return (key, params = {}) => { const template = catalogs[locale]?.[key] ?? catalogs[baseLocale]?.[key] ?? catalogs[fallbackLocale]?.[key] ?? key; return interpolateTranslation(template, params); }; } // src/scripts/slideshow/lang/de.ts var de = { requiresNewerVersion: "Dieses Skript ben\xF6tigt eine neuere Version von Excalidraw. Installiere bitte die neueste Version.", noActiveView: "\xD6ffne eine Excalidraw-Zeichnung, bevor du die Pr\xE4sentation startest.", cannotAccessView: "Auf die aktive Excalidraw-Ansicht konnte nicht zugegriffen werden." }; // src/scripts/slideshow/lang/en.ts var en = { printDialogTitle: "Print slideshow to PDF", printSlideshow: "Slideshow to print", printDialogPrint: "Create PDF", printLayout: "Layout", printTheme: "Print theme", printThemeLight: "Light", printThemeDark: "Dark", printSlidesOnly: "Slides only \u2014 one per page", printNotesPage: "Notes \u2014 one slide per page", printHandout2: "Handout \u2014 two slides with notes per page", printHandout3: "Handout \u2014 three slides with notes per page", printIncludeFrames: "Include frames around slides", printVisibleOnly: "Print only visible slides", printVisibleOnlyHint: "Turn off to include excluded slides.", printPageRanges: "Page ranges", printPageRangesHint: "Leave blank for all pages. Example: 1-3;5;9- (from page 9 to the end). Numbers refer to output pages, including notes continuations.", printInvalidPageRanges: "Enter page numbers or ascending ranges, separated by semicolons: 1-3;5;9-.", printNoPages: "No output pages match the page ranges.", printPreferencesFailed: "Could not save print preferences. Try again.", printPageSize: "Page size", printConfigured: "Configured slide size", printCustom: "Custom", printOrientation: "Orientation", printMargin: "Margins", printMarginNone: "None", printMarginMinimal: "Minimal", printMarginNormal: "Normal", printLandscape: "Landscape", printPortrait: "Portrait", printWidth: "Page width (px)", printHeight: "Page height (px)", printInvalidDimensions: "Enter a width and height between 320 and 14400 pixels.", printNotesHint: "Notes use Markdown formatting. Long notes continue with the slide repeated. Each slide stays inside its page or handout slot.", printContinued: "(continued)", printNoSlides: "No slides match the print selection. Turn off visible slides only to print all.", printFailed: "Could not export the slideshow to PDF.", printViewChanged: "The drawing changed. Open print setup again.", exportMarkdown: "Export frame slides to Markdown", exportMarkdownFilename: "Filename for slide notes (in the drawing's folder)", exportMarkdownDefaultFilename: "{name} slides", exportMarkdownInvalidFilename: "Enter a filename without folder separators or special filename characters.", exportMarkdownExists: "A note with that filename already exists. Choose another filename.", exportMarkdownFailed: "Could not export the slideshow to Markdown.", requiresNewerVersion: "This script requires a newer version of Excalidraw. Please install the latest version.", autostartExplanation: 'Autostart is required for registering the "Edit Slide" button. Autostart does not mean slideshows will autostart when opening a drawing.', noActiveView: "Open an Excalidraw drawing before starting the slideshow.", cannotAccessView: "Could not access the active Excalidraw view.", noPresentationPath: "No configured slideshow is available. Add frames or create a line presentation.", selectedPathOverridesHidden: "Using the selected line instead of the hidden presentation path. Run the slideshow without selecting an element to use the hidden path.", allFramesExcluded: "All frame slides are excluded. Include at least one frame before presenting.", allSlidesExcluded: "All slides are excluded. Include at least one slide before presenting.", sidepanelTitle: "Slideshow", supportPrompt: "Enjoying Slideshow?", supportLink: "Buy me a coffee.", settingsTitle: "Slideshow settings", settingsTransitionStepCount: "Transition step count", settingsTransitionStepCountDesc: "Number of interpolation steps used when moving between slides.", settingsTransitionDelay: "Transition duration (ms)", settingsTransitionDelayDesc: "Approximate duration of the camera transition between slides.", settingsFrameSleep: "Transition frame sleep (ms)", settingsFrameSleepDesc: "Delay yielded between individual camera-transition frames.", settingsEditZoomOut: "Edit zoom factor", settingsEditZoomOutDesc: "Zoom multiplier used when opening a slide for editing. *100[%]", settingsFadeLevel: "Presentation fade level", settingsFadeLevelDesc: "Opacity level used when fading presentation controls. *100[%]", settingsPrintSlideWidth: "Slide width", settingsPrintSlideWidthDesc: "Presentation/PDF width. Sidepanel previews use this aspect ratio.", settingsPrintSlideHeight: "Slide height", settingsPrintSlideHeightDesc: "Presentation/PDF height. Sidepanel previews use this aspect ratio.", settingsMaxZoom: "Maximum zoom", settingsMaxZoomDesc: "Maximum zoom level", settingsSave: "Save", settingsResetDefaults: "Reset defaults", settingsCancel: "Cancel", settingsSaved: "Slideshow settings saved.", settingsSaveFailed: "Could not save slideshow settings.", quickGuideTitle: "Slideshow quick guide", quickGuideButton: "Open slideshow quick guide", quickGuideShortcutsTitle: "Script button shortcuts", quickGuideClick: "Click \u2014 start the slideshow in fullscreen mode.", quickGuideWindowed: "Option/Alt+click \u2014 start the slideshow in a window.", quickGuideEditor: "Command/Ctrl+click \u2014 open the slideshow editor sidepanel.", quickGuideResumeFullscreen: "Shift+click \u2014 continue the slideshow in fullscreen mode.", quickGuideResumeWindowed: "Shift+Option/Alt+click \u2014 continue the slideshow in a window.", quickGuideAuthoringTitle: "Building a slideshow", quickGuideFrameSlides: "Frame slides use the drawing's frames. Reorder slides, exclude frames, and edit slide content from the sorter.", quickGuideLineSlides: "Line slides follow consecutive point pairs on a configured presentation line, which is useful for free-form camera paths.", quickGuideMarkerFrames: "Marker frames are ideal slideshow markers: they define a slide without changing the visual grouping of the drawing.", quickGuideAnimations: "Slides can reveal elements or groups in a sequence using appear, fade, slide-in, zoom-in, and timed animation steps.", quickGuideNotes: "Add presenter notes per slide. With a second display, presenter mode shows notes and the next slide separately from the audience view.", quickGuideLearnMoreTitle: "Learn more", quickGuideVideo: "Getting Started with Obsidian Excalidraw Slideshow v4", quickGuideVideoThumbnailAlt: "Slideshow v4 video thumbnail", quickGuideCourse: "Slideshow mini-course", startPresentation: "Start presentation", startFromBeginning: "From beginning", presentationStartOptions: "Presentation start options", presentationSettings: "Presentation settings", startWithPresenterView: "With presenter notes", startFromCurrentSlide: "Current slide", startFullscreen: "Start fullscreen", startCurrentWindow: "Start in current window", startMode: "Start position", startModeStart: "Start", startModeResume: "Resume", startModeCurrent: "Current", windowMode: "Presentation window", windowModeFullscreen: "Fullscreen", windowModeWindowed: "Windowed", notesMode: "Presenter mode", notesModeWithNotes: "With Notes", notesModeSlidesOnly: "Slides only", presentationDisplay: "Presentation display", presenterDisplay: "Notes display", primaryDisplay: "Primary", displayLabel: "Display {number}", continuePresentation: "Resume presentation", startFromSelectedSlide: "Start presentation from selected slide", selectedSlideNotPresentable: "The selected slide is excluded from this presentation.", noSlides: "No slideshow is available in this drawing.", noActiveDrawing: "Focus an Excalidraw drawing to edit its slideshow.", noEligibleSlides: "No eligible slides selected.", frameDeck: "Frame slideshow", framePresentationSettings: "Frame presentation settings", framePresentationName: "Presentation name", convertFrameToLine: "Create line slideshow", convertFrameToLinePrompt: "Create a line slideshow from this frame presentation.", convertLineToFrame: "Create frame slideshow", convertLineToFramePrompt: "Create a frame slideshow from this line presentation.", conversionDeleteFrames: "Delete source frames", conversionVisibleSlidesOnly: "Create slideshow only from visible slides", conversionDeleteLine: "Delete source line", conversionCreate: "Create slideshow", convertLineToFrameKind: "Frame type", convertLineToFrameMarker: "Marker frames", convertLineToFrameNormal: "Normal frames", convertLineToFrameGeometryTitle: "Frame geometry", convertLineToFrameGeometryPrompt: "Should the frames match the line slide rectangles exactly, or expand to the presentation aspect ratio?", convertLineToFrameExact: "Match line points", convertLineToFrameAspect: "Correct aspect ratio", conversionFailed: "Could not convert the slideshow.", fitFrameToPresentationAspect: "Fit frame to presentation aspect ratio", resizeFrameFailed: "Could not resize the presentation frame.", lineDeck: "Line slideshow", linePresentationDefaultName: "Line presentation", createLinePresentation: "Create a presentation from the selected line", linePresentationSettings: "Line presentation settings", linePresentationName: "Presentation name", removeLinePresentation: "Remove presentation", removeLinePresentationConfirm: "Remove slideshow metadata from this line? The line and its drawing content will remain unchanged.", presentationType: "Presentation type", presentationTypeHint: "Choose whether this drawing presents its frames or presentation path.", slideCount: "{count} slides", visibleSlideCount: "{visible} of {total} included", dragSlide: "Drag to reorder slide", moveSlideUp: "Move slide up", moveSlideDown: "Move slide down", includeSlide: "Include slide in presentation", excludeSlide: "Exclude slide from presentation", notesPresent: "Notes", animationCount: "{count} anims", editAnimations: "Edit animations", animationCheckpoint3: "Animation editing is available for frame slides.", animationEditorTitle: "Animations \u2014 {title}", closeAnimationEditor: "Close animation editor", animationSelectionHint: "Select an element or group to edit its first animation or add a new one. Add step readies the next animation; New step animates the same selection again.", animationOutsideFrameIgnored: "Ignored {count} selected item(s) outside this frame.", animationOutsideSlideIgnored: "Ignored {count} selected item(s) outside this slide.", animationTargets: "Targets", animationNoTargets: "Select elements or groups in this slide.", animationGroupTarget: "Group {id}", animationElementTarget: "{type} {id}", removeAnimationTarget: "Remove target", animationEffect: "Effect", animationEffectAppear: "Appear", animationEffectFade: "Fade", animationEffectSlide: "Slide in", animationEffectZoom: "Zoom in", animationEffectDisappear: "Disappear", animationEffectFadeOut: "Fade out", animationEffectSlideOut: "Slide out", animationEffectZoomOut: "Zoom out", animationTrigger: "Trigger", animationTriggerAdvance: "On advance", animationTriggerDelay: "After delay", animationDelayMs: "Delay (ms)", animationDurationMs: "Duration (ms)", animationDirection: "Direction", animationDirectionLeft: "From left", animationDirectionRight: "From right", animationDirectionUp: "From top", animationDirectionDown: "From bottom", animationDirectionOutLeft: "To left", animationDirectionOutRight: "To right", animationDirectionOutUp: "To top", animationDirectionOutDown: "To bottom", addAnimationStep: "Add step", updateAnimationStep: "Update step", newAnimationStep: "New step", previewAnimation: "Preview", animationSequence: "Animation sequence ({count})", animationNoSteps: "No animation steps yet.", animationStepSummary: "{number}. {effect} \xB7 {targets} target(s)", moveAnimationStepUp: "Move animation step up", moveAnimationStepDown: "Move animation step down", previewAnimationStep: "Preview animation step", deleteAnimationStep: "Delete animation step", animationSaveFailed: "Could not save animation metadata.", notesHeading: "Presenter notes", showPresenterNotes: "Show presenter notes", hidePresenterNotes: "Hide presenter notes", notesPlaceholder: "Add presenter notes for this slide\u2026", notesHint: "Notes support Markdown and are saved automatically.", lineReorderBound: "This presentation path is an arrow. The arrow has a bound start or end. Slides reordering is disabled until you unbind both endpoints.", lineAnimationUnsupported: "Element animation currently requires frame-based slides because frames provide stable slide membership.", showPresentationPath: "Show presentation path", hidePresentationPath: "Hide presentation path", editLineSlide: "Edit this line slide", editLineSlideFailed: "Could not open this line slide for editing.", reorderFailed: "Could not reorder the slide.", metadataSaveFailed: "Could not save slideshow metadata.", zoomSlide: "Zoom editor to this slide", slideLabel: "Slide {number}", slideNumberAndTitle: "{number}. {title}", presentationSlideTitle: "{title} ({number}/{total})", openSlideshowPanel: "Open slideshow panel", editSlideshow: "Edit slideshow", openPanelEndsPresentation: "End presentation and open slideshow panel", switchToFrameSlideshow: "Switch to frame slideshow", switchToLineSlideshow: "Switch to line slideshow", previousSlide: "Previous slide", nextSlide: "Next slide", navigateToSlide: "Navigate to slide", toggleLaser: "Toggle laser pointer and panning mode", refocusSlide: "Re-focus current slide (shortcut: HOME)", toggleFullscreen: "Toggle fullscreen (shortcut: F)", pathVisibility: "Arrow visibility. ON: hidden after presentation, OFF: visible after presentation", keepPresentationPathVisible: "Keep presentation path visible after presentation", keepPresentationPathHidden: "Keep presentation path hidden after presentation", editSlide: "Edit slide", editSlideName: "Edit slide name", slideName: "Slide name", presenterNotesFontSize: "Notes size", sorterThumbnailSize: "Thumbnail size", declareFrameSlideshow: "Create frame slideshow", printPdf: "Print to PDF\nClick to print slides at {width}x{height}\nHold SHIFT to print the presentation as displayed", endPresentation: "End presentation", pathWillRemainHidden: "The presentation path will remain hidden after the presentation. Next time, start the slideshow without selecting the line.", invalidSlide: "The slideshow presentation path does not contain a valid slide.", generatingImage: "Generating image. This can take longer depending on drawing size and device speed.", generatingSlide: "Generating slide {number}", creatingPdf: "Creating PDF document", presenterViewTitle: "Presenter view", presenterView: "Open presenter view", presenterViewDesktopOnly: "Presenter view is available on desktop only.", presenterViewOpenFailed: "Could not open presenter view.", presenterCurrentSlide: "Current slide", presenterSlideCounter: "Slide {number} of {total}", presenterNextSlide: "Next slide", presenterNextBuild: "Next animation", presenterNotes: "Presenter notes", presenterNoNotes: "No presenter notes for this slide.", presenterAnimationProgress: "Build {completed} of {total}", presenterNoAnimations: "No animation builds", presenterEnd: "End of presentation", presenterClose: "Close presenter view", presenterNotesFocusLayout: "Prioritize presenter notes", presenterStandardLayout: "Use standard presenter layout" }; // src/scripts/slideshow/lang/es.ts var es = { requiresNewerVersion: "Este script requiere una versi\xF3n m\xE1s reciente de Excalidraw. Instala la \xFAltima versi\xF3n.", noActiveView: "Abre un dibujo de Excalidraw antes de iniciar la presentaci\xF3n.", cannotAccessView: "No se pudo acceder a la vista activa de Excalidraw." }; // src/scripts/slideshow/lang/fr.ts var fr = { requiresNewerVersion: "Ce script n\xE9cessite une version plus r\xE9cente d\u2019Excalidraw. Installez la derni\xE8re version.", noActiveView: "Ouvrez un dessin Excalidraw avant de d\xE9marrer le diaporama.", cannotAccessView: "Impossible d\u2019acc\xE9der \xE0 la vue Excalidraw active." }; // src/scripts/slideshow/lang/ru.ts var ru = { requiresNewerVersion: "\u0414\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0441\u043A\u0440\u0438\u043F\u0442\u0430 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u0431\u043E\u043B\u0435\u0435 \u043D\u043E\u0432\u0430\u044F \u0432\u0435\u0440\u0441\u0438\u044F Excalidraw. \u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u044E\u044E \u0432\u0435\u0440\u0441\u0438\u044E.", noActiveView: "\u041E\u0442\u043A\u0440\u043E\u0439\u0442\u0435 \u0440\u0438\u0441\u0443\u043D\u043E\u043A Excalidraw \u043F\u0435\u0440\u0435\u0434 \u0437\u0430\u043F\u0443\u0441\u043A\u043E\u043C \u043F\u0440\u0435\u0437\u0435\u043D\u0442\u0430\u0446\u0438\u0438.", cannotAccessView: "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C \u0434\u043E\u0441\u0442\u0443\u043F \u043A \u0430\u043A\u0442\u0438\u0432\u043D\u043E\u043C\u0443 \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u044E Excalidraw." }; // src/scripts/slideshow/lang/zh-cn.ts var zhCn = { requiresNewerVersion: "\u6B64\u811A\u672C\u9700\u8981\u8F83\u65B0\u7248\u672C\u7684 Excalidraw\u3002\u8BF7\u5B89\u88C5\u6700\u65B0\u7248\u672C\u3002", noActiveView: "\u8BF7\u5148\u6253\u5F00 Excalidraw \u7ED8\u56FE\uFF0C\u518D\u5F00\u59CB\u5E7B\u706F\u7247\u653E\u6620\u3002", cannotAccessView: "\u65E0\u6CD5\u8BBF\u95EE\u5F53\u524D\u7684 Excalidraw \u89C6\u56FE\u3002" }; // src/scripts/slideshow/lang/index.ts var CATALOGS = { en, de, es, fr, ru, "zh-cn": zhCn }; function createSlideshowTranslator(locale) { return createTranslator(locale, CATALOGS); } // src/scripts/slideshow/desktopDisplays.ts var DEVICE_KEY_STORAGE = "excalidraw-slideshow-device-key"; function getRemote(win) { const rendererWindow = win; try { const contextRemote = rendererWindow.require?.("@electron/remote"); if (contextRemote?.getCurrentWindow) return contextRemote; } catch { } return rendererWindow.electron?.remote ?? null; } function geometryForWindow(win) { return { screenX: Number.isFinite(win.screenX) ? win.screenX : 0, screenY: Number.isFinite(win.screenY) ? win.screenY : 0, outerWidth: Number.isFinite(win.outerWidth) ? Math.max(win.outerWidth, 1) : 1, outerHeight: Number.isFinite(win.outerHeight) ? Math.max(win.outerHeight, 1) : 1 }; } function geometryScore(candidate, geometry) { const bounds = candidate.getBounds(); return Math.abs(bounds.x - geometry.screenX) * 2 + Math.abs(bounds.y - geometry.screenY) * 2 + Math.abs(bounds.width - geometry.outerWidth) + Math.abs(bounds.height - geometry.outerHeight); } function chooseClosestNativeWindow(windows, geometry) { if (windows.length === 0) return null; let best = null; let bestScore = Number.POSITIVE_INFINITY; for (const candidate of windows) { const score = geometryScore(candidate, geometry); if (score < bestScore) { bestScore = score; best = candidate; } } return best; } function getNativeWindow(win) { const remote = getRemote(win); if (!remote) return null; try { const current = remote.getCurrentWindow(); const candidates = remote.BrowserWindow?.getAllWindows?.() ?? []; if (candidates.length === 0) return current; const geometry = geometryForWindow(win); const closest = chooseClosestNativeWindow(candidates, geometry); if (!closest) return current; const currentScore = geometryScore(current, geometry); const closestScore = geometryScore(closest, geometry); return closestScore + 80 < currentScore ? closest : current; } catch { try { return remote.getCurrentWindow(); } catch { return null; } } } function getNativeWindowId(window2) { const propertyId = window2.id; if (typeof propertyId === "number" && Number.isFinite(propertyId)) return propertyId; const legacyId = window2.getId?.(); return typeof legacyId === "number" && Number.isFinite(legacyId) ? legacyId : null; } function getNativeWindowById(remote, id) { if (id === null) return null; try { const direct = remote.BrowserWindow?.fromId?.(id); if (direct) return direct; return remote.BrowserWindow?.getAllWindows?.().find( (candidate) => getNativeWindowId(candidate) === id ) ?? null; } catch { return null; } } function captureWindowPlacement(win) { try { const remote = getRemote(win); const screen = remote?.screen; if (!remote || !screen) { return null; } const nativeWindow = getNativeWindow(win); if (!nativeWindow) { return null; } const bounds = nativeWindow.getBounds(); const snapshot = { windowId: getNativeWindowId(nativeWindow), sourceDisplayId: screen.getDisplayMatching(bounds).id, bounds: { ...bounds }, maximized: nativeWindow.isMaximized?.() ?? false }; return snapshot; } catch { return null; } } function nativeWindowIdentity(window2) { const id = getNativeWindowId(window2); if (id !== null) return `id:${id}`; const bounds = window2.getBounds(); return `title:${window2.getTitle?.() ?? ""}|${bounds.x},${bounds.y},${bounds.width},${bounds.height}`; } function resolveSameNativeWindow(host, candidate) { const hostNative = getNativeWindow(host); const candidateNative = getNativeWindow(candidate); if (!hostNative || !candidateNative) return null; if (hostNative === candidateNative) return true; const hostId = getNativeWindowId(hostNative); const candidateId = getNativeWindowId(candidateNative); if (hostId !== null && candidateId !== null) return hostId === candidateId; return nativeWindowIdentity(hostNative) === nativeWindowIdentity(candidateNative); } function toDisplay(display, primaryId, index) { const workArea = display.workArea ?? display.bounds; const label = display.label?.trim() ?? ""; return { id: display.id, label, index, bounds: { ...display.bounds }, workArea: { ...workArea }, primary: display.id === primaryId }; } function getSlideshowDeviceKey(win) { try { const existing = win.localStorage?.getItem(DEVICE_KEY_STORAGE)?.trim(); if (existing) return existing; const generated = typeof win.crypto?.randomUUID === "function" ? win.crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`; win.localStorage?.setItem(DEVICE_KEY_STORAGE, generated); return generated; } catch { const nav = win.navigator; return `fallback-${nav.platform || "desktop"}-${nav.userAgent.length}`; } } function getSlideshowDisplayIdentity(display) { const label = display.label.trim().toLowerCase(); return JSON.stringify([ label, display.bounds.width, display.bounds.height, display.primary ]); } function getSlideshowDisplayConfigurationKey(displays) { if (displays.length === 0) return "none"; return JSON.stringify(displays.map(getSlideshowDisplayIdentity).sort()); } function resolveSlideshowDisplayTarget(displays, preferredId, preferredIdentity) { if (preferredId !== null && displays.some((display) => display.id === preferredId)) { return preferredId; } if (!preferredIdentity) return null; return displays.find((display) => getSlideshowDisplayIdentity(display) === preferredIdentity)?.id ?? null; } function getAvailableDisplays(win) { try { const screen = getRemote(win)?.screen; if (!screen) return []; const primaryId = screen.getPrimaryDisplay().id; return screen.getAllDisplays().map((display, index) => toDisplay(display, primaryId, index)); } catch { return []; } } function onDisplayConfigurationChanged(win, callback) { const screen = getRemote(win)?.screen; if (!screen?.on) return () => void 0; const events = ["display-added", "display-removed", "display-metrics-changed"]; const listener = () => callback(); try { for (const event of events) screen.on(event, listener); } catch { return () => void 0; } return () => { for (const event of events) { try { if (screen.off) screen.off(event, listener); else screen.removeListener?.(event, listener); } catch { } } }; } function getCurrentDisplayId(win) { try { const remote = getRemote(win); const screen = remote?.screen; if (!remote || !screen) return null; const nativeWindow = getNativeWindow(win); return nativeWindow ? screen.getDisplayMatching(nativeWindow.getBounds()).id : null; } catch { return null; } } function chooseDefaultDisplayTargets(displays, currentDisplayId) { if (displays.length === 0) { return { presentationDisplayId: null, presenterDisplayId: null }; } const presentation = displays.find((display) => display.id === currentDisplayId) ?? displays.find((display) => display.primary) ?? displays[0]; const presenter = displays.find((display) => display.id !== presentation?.id) ?? presentation; return { presentationDisplayId: presentation?.id ?? null, presenterDisplayId: presenter?.id ?? null }; } async function waitForWindowOnDisplay(win, displayId, timeoutMs = 2e3) { const started = Date.now(); while (Date.now() - started <= timeoutMs) { if (getCurrentDisplayId(win) === displayId) { return true; } await new Promise((resolve) => win.setTimeout(resolve, 75)); } return false; } function moveWindowToDisplay(win, displayId, fillWorkArea = true, moveIfAlreadyOnDisplay = true) { if (displayId === null || displayId === void 0) return null; try { const remote = getRemote(win); const screen = remote?.screen; if (!remote || !screen) { return null; } const target = screen.getAllDisplays().find((display) => display.id === displayId); if (!target) { return null; } const nativeWindow = getNativeWindow(win); if (!nativeWindow) { return null; } const currentBounds = nativeWindow.getBounds(); const currentDisplay = screen.getDisplayMatching(currentBounds); const windowId = getNativeWindowId(nativeWindow); if (currentDisplay.id === displayId && !moveIfAlreadyOnDisplay) { return null; } const snapshot = { windowId, sourceDisplayId: currentDisplay.id, bounds: { ...currentBounds }, maximized: nativeWindow.isMaximized?.() ?? false }; if (snapshot.maximized) nativeWindow.unmaximize?.(); const area = target.workArea ?? target.bounds; const requestedBounds = fillWorkArea ? { ...area } : { x: area.x + Math.round(area.width * 0.08), y: area.y + Math.round(area.height * 0.08), width: Math.max(Math.round(area.width * 0.84), 480), height: Math.max(Math.round(area.height * 0.84), 360) }; nativeWindow.setBounds(requestedBounds, false); const actual = nativeWindow.getBounds(); return snapshot; } catch { return null; } } function rectsOverlap(a, b) { return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y; } function safeRestoreBounds(snapshot, displays, primary) { if (displays.some((display) => rectsOverlap(snapshot.bounds, display.bounds))) { return { ...snapshot.bounds }; } const source = displays.find((display) => display.id === snapshot.sourceDisplayId) ?? primary; const area = source.workArea ?? source.bounds; const width = Math.min(Math.max(snapshot.bounds.width, 480), area.width); const height = Math.min(Math.max(snapshot.bounds.height, 360), area.height); return { x: area.x + Math.max(0, Math.round((area.width - width) / 2)), y: area.y + Math.max(0, Math.round((area.height - height) / 2)), width, height }; } function resolveCapturedNativeWindow(win, snapshot) { const remote = getRemote(win); const screen = remote?.screen; if (!remote || !screen) return null; const nativeWindow = getNativeWindowById(remote, snapshot.windowId) ?? (snapshot.windowId === null ? getNativeWindow(win) : null); return nativeWindow ? { remote, screen, nativeWindow } : null; } function applyRestorePlacement(screen, nativeWindow, snapshot) { const requested = safeRestoreBounds( snapshot, screen.getAllDisplays(), screen.getPrimaryDisplay() ); if (nativeWindow.isMaximized?.()) nativeWindow.unmaximize?.(); nativeWindow.setBounds(requested, false); if (snapshot.maximized) nativeWindow.maximize?.(); return requested; } function placementNeedsRepair(screen, nativeWindow, snapshot) { const bounds = nativeWindow.getBounds(); const displays = screen.getAllDisplays(); const visible = displays.some((display) => rectsOverlap(bounds, display.bounds)); if (!visible) return true; if (snapshot.sourceDisplayId === null) return false; return screen.getDisplayMatching(bounds).id !== snapshot.sourceDisplayId; } function restoreWindowPlacement(win, snapshot) { if (!snapshot) return; try { const resolved = resolveCapturedNativeWindow(win, snapshot); if (!resolved) { return; } const { screen, nativeWindow } = resolved; applyRestorePlacement(screen, nativeWindow, snapshot); } catch { } } async function restoreWindowPlacementStable(win, snapshot, timeoutMs = 2400, monitorMs = 900) { if (!snapshot) return; const resolved = resolveCapturedNativeWindow(win, snapshot); if (!resolved) { return; } const { screen, nativeWindow } = resolved; const started = Date.now(); while (nativeWindow.isFullScreen?.() && Date.now() - started < timeoutMs) { await new Promise((resolve) => win.setTimeout(resolve, 75)); } restoreWindowPlacement(win, snapshot); const monitorStarted = Date.now(); while (Date.now() - monitorStarted < monitorMs) { await new Promise((resolve) => win.setTimeout(resolve, 125)); if (nativeWindow.isFullScreen?.()) continue; if (!placementNeedsRepair(screen, nativeWindow, snapshot)) continue; applyRestorePlacement(screen, nativeWindow, snapshot); } } // src/scripts/slideshow/icons.ts var ANIMATION_ICON_NAMES = { appear: "eye", fade: "circle-fading-plus", slide: "arrow-right-to-line", zoom: "zoom-in", disappear: "eye-off", "slide-out": "arrow-right-from-line", "zoom-out": "zoom-out", left: "arrow-big-left-dash", right: "arrow-big-right-dash", up: "arrow-big-up-dash", down: "arrow-big-down-dash", "after-delay": "timer", advance: "step-forward" }; var FADE_OUT_ICON = ''; function iconMarkup(ea2, iconName) { return ea2.obsidian.getIcon(iconName)?.outerHTML ?? ""; } function getAnimationEditorIcon(ea2, choice, exits) { if (choice === "fade-out") return FADE_OUT_ICON; const direction = exits ? choice : choice === "left" ? "right" : choice === "right" ? "left" : choice === "up" ? "down" : choice === "down" ? "up" : choice; return iconMarkup(ea2, `lucide-${ANIMATION_ICON_NAMES[direction]}`); } function getSlideshowIcons(ea2) { return { finish: iconMarkup(ea2, "lucide-x"), rightArrow: iconMarkup(ea2, "lucide-arrow-right"), leftArrow: iconMarkup(ea2, "lucide-arrow-left"), edit: iconMarkup(ea2, "lucide-pencil"), maximize: iconMarkup(ea2, "lucide-maximize"), minimize: iconMarkup(ea2, "lucide-minimize"), currentWindow: iconMarkup(ea2, "lucide-app-window"), laserOn: iconMarkup(ea2, "lucide-hand"), laserOff: iconMarkup(ea2, "lucide-wand"), printer: iconMarkup(ea2, "lucide-printer"), fileDown: iconMarkup(ea2, "lucide-file-down"), refocus: iconMarkup(ea2, "lucide-scan-eye"), gripVertical: iconMarkup(ea2, "lucide-grip-vertical"), chevronUp: iconMarkup(ea2, "lucide-chevron-up"), chevronDown: iconMarkup(ea2, "lucide-chevron-down"), eye: iconMarkup(ea2, "lucide-eye"), eyeOff: iconMarkup(ea2, "lucide-eye-off"), sparkles: iconMarkup(ea2, "lucide-sparkles"), notebookPen: iconMarkup(ea2, "lucide-notebook-pen"), play: iconMarkup(ea2, "lucide-play"), continuePresentation: iconMarkup(ea2, "lucide-circle-play"), presentation: iconMarkup(ea2, "lucide-presentation"), plus: iconMarkup(ea2, "lucide-plus"), trash: iconMarkup(ea2, "lucide-trash-2"), close: iconMarkup(ea2, "lucide-x"), settings: iconMarkup(ea2, "lucide-settings"), info: iconMarkup(ea2, "info"), frameSlideshow: iconMarkup(ea2, "lucide-frame"), lineSlideshow: iconMarkup(ea2, "lucide-route"), moreHorizontal: iconMarkup(ea2, "lucide-ellipsis") }; } // src/sharedUtils/presentationGeometry.ts function expandSlideRectToAspectRatio(slide, dimensions) { const left = Math.min(slide.x1, slide.x2); const right = Math.max(slide.x1, slide.x2); const top = Math.min(slide.y1, slide.y2); const bottom = Math.max(slide.y1, slide.y2); const width = Math.max(right - left, Number.EPSILON); const height = Math.max(bottom - top, Number.EPSILON); const targetRatio = dimensions.width / dimensions.height; const currentRatio = width / height; const expandedWidth = currentRatio < targetRatio ? height * targetRatio : width; const expandedHeight = currentRatio > targetRatio ? width / targetRatio : height; const centerX = (left + right) / 2; const centerY = (top + bottom) / 2; return { x1: centerX - expandedWidth / 2, y1: centerY - expandedHeight / 2, x2: centerX + expandedWidth / 2, y2: centerY + expandedHeight / 2 }; } function getPresentationFrameName(name, index) { return name ?? `Frame ${(index + 1).toString().padStart(2, "0")}`; } function getNavigationRect(slide, dimensions, maxZoom) { const { x1, y1, x2, y2 } = slide; const { width, height } = dimensions; const ratioX = width / Math.abs(x1 - x2); const ratioY = height / Math.abs(y1 - y2); let ratio = Math.min(Math.max(ratioX, ratioY), maxZoom); const scaledWidth = Math.abs(x1 - x2) * ratio; const scaledHeight = Math.abs(y1 - y2) * ratio; if (scaledWidth > width || scaledHeight > height) { ratio = Math.min(width / Math.abs(x1 - x2), height / Math.abs(y1 - y2)); } const deltaX = (width / ratio - Math.abs(x1 - x2)) / 2; const deltaY = (height / ratio - Math.abs(y1 - y2)) / 2; return { left: Math.min(x1, x2) - deltaX, top: Math.min(y1, y2) - deltaY, right: Math.max(x1, x2) + deltaX, bottom: Math.max(y1, y2) + deltaY, nextZoom: ratio }; } // src/scripts/slideshow/slideshowMetadata.ts var FRAME_SCHEMA_VERSION = 2; var LINE_SCHEMA_VERSION = 2; var animationEffects = /* @__PURE__ */ new Set([ "appear", "fade", "slide", "zoom", "disappear", "fade-out", "slide-out", "zoom-out" ]); var animationTriggers = /* @__PURE__ */ new Set(["advance", "after-delay"]); var animationDirections = /* @__PURE__ */ new Set(["left", "right", "up", "down"]); function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function isNonEmptyString(value) { return typeof value === "string" && value.length > 0; } function isOptionalNonNegativeNumber(value) { return value === void 0 || typeof value === "number" && Number.isFinite(value) && value >= 0; } function normalizeNotes(value) { if (typeof value !== "string" || value.trim().length === 0) { return void 0; } return value; } function readOriginalPathProperties(value) { if (!isRecord(value)) { return null; } if (typeof value.strokeColor !== "string" || typeof value.backgroundColor !== "string" || typeof value.locked !== "boolean") { return null; } return { strokeColor: value.strokeColor, backgroundColor: value.backgroundColor, locked: value.locked }; } function readAnimationTarget(value) { if (!isRecord(value) || !isNonEmptyString(value.id)) { return null; } if (value.type === "element" || value.type === "group") { return { type: value.type, id: value.id, ...value.scope === "viewport" ? { scope: "viewport" } : {} }; } return null; } function readAnimationStep(value) { if (!isRecord(value) || !isNonEmptyString(value.id) || !Array.isArray(value.targets)) { return null; } if (!animationEffects.has(value.effect)) { return null; } if (!animationTriggers.has(value.trigger)) { return null; } if (!isOptionalNonNegativeNumber(value.delayMs) || !isOptionalNonNegativeNumber(value.durationMs)) { return null; } if (value.direction !== void 0 && !animationDirections.has(value.direction)) { return null; } const targets = value.targets.map(readAnimationTarget); if (targets.length === 0 || targets.some((target) => target === null)) { return null; } const result = { id: value.id, targets, effect: value.effect, trigger: value.trigger }; if (value.delayMs !== void 0) result.delayMs = value.delayMs; if (value.durationMs !== void 0) result.durationMs = value.durationMs; if (value.direction !== void 0) result.direction = value.direction; return result; } function readAnimation(value) { if (value === void 0) { return void 0; } if (!isRecord(value) || !Array.isArray(value.steps)) { return null; } const steps = value.steps.map(readAnimationStep); if (steps.some((step) => step === null)) { return null; } return { steps }; } function readLineSlidePair(value) { if (value === void 0) return void 0; if (!Array.isArray(value) || value.length !== 2) return null; const points = value.map((point) => { if (!Array.isArray(point) || point.length !== 2 || typeof point[0] !== "number" || !Number.isFinite(point[0]) || typeof point[1] !== "number" || !Number.isFinite(point[1])) { return null; } return [point[0], point[1]]; }); return points.some((point) => point === null) ? null : points; } function getRawSlideshowMetadata(customData) { return isRecord(customData) ? customData.slideshow : void 0; } function hasFrameSlideshowDeclaration(customData) { const value = getRawSlideshowMetadata(customData); if (!isRecord(value) || value.schemaVersion !== FRAME_SCHEMA_VERSION || value.kind !== "frame") { return false; } if (value.order !== void 0) return readFrameSlideshowData(customData) !== null; return Object.keys(value).every((key) => key === "schemaVersion" || key === "kind"); } function readFrameSlideshowData(customData) { const value = getRawSlideshowMetadata(customData); if (!isRecord(value) || value.schemaVersion !== FRAME_SCHEMA_VERSION || value.kind !== "frame") { return null; } if (typeof value.order !== "number" || !Number.isInteger(value.order) || value.order < 0) { return null; } if (value.excluded !== void 0 && typeof value.excluded !== "boolean") { return null; } if (value.notes !== void 0 && typeof value.notes !== "string") { return null; } if (value.deckName !== void 0 && typeof value.deckName !== "string") { return null; } const animation = readAnimation(value.animation); if (animation === null) { return null; } const result = { schemaVersion: FRAME_SCHEMA_VERSION, kind: "frame", order: value.order }; const deckName = normalizeNotes(value.deckName); if (deckName !== void 0) result.deckName = deckName; if (value.excluded !== void 0) result.excluded = value.excluded; const notes = normalizeNotes(value.notes); if (notes !== void 0) result.notes = notes; if (animation !== void 0) result.animation = animation; return result; } function readLegacyLineSlideshowData(customData) { const value = getRawSlideshowMetadata(customData); if (!isRecord(value) || value.schemaVersion !== void 0 || value.kind !== void 0) { return null; } const originalProps = readOriginalPathProperties(value.originalProps); if (typeof value.hidden !== "boolean" || !originalProps) { return null; } return { hidden: value.hidden, originalProps }; } function readLineSlideRecord(value) { if (!isRecord(value) || !isNonEmptyString(value.id)) { return null; } if (value.notes !== void 0 && typeof value.notes !== "string") { return null; } if (value.excluded !== void 0 && typeof value.excluded !== "boolean") { return null; } if (value.title !== void 0 && typeof value.title !== "string") { return null; } const pair = readLineSlidePair(value.pair); if (pair === null) return null; const animation = readAnimation(value.animation); if (animation === null) return null; const result = { id: value.id }; const title = normalizeNotes(value.title); if (title !== void 0) result.title = title; const notes = normalizeNotes(value.notes); if (notes !== void 0) result.notes = notes; if (value.excluded !== void 0) result.excluded = value.excluded; if (pair !== void 0) result.pair = pair; if (animation !== void 0) result.animation = animation; return result; } function readLineSlideshowDataV2(customData) { const value = getRawSlideshowMetadata(customData); if (!isRecord(value) || value.schemaVersion !== LINE_SCHEMA_VERSION || value.kind !== "path") { return null; } const originalProps = readOriginalPathProperties(value.originalProps); if (typeof value.hidden !== "boolean" || !originalProps || !Array.isArray(value.slides) || value.name !== void 0 && typeof value.name !== "string") { return null; } const slides = value.slides.map(readLineSlideRecord); if (slides.some((slide) => slide === null)) { return null; } const result = { schemaVersion: LINE_SCHEMA_VERSION, kind: "path", hidden: value.hidden, originalProps, slides }; const name = normalizeNotes(value.name); if (name !== void 0) result.name = name; return result; } function makeGeneratedLineSlideId(pathId, index, usedIds) { const base = `slideshow-${pathId}-${index + 1}`; let candidate = base; let suffix = 2; while (usedIds.has(candidate)) { candidate = `${base}-${suffix}`; suffix += 1; } return candidate; } function getAbsoluteLinePoints(x, y, points) { return points.map((point) => [x + point[0], y + point[1]]); } function samePoint(left, right) { return Math.abs(left[0] - right[0]) < 1e-3 && Math.abs(left[1] - right[1]) < 1e-3; } function samePair(left, right) { return samePoint(left[0], right[0]) && samePoint(left[1], right[1]); } function getCurrentLinePairs(points, pairCount) { return Array.from({ length: pairCount }, (_, index) => { const first = points?.[index * 2]; const second = points?.[index * 2 + 1]; return first && second ? [ [first[0], first[1]], [second[0], second[1]] ] : void 0; }); } function copyLineSlideRecord(existing, id, pair) { const record = { id }; const title = normalizeNotes(existing?.title); if (title !== void 0) record.title = title; const notes = normalizeNotes(existing?.notes); if (notes !== void 0) record.notes = notes; if (existing?.excluded === true) record.excluded = true; if (existing?.animation !== void 0) { record.animation = { steps: existing.animation.steps.map((step) => structuredClone(step)) }; } if (pair) record.pair = pair; else if (existing?.pair) record.pair = structuredClone(existing.pair); return record; } function reconcileLineSlideRecords(records, pairCount, pathId, points) { const count = Math.max(0, Math.floor(pairCount)); const result = []; const usedIds = /* @__PURE__ */ new Set(); const usedRecordIndices = /* @__PURE__ */ new Set(); const currentPairs = getCurrentLinePairs(points, count); const matchedRecordByPairIndex = /* @__PURE__ */ new Map(); if (points) { currentPairs.forEach((pair, pairIndex) => { if (!pair) return; const recordIndex = records.findIndex( (record, index) => !usedRecordIndices.has(index) && Boolean(record.pair && samePair(record.pair, pair)) ); if (recordIndex >= 0) { matchedRecordByPairIndex.set(pairIndex, recordIndex); usedRecordIndices.add(recordIndex); } }); } for (let index = 0; index < count; index += 1) { let recordIndex = matchedRecordByPairIndex.get(index); if (recordIndex === void 0) { const indexed = records[index]; const canFallbackByIndex = Boolean(indexed) && !usedRecordIndices.has(index) && (!points || records.length === count || indexed?.pair === void 0); if (canFallbackByIndex) { recordIndex = index; usedRecordIndices.add(index); } } const existing = recordIndex === void 0 ? void 0 : records[recordIndex]; const id = existing && isNonEmptyString(existing.id) && !usedIds.has(existing.id) ? existing.id : makeGeneratedLineSlideId(pathId, index, usedIds); usedIds.add(id); result.push(copyLineSlideRecord(existing, id, currentPairs[index])); } return result; } function reorderLineSlideRecords(records, pairCount, pathId, fromPairIndex, toPairIndex, points) { const reconciled = reconcileLineSlideRecords(records, pairCount, pathId, points); if (!Number.isInteger(fromPairIndex) || !Number.isInteger(toPairIndex) || fromPairIndex < 0 || toPairIndex < 0 || fromPairIndex >= reconciled.length || toPairIndex >= reconciled.length) { throw new RangeError("Line-slide metadata index is outside the presentation path."); } const [record] = reconciled.splice(fromPairIndex, 1); if (!record) { throw new RangeError("The source line-slide metadata record does not exist."); } reconciled.splice(toPairIndex, 0, record); return reconciled; } function readLineSlideshowData(customData, pathId, pairCount, points) { const v2 = readLineSlideshowDataV2(customData); if (v2) { return { source: "v2", data: { ...v2, slides: reconcileLineSlideRecords(v2.slides, pairCount, pathId, points) } }; } const legacy = readLegacyLineSlideshowData(customData); if (!legacy) { return null; } return { source: "legacy", data: { schemaVersion: LINE_SCHEMA_VERSION, kind: "path", hidden: legacy.hidden, originalProps: legacy.originalProps, slides: reconcileLineSlideRecords([], pairCount, pathId, points) } }; } function upgradeLineSlideshowData(customData, pathId, pairCount, fallbackOriginalProps, points) { const existing = readLineSlideshowData(customData, pathId, pairCount, points); if (existing) { return existing.data; } return { schemaVersion: LINE_SCHEMA_VERSION, kind: "path", hidden: false, originalProps: fallbackOriginalProps, slides: reconcileLineSlideRecords([], pairCount, pathId, points) }; } function withNormalizedFrameOrder(customData, order) { const existing = readFrameSlideshowData(customData); const result = { schemaVersion: FRAME_SCHEMA_VERSION, kind: "frame", order }; if (existing?.excluded !== void 0) result.excluded = existing.excluded; if (existing?.deckName !== void 0) result.deckName = existing.deckName; if (existing?.notes !== void 0) result.notes = existing.notes; if (existing?.animation !== void 0) result.animation = existing.animation; return result; } function writeSlideshowMetadata(ea2, elementId, data) { return ea2.addAppendUpdateCustomData(elementId, { slideshow: data }); } // src/scripts/slideshow/SlideDeck.ts function getVisibleSlideIndex(deck, slideId) { if (!slideId) return null; const index = deck.visibleSlides.findIndex((slide) => slide.id === slideId); return index >= 0 ? index : null; } function compareAlphabetically(left, right) { if (left.title === right.title) { return left.sourceIndex - right.sourceIndex; } return left.title > right.title ? 1 : -1; } function orderFrames(frames) { const explicit = frames.some((frame) => frame.metadata !== null); if (!explicit) { return { ordered: [...frames].sort(compareAlphabetically), explicit: false }; } const withOrder = frames.filter((frame) => frame.metadata !== null); const withoutOrder = frames.filter((frame) => frame.metadata === null).sort(compareAlphabetically); withOrder.sort((left, right) => { const orderDelta = (left.metadata?.order ?? 0) - (right.metadata?.order ?? 0); return orderDelta !== 0 ? orderDelta : left.sourceIndex - right.sourceIndex; }); return { ordered: withOrder.concat(withoutOrder), explicit: true }; } function toIndexedFrames(frames) { return frames.map((source, sourceIndex) => ({ source, sourceIndex, title: getPresentationFrameName(source.name, sourceIndex), metadata: readFrameSlideshowData(source.customData) })); } function buildFrameSlideDeck(frames) { const { ordered, explicit } = orderFrames(toIndexedFrames(frames)); const name = ordered.find((frame) => frame.metadata?.deckName)?.metadata?.deckName ?? null; const slides = ordered.map((frame, index) => { const { source, metadata } = frame; const slide = { id: source.id, kind: "frame", frameId: source.id, title: frame.title, rect: { x1: source.x, y1: source.y, x2: source.x + source.width, y2: source.y + source.height }, excluded: metadata?.excluded ?? false, order: index, animationSteps: metadata?.animation?.steps ?? [] }; if (metadata?.notes !== void 0) slide.notes = metadata.notes; return slide; }); return { kind: "frame", name, slides, visibleSlides: slides.filter((slide) => !slide.excluded), hasExplicitFrameOrder: explicit }; } function buildLineSlideDeck(path) { const pairCount = Math.floor(path.points.length / 2); const metadata = readLineSlideshowData( path.customData, path.id, pairCount, getAbsoluteLinePoints(path.x, path.y, path.points) ); const records = metadata?.data.slides ?? []; const slides = []; for (let pairIndex = 0; pairIndex < pairCount; pairIndex += 1) { const pointA = path.points[pairIndex * 2]; const pointB = path.points[pairIndex * 2 + 1]; if (!pointA || !pointB) continue; const record = records[pairIndex]; const slide = { id: record?.id ?? `slideshow-${path.id}-${pairIndex + 1}`, kind: "path", pathId: path.id, pairIndex, title: record?.title ?? `Slide ${pairIndex + 1}`, rect: { x1: path.x + pointA[0], y1: path.y + pointA[1], x2: path.x + pointB[0], y2: path.y + pointB[1] }, excluded: record?.excluded ?? false, animationSteps: record?.animation?.steps ?? [] }; if (record?.notes !== void 0) slide.notes = record.notes; slides.push(slide); } return { kind: "path", name: metadata?.data.name?.trim() || null, slides, visibleSlides: slides.filter((slide) => !slide.excluded), hasExplicitFrameOrder: false }; } function movePair(pairs, fromPairIndex, toPairIndex) { const [pair] = pairs.splice(fromPairIndex, 1); if (!pair) throw new RangeError("The source line-slide pair does not exist."); pairs.splice(toPairIndex, 0, pair); } function reorderLinePointPairs(x, y, points, fromPairIndex, toPairIndex) { const pairCount = Math.floor(points.length / 2); if (!Number.isInteger(fromPairIndex) || !Number.isInteger(toPairIndex) || fromPairIndex < 0 || toPairIndex < 0 || fromPairIndex >= pairCount || toPairIndex >= pairCount) { throw new RangeError("Line-slide pair index is outside the presentation path."); } const absolute = points.map((point) => [x + point[0], y + point[1]]); const pairs = []; for (let index = 0; index < pairCount; index += 1) { const pointA = absolute[index * 2]; const pointB = absolute[index * 2 + 1]; if (pointA && pointB) pairs.push([pointA, pointB]); } movePair(pairs, fromPairIndex, toPairIndex); const reorderedAbsolute = pairs.flat(); const trailingPoint = absolute[pairCount * 2]; if (trailingPoint) reorderedAbsolute.push(trailingPoint); const origin = reorderedAbsolute[0]; if (!origin) return { x, y, points: [] }; return { x: origin[0], y: origin[1], points: reorderedAbsolute.map((point) => [point[0] - origin[0], point[1] - origin[1]]) }; } // src/scripts/slideshow/types.ts function isExitAnimationEffect(effect) { return effect === "disappear" || effect === "fade-out" || effect === "slide-out" || effect === "zoom-out"; } function isInstantAnimationEffect(effect) { return effect === "appear" || effect === "disappear"; } function isLinearPathElement(element) { return element?.type === "line" || element?.type === "arrow"; } function isFrameElement(element) { return element?.type === "frame"; } // src/scripts/slideshow/presentationPath.ts function getNamedFrames(elements) { return elements.filter(isFrameElement).map((frame, index) => ({ ...frame, name: getPresentationFrameName(frame.name, index) })); } function resolveFrameDeck(frames) { if (frames.length === 0) return null; return { deck: buildFrameSlideDeck(frames), pathElement: null, frames }; } function toLinePresentationSource(pathElement, frames) { const metadata = readLineSlideshowData( pathElement.customData, pathElement.id, Math.floor(pathElement.points.length / 2), getAbsoluteLinePoints(pathElement.x, pathElement.y, pathElement.points) ); if (!metadata) return null; return { key: `line:${pathElement.id}`, pathId: pathElement.id, name: metadata.data.name?.trim() || null, resolved: { deck: buildLineSlideDeck(pathElement), pathElement, frames } }; } function resolveLineSources(elements, frames) { const result = []; for (const element of elements) { if (!isLinearPathElement(element)) continue; const source = toLinePresentationSource(element, frames); if (source) result.push(source); } return result; } function isPresentationPathHidden(path) { return readLineSlideshowData( path.customData, path.id, Math.floor(path.points.length / 2), getAbsoluteLinePoints(path.x, path.y, path.points) )?.data.hidden ?? false; } function hasPresentationSource(choices, sourceKey) { if (!sourceKey) return false; if (sourceKey === "frame") return choices.frame !== null; return choices.lines.some((line) => line.key === sourceKey); } function resolvePresentationSource(choices, sourceKey) { if (!sourceKey) return null; if (sourceKey === "frame") return choices.frame; return choices.lines.find((line) => line.key === sourceKey)?.resolved ?? null; } function getPresentationSourceType(sourceKey) { return sourceKey === "frame" ? "frame" : "line"; } function getLinePresentationSourceKey(element) { if (!isLinearPathElement(element)) return null; const metadata = readLineSlideshowData( element.customData, element.id, Math.floor(element.points.length / 2), getAbsoluteLinePoints(element.x, element.y, element.points) ); return metadata ? `line:${element.id}` : null; } function resolveSlideDeckChoices(ea2) { const viewElements = ea2.getViewElements(); const frames = getNamedFrames(viewElements); const frame = resolveFrameDeck(frames); const lines = resolveLineSources(viewElements, frames); const selectedSourceKey = getLinePresentationSourceKey(ea2.getViewSelectedElement()); const defaultSourceKey = selectedSourceKey ? selectedSourceKey : frame ? "frame" : lines[0]?.key ?? null; const defaultType = defaultSourceKey ? getPresentationSourceType(defaultSourceKey) : null; return { frame, lines, line: lines[0]?.resolved ?? null, defaultSourceKey, defaultType }; } function normalizeSourceKey(choices, requested) { if (requested === "frame") return choices.frame ? "frame" : null; if (requested === "line") return choices.lines[0]?.key ?? null; if (requested?.startsWith("line:")) { return hasPresentationSource(choices, requested) ? requested : null; } return choices.defaultSourceKey; } function resolvePresentationSetup(ea2, api, t, presentationSource) { const choices = resolveSlideDeckChoices(ea2); const sourceKey = normalizeSourceKey(choices, presentationSource); const resolved = resolvePresentationSource(choices, sourceKey); const frameRenderingOriginalState = api.getAppState().frameRendering; if (!resolved || !sourceKey) { api.setToast({ message: t?.("noPresentationPath") ?? "Select a configured presentation in the Slideshow panel or add frames.", duration: 3e3, closable: true }); return null; } if (resolved.deck.visibleSlides.length === 0) { api.setToast({ message: t?.("allSlidesExcluded") ?? "All slides are excluded. Include at least one slide before presenting.", duration: 4e3, closable: true }); return null; } if (!resolved.pathElement) { if (frameRenderingOriginalState.enabled) { api.updateScene({ appState: { frameRendering: { ...frameRenderingOriginalState, enabled: false } } }); } return { ...resolved, sourceKey, pathType: "frame", slides: resolved.deck.visibleSlides.map((slide) => slide.rect), slideTitles: resolved.deck.visibleSlides.map((slide) => slide.title), shouldHidePathAfterPresentation: true, isHidden: false, originalPathProperties: null, frameRenderingOriginalState }; } const pathElement = resolved.pathElement; const metadata = readLineSlideshowData( pathElement.customData, pathElement.id, Math.floor(pathElement.points.length / 2), getAbsoluteLinePoints(pathElement.x, pathElement.y, pathElement.points) ); if (!metadata) return null; const originalPathProperties = metadata.data.hidden ? metadata.data.originalProps : { strokeColor: pathElement.strokeColor, backgroundColor: pathElement.backgroundColor, locked: pathElement.locked }; return { ...resolved, sourceKey, pathType: "line", slides: resolved.deck.visibleSlides.map((slide) => slide.rect), slideTitles: resolved.deck.visibleSlides.map((slide) => slide.title), shouldHidePathAfterPresentation: true, isHidden: metadata.data.hidden, originalPathProperties, frameRenderingOriginalState }; } // src/sharedUtils/windowTiming.ts function sleepInWindow(ownerWindow, milliseconds) { return new Promise((resolve) => ownerWindow.setTimeout(resolve, milliseconds)); } // src/scripts/slideshow/AnimationRuntime.ts var ANIMATION_ELIGIBILITY_MARGIN_RATIO = 0.1; function asAnimationShape(element) { return element; } var animationElementContextCache = /* @__PURE__ */ new WeakMap(); function getAnimationElementContext(elements) { const cacheKey = elements; const cached = animationElementContextCache.get(cacheKey); if (cached) return cached; const byId = /* @__PURE__ */ new Map(); const groupMembers = /* @__PURE__ */ new Map(); for (const element of elements) { byId.set(element.id, element); for (const groupId of asAnimationShape(element).groupIds ?? []) { const members = groupMembers.get(groupId); if (members) members.push(element); else groupMembers.set(groupId, [element]); } } const context = { byId, groupMembers }; animationElementContextCache.set(cacheKey, context); return context; } function getAnimationOverlayPlacement(bounds, state, hostViewportOrigin) { const zoom = state.zoom.value; return { left: state.offsetLeft + (bounds.topX + state.scrollX) * zoom - hostViewportOrigin.left, top: state.offsetTop + (bounds.topY + state.scrollY) * zoom - hostViewportOrigin.top, width: Math.max(bounds.width * zoom, 1), height: Math.max(bounds.height * zoom, 1) }; } function getElementRect(element) { const x1 = element.x; const y1 = element.y; const x2 = element.x + element.width; const y2 = element.y + element.height; const left = Math.min(x1, x2); const right = Math.max(x1, x2); const top = Math.min(y1, y2); const bottom = Math.max(y1, y2); const angle = element.angle ?? 0; if (angle === 0) return { left, top, right, bottom }; const centerX = (left + right) / 2; const centerY = (top + bottom) / 2; const cos = Math.cos(angle); const sin = Math.sin(angle); const corners = [ [left, top], [right, top], [right, bottom], [left, bottom] ]; const rotated = corners.map(([x, y]) => { const dx = x - centerX; const dy = y - centerY; return [centerX + dx * cos - dy * sin, centerY + dx * sin + dy * cos]; }); return { left: Math.min(...rotated.map(([x]) => x)), top: Math.min(...rotated.map(([, y]) => y)), right: Math.max(...rotated.map(([x]) => x)), bottom: Math.max(...rotated.map(([, y]) => y)) }; } function rectsOverlap2(left, right) { return left.left <= right.right && left.right >= right.left && left.top <= right.bottom && left.bottom >= right.top; } function rectFromSlideRect(rect) { return { left: Math.min(rect.x1, rect.x2), top: Math.min(rect.y1, rect.y2), right: Math.max(rect.x1, rect.x2), bottom: Math.max(rect.y1, rect.y2) }; } function getAnimationSlideScope(slide, config, viewportDimensions) { if (!config) { return { rect: slide.rect, ownerElementId: slide.kind === "frame" ? slide.frameId : slide.pathId }; } const configuredViewport = getNavigationRect( slide.rect, { width: config.printSlideWidth, height: config.printSlideHeight }, config.maxZoom ); const liveViewport = viewportDimensions ? getNavigationRect(slide.rect, viewportDimensions, config.maxZoom) : configuredViewport; const left = Math.min(configuredViewport.left, liveViewport.left); const top = Math.min(configuredViewport.top, liveViewport.top); const right = Math.max(configuredViewport.right, liveViewport.right); const bottom = Math.max(configuredViewport.bottom, liveViewport.bottom); const width = Math.max(right - left, Number.EPSILON); const height = Math.max(bottom - top, Number.EPSILON); const marginX = width * ANIMATION_ELIGIBILITY_MARGIN_RATIO; const marginY = height * ANIMATION_ELIGIBILITY_MARGIN_RATIO; return { rect: { x1: left - marginX, y1: top - marginY, x2: right + marginX, y2: bottom + marginY }, legacyRect: slide.rect, ownerElementId: slide.kind === "frame" ? slide.frameId : slide.pathId }; } function resolveAnimationScope(scope, elements) { if (typeof scope !== "string") return scope; const frame = getElementById(elements, scope); if (!frame) return null; return { rect: { x1: frame.x, y1: frame.y, x2: frame.x + frame.width, y2: frame.y + frame.height }, ownerElementId: frame.id }; } function elementOverlapsScope(element, scope, useViewportScope = false) { const rect = useViewportScope ? scope.rect : scope.legacyRect ?? scope.rect; return element.id !== scope.ownerElementId && rectsOverlap2(getElementRect(element), rectFromSlideRect(rect)); } function getElementById(elements, id) { return getAnimationElementContext(elements).byId.get(id); } function getGroupMembers(elements, groupId) { return getAnimationElementContext(elements).groupMembers.get(groupId) ?? []; } function canonicalElementTargetId(element, elements) { const shape = asAnimationShape(element); if (element.type === "text" && shape.containerId) { const container = getElementById(elements, shape.containerId); if (container) return container.id; } return element.id; } function expandBoundVisualUnit(initialIds, elements) { const result = /* @__PURE__ */ new Set(); const queue = [...initialIds]; while (queue.length > 0) { const id = queue.shift(); if (!id || result.has(id)) continue; const element = getElementById(elements, id); if (!element) continue; result.add(id); const shape = asAnimationShape(element); if (element.type === "text" && shape.containerId) queue.push(shape.containerId); for (const bound of shape.boundElements ?? []) { const boundElement = getElementById(elements, bound.id); if (boundElement?.type === "text") queue.push(bound.id); } } return [...result]; } function visualUnitOverlapsScope(element, scope, elements, useViewportScope = false) { return expandBoundVisualUnit([element.id], elements).some((id) => { const candidate = getElementById(elements, id); return candidate ? elementOverlapsScope(candidate, scope, useViewportScope) : false; }); } function resolveAnimationTargetElementIds(slideScope, targets, elements) { const scope = resolveAnimationScope(slideScope, elements); if (!scope) return []; const baseIds = /* @__PURE__ */ new Set(); for (const target of targets) { const useViewportScope = target.scope === "viewport"; if (target.type === "element") { const element = getElementById(elements, target.id); if (element && visualUnitOverlapsScope(element, scope, elements, useViewportScope)) { baseIds.add(canonicalElementTargetId(element, elements)); } continue; } for (const element of getGroupMembers(elements, target.id)) { const shape = asAnimationShape(element); if (shape.groupIds?.includes(target.id) && elementOverlapsScope(element, scope, useViewportScope)) { baseIds.add(element.id); } } } return expandBoundVisualUnit(baseIds, elements); } function animationTargetExists(target, elements) { if (target.type === "element") { return getElementById(elements, target.id) !== void 0; } return getGroupMembers(elements, target.id).length > 0; } function recycleMissingAnimationTargets(steps, elements) { return steps.flatMap((step) => { const targets = step.targets.filter((target) => animationTargetExists(target, elements)).map((target) => structuredClone(target)); return targets.length === 0 ? [] : [{ ...structuredClone(step), targets }]; }); } function captureAnimationTargets(slideScope, elements, selectedElementIds, selectedGroupIds) { const scope = resolveAnimationScope(slideScope, elements); if (!scope) return { targets: [], ignoredSelectionCount: Object.keys(selectedElementIds).length }; const targets = []; const seen = /* @__PURE__ */ new Set(); let ignoredSelectionCount = 0; const selectedGroups = Object.entries(selectedGroupIds).filter(([, selected]) => selected).map(([groupId]) => groupId); for (const groupId of selectedGroups) { const members = getGroupMembers(elements, groupId); const inViewport = members.filter((element) => elementOverlapsScope(element, scope, true)); const selectedOutside = members.some( (element) => selectedElementIds[element.id] && !elementOverlapsScope(element, scope, true) ); if (inViewport.length > 0) { const key = `group:${groupId}`; if (!seen.has(key)) { seen.add(key); const needsViewportScope = inViewport.some( (element) => !elementOverlapsScope(element, scope) ); targets.push({ type: "group", id: groupId, ...needsViewportScope ? { scope: "viewport" } : {} }); } } if (selectedOutside) ignoredSelectionCount += 1; } for (const element of elements) { if (!selectedElementIds[element.id] || element.id === scope.ownerElementId) continue; const shape = asAnimationShape(element); if (selectedGroups.some((groupId) => shape.groupIds?.includes(groupId))) continue; if (!visualUnitOverlapsScope(element, scope, elements, true)) { ignoredSelectionCount += 1; continue; } const id = canonicalElementTargetId(element, elements); const key = `element:${id}`; if (!seen.has(key)) { seen.add(key); targets.push({ type: "element", id, ...!visualUnitOverlapsScope(element, scope, elements) ? { scope: "viewport" } : {} }); } } return { targets, ignoredSelectionCount }; } function getOpacity(element) { return asAnimationShape(element).opacity; } function resolveRuntimeSteps(slideScope, steps, elements) { const resolved = steps.map((step) => ({ step: structuredClone(step), elementIds: resolveAnimationTargetElementIds(slideScope, step.targets, elements) })); return resolved.filter((step) => step.elementIds.length > 0); } var AnimationRuntime = class { ea; api; hostView; ownerWindow; onStateChange; config; active = null; timer = 0; generation = 0; overlays = /* @__PURE__ */ new Set(); overlayMarkupCache = /* @__PURE__ */ new Map(); buildQueue = Promise.resolve(); constructor(options) { this.ea = options.ea; this.api = options.api; this.hostView = options.hostView; this.ownerWindow = options.hostView.ownerWindow; this.config = options.config; this.onStateChange = options.onStateChange; } /** Returns current build progress for presentation-state consumers. */ getState() { return { completedSteps: this.active?.completedSteps ?? 0, stepCount: this.active?.steps.length ?? 0 }; } /** Returns original opacity for active animated elements, for presenter build previews. */ getOriginalOpacities() { const opacities = /* @__PURE__ */ new Map(); for (const [id, element] of this.active?.originals ?? []) opacities.set(id, element.opacity); return opacities; } /** Restores the prior slide, resolves the destination's dynamic targets, and applies its build state. */ async enterSlide(slide, fullyBuilt, startTimedSteps = true) { await this.leaveSlide(); const elements = this.api.getSceneElements(); const appState = this.config ? this.api.getAppState() : null; const scope = getAnimationSlideScope( slide, this.config, appState ? { width: appState.width, height: appState.height } : void 0 ); const steps = resolveRuntimeSteps(scope, slide.animationSteps, elements); const allIds = new Set(steps.flatMap((step) => step.elementIds)); const originals = /* @__PURE__ */ new Map(); for (const element of elements) { if (allIds.has(element.id)) originals.set(element.id, element); } this.active = { scope, steps, originals, completedSteps: fullyBuilt ? steps.length : 0 }; const generation = this.generation; try { this.applyBuildState(); this.emitState(); if (startTimedSteps) this.schedulePendingTimedStep(); } catch (error) { if (generation === this.generation) await this.leaveSlide(); throw error; } } /** Starts the pending timed step after viewport navigation has completed. */ startPendingTimer() { this.schedulePendingTimedStep(); } /** Pauses only the pending after-delay timer without changing build state. */ pauseTimedStep() { this.cancelTimer(); } /** Reveals the next build step, returning false only when the slide is fully built. */ advance() { const requestedGeneration = this.generation; return this.enqueueBuildAction( requestedGeneration, () => this.advanceCurrentStep(requestedGeneration) ); } /** Reverses the most recently completed build step, returning false at the slide's initial state. */ reverse() { const requestedGeneration = this.generation; return this.enqueueBuildAction( requestedGeneration, () => this.reverseCurrentStep(requestedGeneration) ); } enqueueBuildAction(requestedGeneration, task) { const result = this.buildQueue.then(() => { if (requestedGeneration !== this.generation) return true; return task(); }); this.buildQueue = result.then( () => void 0, () => void 0 ); return result; } async advanceCurrentStep(generation) { const active = this.active; if (!active || active.completedSteps >= active.steps.length) return false; this.cancelTimer(); const resolved = active.steps[active.completedSteps]; if (!resolved) return false; try { await this.runStepEffect(resolved, false, generation); if (!this.active || generation !== this.generation) return true; this.active.completedSteps += 1; this.emitState(); this.schedulePendingTimedStep(); return true; } catch (error) { if (generation === this.generation) await this.leaveSlide(); throw error; } } async reverseCurrentStep(generation) { const active = this.active; if (!active || active.completedSteps <= 0) return false; this.cancelTimer(); const resolved = active.steps[active.completedSteps - 1]; if (!resolved) return false; try { await this.runStepEffect(resolved, true, generation); if (!this.active || generation !== this.generation) return true; this.active.completedSteps -= 1; this.applyBuildState(); this.emitState(); return true; } catch (error) { if (generation === this.generation) await this.leaveSlide(); throw error; } } /** Drops transient animation state without touching the current scene. */ abandonActiveSlide() { this.invalidateAsyncWork(); this.active = null; this.overlayMarkupCache.clear(); this.emitState(); } /** Restores every animation target to its final/original visibility and invalidates callbacks. */ async finishActiveSlide() { this.invalidateAsyncWork(); if (this.active) this.restoreOriginalOpacities(); this.active = null; this.overlayMarkupCache.clear(); this.emitState(); } /** Leaves a slide with every animation target restored to its final/original visibility. */ async leaveSlide() { await this.finishActiveSlide(); } /** Runs one animation from the sidepanel and restores the drawing when the preview completes. */ async previewStep(slideScope, step) { await this.leaveSlide(); const elements = this.api.getSceneElements(); const scope = resolveAnimationScope(slideScope, elements); if (!scope) return; const elementIds = resolveAnimationTargetElementIds(scope, step.targets, elements); const originals = /* @__PURE__ */ new Map(); for (const element of elements) { if (elementIds.includes(element.id)) originals.set(element.id, element); } this.active = { scope, steps: elementIds.length > 0 ? [{ step: structuredClone(step), elementIds }] : [], originals, completedSteps: 0 }; const generation = this.generation; try { this.applyBuildState(); await this.wait(250, generation); if (this.active.steps[0] && generation === this.generation) { await this.runStepEffect(this.active.steps[0], false, generation); } await this.wait(Math.max(step.durationMs ?? 350, 150) + 120, generation); } finally { if (generation === this.generation && this.active) await this.leaveSlide(); } } /** Temporarily exposes the fully built current slide for PDF export, then restores build state. */ async withFinalState(task) { const active = this.active; if (!active) return task(); const completedSteps = active.completedSteps; this.invalidateAsyncWork(); active.completedSteps = active.steps.length; this.applyBuildState(); try { return await task(); } finally { if (this.active === active) { active.completedSteps = completedSteps; this.applyBuildState(); this.emitState(); this.schedulePendingTimedStep(); } } } emitState() { this.onStateChange?.(this.getState()); } schedulePendingTimedStep() { this.cancelTimer(); const active = this.active; const pending = active?.steps[active.completedSteps]; if (!active || !pending || pending.step.trigger !== "after-delay") return; const generation = this.generation; this.timer = this.ownerWindow.setTimeout(() => { this.timer = 0; if (generation !== this.generation) return; void this.advance().catch((error) => { console.error("Slideshow timed animation failed", error); }); }, pending.step.delayMs ?? 1e3); } applyBuildState() { const active = this.active; if (!active) return; const hiddenIds = /* @__PURE__ */ new Set(); const initialized = /* @__PURE__ */ new Set(); for (const resolved of active.steps) { const exits = isExitAnimationEffect(resolved.step.effect); for (const id of resolved.elementIds) { if (initialized.has(id)) continue; initialized.add(id); if (!exits) hiddenIds.add(id); } } for (const resolved of active.steps.slice(0, active.completedSteps)) { const exits = isExitAnimationEffect(resolved.step.effect); for (const id of resolved.elementIds) { if (exits) hiddenIds.add(id); else hiddenIds.delete(id); } } const opacities = /* @__PURE__ */ new Map(); for (const [id, original] of active.originals) { opacities.set(id, hiddenIds.has(id) ? 0 : getOpacity(original)); } this.applyOpacities(opacities); } restoreOriginalOpacities() { const active = this.active; if (!active || active.originals.size === 0) return; const opacities = /* @__PURE__ */ new Map(); for (const [id, original] of active.originals) opacities.set(id, getOpacity(original)); this.applyOpacities(opacities); } applyOpacities(opacities) { if (opacities.size === 0) return; const current = this.api.getSceneElements(); let changed = false; const elements = current.map((element) => { const opacity = opacities.get(element.id); if (opacity === void 0 || getOpacity(element) === opacity) return element; changed = true; return { ...element, opacity }; }); if (!changed) return; this.api.updateScene({ elements, captureUpdate: "NEVER" }); } async runStepEffect(resolved, reverse, generation) { const { step } = resolved; const endsHidden = isExitAnimationEffect(step.effect) !== reverse; if (step.effect === "appear" || step.effect === "disappear") { this.applyResolvedOpacity(resolved, endsHidden ? 0 : null); return; } if (step.effect === "fade" || step.effect === "fade-out") { await this.animateFade(resolved, reverse, generation); return; } await this.animateOverlay(resolved, reverse, generation); } applyResolvedOpacity(resolved, opacity) { const active = this.active; if (!active) return; const opacities = /* @__PURE__ */ new Map(); for (const id of resolved.elementIds) { const original = active.originals.get(id); if (original) opacities.set(id, opacity ?? getOpacity(original)); } this.applyOpacities(opacities); } async animateFade(resolved, reverse, generation) { const active = this.active; if (!active) return; const endsHidden = isExitAnimationEffect(resolved.step.effect) !== reverse; const duration = resolved.step.durationMs ?? 350; const started = this.ownerWindow.performance.now(); while (generation === this.generation) { const elapsed = this.ownerWindow.performance.now() - started; const progress = duration <= 0 ? 1 : Math.min(elapsed / duration, 1); const opacities = /* @__PURE__ */ new Map(); for (const id of resolved.elementIds) { const original = active.originals.get(id); if (!original) continue; const originalOpacity = getOpacity(original); opacities.set(id, originalOpacity * (endsHidden ? 1 - progress : progress)); } this.applyOpacities(opacities); if (progress >= 1) break; await this.nextFrame(generation); } } async animateOverlay(resolved, reverse, generation) { const overlay = await this.createOverlay(resolved.elementIds); if (!overlay || generation !== this.generation) { overlay?.remove(); return; } this.overlays.add(overlay); const duration = resolved.step.durationMs ?? 350; const endsHidden = isExitAnimationEffect(resolved.step.effect) !== reverse; const motion = this.getOverlayMotion(resolved.step, overlay); overlay.style.transition = "none"; overlay.style.opacity = "1"; overlay.style.transform = endsHidden ? motion.end : motion.start; this.applyResolvedOpacity(resolved, 0); await this.nextFrame(generation); await this.nextFrame(generation); if (generation !== this.generation) return; overlay.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`; overlay.style.transform = endsHidden ? motion.start : motion.end; if (endsHidden && (resolved.step.effect === "zoom" || resolved.step.effect === "zoom-out")) { overlay.style.opacity = "0"; } await this.wait(duration + 24, generation); if (generation === this.generation) { this.applyResolvedOpacity(resolved, endsHidden ? 0 : null); if (!endsHidden) { await this.nextFrame(generation); await this.nextFrame(generation); } } overlay.remove(); this.overlays.delete(overlay); } getOverlayMotion(step, overlay) { if (step.effect === "zoom" || step.effect === "zoom-out") { return { start: "scale(0.05)", end: "scale(1)" }; } const rect = overlay.getBoundingClientRect(); const appState = this.api.getAppState(); const horizontal = Math.max(rect.width, appState.width * 0.2, 80); const vertical = Math.max(rect.height, appState.height * 0.2, 80); const start = step.direction === "right" ? `translateX(${horizontal}px)` : step.direction === "up" ? `translateY(-${vertical}px)` : step.direction === "down" ? `translateY(${vertical}px)` : `translateX(-${horizontal}px)`; return { start, end: "translate(0, 0)" }; } async createOverlay(elementIds) { const active = this.active; if (!active) return null; const originals = elementIds.map((id) => active.originals.get(id)).filter((element) => Boolean(element)); if (originals.length === 0) return null; this.ea.setView(this.hostView); const state = this.api.getAppState(); const overlayCacheKey = `${state.theme}|${elementIds.join(",")}`; let svgMarkup = this.overlayMarkupCache.get(overlayCacheKey); if (!svgMarkup) { const svg = await this.ea.createViewSVG({ withBackground: false, theme: state.theme, frameRendering: { enabled: false, name: false, outline: false, clip: false }, padding: 0, selectedOnly: false, skipInliningFonts: false, embedScene: false, elementsOverride: originals }); svgMarkup = svg.outerHTML; this.overlayMarkupCache.set(overlayCacheKey, svgMarkup); } const excalidraw = this.hostView.contentEl.querySelector(".excalidraw"); if (!excalidraw) return null; const bounds = this.ea.getBoundingBox(originals); const hostRect = excalidraw.getBoundingClientRect(); const placement = getAnimationOverlayPlacement(bounds, state, { left: hostRect.left + excalidraw.clientLeft, top: hostRect.top + excalidraw.clientTop }); const overlay = this.hostView.ownerDocument.createElement("div"); overlay.className = "slideshow-animation-overlay"; overlay.style.position = "absolute"; overlay.style.pointerEvents = "none"; overlay.style.zIndex = "4"; overlay.style.left = `${placement.left}px`; overlay.style.top = `${placement.top}px`; overlay.style.width = `${placement.width}px`; overlay.style.height = `${placement.height}px`; overlay.style.transformOrigin = "center center"; overlay.innerHTML = svgMarkup; const child = overlay.firstElementChild; if (child) { child.setAttribute("width", "100%"); child.setAttribute("height", "100%"); child.style.display = "block"; child.style.overflow = "visible"; } excalidraw.appendChild(overlay); return overlay; } cancelTimer() { if (this.timer) this.ownerWindow.clearTimeout(this.timer); this.timer = 0; } invalidateAsyncWork() { this.generation += 1; this.cancelTimer(); for (const overlay of this.overlays) overlay.remove(); this.overlays.clear(); } nextFrame(generation) { if (generation !== this.generation) return Promise.resolve(); return new Promise((resolve) => { this.ownerWindow.requestAnimationFrame(() => resolve()); }); } wait(delay, generation) { if (generation !== this.generation) return Promise.resolve(); return new Promise((resolve) => { this.ownerWindow.setTimeout(resolve, delay); }); } }; // src/scripts/slideshow/PresentationControls.ts var PresentationControls = class { constructor(options) { this.options = options; } options; panel = null; select = null; fullscreenButton = null; fadeTimeout = 0; posX1 = 0; posY1 = 0; posX2 = 0; posY2 = 0; /** Creates and attaches the complete slideshow toolbar. */ create() { const { contentElement, slidesCount, pathType, slideTitles, shouldOfferPathVisibility, isPathHidden, ea: ea2, callbacks, icons, t, ownerDocument } = this.options; const excalidrawContainer = contentElement.querySelector(".excalidraw"); if (!excalidrawContainer) { throw new Error("Could not find the Excalidraw container for slideshow controls."); } const top = contentElement.innerHeight; this.panel = excalidrawContainer.createDiv({ cls: [ "excalidraw-presentation-panel", ...ea2.DEVICE.isMobile ? ["slideshow-presentation-panel--mobile"] : [] ], attr: { style: ` width: fit-content; max-width: calc(100% - 12px); z-index:5; position: absolute; top:calc(${top}px - var(--default-button-size)*2); left:50%; transform:translateX(-50%);` } }); if (ea2.DEVICE.isMobile) { this.panel.style.top = "auto"; this.panel.style.bottom = "8px"; } this.setFadeTimeout(this.options.transitionDelay * 3); const panelColumn = this.panel.createDiv({ cls: "panelColumn" }); panelColumn.createDiv( { cls: ["Island", "buttonList"], attr: { style: ` max-width: calc(100vw - 12px); justify-content: space-between; height: calc(var(--default-button-size)*1.5); width: max-content; background: var(--island-bg-color); display: flex; align-items: center;` } }, (buttonList) => { buttonList.createEl("style", { text: ` .excalidraw-presentation-panel select:focus { box-shadow: var(--input-shadow); } .excalidraw-presentation-panel .buttonList { max-width: calc(100vw - 12px); } .excalidraw-presentation-panel.slideshow-presentation-panel--mobile .buttonList { flex-wrap: wrap; height: auto !important; justify-content: center !important; } .excalidraw-presentation-panel.slideshow-presentation-panel--mobile select { width: clamp(76px, 24vw, 132px); max-width: 132px; text-overflow: ellipsis; } ` }); buttonList.createEl( "button", { attr: { style: "margin-left: calc(var(--default-button-size)*0.25);", "aria-label": t("previousSlide") } }, (button) => { button.innerHTML = icons.leftArrow; button.onclick = callbacks.previous; } ); this.select = buttonList.createEl( "select", { attr: { style: ` font-size: inherit; background-color: var(--island-bg-color); border: none; color: var(--color-gray-100); cursor: pointer;`, "aria-label": t("navigateToSlide") } }, (selectElement) => { for (let index = 0; index < slidesCount; index += 1) { const option = ownerDocument.createElement("option"); option.text = t("presentationSlideTitle", { title: slideTitles[index] ?? t("slideLabel", { number: index + 1 }), number: index + 1, total: slidesCount }); option.value = String(index + 1); selectElement.add(option); } selectElement.addEventListener("change", () => { const selectedSlideNumber = Number.parseInt(selectElement.value, 10); selectElement.blur(); callbacks.navigateToSlide(selectedSlideNumber); }); } ); buttonList.createEl( "button", { attr: { "aria-label": t("nextSlide") } }, (button) => { button.innerHTML = icons.rightArrow; button.onclick = callbacks.next; } ); if (!ea2.DEVICE.isMobile) { buttonList.createDiv({ attr: { style: ` width: 1px; height: var(--default-button-size); background-color: var(--default-border-color); margin: 0px auto;` } }); } buttonList.createEl( "button", { attr: { "aria-label": t("toggleLaser") } }, (button) => { button.innerHTML = icons.laserOff; button.onclick = () => { const laserIsOn = callbacks.toggleLaser(); button.innerHTML = laserIsOn ? icons.laserOn : icons.laserOff; }; } ); buttonList.createEl( "button", { attr: { "aria-label": t("refocusSlide") } }, (button) => { button.innerHTML = icons.refocus; button.onclick = callbacks.refocus; } ); if (!ea2.DEVICE.isMobile) { buttonList.createEl( "button", { attr: { "aria-label": t("toggleFullscreen") } }, (button) => { this.fullscreenButton = button; button.innerHTML = this.options.isFullscreen ? icons.minimize : icons.maximize; button.onclick = callbacks.toggleFullscreen; } ); } if (pathType === "line") { if (shouldOfferPathVisibility) { let pathHidden = isPathHidden; buttonList.createEl( "button", { attr: { "aria-label": t("pathVisibility") } }, (button) => { const renderPathVisibility = () => { const label = pathHidden ? t("keepPresentationPathHidden") : t("keepPresentationPathVisible"); button.innerHTML = pathHidden ? icons.eyeOff : icons.eye; button.setAttribute("aria-label", label); button.setAttribute("aria-pressed", String(pathHidden)); }; renderPathVisibility(); button.onclick = () => { pathHidden = !pathHidden; renderPathVisibility(); callbacks.togglePathVisibility(pathHidden); }; } ); } buttonList.createEl( "button", { attr: { "aria-label": t("editSlide") } }, (button) => { button.innerHTML = icons.edit; button.onclick = callbacks.editSlide; } ); } buttonList.createEl( "button", { attr: { "aria-label": t("openSlideshowPanel") } }, (button) => { button.innerHTML = icons.settings; button.onclick = callbacks.openSidepanel; } ); if (ea2.DEVICE.isDesktop) { buttonList.createEl( "button", { attr: { style: "margin-right: calc(var(--default-button-size)*0.25);", "aria-label": t("printDialogTitle") } }, (button) => { button.innerHTML = icons.printer; button.onclick = callbacks.print; } ); } buttonList.createEl( "button", { attr: { style: "margin-right: calc(var(--default-button-size)*0.25);", "aria-label": t("endPresentation") } }, (button) => { button.innerHTML = icons.finish; button.onclick = callbacks.finish; } ); } ); this.panel.addEventListener("pointerdown", this.onPointerDown, false); this.panel.addEventListener("mouseenter", this.onMouseEnter, false); this.panel.addEventListener("mouseleave", this.onMouseLeave, false); this.options.ownerWindow.addEventListener("pointerup", this.onPointerUp, false); } /** Repositions the panel and restores the current slide's viewport. */ resetPosition(refocus = true) { if (!this.panel) return; const top = this.options.contentElement.innerHeight; if (this.options.ea.DEVICE.isMobile) { this.panel.style.top = "auto"; this.panel.style.bottom = "8px"; } else { this.panel.style.top = `calc(${top}px - var(--default-button-size)*2)`; this.panel.style.bottom = "auto"; } this.panel.style.left = "50%"; this.panel.style.transform = "translateX(-50%)"; if (refocus) this.options.callbacks.refocus(); } /** Updates the slide picker to the one-based slide number. */ setSelectedSlide(slideNumber) { if (this.select) this.select.value = String(slideNumber); } /** Updates the fullscreen button without rebuilding the toolbar. */ setFullscreen(fullscreen) { if (this.fullscreenButton) { this.fullscreenButton.innerHTML = fullscreen ? this.options.icons.minimize : this.options.icons.maximize; } } /** Removes the panel and every event listener owned by it. */ destroy() { this.clearFadeTimeout(); this.options.ownerWindow.removeEventListener("pointermove", this.onDrag, true); this.options.ownerWindow.removeEventListener("pointerup", this.onPointerUp, false); this.panel?.removeEventListener("pointerdown", this.onPointerDown, false); this.panel?.removeEventListener("mouseenter", this.onMouseEnter, false); this.panel?.removeEventListener("mouseleave", this.onMouseLeave, false); this.panel?.parentElement?.removeChild(this.panel); this.panel = null; this.select = null; this.fullscreenButton = null; } setFadeTimeout(delay = this.options.transitionDelay) { this.fadeTimeout = this.options.ownerWindow.setTimeout(() => { this.fadeTimeout = 0; if (this.options.ownerDocument.activeElement === this.select) { this.setFadeTimeout(delay); return; } if (this.panel) this.panel.style.opacity = String(this.options.fadeLevel); }, delay); } clearFadeTimeout() { if (this.fadeTimeout) { this.options.ownerWindow.clearTimeout(this.fadeTimeout); this.fadeTimeout = 0; } if (this.panel) this.panel.style.opacity = "1"; } onPointerUp = () => { this.options.ownerWindow.removeEventListener("pointermove", this.onDrag, true); }; onPointerDown = (event) => { this.clearFadeTimeout(); this.setFadeTimeout(); if (this.panel && this.panel.style.bottom !== "auto" && this.panel.style.bottom !== "") { this.panel.style.top = `${this.panel.offsetTop}px`; this.panel.style.bottom = "auto"; } this.posX2 = event.clientX; this.posY2 = event.clientY; this.options.ownerWindow.addEventListener("pointermove", this.onDrag, true); }; onDrag = (event) => { event.preventDefault(); this.posX1 = this.posX2 - event.clientX; this.posY1 = this.posY2 - event.clientY; this.posX2 = event.clientX; this.posY2 = event.clientY; this.updatePosition(this.posY1, this.posX1); }; updatePosition(deltaY = 0, deltaX = 0) { if (!this.panel) return; this.panel.style.top = `${this.panel.offsetTop - deltaY}px`; this.panel.style.left = `${this.panel.offsetLeft - deltaX}px`; } onMouseEnter = () => this.clearFadeTimeout(); onMouseLeave = () => this.setFadeTimeout(); }; // src/sharedUtils/previewUtils.ts var elementFingerprintCache = /* @__PURE__ */ new WeakMap(); function cloneWithoutMetadata(element) { const copy = { ...element }; const customData = copy.customData; if (typeof customData === "object" && customData !== null && !Array.isArray(customData)) { const visualCustomData = { ...customData }; delete visualCustomData.slideshow; if (Object.keys(visualCustomData).length === 0) delete copy.customData; else copy.customData = visualCustomData; } delete copy.version; delete copy.versionNonce; delete copy.updated; if (copy.type === "frame") delete copy.name; return copy; } function getSceneVisualFingerprint(elements) { return `[${elements.map((element) => { const raw = element; const cacheKey = element; if (raw.version === void 0 && raw.versionNonce === void 0) { return JSON.stringify(cloneWithoutMetadata(element)); } const cached = elementFingerprintCache.get(cacheKey); if (cached && cached.version === raw.version && cached.versionNonce === raw.versionNonce) { return cached.value; } const value = JSON.stringify(cloneWithoutMetadata(element)); elementFingerprintCache.set(cacheKey, { version: raw.version, versionNonce: raw.versionNonce, value }); return value; }).join(",")}]`; } function exportAreaPreviewPNG(ea2, options) { const scale = Math.min(2, Math.max(options.targetWidth / Math.max(options.area.width, 1), 0.01)); return ea2.createViewPNG({ withBackground: true, theme: options.theme, frameRendering: { enabled: true, name: false, outline: false, clip: false }, padding: 0, selectedOnly: false, embedScene: false, elementsOverride: options.elements, exportArea: options.area, scale }); } // src/sharedUtils/AsyncTaskQueue.ts var AsyncTaskQueue = class { constructor(concurrency = 1) { this.concurrency = concurrency; if (!Number.isInteger(concurrency) || concurrency < 1) { throw new RangeError("AsyncTaskQueue concurrency must be a positive integer."); } } concurrency; generation = 0; activeCount = 0; pending = /* @__PURE__ */ new Map(); waiting = []; idleResolvers = /* @__PURE__ */ new Set(); enqueue(key, task, isRelevant = () => true) { const existing = this.pending.get(key); if (existing) return existing; const generation = this.generation; let resolveResult = () => void 0; let rejectResult = () => void 0; const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject; }); this.pending.set(key, result); this.waiting.push({ generation, isRelevant, task, resolve: resolveResult, reject: rejectResult }); const removePending = () => { if (this.pending.get(key) === result) this.pending.delete(key); this.resolveIdleIfNeeded(); }; void result.then(removePending, removePending); this.pump(); return result; } clear() { this.generation += 1; this.pending.clear(); for (const waiting of this.waiting.splice(0)) waiting.resolve(void 0); this.resolveIdleIfNeeded(); } async idle() { if (this.activeCount === 0 && this.waiting.length === 0) return; await new Promise((resolve) => this.idleResolvers.add(resolve)); } pump() { while (this.activeCount < this.concurrency && this.waiting.length > 0) { const next = this.waiting.shift(); if (!next) break; if (next.generation !== this.generation) { next.resolve(void 0); continue; } try { if (!next.isRelevant()) { next.resolve(void 0); continue; } } catch (error) { next.reject(error); continue; } this.activeCount += 1; void Promise.resolve().then(next.task).then(next.resolve, next.reject).finally(() => { this.activeCount -= 1; this.pump(); this.resolveIdleIfNeeded(); }); } this.resolveIdleIfNeeded(); } resolveIdleIfNeeded() { if (this.activeCount !== 0 || this.waiting.length !== 0) return; for (const resolve of this.idleResolvers) resolve(); this.idleResolvers.clear(); } }; // src/sharedUtils/ByteBudgetLruCache.ts var ByteBudgetLruCache = class { constructor(maximumSize, dispose) { this.maximumSize = maximumSize; this.dispose = dispose; } maximumSize; dispose; values = /* @__PURE__ */ new Map(); totalSize = 0; get size() { return this.totalSize; } get(key) { const entry = this.values.get(key); if (!entry) return void 0; this.values.delete(key); this.values.set(key, entry); return entry.value; } set(key, value, size) { this.delete(key); const normalizedSize = Math.max(0, Math.trunc(size)); this.values.set(key, { value, size: normalizedSize }); this.totalSize += normalizedSize; while (this.totalSize > this.maximumSize && this.values.size > 1) { const oldest = this.values.keys().next().value; if (oldest === void 0) break; this.delete(oldest); } } delete(key) { const entry = this.values.get(key); if (!entry) return false; this.values.delete(key); this.totalSize -= entry.size; this.dispose?.(entry.value); return true; } clear() { for (const entry of this.values.values()) this.dispose?.(entry.value); this.values.clear(); this.totalSize = 0; } }; // src/scripts/slideshow/previewAppearance.ts function getPreviewAppearance(state) { const color = typeof state.viewBackgroundColor === "string" ? state.viewBackgroundColor : "#ffffff"; const backgroundColor = state.theme === "dark" ? window.ExcalidrawLib.applyDarkModeFilter(color) : color; return { theme: state.theme, backgroundColor, key: `${state.theme}|${color}` }; } // src/scripts/slideshow/SlidePreviewService.ts var PREVIEW_CACHE_BYTES = 64 * 1024 * 1024; var DEFAULT_PREVIEW_WIDTH = 960; var PREVIEW_EXPORT_CONCURRENCY = 2; function getPreviewNavigationRect(slide, maxZoom, printSlideWidth = 1920, printSlideHeight = 1080) { return getNavigationRect( slide.rect, { width: printSlideWidth, height: printSlideHeight }, maxZoom ); } function getSlideVisualFingerprint(elements, slide) { return getSceneVisualFingerprint( slide.kind === "path" ? elements.filter((element) => element.id !== slide.pathId) : elements ); } function getHiddenBuildElementIds(slide, completedAnimationSteps, elements, config) { if (slide.animationSteps.length === 0) return []; if (completedAnimationSteps === void 0 && !slide.animationSteps.some((step) => isExitAnimationEffect(step.effect))) { return []; } const completed = Math.min( Math.max( Math.trunc(completedAnimationSteps ?? slide.animationSteps.length), 0 ), slide.animationSteps.length ); const scope = getAnimationSlideScope(slide, config); const resolved = slide.animationSteps.map((step) => ({ step, ids: resolveAnimationTargetElementIds(scope, step.targets, elements) })); const hiddenIds = /* @__PURE__ */ new Set(); const initialized = /* @__PURE__ */ new Set(); for (const current of resolved) { const exits = isExitAnimationEffect(current.step.effect); for (const id of current.ids) { if (initialized.has(id)) continue; initialized.add(id); if (!exits) hiddenIds.add(id); } } for (const current of resolved.slice(0, completed)) { const exits = isExitAnimationEffect(current.step.effect); for (const id of current.ids) { if (exits) hiddenIds.add(id); else hiddenIds.delete(id); } } return [...hiddenIds].sort(); } var SlidePreviewService = class { constructor(ea2, api, config) { this.ea = ea2; this.api = api; this.config = config; } ea; api; config; queue = new AsyncTaskQueue(PREVIEW_EXPORT_CONCURRENCY); cached = new ByteBudgetLruCache( PREVIEW_CACHE_BYTES, (preview) => URL.revokeObjectURL(preview.objectUrl) ); generation = 0; /** Returns the drawing background used behind previews. */ getBackgroundColor() { return getPreviewAppearance(this.api.getAppState()).backgroundColor; } /** Returns the configured presentation aspect ratio used by sorter previews. */ getAspectRatio() { return `${this.config.printSlideWidth} / ${this.config.printSlideHeight}`; } /** Invalidates queued preview work while retaining already-rendered bitmaps. */ cancelPending() { this.generation += 1; this.queue.clear(); } /** Drops cached previews and invalidates queued work, for example after switching drawings. */ clear() { this.cancelPending(); this.cached.clear(); } createPreviewElement(cached, ownerDocument) { const image = ownerDocument.createElement("img"); image.src = cached.objectUrl; image.alt = ""; image.decoding = "async"; image.draggable = false; image.setAttribute("aria-hidden", "true"); image.style.width = "100%"; image.style.height = "100%"; image.style.objectFit = "contain"; image.style.backgroundColor = cached.backgroundColor; return image; } async exportPreview(localElements, slide, hiddenElementIds, originalOpacities, targetWidth, generation, cacheKey, appearance = getPreviewAppearance(this.api.getAppState())) { const rect = getPreviewNavigationRect( slide, this.config.maxZoom, this.config.printSlideWidth, this.config.printSlideHeight ); const exportArea = { x: Math.min(rect.left, rect.right), y: Math.min(rect.top, rect.bottom), width: Math.abs(rect.right - rect.left), height: Math.abs(rect.bottom - rect.top) }; if (generation !== this.generation || getPreviewAppearance(this.api.getAppState()).key !== appearance.key) return void 0; const hiddenIds = new Set(hiddenElementIds); const exportElements = localElements.map((element) => { let opacity = element.opacity; if (slide.kind === "path" && element.id === slide.pathId) opacity = 0; const originalOpacity = originalOpacities?.get(element.id); if (originalOpacity !== void 0) opacity = originalOpacity; if (hiddenIds.has(element.id)) opacity = 0; if (opacity === element.opacity) return element; return { ...element, opacity }; }); const blob = await exportAreaPreviewPNG(this.ea, { elements: exportElements, area: exportArea, targetWidth, theme: appearance.theme }); if (generation !== this.generation || getPreviewAppearance(this.api.getAppState()).key !== appearance.key) return void 0; const cached = { objectUrl: URL.createObjectURL(blob), backgroundColor: appearance.backgroundColor }; this.cached.set(cacheKey, cached, blob.size); return cached; } /** Creates a bounded raster preview in the caller's owner document. */ async createPreview(slide, ownerDocument, state = {}) { const elements = this.ea.getViewElements(); if (elements.length === 0) return null; const hiddenElementIds = getHiddenBuildElementIds( slide, state.completedAnimationSteps, elements, this.config ); const appState = this.api.getAppState(); const appearance = getPreviewAppearance(appState); const targetWidth = Math.max(Math.trunc(state.targetWidth ?? DEFAULT_PREVIEW_WIDTH), 1); const opacityKey = state.originalOpacities ? [...state.originalOpacities.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([id, opacity]) => `${id}:${opacity}`).join(",") : "none"; const rect = getPreviewNavigationRect( slide, this.config.maxZoom, this.config.printSlideWidth, this.config.printSlideHeight ); const exportArea = { x: Math.min(rect.left, rect.right), y: Math.min(rect.top, rect.bottom), width: Math.abs(rect.right - rect.left), height: Math.abs(rect.bottom - rect.top) }; const localElements = this.ea.getElementsIntersectionArea(elements, exportArea, { includeBoundElements: true }); const cacheKey = [ appearance.key, slide.kind === "path" ? `path:${slide.pathId}` : "frame", `hidden:${hiddenElementIds.join(",")}`, `opacity:${opacityKey}`, `area:${rect.left},${rect.top},${rect.right},${rect.bottom}`, `width:${targetWidth}`, getSlideVisualFingerprint(localElements, slide) ].join("|"); const existing = this.cached.get(cacheKey); if (existing) return this.createPreviewElement(existing, ownerDocument); const generation = this.generation; const cached = await this.queue.enqueue( cacheKey, () => this.exportPreview( localElements, slide, hiddenElementIds, state.originalOpacities, targetWidth, generation, cacheKey, appearance ), () => generation === this.generation ); return cached ? this.createPreviewElement(cached, ownerDocument) : null; } }; // src/scripts/slideshow/slideshowSettings.ts var DEFAULT_SLIDESHOW_CONFIG = { transitionStepCount: 100, transitionDelay: 1e3, frameSleep: 1, editZoomOut: 0.7, fadeLevel: 0.1, printSlideWidth: 1920, printSlideHeight: 1080, maxZoom: 30 }; var CONFIG_KEYS = Object.keys(DEFAULT_SLIDESHOW_CONFIG); var START_MODE_SETTING = "slideshowStartMode"; var WINDOW_MODE_SETTING = "slideshowWindowMode"; var NOTES_MODE_SETTING = "slideshowNotesMode"; var PRESENTATION_TYPE_SETTING = "slideshowPresentationType"; var PRESENTATION_SOURCE_BY_DRAWING_SETTING = "slideshowPresentationSourceByDrawing"; var DISPLAY_TARGETS_SETTING = "slideshowDisplayTargetsByDevice"; var DISPLAY_TARGETS_BY_CONFIGURATION_SETTING = "slideshowDisplayTargetsByDeviceConfiguration"; var PRESENTER_NOTES_FONT_SIZE_SETTING = "slideshowPresenterNotesFontSize"; var PRESENTER_NOTES_FONT_SIZE_BY_DISPLAY_SETTING = "slideshowPresenterNotesFontSizeByDeviceConfigurationDisplay"; var SORTER_THUMBNAIL_MAX_WIDTH_SETTING = "slideshowSorterThumbnailMaxWidth"; var LEGACY_LAUNCH_MODE_SETTING = "slideshowLaunchMode"; var LEGACY_START_FULLSCREEN_SETTING = "slideshowStartFullscreen"; var DEFAULT_PRESENTER_NOTES_FONT_SIZE = 18; var DEFAULT_SORTER_THUMBNAIL_MAX_WIDTH = 280; function readSettings(ea2) { const getSettings = ea2.getScriptSettings; return typeof getSettings === "function" ? getSettings.call(ea2) : {}; } function loadSlideshowLaunchPreferences(ea2) { const settings = readSettings(ea2); const legacyMode = settings[LEGACY_LAUNCH_MODE_SETTING]; const rawStartMode = settings[START_MODE_SETTING]; const startMode = rawStartMode === "resume" || rawStartMode === "current" ? rawStartMode : rawStartMode === "beginning" ? "beginning" : legacyMode === "resume" || legacyMode === "current" ? legacyMode : "beginning"; const rawWindowMode = settings[WINDOW_MODE_SETTING]; const windowMode = rawWindowMode === "window" || rawWindowMode === "fullscreen" ? rawWindowMode : settings[LEGACY_START_FULLSCREEN_SETTING] === false ? "window" : "fullscreen"; const rawNotesMode = settings[NOTES_MODE_SETTING]; const notesMode = rawNotesMode === "presenter" || rawNotesMode === "slides" ? rawNotesMode : legacyMode === "presenter" ? "presenter" : "slides"; const rawPresentationType = settings[PRESENTATION_TYPE_SETTING]; const presentationType = rawPresentationType === "frame" || rawPresentationType === "line" ? rawPresentationType : void 0; return { startMode, windowMode, notesMode, ...presentationType ? { presentationType } : {} }; } async function saveSlideshowLaunchPreferences(ea2, preferences) { const settings = ea2.getScriptSettings(); await ea2.setScriptSettings({ ...settings, [START_MODE_SETTING]: preferences.startMode, [WINDOW_MODE_SETTING]: preferences.windowMode, [NOTES_MODE_SETTING]: preferences.notesMode, ...preferences.presentationType ? { [PRESENTATION_TYPE_SETTING]: preferences.presentationType } : {} }); } function loadSlideshowPresentationSource(ea2, drawingPath) { const raw = readSettings(ea2)[PRESENTATION_SOURCE_BY_DRAWING_SETTING]; if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0; const source = raw[drawingPath]; if (source === "frame") return "frame"; return typeof source === "string" && source.startsWith("line:") ? source : void 0; } async function saveSlideshowPresentationSource(ea2, drawingPath, source) { const settings = ea2.getScriptSettings(); const raw = settings[PRESENTATION_SOURCE_BY_DRAWING_SETTING]; const byDrawing = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}; await ea2.setScriptSettings({ ...settings, [PRESENTATION_SOURCE_BY_DRAWING_SETTING]: { ...byDrawing, [drawingPath]: source } }); } function asDisplayPreferences(value) { if (!value || typeof value !== "object" || Array.isArray(value)) return null; const record = value; const normalizeId = (id) => { if (id === null) return null; return typeof id === "number" && Number.isFinite(id) ? id : void 0; }; const normalizeIdentity = (identity) => { if (identity === null) return null; return typeof identity === "string" && identity.length > 0 ? identity : void 0; }; const presentationDisplayId = normalizeId(record.presentationDisplayId); const presenterDisplayId = normalizeId(record.presenterDisplayId); if (presentationDisplayId === void 0 || presenterDisplayId === void 0) return null; const presentationDisplayIdentity = normalizeIdentity(record.presentationDisplayIdentity); const presenterDisplayIdentity = normalizeIdentity(record.presenterDisplayIdentity); return { presentationDisplayId, presenterDisplayId, ...presentationDisplayIdentity !== void 0 ? { presentationDisplayIdentity } : {}, ...presenterDisplayIdentity !== void 0 ? { presenterDisplayIdentity } : {} }; } function loadSlideshowDisplayPreferences(ea2, deviceKey, configurationKey) { const settings = readSettings(ea2); if (configurationKey) { const configuredRaw = settings[DISPLAY_TARGETS_BY_CONFIGURATION_SETTING]; if (configuredRaw && typeof configuredRaw === "object" && !Array.isArray(configuredRaw)) { const byDevice = configuredRaw[deviceKey]; if (byDevice && typeof byDevice === "object" && !Array.isArray(byDevice)) { const configured = asDisplayPreferences( byDevice[configurationKey] ); if (configured) return configured; } } } const legacyRaw = settings[DISPLAY_TARGETS_SETTING]; if (!legacyRaw || typeof legacyRaw !== "object" || Array.isArray(legacyRaw)) return null; return asDisplayPreferences(legacyRaw[deviceKey]); } async function saveSlideshowDisplayPreferences(ea2, deviceKey, preferences, configurationKey) { const settings = ea2.getScriptSettings(); if (!configurationKey) { const existingRaw2 = settings[DISPLAY_TARGETS_SETTING]; const existing2 = existingRaw2 && typeof existingRaw2 === "object" && !Array.isArray(existingRaw2) ? existingRaw2 : {}; await ea2.setScriptSettings({ ...settings, [DISPLAY_TARGETS_SETTING]: { ...existing2, [deviceKey]: { ...preferences } } }); return; } const existingRaw = settings[DISPLAY_TARGETS_BY_CONFIGURATION_SETTING]; const existing = existingRaw && typeof existingRaw === "object" && !Array.isArray(existingRaw) ? existingRaw : {}; const existingDeviceRaw = existing[deviceKey]; const existingDevice = existingDeviceRaw && typeof existingDeviceRaw === "object" && !Array.isArray(existingDeviceRaw) ? existingDeviceRaw : {}; await ea2.setScriptSettings({ ...settings, [DISPLAY_TARGETS_BY_CONFIGURATION_SETTING]: { ...existing, [deviceKey]: { ...existingDevice, [configurationKey]: { ...preferences } } } }); } function loadPresenterNotesFontSize(ea2, deviceKey, configurationKey, displayIdentity) { const settings = readSettings(ea2); let raw; if (deviceKey && configurationKey && displayIdentity) { const byDevice = settings[PRESENTER_NOTES_FONT_SIZE_BY_DISPLAY_SETTING]; if (byDevice && typeof byDevice === "object" && !Array.isArray(byDevice)) { const device = byDevice[deviceKey]; if (device && typeof device === "object" && !Array.isArray(device)) { const configuration = device[configurationKey]; if (configuration && typeof configuration === "object" && !Array.isArray(configuration)) { raw = configuration[displayIdentity]; } } } } if (raw === void 0) raw = settings[PRESENTER_NOTES_FONT_SIZE_SETTING]; const value = typeof raw === "number" && Number.isFinite(raw) ? raw : DEFAULT_PRESENTER_NOTES_FONT_SIZE; return Math.min(48, Math.max(12, Math.round(value))); } async function savePresenterNotesFontSize(ea2, fontSize, deviceKey, configurationKey, displayIdentity) { const value = Math.min(48, Math.max(12, Math.round(fontSize))); const settings = ea2.getScriptSettings(); if (!deviceKey || !configurationKey || !displayIdentity) { await ea2.setScriptSettings({ ...settings, [PRESENTER_NOTES_FONT_SIZE_SETTING]: value }); return; } const raw = settings[PRESENTER_NOTES_FONT_SIZE_BY_DISPLAY_SETTING]; const byDevice = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}; const rawDevice = byDevice[deviceKey]; const device = rawDevice && typeof rawDevice === "object" && !Array.isArray(rawDevice) ? rawDevice : {}; const rawConfiguration = device[configurationKey]; const configuration = rawConfiguration && typeof rawConfiguration === "object" && !Array.isArray(rawConfiguration) ? rawConfiguration : {}; await ea2.setScriptSettings({ ...settings, [PRESENTER_NOTES_FONT_SIZE_BY_DISPLAY_SETTING]: { ...byDevice, [deviceKey]: { ...device, [configurationKey]: { ...configuration, [displayIdentity]: value } } } }); } function loadSorterThumbnailMaxWidth(ea2) { const raw = readSettings(ea2)[SORTER_THUMBNAIL_MAX_WIDTH_SETTING]; const value = typeof raw === "number" && Number.isFinite(raw) ? raw : DEFAULT_SORTER_THUMBNAIL_MAX_WIDTH; return Math.min(520, Math.max(140, Math.round(value))); } async function saveSorterThumbnailMaxWidth(ea2, width) { const value = Math.min(520, Math.max(140, Math.round(width))); await ea2.setScriptSettings({ ...ea2.getScriptSettings(), [SORTER_THUMBNAIL_MAX_WIDTH_SETTING]: value }); } function finiteNumber(value, fallback) { return typeof value === "number" && Number.isFinite(value) ? value : fallback; } function normalizeSlideshowConfig(settings) { return { transitionStepCount: Math.max( 1, Math.round(finiteNumber(settings.transitionStepCount, DEFAULT_SLIDESHOW_CONFIG.transitionStepCount)) ), transitionDelay: Math.max( 1, finiteNumber(settings.transitionDelay, DEFAULT_SLIDESHOW_CONFIG.transitionDelay) ), frameSleep: Math.max(0, finiteNumber(settings.frameSleep, DEFAULT_SLIDESHOW_CONFIG.frameSleep)), editZoomOut: Math.max( 0.05, finiteNumber(settings.editZoomOut, DEFAULT_SLIDESHOW_CONFIG.editZoomOut) ), fadeLevel: Math.min( 1, Math.max(0, finiteNumber(settings.fadeLevel, DEFAULT_SLIDESHOW_CONFIG.fadeLevel)) ), printSlideWidth: Math.max( 1, Math.round(finiteNumber(settings.printSlideWidth, DEFAULT_SLIDESHOW_CONFIG.printSlideWidth)) ), printSlideHeight: Math.max( 1, Math.round(finiteNumber(settings.printSlideHeight, DEFAULT_SLIDESHOW_CONFIG.printSlideHeight)) ), maxZoom: Math.max(0.1, finiteNumber(settings.maxZoom, DEFAULT_SLIDESHOW_CONFIG.maxZoom)) }; } function loadSlideshowConfig(ea2) { return normalizeSlideshowConfig(ea2.getScriptSettings()); } async function saveSlideshowConfig(ea2, config) { const existing = ea2.getScriptSettings(); const next = { ...existing }; for (const key of CONFIG_KEYS) next[key] = config[key]; await ea2.setScriptSettings(next); } function resetSlideshowConfigToDefaults(config) { Object.assign(config, DEFAULT_SLIDESHOW_CONFIG); } function addNumberSetting(ea2, container, name, description, value, onChange) { new ea2.obsidian.Setting(container).setName(name).setDesc(description).addText((text) => { text.inputEl.type = "number"; text.inputEl.step = "any"; text.setValue(String(value)).onChange((raw) => { const parsed = Number(raw); if (Number.isFinite(parsed)) onChange(parsed); }); }); } function openSlideshowSettingsModal(ea2, config, t, onSaved) { const modal = new ea2.obsidian.Modal(app); modal.titleEl.setText(t("settingsTitle")); const draft = { ...config }; const renderContent = () => { const { contentEl } = modal; contentEl.empty(); addNumberSetting( ea2, contentEl, t("settingsTransitionStepCount"), t("settingsTransitionStepCountDesc"), draft.transitionStepCount, (value) => { draft.transitionStepCount = value; } ); addNumberSetting( ea2, contentEl, t("settingsTransitionDelay"), t("settingsTransitionDelayDesc"), draft.transitionDelay, (value) => { draft.transitionDelay = value; } ); addNumberSetting( ea2, contentEl, t("settingsFrameSleep"), t("settingsFrameSleepDesc"), draft.frameSleep, (value) => { draft.frameSleep = value; } ); addNumberSetting( ea2, contentEl, t("settingsEditZoomOut"), t("settingsEditZoomOutDesc"), draft.editZoomOut, (value) => { draft.editZoomOut = value; } ); addNumberSetting( ea2, contentEl, t("settingsFadeLevel"), t("settingsFadeLevelDesc"), draft.fadeLevel, (value) => { draft.fadeLevel = value; } ); addNumberSetting( ea2, contentEl, t("settingsPrintSlideWidth"), t("settingsPrintSlideWidthDesc"), draft.printSlideWidth, (value) => { draft.printSlideWidth = value; } ); addNumberSetting( ea2, contentEl, t("settingsPrintSlideHeight"), t("settingsPrintSlideHeightDesc"), draft.printSlideHeight, (value) => { draft.printSlideHeight = value; } ); addNumberSetting( ea2, contentEl, t("settingsMaxZoom"), t("settingsMaxZoomDesc"), draft.maxZoom, (value) => { draft.maxZoom = value; } ); const actions = contentEl.createDiv({ cls: "modal-button-container" }); actions.style.justifyContent = "flex-end"; const resetButton = actions.createEl("button", { text: t("settingsResetDefaults") }); resetButton.addEventListener("click", () => { resetSlideshowConfigToDefaults(draft); renderContent(); }); const cancelButton = actions.createEl("button", { text: t("settingsCancel") }); cancelButton.addEventListener("click", () => modal.close()); const saveButton = actions.createEl("button", { text: t("settingsSave"), cls: "mod-cta" }); saveButton.addEventListener("click", () => { void (async () => { try { const normalized = normalizeSlideshowConfig( draft ); await saveSlideshowConfig(ea2, normalized); Object.assign(config, normalized); onSaved(); modal.close(); new Notice(t("settingsSaved")); } catch (error) { console.error("Slideshow settings save failed", error); new Notice(t("settingsSaveFailed")); } })(); }); }; modal.onOpen = renderContent; modal.open(); } // src/scripts/slideshow/styles.ts var SLIDESHOW_SIDEPANEL_STYLES = ` .slideshow-sidepanel { display:flex; flex-direction:column; gap:12px; padding:10px; height:100%; box-sizing:border-box; container-type:inline-size; container-name:slideshow-panel; } .slideshow-sidepanel__support { color:var(--text-muted); font-size:var(--font-ui-smaller); line-height:1.3; } .slideshow-sidepanel__support a { color:var(--text-accent); } .slideshow-sidepanel__header { display:flex; flex-wrap:wrap; gap:8px; align-items:center; } .slideshow-sidepanel__header button { display:inline-flex; align-items:center; justify-content:center; gap:6px; } .slideshow-sidepanel__header .slideshow-sidepanel__icon-button { width:36px; height:36px; min-width:36px; padding:7px; } .slideshow-sidepanel__launch-main { flex:0 0 auto; } .slideshow-sidepanel__launch-settings { border:1px solid var(--background-modifier-border); border-radius:8px; background:var(--background-secondary-alt); overflow:visible; } .slideshow-sidepanel__launch-settings-summary { cursor:pointer; padding:8px 10px; color:var(--text-muted); font-size:var(--font-ui-small); font-weight:600; user-select:none; } .slideshow-sidepanel__launch-settings[open] .slideshow-sidepanel__launch-settings-summary { border-bottom:1px solid var(--background-modifier-border); } .slideshow-sidepanel__launch-options { display:flex; flex-direction:column; gap:7px; padding:9px; } .slideshow-sidepanel__launch-option { display:block; min-width:0; } .slideshow-sidepanel__launch-option select { width:100%; min-width:0; } .slideshow-sidepanel__display-controls { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; padding:0 9px 9px; } .slideshow-sidepanel__display-controls label { min-width:0; display:flex; flex-direction:column; gap:4px; color:var(--text-muted); font-size:var(--font-ui-smaller); } .slideshow-sidepanel__display-controls select { min-width:0; width:100%; } .slideshow-sidepanel__summary-row { display:flex; align-items:center; gap:6px; min-width:0; } .slideshow-sidepanel__summary { flex:1 1 auto; min-width:0; color:var(--text-muted); font-size:var(--font-ui-smaller); } .slideshow-sidepanel__thumbnail-size-control { flex:0 1 180px; min-width:100px; max-width:240px; display:flex; align-items:center; } .slideshow-sidepanel__thumbnail-size-control input { width:100%; min-width:0; margin:0; } .slideshow-sidepanel__presentation-settings { flex:0 0 auto; width:28px; height:28px; min-width:28px; padding:5px; } .slideshow-sidepanel__path-actions { display:flex; flex-wrap:wrap; gap:8px; } .slideshow-sidepanel__path-actions button { display:inline-flex; align-items:center; gap:6px; } .slideshow-sorter { display:flex; flex-direction:column; gap:8px; min-height:0; overflow:auto; padding-right:2px; align-items:flex-start; } .slideshow-sorter__row { position:relative; display:flex; flex-direction:column; gap:7px; width:100%; box-sizing:border-box; border:1px solid var(--background-modifier-border); border-radius:8px; padding:8px; background:var(--background-primary); outline:none; transition:margin .1s ease; } .slideshow-sorter__row:focus, .slideshow-sorter__row.is-selected { border-color:var(--interactive-accent); box-shadow:0 0 0 1px var(--interactive-accent); } .slideshow-sorter__row.is-excluded { opacity:.5; } .slideshow-sorter__row.is-dragging { opacity:.35; } .slideshow-sorter__row.is-drop-before { margin-top:22px; } .slideshow-sorter__row.is-drop-after { margin-bottom:22px; } .slideshow-sorter__row.is-drop-before::before, .slideshow-sorter__row.is-drop-after::after { content:""; position:absolute; left:8px; right:8px; border-top:2px dashed var(--interactive-accent); pointer-events:none; } .slideshow-sorter__row.is-drop-before::before { top:-13px; } .slideshow-sorter__row.is-drop-after::after { bottom:-13px; } .slideshow-sorter__top { display:flex; flex-direction:column; gap:5px; align-items:stretch; padding:6px 8px; border-radius:6px; background:var(--background-secondary); } .slideshow-sorter__top.is-draggable { cursor:grab; user-select:none; background-color:var(--background-secondary); background-image:radial-gradient(circle, var(--color-base-30) .8px, transparent .9px); background-size:5px 5px; } .slideshow-sorter__top.is-draggable:active { cursor:grabbing; } .slideshow-sorter__title-row { display:flex; align-items:center; gap:5px; width:100%; min-width:0; } .slideshow-sorter__title { flex:1 1 auto; min-width:0; font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; line-height:1.35; } .slideshow-sorter__title-edit { flex:0 0 auto; width:22px; height:22px; min-width:22px; padding:3px; display:flex; align-items:center; justify-content:center; } .slideshow-sidepanel .slideshow-sorter__title-edit svg { width:14px; height:14px; } .slideshow-sorter__badges { width:100%; min-width:0; display:flex; gap:5px; flex-wrap:wrap; justify-content:flex-end; color:var(--text-muted); font-size:var(--font-ui-smaller); } .slideshow-sorter__badge { display:inline-flex; align-items:center; gap:3px; white-space:nowrap; } .slideshow-sorter__badge svg { width:14px; height:14px; } .slideshow-sorter__badge-compact-count { display:none; } .slideshow-sorter__content { display:flex; flex-direction:column; gap:6px; align-items:flex-start; min-width:0; } .slideshow-sorter__preview { width:min(100%, var(--slideshow-sorter-thumbnail-max-width, 280px)); aspect-ratio:16/9; overflow:hidden; border-radius:5px; background:var(--background-secondary); display:flex; align-items:center; justify-content:center; } .slideshow-sorter__preview svg { width:100%; height:100%; display:block; } .slideshow-sorter__actions { display:flex; flex-wrap:wrap; gap:3px; align-items:center; } .slideshow-sorter__actions button { width:30px; height:30px; padding:5px; display:flex; align-items:center; justify-content:center; } .slideshow-sorter__actions button.is-active { color:var(--interactive-accent); background:var(--background-modifier-hover); } .slideshow-sorter__actions svg { width:16px; height:16px; } .slideshow-notes { border-top:1px solid var(--background-modifier-border); padding-top:8px; display:flex; flex-direction:column; gap:7px; } .slideshow-notes textarea { width:100%; min-height:100px; resize:vertical; box-sizing:border-box; } .slideshow-notes__hint, .slideshow-warning, .slideshow-empty { color:var(--text-muted); font-size:var(--font-ui-smaller); } .slideshow-warning { padding:8px; border-radius:6px; background:var(--background-secondary); } .slideshow-sorter__animation { border-top:1px solid var(--background-modifier-border); padding-top:8px; } .slideshow-animation-editor { display:flex; flex-direction:column; gap:10px; min-height:0; overflow:visible; padding-bottom:4px; } .slideshow-animation-editor__hint, .slideshow-animation-editor__muted { color:var(--text-muted); font-size:var(--font-ui-smaller); } .slideshow-animation-editor__section { display:flex; flex-direction:column; gap:6px; } .slideshow-animation-editor__section-title { font-weight:600; font-size:var(--font-ui-small); } .slideshow-animation-editor__targets { display:flex; flex-wrap:wrap; gap:5px; } .slideshow-animation-editor__target { display:inline-flex; align-items:center; gap:4px; padding:4px; border-radius:8px; background:var(--background-secondary); } .slideshow-animation-editor__target-preview { width:64px; height:56px; display:flex; align-items:center; justify-content:center; overflow:hidden; border-radius:4px; } .slideshow-animation-editor__target-preview img { width:100%; height:100%; object-fit:contain; } .slideshow-animation-editor__target button { width:22px; height:22px; min-width:22px; padding:3px; display:flex; align-items:center; justify-content:center; } .slideshow-animation-editor__form { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; } .slideshow-animation-editor__form label { display:flex; flex-direction:column; gap:4px; color:var(--text-muted); font-size:var(--font-ui-smaller); } .slideshow-animation-editor__form select, .slideshow-animation-editor__form input { width:100%; box-sizing:border-box; } .slideshow-animation-editor__choices-section { grid-column:1/-1; display:flex; flex-direction:column; gap:5px; color:var(--text-muted); font-size:var(--font-ui-smaller); } .slideshow-animation-editor__choices { display:grid; grid-template-columns:repeat(auto-fit,minmax(90px,1fr)); gap:5px; } .slideshow-animation-editor__choices button { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:5px; min-height:64px; height:auto; padding:7px; white-space:normal; } .slideshow-animation-editor__choice-icon { display:flex; flex:0 0 24px; align-items:center; justify-content:center; } .slideshow-animation-editor .slideshow-animation-editor__choice-icon svg { width:24px; height:24px; } .slideshow-animation-editor__choices button[aria-pressed="true"] { color:var(--text-accent); border:1px solid var(--interactive-accent); background:var(--background-modifier-hover); box-shadow:0 0 0 1px var(--interactive-accent); } .slideshow-animation-editor__form-actions { display:flex; flex-wrap:wrap; gap:6px; } .slideshow-animation-editor__form-actions button { display:inline-flex; align-items:center; gap:5px; } .slideshow-animation-editor__steps { display:flex; flex-direction:column; gap:6px; } .slideshow-animation-editor__step { display:grid; grid-template-columns:minmax(0,1fr) auto; gap:6px; padding:6px; border:1px solid var(--background-modifier-border); border-radius:6px; background:var(--background-primary); } .slideshow-animation-editor__step.is-selected { border-color:var(--interactive-accent); box-shadow:0 0 0 1px var(--interactive-accent); } .slideshow-animation-editor__step-summary { display:flex; align-items:center; gap:10px; min-width:0; height:auto; text-align:left; white-space:normal; } .slideshow-animation-editor__step-preview { flex:0 0 64px; height:56px; display:flex; align-items:center; justify-content:center; overflow:hidden; border-radius:4px; background:var(--background-secondary); } .slideshow-animation-editor__step-preview img { width:100%; height:100%; object-fit:contain; } .slideshow-animation-editor__step-actions { display:grid; grid-template-columns:repeat(2,28px); gap:3px; } .slideshow-animation-editor__step-actions button { width:28px; height:28px; padding:4px; display:flex; align-items:center; justify-content:center; } @container slideshow-panel (max-width: 390px) { .slideshow-sidepanel__display-controls { grid-template-columns:1fr; } .slideshow-animation-editor__form { grid-template-columns:1fr; } .slideshow-animation-editor__step { grid-template-columns:1fr; } .slideshow-animation-editor__step-actions { display:flex; flex-wrap:wrap; justify-content:flex-end; } .slideshow-sorter__actions { justify-content:flex-end; } } .slideshow-sorter:not(.has-expanded-editor) { display:grid; grid-template-columns:repeat(auto-fill,minmax(160px,max(160px,var(--slideshow-sorter-thumbnail-max-width,280px)))); align-content:start; align-items:stretch; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__row { width:100%; height:100%; box-sizing:border-box; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__top { min-height:0; box-sizing:border-box; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__badges { min-height:18px; flex-wrap:nowrap; overflow:hidden; align-items:center; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__badge { flex:0 0 auto; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__badge-text { display:none; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__badge-compact-count { display:inline; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__content { flex:1 1 auto; justify-content:space-between; align-items:center; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__preview { width:min(100%,var(--slideshow-sorter-thumbnail-max-width,280px)); margin-inline:auto; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__actions { width:100%; justify-content:center; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__actions button { width:26px; height:26px; padding:4px; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__actions svg { width:15px; height:15px; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__row.is-drop-before, .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__row.is-drop-after { margin:0; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__row.is-drop-before::before, .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__row.is-drop-after::after { top:8px; bottom:8px; width:0; border-top:0; border-left:2px dashed var(--interactive-accent); } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__row.is-drop-before::before { left:-6px; right:auto; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__row.is-drop-after::after { right:-6px; left:auto; } .slideshow-sorter:not(.has-expanded-editor).is-single-column .slideshow-sorter__row.is-drop-before { margin-top:22px; } .slideshow-sorter:not(.has-expanded-editor).is-single-column .slideshow-sorter__row.is-drop-after { margin-bottom:22px; } .slideshow-sorter:not(.has-expanded-editor).is-single-column .slideshow-sorter__row.is-drop-before::before, .slideshow-sorter:not(.has-expanded-editor).is-single-column .slideshow-sorter__row.is-drop-after::after { left:8px; right:8px; width:auto; border-left:0; border-top:2px dashed var(--interactive-accent); } .slideshow-sorter:not(.has-expanded-editor).is-single-column .slideshow-sorter__row.is-drop-before::before { top:-13px; bottom:auto; } .slideshow-sorter:not(.has-expanded-editor).is-single-column .slideshow-sorter__row.is-drop-after::after { top:auto; bottom:-13px; } .slideshow-sorter.has-expanded-editor .slideshow-sorter__row { width:min(100%,820px); box-sizing:border-box; } @container slideshow-panel (max-width: 300px) { .slideshow-sorter:not(.has-expanded-editor) { display:flex; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__row { width:100%; height:auto; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__top { min-height:0; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__badges { min-height:0; flex-wrap:wrap; overflow:visible; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__badge-text { display:inline; } .slideshow-sorter:not(.has-expanded-editor) .slideshow-sorter__badge-compact-count { display:none; } .slideshow-sorter__actions { justify-content:flex-start; } } .slideshow-sidepanel button svg { width:16px; height:16px; } `; var SLIDESHOW_PRESENTER_STYLES = ` .slideshow-presenter { display:flex; flex-direction:column; gap:14px; height:100%; box-sizing:border-box; padding:16px; overflow:auto; background:var(--background-primary); color:var(--text-normal); } .slideshow-presenter__header { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; } .slideshow-presenter__heading { min-width:0; display:flex; flex-direction:column; gap:3px; } .slideshow-presenter__title { font-size:var(--font-ui-large); font-weight:700; line-height:1.25; overflow-wrap:anywhere; } .slideshow-presenter__counter { color:var(--text-muted); font-size:var(--font-ui-small); } .slideshow-presenter__header-actions { display:flex; gap:6px; flex:0 0 auto; } .slideshow-presenter__font-size-control { display:flex; align-items:center; gap:6px; color:var(--text-muted); font-size:var(--font-ui-smaller); white-space:nowrap; } .slideshow-presenter__font-size-control input { width:120px; } .slideshow-presenter__close, .slideshow-presenter__layout-toggle { flex:0 0 auto; width:38px; height:38px; display:flex; align-items:center; justify-content:center; } .slideshow-presenter__layout-toggle.is-active { color:var(--interactive-accent); background:var(--background-modifier-hover); } .slideshow-presenter__grid { display:grid; flex:1 1 auto; grid-template-columns:minmax(220px,.8fr) minmax(300px,1.2fr); grid-template-rows:auto minmax(160px,1fr); grid-template-areas:"current next" "notes next"; gap:16px; align-items:stretch; min-height:0; } .slideshow-presenter__column { min-width:0; display:flex; flex-direction:column; gap:9px; } .slideshow-presenter__column:nth-child(1) { grid-area:current; } .slideshow-presenter__column:nth-child(2) { grid-area:next; } .slideshow-presenter__notes-column { grid-area:notes; min-height:0; height:100%; } .slideshow-presenter__section-title { color:var(--text-muted); font-size:var(--font-ui-smaller); font-weight:600; text-transform:uppercase; letter-spacing:.04em; } .slideshow-presenter__preview { width:100%; overflow:hidden; border-radius:8px; background:var(--background-secondary); border:1px solid var(--background-modifier-border); display:flex; align-items:center; justify-content:center; } .slideshow-presenter__preview svg { width:100%; height:100%; display:block; } .slideshow-presenter__current-preview { max-width:520px; } .slideshow-presenter__next-preview { width:100%; } .slideshow-presenter__end { display:flex; align-items:center; justify-content:center; min-height:180px; color:var(--text-muted); font-size:var(--font-ui-medium); border:1px dashed var(--background-modifier-border); border-radius:8px; } .slideshow-presenter__notes { flex:1 1 auto; min-height:120px; font-size:var(--slideshow-presenter-notes-font-size, 18px); padding:12px; border-radius:8px; background:var(--background-secondary); border:1px solid var(--background-modifier-border); overflow-wrap:anywhere; overflow:auto; } .slideshow-presenter__notes.is-empty { color:var(--text-muted); font-style:italic; } .slideshow-presenter__progress { display:flex; align-items:center; gap:8px; color:var(--text-muted); font-size:var(--font-ui-small); } .slideshow-presenter__controls { display:flex; flex-wrap:wrap; gap:8px; margin-top:auto; padding-top:4px; } .slideshow-presenter:not(.is-notes-focused) .slideshow-presenter__controls { align-self:flex-end; } .slideshow-presenter__controls button { min-width:44px; min-height:40px; display:inline-flex; align-items:center; justify-content:center; gap:6px; } .slideshow-presenter__controls svg, .slideshow-presenter__close svg, .slideshow-presenter__layout-toggle svg { width:18px; height:18px; } .slideshow-presenter.is-notes-focused { overflow:hidden; } .slideshow-presenter.is-notes-focused .slideshow-presenter__grid { flex:1; grid-template-columns:minmax(0,17fr) minmax(150px,3fr); grid-template-rows:minmax(0,1fr) minmax(0,1fr); grid-template-areas:"notes current" "notes next"; align-items:stretch; } .slideshow-presenter.is-notes-focused .slideshow-presenter__notes-column { min-height:0; } .slideshow-presenter.is-notes-focused .slideshow-presenter__notes { flex:1; min-height:0; font-size:var(--slideshow-presenter-notes-font-size, 18px); } .slideshow-presenter.is-notes-focused .slideshow-presenter__current-preview { max-width:none; } .slideshow-presenter.is-notes-focused .slideshow-presenter__column:nth-child(1), .slideshow-presenter.is-notes-focused .slideshow-presenter__column:nth-child(2) { min-height:0; overflow:hidden; } @media (max-width: 700px) { .slideshow-presenter__grid, .slideshow-presenter.is-notes-focused .slideshow-presenter__grid { flex:none; grid-template-columns:1fr; grid-template-rows:auto; grid-template-areas:"current" "next" "notes"; } .slideshow-presenter__current-preview { max-width:none; } .slideshow-presenter.is-notes-focused { overflow:auto; } } `; // src/scripts/slideshow/PresenterViewController.ts async function waitForPresenterOwnerWindow(leaf, hostWindow, timeoutMs = 3e3) { const started = Date.now(); while (Date.now() - started <= timeoutMs) { const win = leaf.view.containerEl.ownerDocument.defaultView; if (win && win !== hostWindow) return { win, elapsedMs: Date.now() - started }; await sleepInWindow(hostWindow, 50); } return { win: null, elapsedMs: Date.now() - started }; } function getPresenterKeyboardAction(key) { switch (key) { case " ": case "Space": case "Spacebar": case "ArrowRight": case "ArrowDown": return "next"; case "ArrowLeft": case "ArrowUp": return "previous"; case "Home": return "first"; case "End": return "last"; case "Backspace": case "Escape": return "finish"; default: return null; } } var PresenterViewController = class { constructor(options) { this.options = options; this.previewService = new SlidePreviewService(options.ea, options.api, options.config); const displays = getAvailableDisplays(options.hostView.ownerWindow); const targetDisplayId = options.targetDisplayId ?? getCurrentDisplayId(options.hostView.ownerWindow); const targetDisplay = displays.find((display) => display.id === targetDisplayId); this.notesPreference = targetDisplay ? { deviceKey: getSlideshowDeviceKey(options.hostView.ownerWindow), configurationKey: getSlideshowDisplayConfigurationKey(displays), displayIdentity: JSON.stringify([ getSlideshowDisplayIdentity(targetDisplay), targetDisplay.bounds.x, targetDisplay.bounds.y ]) } : null; this.notesFontSize = this.notesPreference ? loadPresenterNotesFontSize( options.ea, this.notesPreference.deviceKey, this.notesPreference.configurationKey, this.notesPreference.displayIdentity ) : loadPresenterNotesFontSize(options.ea); } options; leaf = null; ownerWindow = null; root = null; titleEl = null; counterEl = null; currentPreviewEl = null; nextPreviewEl = null; notesEl = null; progressEl = null; layoutButton = null; notesFocusedLayout = false; notesFontSize; nextSectionTitleEl = null; markdownComponent = null; lastNotesSlideId = null; updateGeneration = 0; previewQueue = Promise.resolve(); closed = false; destroying = false; previewService; notesPreference; /** Opens the popout, waits for real window migration, and renders its initial state. */ async open(initialState) { if (this.leaf) { this.update(initialState); await app.workspace.revealLeaf(this.leaf); app.workspace.setActiveLeaf(this.leaf, { focus: true }); return; } const leaf = app.workspace.openPopoutLeaf(); this.leaf = leaf; await app.workspace.revealLeaf(leaf); app.workspace.setActiveLeaf(leaf, { focus: true }); const migrated = await waitForPresenterOwnerWindow(leaf, this.options.hostView.ownerWindow); const win = migrated.win; if (!win) { leaf.detach(); this.leaf = null; throw new Error("Presenter popout did not migrate to a distinct window."); } const container = leaf.view.containerEl; const doc = container.ownerDocument; this.ownerWindow = win; doc.title = this.options.t("presenterViewTitle"); const headerTitle = container.querySelector(".view-header-title"); if (headerTitle) headerTitle.textContent = this.options.t("presenterViewTitle"); const content = container.querySelector(".view-content") ?? container; content.replaceChildren(); this.renderShell(content, doc); win.addEventListener("keydown", this.keydownListener, true); win.addEventListener("beforeunload", this.windowClosingListener, { once: true }); this.update(initialState); app.workspace.setActiveLeaf(leaf, { focus: true }); await sleepInWindow(win, 100); if (this.options.targetDisplayId !== void 0) { const sameNative = resolveSameNativeWindow(this.options.hostView.ownerWindow, win); if (sameNative === false) { const moved = moveWindowToDisplay(win, this.options.targetDisplayId, true); if (moved) { await waitForWindowOnDisplay(win, this.options.targetDisplayId, 2500); await sleepInWindow(win, 150); } } } } /** Brings an already-open presenter window to the foreground. */ async focus() { if (!this.leaf) return; await app.workspace.revealLeaf(this.leaf); app.workspace.setActiveLeaf(this.leaf, { focus: true }); } /** Updates text synchronously and refreshes previews/Markdown asynchronously. */ update(state) { if (this.closed || !this.root) return; const slide = this.getSlide(state.currentSlideId); if (this.titleEl) { this.titleEl.textContent = slide?.title ?? this.options.t("slideLabel", { number: state.currentIndex + 1 }); } if (this.counterEl) { this.counterEl.textContent = this.options.t("presenterSlideCounter", { number: state.currentIndex + 1, total: state.visibleSlideCount }); } if (this.progressEl) { this.progressEl.textContent = state.animationStepCount > 0 ? this.options.t("presenterAnimationProgress", { completed: state.completedAnimationSteps, total: state.animationStepCount }) : this.options.t("presenterNoAnimations"); } if (this.nextSectionTitleEl) { this.nextSectionTitleEl.textContent = state.nextAction === "build" ? this.options.t("presenterNextBuild") : this.options.t("presenterNextSlide"); } const generation = ++this.updateGeneration; if (state.currentSlideId !== this.lastNotesSlideId) { this.lastNotesSlideId = state.currentSlideId; void this.renderNotes(slide, generation); } const queuedPreview = this.previewQueue.then(async () => { if (generation !== this.updateGeneration || this.closed) return; await this.renderPreviews(state, generation); }); this.previewQueue = queuedPreview.catch((error) => { console.error("Slideshow presenter preview failed", error); }); } /** Waits for any in-flight EA-backed preview export to release the shared workbench. */ async waitForIdle() { await this.previewQueue; } /** Removes listeners/renderers and optionally detaches the presenter leaf/popout. */ async destroy(detachLeaf = true) { if (this.destroying) return; this.destroying = true; const leaf = this.leaf; const win = this.ownerWindow; this.closed = true; this.updateGeneration += 1; if (win) { win.removeEventListener("keydown", this.keydownListener, true); win.removeEventListener("beforeunload", this.windowClosingListener); } this.markdownComponent?.unload(); this.markdownComponent = null; this.root?.remove(); this.root = null; this.leaf = null; this.ownerWindow = null; if (detachLeaf && leaf) { try { leaf.detach(); } catch { } } await this.previewQueue.catch(() => void 0); this.previewService.clear(); this.options.onClosed(); } renderShell(content, doc) { const style = doc.createElement("style"); style.textContent = SLIDESHOW_PRESENTER_STYLES; content.appendChild(style); const root = doc.createElement("div"); root.className = "slideshow-presenter"; root.style.setProperty("--slideshow-presenter-notes-font-size", `${this.notesFontSize}px`); content.appendChild(root); this.root = root; const header = doc.createElement("div"); header.className = "slideshow-presenter__header"; root.appendChild(header); const heading = doc.createElement("div"); heading.className = "slideshow-presenter__heading"; header.appendChild(heading); this.titleEl = doc.createElement("div"); this.titleEl.className = "slideshow-presenter__title"; heading.appendChild(this.titleEl); this.counterEl = doc.createElement("div"); this.counterEl.className = "slideshow-presenter__counter"; heading.appendChild(this.counterEl); const headerActions = doc.createElement("div"); headerActions.className = "slideshow-presenter__header-actions"; header.appendChild(headerActions); this.layoutButton = doc.createElement("button"); this.layoutButton.type = "button"; this.layoutButton.className = "slideshow-presenter__layout-toggle"; this.layoutButton.innerHTML = this.options.icons.notebookPen; this.layoutButton.addEventListener("click", () => this.toggleNotesFocusedLayout()); headerActions.appendChild(this.layoutButton); this.updateLayoutButton(); const fontSizeControl = doc.createElement("label"); fontSizeControl.className = "slideshow-presenter__font-size-control"; fontSizeControl.setAttribute("aria-label", this.options.t("presenterNotesFontSize")); const fontSizeLabel = doc.createElement("span"); fontSizeLabel.textContent = this.options.t("presenterNotesFontSize"); fontSizeControl.appendChild(fontSizeLabel); const fontSizeSlider = doc.createElement("input"); fontSizeSlider.type = "range"; fontSizeSlider.min = "12"; fontSizeSlider.max = "48"; fontSizeSlider.step = "1"; fontSizeSlider.value = String(this.notesFontSize); fontSizeSlider.addEventListener("input", () => { this.notesFontSize = Number(fontSizeSlider.value); root.style.setProperty("--slideshow-presenter-notes-font-size", `${this.notesFontSize}px`); }); fontSizeSlider.addEventListener("change", () => { const preference = this.notesPreference; void savePresenterNotesFontSize( this.options.ea, this.notesFontSize, preference?.deviceKey, preference?.configurationKey, preference?.displayIdentity ).catch((error) => { console.error("Slideshow presenter notes font-size save failed", error); }); }); fontSizeControl.appendChild(fontSizeSlider); headerActions.appendChild(fontSizeControl); const close = doc.createElement("button"); close.type = "button"; close.className = "slideshow-presenter__close"; close.setAttribute("aria-label", this.options.t("presenterClose")); close.innerHTML = this.options.icons.close; close.addEventListener("click", () => void this.destroy(true)); headerActions.appendChild(close); const grid = doc.createElement("div"); grid.className = "slideshow-presenter__grid"; root.appendChild(grid); const currentColumn = doc.createElement("section"); currentColumn.className = "slideshow-presenter__column"; grid.appendChild(currentColumn); currentColumn.appendChild(this.sectionTitle(doc, this.options.t("presenterCurrentSlide"))); this.currentPreviewEl = doc.createElement("div"); this.currentPreviewEl.className = "slideshow-presenter__preview slideshow-presenter__current-preview"; this.currentPreviewEl.style.aspectRatio = this.previewService.getAspectRatio(); currentColumn.appendChild(this.currentPreviewEl); const nextColumn = doc.createElement("section"); nextColumn.className = "slideshow-presenter__column"; grid.appendChild(nextColumn); this.nextSectionTitleEl = this.sectionTitle(doc, this.options.t("presenterNextSlide")); nextColumn.appendChild(this.nextSectionTitleEl); this.nextPreviewEl = doc.createElement("div"); this.nextPreviewEl.className = "slideshow-presenter__preview slideshow-presenter__next-preview"; this.nextPreviewEl.style.aspectRatio = this.previewService.getAspectRatio(); nextColumn.appendChild(this.nextPreviewEl); this.progressEl = doc.createElement("div"); this.progressEl.className = "slideshow-presenter__progress"; nextColumn.appendChild(this.progressEl); const notesColumn = doc.createElement("section"); notesColumn.className = "slideshow-presenter__column slideshow-presenter__notes-column"; grid.appendChild(notesColumn); notesColumn.appendChild(this.sectionTitle(doc, this.options.t("presenterNotes"))); this.notesEl = doc.createElement("div"); this.notesEl.className = "slideshow-presenter__notes"; notesColumn.appendChild(this.notesEl); const controls = doc.createElement("div"); controls.className = "slideshow-presenter__controls"; root.appendChild(controls); controls.appendChild(this.iconButton(doc, this.options.icons.leftArrow, this.options.t("previousSlide"), this.options.callbacks.previous)); controls.appendChild(this.iconButton(doc, this.options.icons.rightArrow, this.options.t("nextSlide"), this.options.callbacks.next)); controls.appendChild(this.iconButton(doc, this.options.icons.finish, this.options.t("endPresentation"), this.options.callbacks.finish)); } toggleNotesFocusedLayout() { this.notesFocusedLayout = !this.notesFocusedLayout; this.root?.classList.toggle("is-notes-focused", this.notesFocusedLayout); this.updateLayoutButton(); } updateLayoutButton() { if (!this.layoutButton) return; const label = this.options.t( this.notesFocusedLayout ? "presenterStandardLayout" : "presenterNotesFocusLayout" ); this.layoutButton.setAttribute("aria-label", label); this.layoutButton.classList.toggle("is-active", this.notesFocusedLayout); } sectionTitle(doc, text) { const title = doc.createElement("div"); title.className = "slideshow-presenter__section-title"; title.textContent = text; return title; } iconButton(doc, icon, label, callback) { const button = doc.createElement("button"); button.type = "button"; button.setAttribute("aria-label", label); button.innerHTML = icon; button.addEventListener("click", callback); return button; } getSlide(slideId) { if (!slideId) return null; return this.options.setup.deck.visibleSlides.find((slide) => slide.id === slideId) ?? null; } async renderNotes(slide, generation) { const notesEl = this.notesEl; if (!notesEl) return; this.markdownComponent?.unload(); this.markdownComponent = null; notesEl.replaceChildren(); const notes = slide?.notes?.trim() ?? ""; notesEl.classList.toggle("is-empty", notes.length === 0); if (!notes) { notesEl.textContent = this.options.t("presenterNoNotes"); return; } const component = new this.options.ea.obsidian.Component(); component.load(); this.markdownComponent = component; try { await this.options.ea.obsidian.MarkdownRenderer.render( app, notes, notesEl, this.options.hostView.file.path, component ); if (generation !== this.updateGeneration) component.unload(); } catch (error) { if (generation === this.updateGeneration) notesEl.textContent = notes; console.error("Slideshow presenter notes render failed", error); } } async renderPreviews(state, generation) { const currentHost = this.currentPreviewEl; const nextHost = this.nextPreviewEl; if (!currentHost || !nextHost) return; const doc = currentHost.ownerDocument; const currentSlide = this.getSlide(state.currentSlideId); const nextSlide = this.getSlide(state.nextSlideId); const originalOpacities = this.options.getAnimationOriginalOpacities?.(); const currentPreview = currentSlide ? await this.previewService.createPreview( currentSlide, doc, { completedAnimationSteps: state.completedAnimationSteps, ...originalOpacities ? { originalOpacities } : {}, targetWidth: 1280 } ) : null; const nextPreview = nextSlide ? await this.previewService.createPreview( nextSlide, doc, { completedAnimationSteps: state.nextCompletedAnimationSteps ?? 0, ...originalOpacities ? { originalOpacities } : {}, targetWidth: 1280 } ) : null; if (generation !== this.updateGeneration || this.closed) return; currentHost.replaceChildren(); if (currentPreview) currentHost.appendChild(currentPreview); nextHost.replaceChildren(); if (nextPreview) { nextHost.classList.remove("slideshow-presenter__end"); nextHost.appendChild(nextPreview); } else { nextHost.classList.add("slideshow-presenter__end"); nextHost.textContent = this.options.t("presenterEnd"); } } keydownListener = (event) => { if (event.defaultPrevented || event.repeat) return; const target = event.target; if (target?.matches("input, textarea, select, [contenteditable='true']")) return; const action = getPresenterKeyboardAction(event.key); if (!action) return; event.preventDefault(); event.stopImmediatePropagation(); switch (action) { case "next": this.options.callbacks.next(); break; case "previous": this.options.callbacks.previous(); break; case "first": this.options.callbacks.first(); break; case "last": this.options.callbacks.last(); break; case "finish": this.options.callbacks.finish(); break; } }; windowClosingListener = () => { void this.destroy(false); }; }; // src/scripts/slideshow/presentationState.ts function buildPresentationState(deck, currentIndex, animationState = { completedSteps: 0, stepCount: 0 }) { const visibleSlides = deck.visibleSlides; const boundedIndex = Math.min(Math.max(currentIndex, 0), Math.max(visibleSlides.length - 1, 0)); const current = visibleSlides[boundedIndex]; const followingSlide = visibleSlides[boundedIndex + 1]; const hasPendingBuild = Boolean(current) && animationState.completedSteps < animationState.stepCount; return { currentSlideId: current?.id ?? "", currentIndex: boundedIndex, visibleSlideCount: visibleSlides.length, completedAnimationSteps: animationState.completedSteps, animationStepCount: animationState.stepCount, nextSlideId: hasPendingBuild ? current?.id ?? null : followingSlide?.id ?? null, nextAction: hasPendingBuild ? "build" : followingSlide ? "slide" : "end", nextCompletedAnimationSteps: hasPendingBuild ? Math.min(animationState.completedSteps + 1, animationState.stepCount) : followingSlide ? 0 : null }; } // src/sharedUtils/SingleNotice.ts var SingleNotice = class { notice = null; noticeElement = null; /** Shows a new notice or replaces the current notice's message. */ setMessage(message) { if (this.notice && this.noticeElement?.parentElement) { this.notice.setMessage(message); return; } this.notice = new Notice(message, 0); this.noticeElement = this.notice.containerEl ?? this.notice.noticeEl; } /** Hides the notice if it is currently attached. */ hide() { if (this.noticeElement?.parentElement) { this.notice?.hide(); } } }; // src/scripts/slideshow/printLayout.ts function getPrintContentBox(settings) { const margin = { none: 0, minimal: 10, normal: 60 }[settings.margin]; return { x: margin, y: margin, width: settings.width - margin * 2, height: settings.height - margin * 2 }; } function fitPrintBox(box, aspect) { const width = Math.min(box.width, box.height * aspect); return { ...box, width, height: width / aspect }; } function validPrintDimensions(width, height) { return [width, height].every((value) => Number.isFinite(value) && value >= 320 && value <= 14400); } function getHandoutBoxes(settings) { const rows = settings.layout === "handout-3" ? 3 : settings.layout === "handout-2" ? 2 : 1; const content = getPrintContentBox(settings); const margin = content.x; const rowHeight = content.height / rows; const width = content.width; const contentHeight = rowHeight - 44; const below = settings.layout === "notes"; return { rows, rowHeight, slide: { x: margin, y: margin + 24, width: below ? width : width * 0.46, height: below ? contentHeight * 0.48 : contentHeight }, notes: { x: below ? margin : margin + width * 0.5, y: below ? margin + 36 + contentHeight * 0.48 : margin + 24, width: below ? width : width * 0.5, height: below ? contentHeight * 0.52 - 12 : contentHeight } }; } function wrapPrintText(text, width, measure) { const result = []; for (const paragraph of text.replace(/\r\n?/g, "\n").split("\n")) { let line = ""; for (const character of paragraph) { const candidate = line + character; if (line && measure(candidate) > width) { const space = line.lastIndexOf(" "); if (space > 0) { result.push(line.slice(0, space)); line = line.slice(space + 1) + character; } else { result.push(line); line = character; } } else line = candidate; } result.push(line); } return result; } function getPrintColors(theme) { return theme === "dark" ? { background: "#121212", foreground: "#e0e0e0", border: "#666666" } : { background: "#ffffff", foreground: "#202020", border: "#aaaaaa" }; } // src/scripts/slideshow/MarkdownPrintNotes.ts function getBoundaries(root) { const boundaries = []; const visit = (node) => { if (node.nodeType === 3) { let offset = 0; for (const character of node.textContent ?? "") { offset += character.length; boundaries.push({ node, offset }); } } else if (node.nodeType === 1 && node.matches("img, svg, canvas, video, iframe, hr, br, input")) { const parent = node.parentNode; boundaries.push({ node: parent, offset: Array.from(parent.childNodes).indexOf(node) + 1 }); } else { for (const child of Array.from(node.childNodes)) visit(child); } }; visit(root); boundaries.push({ node: root, offset: root.childNodes.length }); return boundaries; } function styleNotes(root, box, theme) { const colors = getPrintColors(theme); root.classList.add(theme === "dark" ? "theme-dark" : "theme-light"); root.setCssStyles({ width: `${box.width}px`, margin: "0", padding: "0", border: "0", font: "14px/20px Arial, sans-serif", color: colors.foreground, backgroundColor: colors.background, overflowWrap: "anywhere", boxSizing: "border-box", minHeight: "0" }); for (const element of Array.from(root.querySelectorAll("*"))) { element.setCssStyles({ maxWidth: "100%", boxSizing: "border-box", color: colors.foreground }); if (element.matches("p, ul, ol, blockquote, pre, table")) element.setCssStyles({ marginTop: "0", marginBottom: "6px" }); if (element.matches("h1, h2, h3, h4, h5, h6")) element.setCssStyles({ fontSize: `${Math.min(22, box.height / 2)}px`, lineHeight: "1.2", margin: "0 0 6px" }); if (element.matches("ul, ol")) element.setCssStyles({ paddingLeft: "24px" }); if (element.matches("pre, code")) element.setCssStyles({ whiteSpace: "pre-wrap", overflowWrap: "anywhere", fontSize: "12px" }); if (element.matches("img, svg, canvas, video, iframe")) element.setCssStyles({ maxHeight: `${box.height}px`, objectFit: "contain" }); if (element.matches("table")) element.setCssStyles({ width: "100%", tableLayout: "fixed", borderCollapse: "collapse" }); if (element.matches("th, td")) element.setCssStyles({ border: `1px solid ${colors.border}`, padding: "3px", whiteSpace: "normal" }); } } async function renderPrintNotes(ea2, notes, sourcePath, box, ownerDocument, theme = "light") { const host = ownerDocument.body.createDiv(); host.setCssStyles({ position: "fixed", left: "-100000px", top: "0", visibility: "hidden", width: `${box.width}px`, pointerEvents: "none" }); const root = host.createDiv({ cls: "markdown-rendered" }); const component = new ea2.obsidian.Component(); component.load(); try { await ea2.obsidian.MarkdownRenderer.render(app, notes, root, sourcePath, component); await Promise.all( Array.from(root.querySelectorAll("img"), async (image) => { const win = ownerDocument.defaultView; let timer = 0; try { await Promise.race([ image.decode().catch(() => void 0), new Promise((resolve) => { timer = win.setTimeout(resolve, 3e3); }) ]); } finally { win.clearTimeout(timer); } }) ); styleNotes(root, box, theme); const boundaries = getBoundaries(root); const pages = []; let start = { node: root, offset: 0 }; let first = 0; while (first < boundaries.length) { const slice = (end) => { const range = ownerDocument.createRange(); range.setStart(start.node, start.offset); range.setEnd(end.node, end.offset); const clone = root.cloneNode(false); clone.appendChild(range.cloneContents()); return clone; }; const fits = (end) => { const candidate = slice(boundaries[end]); host.appendChild(candidate); const height2 = candidate.getBoundingClientRect().height; candidate.remove(); return height2 <= box.height; }; let low = first; let high = boundaries.length - 1; let last = first - 1; while (low <= high) { const middle = Math.floor((low + high) / 2); if (fits(middle)) { last = middle; low = middle + 1; } else high = middle - 1; } let wordEnd = last; while (wordEnd > first) { const boundary = boundaries[wordEnd]; const text = boundary.node.textContent ?? ""; if (boundary.node.nodeType !== 3 || boundary.offset === text.length || /\s/.test(text[boundary.offset - 1] ?? "") || /\s/.test(text[boundary.offset] ?? "")) break; wordEnd -= 1; } if (wordEnd > first) last = wordEnd; last = Math.max(first, last); const chunk = slice(boundaries[last]); host.appendChild(chunk); const height = chunk.getBoundingClientRect().height; chunk.remove(); if (height > box.height) { chunk.setCssStyles({ transform: `scale(${box.height / height})`, transformOrigin: "top left" }); } pages.push(chunk); start = boundaries[last]; first = last + 1; } return pages; } finally { component.unload(); host.remove(); } } function appendPrintNotes(page, notes, box) { const foreignObject = page.createSvg("foreignObject", { attr: { x: box.x, y: box.y, width: box.width, height: box.height } }); notes.setAttribute("xmlns", "http://www.w3.org/1999/xhtml"); foreignObject.appendChild(notes); } // src/scripts/slideshow/printRanges.ts function parsePrintRanges(value) { if (!value.trim()) return []; return value.split(/[;,]/).map((part) => { const match = /^\s*(\d+)\s*(?:-\s*(\d*)\s*)?$/.exec(part); if (!match) throw new Error("INVALID_PRINT_RANGE"); const first = Number(match[1]); const last = match[2] === void 0 ? first : match[2] === "" ? Infinity : Number(match[2]); if (!Number.isSafeInteger(first) || first < 1 || last !== Infinity && !Number.isSafeInteger(last) || last < first) throw new Error("INVALID_PRINT_RANGE"); return { first, last }; }); } function selectPrintPages(pages, range) { const ranges = parsePrintRanges(range); return ranges.length === 0 ? pages : pages.filter( (_, index) => ranges.some(({ first, last }) => index + 1 >= first && index + 1 <= last) ); } // src/scripts/slideshow/printPreferences.ts var PRINT_SETTING = "slideshowPrintPreferences"; function loadPrintPreferences(ea2, width, height) { const defaults = { layout: "slides", visibleOnly: true, includeFrames: false, margin: "none", width, height, pageRanges: "", preset: "configured" }; const settings = ea2.getScriptSettings(); const raw = settings[PRINT_SETTING]; if (!raw || typeof raw !== "object" || Array.isArray(raw)) return defaults; const saved = raw; if (["slides", "notes", "handout-2", "handout-3"].includes(String(saved.layout))) defaults.layout = saved.layout; if (typeof saved.visibleOnly === "boolean") defaults.visibleOnly = saved.visibleOnly; if (typeof saved.includeFrames === "boolean") defaults.includeFrames = saved.includeFrames; if (["none", "minimal", "normal"].includes(String(saved.margin))) defaults.margin = saved.margin; if (["configured", "A4", "Letter", "16:9", "custom"].includes(String(saved.preset))) defaults.preset = saved.preset; if (typeof saved.width === "number" && typeof saved.height === "number" && validPrintDimensions(saved.width, saved.height)) { defaults.width = saved.width; defaults.height = saved.height; } if (typeof saved.pageRanges === "string") { try { parsePrintRanges(saved.pageRanges); defaults.pageRanges = saved.pageRanges; } catch { } } return defaults; } async function savePrintPreferences(ea2, preferences) { await ea2.setScriptSettings({ ...ea2.getScriptSettings(), [PRINT_SETTING]: preferences }); } // src/scripts/slideshow/presentationSources.ts function getPresentationSourceLabels(choices, frameLabel, defaultLineLabel) { const result = []; if (choices.frame) result.push({ key: "frame", label: choices.frame.deck.name?.trim() || frameLabel }); const bases = choices.lines.map((line) => line.name?.trim() || defaultLineLabel); const totals = /* @__PURE__ */ new Map(); for (const base of bases) totals.set(base, (totals.get(base) ?? 0) + 1); const seen = /* @__PURE__ */ new Map(); choices.lines.forEach((line, index) => { const base = bases[index] ?? defaultLineLabel; const ordinal = (seen.get(base) ?? 0) + 1; seen.set(base, ordinal); result.push({ key: line.key, label: (totals.get(base) ?? 0) > 1 ? `${base} (${ordinal})` : base }); }); return result; } // src/scripts/slideshow/PrintDialog.ts function openSlideshowPrintDialog(ea2, defaults, t) { return new Promise((resolve) => { const preferences = loadPrintPreferences(ea2, defaults.width, defaults.height); if (defaults.viewportSize) { preferences.width = defaults.width; preferences.height = defaults.height; preferences.preset = "custom"; } const modal = new ea2.FloatingModal(app); modal.titleEl.setText(t("printDialogTitle")); let settled = false; const finish = (result) => { if (settled) return; settled = true; resolve(result); modal.close(); }; const select = (label, entries) => { const row = new ea2.obsidian.Setting(modal.contentEl).setName(label); row.controlEl.setCssStyles({ minWidth: "0", flexShrink: "1" }); const input = row.controlEl.createEl("select", { attr: { "aria-label": label } }); input.setCssStyles({ maxWidth: "100%" }); for (const [value, text] of entries) input.createEl("option", { value, text }); return input; }; const source = select( t("printSlideshow"), getPresentationSourceLabels( defaults.choices, t("frameDeck"), t("linePresentationDefaultName") ).map((item) => { const kind = item.key === "frame" ? t("frameDeck") : t("linePresentationDefaultName"); return [item.key, item.label === kind ? kind : `${kind}: ${item.label}`]; }) ); source.value = defaults.sourceKey; if (!source.value) source.selectedIndex = 0; const layout = select(t("printLayout"), [ ["slides", t("printSlidesOnly")], ["notes", t("printNotesPage")], ["handout-2", t("printHandout2")], ["handout-3", t("printHandout3")] ]); layout.value = preferences.layout; let includeFrames = preferences.includeFrames ?? false; const framesRow = new ea2.obsidian.Setting(modal.contentEl).setName(t("printIncludeFrames")).addToggle( (toggle) => toggle.setValue(includeFrames).onChange((value) => { includeFrames = value; }) ); const updateFramesVisibility = () => framesRow.settingEl.toggle(layout.value !== "slides"); layout.addEventListener("change", updateFramesVisibility); updateFramesVisibility(); const theme = select(t("printTheme"), [ ["light", t("printThemeLight")], ["dark", t("printThemeDark")] ]); theme.value = ea2.getExcalidrawAPI().getAppState().theme === "dark" ? "dark" : "light"; let visibleOnly = preferences.visibleOnly; new ea2.obsidian.Setting(modal.contentEl).setName(t("printVisibleOnly")).setDesc(t("printVisibleOnlyHint")).addToggle( (toggle) => toggle.setValue(visibleOnly).onChange((value) => { visibleOnly = value; }) ); const rangeRow = new ea2.obsidian.Setting(modal.contentEl).setName(t("printPageRanges")).setDesc(t("printPageRangesHint")); const ranges = rangeRow.controlEl.createEl("input", { type: "text", value: preferences.pageRanges ?? "", attr: { "aria-label": t("printPageRanges"), placeholder: "1-3;5;9-" } }); const preset = select(t("printPageSize"), [ ["configured", t("printConfigured")], ["A4", "A4"], ["Letter", "Letter"], ["16:9", "16:9"], ["custom", t("printCustom")] ]); const orientation = select(t("printOrientation"), [ ["landscape", t("printLandscape")], ["portrait", t("printPortrait")] ]); const margin = select(t("printMargin"), [ ["none", t("printMarginNone")], ["minimal", t("printMarginMinimal")], ["normal", t("printMarginNormal")] ]); preset.value = preferences.preset; margin.value = preferences.margin; orientation.value = preferences.width >= preferences.height ? "landscape" : "portrait"; const dimension = (label, value) => { const row = new ea2.obsidian.Setting(modal.contentEl).setName(label); return row.controlEl.createEl("input", { type: "number", value: String(value), attr: { min: "320", max: "14400", step: "any", "aria-label": label } }); }; const width = dimension(t("printWidth"), preferences.width); const height = dimension(t("printHeight"), preferences.height); const applyPreset = () => { let size = { width: Number(width.value), height: Number(height.value) }; if (preset.value === "A4" || preset.value === "Letter") { size = ea2.getPagePDFDimensions(preset.value, "landscape"); } else if (preset.value === "16:9") size = { width: 1920, height: 1080 }; else if (preset.value === "configured") size = defaults; const long = Math.max(size.width, size.height); const short = Math.min(size.width, size.height); width.value = String(orientation.value === "landscape" ? long : short); height.value = String(orientation.value === "landscape" ? short : long); }; preset.addEventListener("change", applyPreset); orientation.addEventListener("change", applyPreset); for (const input of [width, height]) input.addEventListener("input", () => { preset.value = "custom"; orientation.value = Number(width.value) >= Number(height.value) ? "landscape" : "portrait"; }); modal.contentEl.createEl("p", { text: t("printNotesHint"), cls: "setting-item-description" }); const error = modal.contentEl.createEl("p", { cls: "mod-warning", attr: { role: "alert" } }); const actions = modal.contentEl.createDiv({ cls: "modal-button-container" }); actions.createEl("button", { text: t("settingsCancel") }).addEventListener("click", () => finish(null)); actions.createEl("button", { text: t("printDialogPrint"), cls: "mod-cta" }).addEventListener("click", () => { const size = { width: Number(width.value), height: Number(height.value) }; if (!validPrintDimensions(size.width, size.height)) { error.setText(t("printInvalidDimensions")); return; } try { parsePrintRanges(ranges.value); } catch { error.setText(t("printInvalidPageRanges")); ranges.focus(); return; } const result = { ...size, sourceKey: source.value, layout: layout.value, visibleOnly, includeFrames: layout.value !== "slides" && includeFrames, theme: theme.value, pageRanges: ranges.value.trim(), margin: margin.value }; void savePrintPreferences(ea2, { layout: result.layout, visibleOnly, includeFrames, margin: result.margin, width: result.width, height: result.height, pageRanges: result.pageRanges, preset: preset.value }).then(() => finish(result)).catch((reason) => { console.error("Slideshow print preferences save failed", reason); error.setText(t("printPreferencesFailed")); }); }); modal.onClose = () => finish(null); modal.open(); }); } // src/scripts/slideshow/printToPdf.ts async function printSlideshowToPdf(options) { const view = options.ea.targetView; const file = view?.file; const state = options.api.getAppState(); const settings = await openSlideshowPrintDialog( options.ea, { width: options.event.shiftKey ? state.width : options.printSlideWidth, height: options.event.shiftKey ? state.height : options.printSlideHeight, choices: options.choices, sourceKey: options.sourceKey, viewportSize: options.event.shiftKey }, options.t ); if (!settings) return; if (options.ea.targetView !== view || view?.file !== file || options.ea.getExcalidrawAPI() !== options.api) { new options.ea.obsidian.Notice(options.t("printViewChanged")); return; } await generateSlideshowPdf(options, settings); } async function exportSlide(options, slide, box, theme) { const left = Math.min(slide.rect.x1, slide.rect.x2); const top = Math.min(slide.rect.y1, slide.rect.y2); const width = Math.max(Math.abs(slide.rect.x2 - slide.rect.x1), 1); const height = Math.max(Math.abs(slide.rect.y2 - slide.rect.y1), 1); const svg = await options.ea.createViewSVG({ withBackground: true, theme, frameRendering: { enabled: false, name: false, outline: false, clip: false }, padding: 0, selectedOnly: false, skipInliningFonts: false, embedScene: false, exportArea: { x: left, y: top, width, height } }); svg.setAttribute("width", String(box.width)); svg.setAttribute("height", String(box.height)); svg.setAttribute("preserveAspectRatio", "xMidYMid meet"); svg.setCssStyles({ overflow: "hidden" }); return svg; } function createPrintPage(settings, backgroundColor) { const page = createFragment().createSvg("svg", { attr: { xmlns: "http://www.w3.org/2000/svg", width: settings.width, height: settings.height, viewBox: `0 0 ${settings.width} ${settings.height}` } }); page.createSvg("rect", { attr: { width: settings.width, height: settings.height, fill: backgroundColor } }); return page; } function addText(page, text, x, y, color) { const element = page.createSvg("text", { attr: { x, y, fill: color, "font-family": "Arial, sans-serif", "font-size": 14, "font-weight": "bold", "xml:space": "preserve" } }); element.textContent = text; } async function generateSlideshowPdf(options, settings) { if (!validPrintDimensions(settings.width, settings.height)) throw new Error("INVALID_PRINT_DIMENSIONS"); const { ea: ea2, t } = options; const targetView = ea2.targetView; const targetFile = targetView?.file; const theme = settings.theme ?? (options.api.getAppState().theme === "dark" ? "dark" : "light"); const colors = getPrintColors(theme); const pageBackground = settings.layout === "slides" && theme === "light" ? options.api.getAppState().viewBackgroundColor : colors.background; const assertTarget = () => { if (ea2.targetView !== targetView || targetView?.file !== targetFile || ea2.getExcalidrawAPI() !== options.api) throw new Error("PRINT_VIEW_CHANGED"); }; const exportCurrentSlide = async (slide, box) => { assertTarget(); const image = await exportSlide(options, slide, box, theme); assertTarget(); return image; }; const deck = resolvePresentationSource(options.choices, settings.sourceKey)?.deck; const slides = deck?.slides.filter((slide) => !settings.visibleOnly || !slide.excluded) ?? []; if (slides.length === 0) { new ea2.obsidian.Notice(t("printNoSlides")); return; } const notice = new SingleNotice(); const pages = []; try { notice.setMessage(t("generatingImage")); if (settings.layout === "slides") { for (const [index, slide] of slides.entries()) { notice.setMessage(t("generatingSlide", { number: index + 1 })); const box = getPrintContentBox(settings); const image = await exportCurrentSlide(slide, box); image.setAttribute("x", String(box.x)); image.setAttribute("y", String(box.y)); const page = createPrintPage(settings, pageBackground); page.appendChild(image); pages.push(page); } } else { const view = ea2.targetView; if (!view) throw new Error("MISSING_PRINT_VIEW"); const canvas = createFragment().createEl("canvas"); const context = canvas.getContext("2d"); if (!context) throw new Error("MISSING_TEXT_MEASUREMENT"); context.font = "14px Arial"; const measure = (text) => context.measureText(text).width; const boxes = getHandoutBoxes(settings); const slideBox = fitPrintBox(boxes.slide, options.printSlideWidth / options.printSlideHeight); let slot = 0; let page; for (const [index, slide] of slides.entries()) { notice.setMessage(t("generatingSlide", { number: index + 1 })); const image = await exportCurrentSlide(slide, slideBox); const chunks = await renderPrintNotes( ea2, slide.notes ?? "", targetFile.path, boxes.notes, view.ownerDocument, theme ); assertTarget(); for (const [offset, notes] of chunks.entries()) { if (slot % boxes.rows === 0) { page = createPrintPage(settings, pageBackground); pages.push(page); } const y = slot % boxes.rows * boxes.rowHeight; const continuation = offset > 0 ? ` ${t("printContinued")}` : ""; const title = `${index + 1}. ${slide.title.replace(/[\r\n]/g, " ")}${continuation}`; const content = getPrintContentBox(settings); const titleLines = wrapPrintText(title, content.width, measure); addText( page, (titleLines[0] ?? "") + (titleLines.length > 1 ? "\u2026" : ""), content.x, content.y + 16 + y, colors.foreground ); const clone = image.cloneNode(true); clone.setAttribute("x", String(boxes.slide.x)); clone.setAttribute("y", String(boxes.slide.y + y)); page.appendChild(clone); if (settings.includeFrames) { page.createSvg("rect", { attr: { x: slideBox.x, y: slideBox.y + y, width: slideBox.width, height: slideBox.height, fill: "none", stroke: colors.border, "stroke-width": 1 } }); } appendPrintNotes(page, notes, { ...boxes.notes, y: boxes.notes.y + y }); slot += 1; } } } const selectedPages = selectPrintPages(pages, settings.pageRanges ?? ""); if (selectedPages.length === 0) { new ea2.obsidian.Notice(t("printNoPages")); return; } notice.setMessage(t("creatingPdf")); assertTarget(); await ea2.createPDF({ SVG: selectedPages, scale: { fitToPage: 0, zoom: 1 }, pageProps: { dimensions: { width: settings.width, height: settings.height }, backgroundColor: pageBackground, margin: { left: 0, right: 0, top: 0, bottom: 0 }, alignment: "center" }, filename: `${targetFile?.basename ?? "slideshow"}.pdf` }); } finally { notice.hide(); } } // src/scripts/slideshow/presentationViewport.ts async function waitForPresentationViewport(view, api) { const container = view.excalidrawContainer ?? view.contentEl; let previous = ""; let stableSamples = 0; for (let sample = 0; sample < 40; sample += 1) { await sleepInWindow(view.ownerWindow, 50); const { width, height } = container.getBoundingClientRect(); const state = api.getAppState(); const size = `${width}:${height}`; const matches = width > 0 && height > 0 && Math.abs(width - state.width) <= 2 && Math.abs(height - state.height) <= 2; stableSamples = matches && size === previous ? stableSamples + 1 : 0; if (stableSamples >= 3) return; previous = size; } } // src/scripts/slideshow/SlideshowController.ts var SlideshowController = class { ea; api; hostView; hostLeaf; ownerWindow; ownerDocument; contentElement; setup; config; icons; statusBarElement; shouldStartFullscreen; openPresenterViewOnStart; presentationDisplayId; presenterDisplayId; t; onSlideChange; onExit; openSidepanel; animationRuntime; controls = null; presenter = null; slide; isFullscreen = false; isLaserOn = false; shouldSaveAfterPresentation = false; busy = false; preventFullscreenExit = true; exitPromise = null; navigationQueue = Promise.resolve(); stateEmissionPauseDepth = 0; hostWindowPlacement = null; hostPlacementPrepared = false; hiddenMobileNavbars = []; constructor(options) { this.ea = options.ea; this.api = options.api; this.hostView = options.hostView; this.hostLeaf = options.hostView.leaf; this.ownerWindow = options.hostView.ownerWindow; this.ownerDocument = options.hostView.ownerDocument; this.contentElement = options.hostView.contentEl; this.setup = options.setup; this.config = options.config; this.icons = options.icons; this.statusBarElement = options.statusBarElement; this.slide = Math.min( Math.max(options.initialSlide, 0), Math.max(options.setup.slides.length - 1, 0) ); this.shouldStartFullscreen = options.ea.DEVICE.isMobile ? true : options.startFullscreen; this.openPresenterViewOnStart = options.openPresenterViewOnStart ?? false; this.presentationDisplayId = options.presentationDisplayId; this.presenterDisplayId = options.presenterDisplayId; this.t = options.t; this.onSlideChange = options.onSlideChange; this.onExit = options.onExit; this.openSidepanel = options.openSidepanel; this.animationRuntime = new AnimationRuntime({ ea: options.ea, api: options.api, hostView: options.hostView, config: options.config, onStateChange: () => this.emitPresentationState() }); } /** Starts the presentation and installs all temporary UI and handlers. */ async start() { this.ea.setView(this.hostView); this.hideMobileNavbar(); if (this.statusBarElement) this.statusBarElement.style.display = "none"; this.ea.setViewModeEnabled(true); const helpButton = this.hostView.excalidrawContainer?.querySelector( ".ToolIcon__icon.help-icon" ); if (helpButton) helpButton.style.display = "none"; const zoomButton = this.hostView.excalidrawContainer?.querySelector( ".Stack.Stack_vertical.zoom-actions" ); if (zoomButton) zoomButton.style.display = "none"; this.createControls(); this.initializeEventListeners(); this.hostWindowPlacement = captureWindowPlacement(this.ownerWindow); if (this.openPresenterViewOnStart) { await this.openPresenterView(); app.workspace.setActiveLeaf(this.hostLeaf, { focus: true }); } await this.prepareHostWindowPlacement(this.shouldStartFullscreen); if (this.shouldStartFullscreen) await this.gotoFullscreen(false); else this.controls?.resetPosition(false); if (this.setup.pathType === "line") await this.togglePathVisibility(this.setup.isHidden); await waitForPresentationViewport(this.hostView, this.api); this.controls?.resetPosition(false); this.stateEmissionPauseDepth += 1; try { await this.enterSlide(this.slide, false); } finally { this.stateEmissionPauseDepth -= 1; } this.controls?.setSelectedSlide(this.slide + 1); this.emitPresentationState(); this.hostView.clearDirty(); } /** Advances this presentation when the script is invoked again for its view. */ advance() { this.enqueueNavigation(() => this.navigate("fwd")); } /** Navigates backward through builds/slides from presenter-window controls. */ previous() { this.enqueueNavigation(() => this.navigate("bkwd")); } /** Jumps directly to a zero-based visible slide index. */ goToSlide(index) { this.enqueueNavigation(() => this.jumpToSlide(index)); } /** Opens or focuses the desktop presenter popout for this presentation. */ async openPresenterView() { if (this.ea.DEVICE.isMobile) { new Notice(this.t("presenterViewDesktopOnly")); return; } if (this.presenter) { await this.presenter.focus(); this.presenter.update(this.getPresentationState()); return; } const presenter = new PresenterViewController({ ea: this.ea, api: this.api, hostView: this.hostView, setup: this.setup, config: this.config, icons: this.icons, t: this.t, callbacks: { previous: () => this.previous(), next: () => this.advance(), first: () => this.goToSlide(0), last: () => this.goToSlide(this.setup.slides.length - 1), finish: () => void this.exit() }, ...this.presenterDisplayId === void 0 ? {} : { targetDisplayId: this.presenterDisplayId }, getAnimationOriginalOpacities: () => this.animationRuntime?.getOriginalOpacities() ?? /* @__PURE__ */ new Map(), onClosed: () => { if (this.presenter === presenter) this.presenter = null; } }); this.presenter = presenter; try { await presenter.open(this.getPresentationState()); } catch (error) { if (this.presenter === presenter) this.presenter = null; await presenter.destroy(false).catch(() => void 0); console.error("Slideshow presenter view failed to open", error); new Notice(this.t("presenterViewOpenFailed")); } } /** Returns the authoritative state shared by floating controls and presenter view. */ getPresentationState() { let animationState = this.animationRuntime?.getState() ?? { completedSteps: 0, stepCount: 0 }; if (animationState.stepCount === 0) { const current = this.setup.deck.visibleSlides[this.slide]; if (current) animationState = { completedSteps: 0, stepCount: current.animationSteps.length }; } return buildPresentationState(this.setup.deck, this.slide, animationState); } emitPresentationState() { if (this.stateEmissionPauseDepth > 0) return; this.presenter?.update(this.getPresentationState()); } enqueueNavigation(task) { const queued = this.navigationQueue.then(async () => { if (!this.exitPromise) await task(); }); this.navigationQueue = queued.catch((error) => { console.error("Slideshow navigation failed", error); }); } createControls() { this.controls = new PresentationControls({ ea: this.ea, ownerWindow: this.ownerWindow, ownerDocument: this.ownerDocument, contentElement: this.contentElement, slidesCount: this.setup.slides.length, pathType: this.setup.pathType, slideTitles: this.setup.slideTitles, shouldOfferPathVisibility: this.setup.shouldHidePathAfterPresentation, isPathHidden: this.setup.isHidden, isFullscreen: this.isFullscreen, fadeLevel: this.config.fadeLevel, transitionDelay: this.config.transitionDelay, printSlideWidth: this.config.printSlideWidth, printSlideHeight: this.config.printSlideHeight, icons: this.icons, t: this.t, callbacks: { previous: () => this.enqueueNavigation(() => this.navigate("bkwd")), next: () => this.enqueueNavigation(() => this.navigate("fwd")), navigateToSlide: (slideNumber) => this.enqueueNavigation(() => this.jumpToSlide(slideNumber - 1)), toggleLaser: () => this.toggleLaser(), refocus: () => this.enqueueNavigation(() => this.jumpToSlide(this.slide)), toggleFullscreen: () => this.enqueueNavigation(() => this.toggleFullscreen()), togglePathVisibility: (hidden) => { this.shouldSaveAfterPresentation = true; if (hidden) { this.api.setToast({ message: this.t("pathWillRemainHidden"), duration: 5e3, closable: true }); } void this.togglePathVisibility(hidden, true); }, editSlide: () => { if (this.setup.shouldHidePathAfterPresentation) void this.togglePathVisibility(false); void this.exit(true); }, openSidepanel: () => { void this.exit().then(() => this.openSidepanel()); }, print: (event) => void this.print(event), finish: () => void this.exit() } }); this.controls.create(); } toggleLaser() { this.isLaserOn = !this.isLaserOn; this.api.setActiveTool({ type: this.isLaserOn ? "laser" : "selection" }); return this.isLaserOn; } async waitForExcalidrawResize() { await sleepInWindow(this.ownerWindow, 100); const deltaWidth = () => Math.abs(this.contentElement.clientWidth - this.api.getAppState().width); const deltaHeight = () => Math.abs(this.contentElement.clientHeight - this.api.getAppState().height); let watchdog = 0; while ((deltaWidth() > 50 || deltaHeight() > 50) && watchdog++ < 20) { await sleepInWindow(this.ownerWindow, 50); } } async prepareHostWindowPlacement(fillWorkArea) { if (this.hostPlacementPrepared || this.presentationDisplayId === void 0) return; this.hostWindowPlacement ??= captureWindowPlacement(this.ownerWindow); moveWindowToDisplay( this.ownerWindow, this.presentationDisplayId, fillWorkArea, false ); this.hostPlacementPrepared = true; await waitForWindowOnDisplay(this.ownerWindow, this.presentationDisplayId, 3e3); await sleepInWindow(this.ownerWindow, 350); app.workspace.setActiveLeaf(this.hostLeaf, { focus: true }); } async gotoFullscreen(refocus = true) { if (this.isFullscreen) return; this.preventFullscreenExit = true; await this.prepareHostWindowPlacement(true); this.animationRuntime?.pauseTimedStep(); if (this.ea.DEVICE.isMobile) this.ea.viewToggleFullScreen(); else await this.contentElement.webkitRequestFullscreen(); await this.waitForExcalidrawResize(); this.hideMobileNavbar(); const layerUiWrapper = this.contentElement.querySelector(".layer-ui__wrapper"); if (!layerUiWrapper?.hasClass("excalidraw-hidden")) layerUiWrapper?.addClass("excalidraw-hidden"); this.controls?.setFullscreen(true); this.controls?.resetPosition(false); this.isFullscreen = true; if (refocus) await this.scrollToSlide(this.slide, 1); this.animationRuntime?.startPendingTimer(); } async exitFullscreen(refocus = true, restoreHostPlacement = true) { if (!this.isFullscreen) return; this.preventFullscreenExit = true; this.animationRuntime?.pauseTimedStep(); if (!this.ea.DEVICE.isMobile && this.ownerDocument.fullscreenElement) { await this.ownerDocument.exitFullscreen(); } if (this.ea.DEVICE.isMobile) this.ea.viewToggleFullScreen(); this.controls?.setFullscreen(false); await this.waitForExcalidrawResize(); this.controls?.resetPosition(false); this.isFullscreen = false; if (restoreHostPlacement && this.hostWindowPlacement && this.hostPlacementPrepared) { await restoreWindowPlacementStable(this.ownerWindow, this.hostWindowPlacement); this.hostPlacementPrepared = false; } if (refocus) await this.scrollToSlide(this.slide, 1); this.animationRuntime?.startPendingTimer(); } async toggleFullscreen() { if (this.isFullscreen) await this.exitFullscreen(); else await this.gotoFullscreen(); } async togglePathVisibility(setToHidden, isMetadataEdit = false) { await this.presenter?.waitForIdle(); const pathElement = this.setup.pathElement; const originalProps = this.setup.originalPathProperties; if (!pathElement || !originalProps) return; this.ea.setView(this.hostView); this.ea.clear(); this.ea.copyViewElementsToEAforEditing( this.ea.getViewElements().filter((element2) => element2.id === pathElement.id) ); const element = this.ea.getElement( pathElement.id ); if (!element) return; element.strokeColor = "transparent"; element.backgroundColor = "transparent"; const shouldRemainHidden = setToHidden && this.setup.shouldHidePathAfterPresentation; if (shouldRemainHidden) element.locked = true; if (isMetadataEdit) { const metadata = upgradeLineSlideshowData( element.customData, element.id, Math.floor(element.points.length / 2), originalProps, getAbsoluteLinePoints(element.x, element.y, element.points) ); metadata.hidden = shouldRemainHidden; writeSlideshowMetadata(this.ea, element.id, metadata); } this.setup.isHidden = shouldRemainHidden; await this.ea.addElementsToView( false, isMetadataEdit, false, false, isMetadataEdit ? "IMMEDIATELY" : "NEVER" ); } getSlideNavigationRect(index) { const targetSlide = this.setup.slides[index]; if (!targetSlide) throw new Error(this.t("invalidSlide")); const appState = this.api.getAppState(); return getNavigationRect( targetSlide, { width: appState.width, height: appState.height }, this.config.maxZoom ); } async scrollToSlide(index, steps = this.config.transitionStepCount) { await this.scrollToRect(this.getSlideNavigationRect(index), steps); } async enterSlide(index, fullyBuilt) { const deckSlide = this.setup.deck.visibleSlides[index]; if (deckSlide && this.animationRuntime) { await this.animationRuntime.enterSlide(deckSlide, fullyBuilt, false); } else { await this.animationRuntime?.leaveSlide(); } await this.scrollToSlide(index); this.animationRuntime?.startPendingTimer(); } async scrollToRect(rect, steps = this.config.transitionStepCount) { let watchdog = 0; while (this.busy && watchdog++ < 15) await sleepInWindow(this.ownerWindow, 100); if (this.busy && watchdog >= 15) return; this.busy = true; try { this.api.updateScene({ appState: { shouldCacheIgnoreZoom: true }, captureUpdate: "NEVER" }); const { scrollX, scrollY, zoom } = this.api.getAppState(); const stepCount = Math.max(1, Math.trunc(steps)); const zoomStep = (zoom.value - rect.nextZoom) / stepCount; const xStep = (rect.left + scrollX) / stepCount; const yStep = (rect.top + scrollY) / stepCount; const startTimer = Date.now(); let renderedStep = 0; while (renderedStep < stepCount) { const elapsed = Date.now() - startTimer; const nextStep = this.config.transitionDelay <= 0 || elapsed >= this.config.transitionDelay ? stepCount : Math.max( 1, Math.min( Math.round(stepCount * (elapsed / this.config.transitionDelay)), stepCount ) ); if (nextStep <= renderedStep) { await sleepInWindow(this.ownerWindow, this.config.frameSleep); continue; } renderedStep = nextStep; this.api.updateScene({ appState: { scrollX: scrollX - xStep * renderedStep, scrollY: scrollY - yStep * renderedStep, zoom: { value: zoom.value - zoomStep * renderedStep } }, captureUpdate: "NEVER" }); if (renderedStep < stepCount) { await sleepInWindow(this.ownerWindow, this.config.frameSleep); } } if (this.isLaserOn) this.api.setActiveTool({ type: "laser" }); } finally { this.api.updateScene({ appState: { shouldCacheIgnoreZoom: false }, captureUpdate: "NEVER" }); this.busy = false; } } async navigate(direction) { if (direction === "fwd") { if (await this.animationRuntime?.advance()) return; if (this.slide >= this.setup.slides.length - 1) { void this.exit(); return; } this.stateEmissionPauseDepth += 1; try { this.slide += 1; this.controls?.setSelectedSlide(this.slide + 1); await this.enterSlide(this.slide, false); } finally { this.stateEmissionPauseDepth -= 1; } this.onSlideChange(this.slide); this.emitPresentationState(); return; } if (await this.animationRuntime?.reverse()) return; if (this.slide <= 0) { void this.exit(); return; } this.stateEmissionPauseDepth += 1; try { this.slide -= 1; this.controls?.setSelectedSlide(this.slide + 1); await this.enterSlide(this.slide, true); } finally { this.stateEmissionPauseDepth -= 1; } this.onSlideChange(this.slide); this.emitPresentationState(); } async jumpToSlide(index) { const bounded = Math.min(Math.max(index, 0), this.setup.slides.length - 1); this.stateEmissionPauseDepth += 1; try { this.slide = bounded; this.controls?.setSelectedSlide(this.slide + 1); await this.enterSlide(this.slide, false); } finally { this.stateEmissionPauseDepth -= 1; } this.onSlideChange(this.slide); this.emitPresentationState(); } keydownListener = (event) => { if (event.defaultPrevented || event.repeat) return; if (!this.ownerDocument.hasFocus()) return; if (this.hostLeaf !== app.workspace.activeLeaf) return; if (this.hostLeaf.width === 0 && this.hostLeaf.height === 0) return; switch (event.key) { case "Backspace": case "Escape": event.preventDefault(); void this.exit(); break; case "Space": case "ArrowRight": case "ArrowDown": event.preventDefault(); this.enqueueNavigation(() => this.navigate("fwd")); break; case "ArrowLeft": case "ArrowUp": event.preventDefault(); this.enqueueNavigation(() => this.navigate("bkwd")); break; case "End": event.preventDefault(); this.enqueueNavigation(() => this.jumpToSlide(this.setup.slides.length - 1)); break; case "Home": event.preventDefault(); this.enqueueNavigation(() => this.jumpToSlide(this.slide)); break; case "e": if (this.setup.pathType !== "line") return; event.preventDefault(); void (async () => { await this.togglePathVisibility(false); await this.exit(true); })(); break; case "f": event.preventDefault(); this.enqueueNavigation(() => this.toggleFullscreen()); break; } }; fullscreenListener = (event) => { if (this.preventFullscreenExit) { this.preventFullscreenExit = false; return; } event.preventDefault(); void this.exit(); }; hideMobileNavbar() { if (!this.ea.DEVICE.isMobile) return; const tracked = new Set(this.hiddenMobileNavbars.map(({ element }) => element)); const navbars = Array.from( this.ownerDocument.querySelectorAll( ".mobile-navbar.excalidraw-mobile-navbar-docked" ) ); for (const element of navbars) { if (!tracked.has(element)) { this.hiddenMobileNavbars.push({ element, display: element.style.display }); } element.style.display = "none"; } } restoreMobileNavbar() { for (const { element, display } of this.hiddenMobileNavbars) { element.style.display = display; } this.hiddenMobileNavbars = []; } initializeEventListeners() { this.ownerWindow.addEventListener("keydown", this.keydownListener); this.ea.onLinkClickHook = this.linkClickHook; if (!this.ea.DEVICE.isMobile) { this.contentElement.addEventListener("webkitfullscreenchange", this.fullscreenListener); this.contentElement.addEventListener("fullscreenchange", this.fullscreenListener); } } linkClickHook = () => { void this.exit(); return true; }; removeEventListeners() { if (this.ea.onLinkClickHook === this.linkClickHook) this.ea.onLinkClickHook = null; this.controls?.destroy(); this.controls = null; if (!this.ea.DEVICE.isMobile) { this.contentElement.removeEventListener("webkitfullscreenchange", this.fullscreenListener); this.contentElement.removeEventListener("fullscreenchange", this.fullscreenListener); } this.ownerWindow.removeEventListener("keydown", this.keydownListener); this.contentElement.querySelector(".layer-ui__wrapper")?.removeClass("excalidraw-hidden"); } /** Restores the drawing and Excalidraw UI after the presentation. */ exit(openForEdit = false) { this.exitPromise ??= this.performExit(openForEdit).finally(this.onExit); return this.exitPromise; } async performExit(openForEdit) { this.ea.setView(this.hostView); const presenter = this.presenter; this.presenter = null; await presenter?.destroy(true).catch(() => void 0); await presenter?.waitForIdle().catch(() => void 0); try { await this.animationRuntime?.finishActiveSlide(); this.isLaserOn = false; if (this.statusBarElement) this.statusBarElement.style.display = "inherit"; if (openForEdit) this.hostView.preventAutozoom(); await this.exitFullscreen(false, false); if (this.hostWindowPlacement) { const originalPlacement = this.hostWindowPlacement; this.hostWindowPlacement = null; this.hostPlacementPrepared = false; await restoreWindowPlacementStable(this.ownerWindow, originalPlacement); } await this.waitForExcalidrawResize(); this.ea.setViewModeEnabled(false); if (this.setup.pathType === "line" && this.setup.pathElement && this.setup.originalPathProperties) { await this.restoreLinePathForExit(openForEdit); } else if (this.setup.frameRenderingOriginalState.enabled) { this.api.updateScene({ appState: { frameRendering: { ...this.setup.frameRenderingOriginalState, enabled: true } } }); } } finally { await this.animationRuntime?.finishActiveSlide().catch(() => void 0); this.restoreMobileNavbar(); this.removeEventListeners(); this.ownerWindow.setTimeout(() => { this.hostView.refreshCanvasOffset(); this.api.setActiveTool({ type: "selection" }); }); if (!this.shouldSaveAfterPresentation) this.hostView.clearDirty(); } } async restoreLinePathForExit(openForEdit) { const pathElement = this.setup.pathElement; const originalProps = this.setup.originalPathProperties; if (!pathElement || !originalProps) return; this.ea.clear(); this.ea.copyViewElementsToEAforEditing( this.ea.getViewElements().filter((element2) => element2.id === pathElement.id) ); const element = this.ea.getElement( pathElement.id ); if (!element) return; if (!this.setup.isHidden) { element.strokeColor = originalProps.strokeColor; element.backgroundColor = originalProps.backgroundColor; element.locked = openForEdit ? false : originalProps.locked; } await this.ea.addElementsToView(false, false, false, false, "NEVER"); if (!this.setup.isHidden) this.ea.selectElementsInView([element]); if (!openForEdit) return; const deckSlide = this.setup.deck.visibleSlides[this.slide]; const pairIndex = deckSlide?.kind === "path" ? deckSlide.pairIndex : this.slide; let nextRect = this.getSlideNavigationRect(this.slide); const offsetWidth = (nextRect.right - nextRect.left) * (1 - this.config.editZoomOut) / 2; const offsetHeight = (nextRect.bottom - nextRect.top) * (1 - this.config.editZoomOut) / 2; nextRect = { left: nextRect.left - offsetWidth, right: nextRect.right + offsetWidth, top: nextRect.top - offsetHeight, bottom: nextRect.bottom + offsetHeight, nextZoom: Math.max(nextRect.nextZoom * this.config.editZoomOut, 0.1) }; await this.scrollToRect(nextRect, 1); this.api.startLineEditor(element, [pairIndex * 2, pairIndex * 2 + 1]); } async print(event) { await this.presenter?.waitForIdle(); this.ea.setView(this.hostView); const task = () => printSlideshowToPdf({ event, ea: this.ea, api: this.api, choices: resolveSlideDeckChoices(this.ea), sourceKey: this.setup.sourceKey, printSlideWidth: this.config.printSlideWidth, printSlideHeight: this.config.printSlideHeight, maxZoom: this.config.maxZoom, t: this.t }); try { if (this.animationRuntime) await this.animationRuntime.withFinalState(task); else await task(); } catch (error) { console.error("Slideshow PDF export failed", error); new this.ea.obsidian.Notice(this.t("printFailed")); } } }; // src/sharedUtils/confirmationModal.ts function openConfirmationModal(ea2, app2, options) { return new Promise((resolve) => { const modal = new ea2.obsidian.Modal(app2); let settled = false; const finish = (confirmed) => { if (settled) return; settled = true; resolve(confirmed); modal.close(); }; if (options.title) modal.titleEl.setText(options.title); modal.contentEl.createEl("p", { text: options.message }); const actions = modal.contentEl.createDiv({ cls: "modal-button-container" }); actions.style.display = "flex"; actions.style.justifyContent = "flex-end"; actions.style.gap = "var(--size-4-2)"; new ea2.obsidian.ButtonComponent(actions).setButtonText(options.cancelText).onClick(() => finish(false)); const confirmButton = new ea2.obsidian.ButtonComponent(actions).setButtonText(options.confirmText).setCta().onClick(() => finish(true)); modal.onClose = () => { if (!settled) { settled = true; resolve(false); } modal.contentEl.empty(); }; modal.open(); confirmButton.buttonEl.focus(); }); } // src/scripts/slideshow/AnimationTargetPreviewService.ts var AnimationTargetPreviewService = class { constructor(ea2, api) { this.ea = ea2; this.api = api; } ea; api; queue = new AsyncTaskQueue(1); cache = new ByteBudgetLruCache( 4 * 1024 * 1024, (url) => URL.revokeObjectURL(url) ); destroyed = false; /** Exports only the scoped visual targets, including bound text, at at most 160px per side. */ async createPreview(scope, targets, doc, isRelevant, originalOpacities) { if (this.destroyed) return null; const elements = this.ea.getViewElements(); const ids = new Set(resolveAnimationTargetElementIds(scope, targets, elements)); const selected = elements.filter((element) => ids.has(element.id)).map((element) => { const opacity = originalOpacities?.get(element.id) ?? element.opacity; return opacity === element.opacity ? element : { ...element, opacity }; }); if (selected.length === 0) return null; const appearance = getPreviewAppearance(this.api.getAppState()); const key = `${appearance.key}|${getSceneVisualFingerprint(selected)}`; let url = this.cache.get(key); if (!url) { url = await this.queue.enqueue(key, async () => { if (getPreviewAppearance(this.api.getAppState()).key !== appearance.key) return void 0; const bounds = this.ea.getBoundingBox(selected); const blob = await this.ea.createViewPNG({ withBackground: true, theme: appearance.theme, frameRendering: { enabled: false, name: false, outline: false, clip: false }, padding: 4, selectedOnly: false, embedScene: false, elementsOverride: selected, scale: Math.min(2, 160 / Math.max(bounds.width + 8, bounds.height + 8, 1)) }); if (this.destroyed || getPreviewAppearance(this.api.getAppState()).key !== appearance.key) return void 0; const objectUrl = URL.createObjectURL(blob); this.cache.set(key, objectUrl, blob.size); return objectUrl; }, () => !this.destroyed); } await Promise.resolve(); if (!url || this.destroyed || !isRelevant()) return null; const image = doc.createElement("img"); image.src = url; image.alt = ""; image.draggable = false; image.style.backgroundColor = appearance.backgroundColor; return image; } /** Invalidates queued exports and releases URLs, including when a running export finishes later. */ destroy() { this.destroyed = true; this.queue.clear(); this.cache.clear(); } }; // src/scripts/slideshow/slideDeckMutations.ts function normalizeNotes2(notes) { return notes.trim().length === 0 ? void 0 : notes; } function getFrameElements(ea2) { return ea2.getViewElements().filter(isFrameElement); } function moveId(ids, fromIndex, toIndex) { if (!Number.isInteger(fromIndex) || !Number.isInteger(toIndex) || fromIndex < 0 || toIndex < 0 || fromIndex >= ids.length || toIndex >= ids.length) { throw new RangeError("Frame-slide index is outside the deck."); } const [id] = ids.splice(fromIndex, 1); if (!id) throw new RangeError("The source frame slide does not exist."); ids.splice(toIndex, 0, id); } async function commitWorkbench(ea2) { const committed = await ea2.addElementsToView(false, true, false, false, "IMMEDIATELY"); if (!committed) throw new Error("The slideshow metadata could not be applied to the drawing."); } async function writeFrameMetadataSet(ea2, orderedIds, targetId, mutateTarget) { const frames = getFrameElements(ea2); const byId = new Map(frames.map((frame) => [frame.id, frame])); if (orderedIds.length !== frames.length || orderedIds.some((id) => !byId.has(id))) { throw new Error("The frame deck changed before the slideshow metadata could be saved."); } const deckName = frames.map((frame) => readFrameSlideshowData(frame.customData)?.deckName).find((name) => typeof name === "string" && name.trim().length > 0); ea2.clear(); ea2.copyViewElementsToEAforEditing(frames); orderedIds.forEach((frameId, order) => { const source = byId.get(frameId); if (!source) return; const data = withNormalizedFrameOrder(source.customData, order); if (deckName && !data.deckName) data.deckName = deckName; if (frameId === targetId) mutateTarget?.(data); writeSlideshowMetadata(ea2, frameId, data); }); await commitWorkbench(ea2); } async function declareFrameSlideshow(ea2, selectedFrameId) { const frame = getFrameElements(ea2).find((candidate) => candidate.id === selectedFrameId); if (!frame) throw new Error("The selected frame no longer exists."); ea2.clear(); ea2.copyViewElementsToEAforEditing([frame]); const updated = ea2.addAppendUpdateCustomData(selectedFrameId, { slideshow: { schemaVersion: 2, kind: "frame" } }); if (!updated) throw new Error("The selected frame could not be edited."); await commitWorkbench(ea2); } async function renameFrameSlide(ea2, frameId, name) { const source = ea2.getViewElements().find((element) => element.id === frameId); if (!isFrameElement(source)) throw new Error("The selected frame no longer exists."); ea2.clear(); ea2.copyViewElementsToEAforEditing([source]); const frame = ea2.getElement(frameId); if (!frame) throw new Error("The selected frame could not be edited."); frame.name = name.trim().length === 0 ? null : name; await commitWorkbench(ea2); } async function reorderFrameSlides(ea2, fromIndex, toIndex) { const frames = getFrameElements(ea2); const orderedIds = buildFrameSlideDeck(frames).slides.map((slide) => slide.id); moveId(orderedIds, fromIndex, toIndex); await writeFrameMetadataSet(ea2, orderedIds, null); } async function setFrameExcluded(ea2, frameId, excluded) { const frames = getFrameElements(ea2); const orderedIds = buildFrameSlideDeck(frames).slides.map((slide) => slide.id); await writeFrameMetadataSet(ea2, orderedIds, frameId, (data) => { if (excluded) data.excluded = true; else delete data.excluded; }); } async function saveFrameNotes(ea2, frameId, notes) { const frames = getFrameElements(ea2); const orderedIds = buildFrameSlideDeck(frames).slides.map((slide) => slide.id); if (!orderedIds.includes(frameId)) { throw new Error("The selected frame slide no longer exists."); } const normalized = normalizeNotes2(notes); await writeFrameMetadataSet(ea2, orderedIds, frameId, (data) => { if (normalized === void 0) delete data.notes; else data.notes = normalized; }); } async function saveFrameAnimationSteps(ea2, frameId, steps) { const frames = getFrameElements(ea2); const orderedIds = buildFrameSlideDeck(frames).slides.map((slide) => slide.id); if (!orderedIds.includes(frameId)) { throw new Error("The selected frame slide no longer exists."); } await writeFrameMetadataSet(ea2, orderedIds, frameId, (data) => { if (steps.length === 0) delete data.animation; else data.animation = { steps: steps.map((step) => structuredClone(step)) }; }); } function hasBoundLineEndpoint(path) { const bindingPath = path; return bindingPath.startBinding !== null && bindingPath.startBinding !== void 0 || bindingPath.endBinding !== null && bindingPath.endBinding !== void 0; } function fallbackPathProperties(path) { return { strokeColor: path.strokeColor, backgroundColor: path.backgroundColor, locked: path.locked }; } async function createLinePresentation(ea2, pathId, name) { const source = ea2.getViewElements().find((element2) => element2.id === pathId); if (!isLinearPathElement(source)) throw new Error("The selected line no longer exists."); if (Math.floor(source.points.length / 2) <= 0) { throw new Error("The selected line does not contain a complete slide point pair."); } ea2.clear(); ea2.copyViewElementsToEAforEditing([source]); const element = ea2.getElement(pathId); if (!element) throw new Error("The selected line could not be edited."); const metadata = upgradeLineSlideshowData( element.customData, element.id, Math.floor(element.points.length / 2), fallbackPathProperties(source), getAbsoluteLinePoints(element.x, element.y, element.points) ); const normalizedName = normalizeNotes2(name ?? ""); if (normalizedName === void 0) delete metadata.name; else metadata.name = normalizedName; writeSlideshowMetadata(ea2, element.id, metadata); await commitWorkbench(ea2); } async function renameLinePresentation(ea2, pathId, name) { const source = ea2.getViewElements().find((element2) => element2.id === pathId); if (!isLinearPathElement(source)) throw new Error("The presentation path no longer exists."); ea2.clear(); ea2.copyViewElementsToEAforEditing([source]); const element = ea2.getElement(pathId); if (!element) throw new Error("The presentation path could not be edited."); const metadata = upgradeLineSlideshowData( element.customData, element.id, Math.floor(element.points.length / 2), fallbackPathProperties(source), getAbsoluteLinePoints(element.x, element.y, element.points) ); const normalizedName = normalizeNotes2(name); if (normalizedName === void 0) delete metadata.name; else metadata.name = normalizedName; writeSlideshowMetadata(ea2, element.id, metadata); await commitWorkbench(ea2); } async function removeLinePresentation(ea2, pathId) { const source = ea2.getViewElements().find((element2) => element2.id === pathId); if (!isLinearPathElement(source)) throw new Error("The presentation path no longer exists."); ea2.clear(); ea2.copyViewElementsToEAforEditing([source]); const element = ea2.getElement(pathId); if (!element) throw new Error("The presentation path could not be edited."); const existing = upgradeLineSlideshowData( element.customData, element.id, Math.floor(element.points.length / 2), fallbackPathProperties(source), getAbsoluteLinePoints(element.x, element.y, element.points) ); if (existing.hidden) { element.strokeColor = existing.originalProps.strokeColor; element.backgroundColor = existing.originalProps.backgroundColor; element.locked = existing.originalProps.locked; } writeSlideshowMetadata(ea2, element.id, void 0); await commitWorkbench(ea2); } async function reorderLineSlides(ea2, pathId, fromPairIndex, toPairIndex) { const source = ea2.getViewElements().find((element2) => element2.id === pathId); if (!isLinearPathElement(source)) throw new Error("The presentation path no longer exists."); if (hasBoundLineEndpoint(source)) { throw new Error("BOUND_PRESENTATION_PATH"); } ea2.clear(); ea2.copyViewElementsToEAforEditing([source]); const element = ea2.getElement(pathId); if (!element) throw new Error("The presentation path could not be edited."); const pairCount = Math.floor(element.points.length / 2); const reordered = reorderLinePointPairs( element.x, element.y, element.points, fromPairIndex, toPairIndex ); const metadata = upgradeLineSlideshowData( element.customData, element.id, pairCount, fallbackPathProperties(source), getAbsoluteLinePoints(element.x, element.y, element.points) ); metadata.slides = reorderLineSlideRecords( metadata.slides, pairCount, element.id, fromPairIndex, toPairIndex, getAbsoluteLinePoints(element.x, element.y, element.points) ); metadata.slides.forEach((record, index) => { const first = reordered.points[index * 2]; const second = reordered.points[index * 2 + 1]; if (first && second) { record.pair = [ [reordered.x + first[0], reordered.y + first[1]], [reordered.x + second[0], reordered.y + second[1]] ]; } }); element.x = reordered.x; element.y = reordered.y; element.points = reordered.points; writeSlideshowMetadata(ea2, element.id, metadata); await commitWorkbench(ea2); } async function saveLineNotes(ea2, pathId, slideId, notes) { const source = ea2.getViewElements().find((element2) => element2.id === pathId); if (!isLinearPathElement(source)) throw new Error("The presentation path no longer exists."); ea2.clear(); ea2.copyViewElementsToEAforEditing([source]); const element = ea2.getElement(pathId); if (!element) throw new Error("The presentation path could not be edited."); const metadata = upgradeLineSlideshowData( element.customData, element.id, Math.floor(element.points.length / 2), fallbackPathProperties(source), getAbsoluteLinePoints(element.x, element.y, element.points) ); const record = metadata.slides.find((candidate) => candidate.id === slideId); if (!record) throw new Error("The selected line slide no longer exists."); const normalized = normalizeNotes2(notes); if (normalized === void 0) delete record.notes; else record.notes = normalized; writeSlideshowMetadata(ea2, element.id, metadata); await commitWorkbench(ea2); } async function setLineSlideExcluded(ea2, pathId, slideId, excluded) { const source = ea2.getViewElements().find((element2) => element2.id === pathId); if (!isLinearPathElement(source)) throw new Error("The presentation path no longer exists."); ea2.clear(); ea2.copyViewElementsToEAforEditing([source]); const element = ea2.getElement(pathId); if (!element) throw new Error("The presentation path could not be edited."); const metadata = upgradeLineSlideshowData( element.customData, element.id, Math.floor(element.points.length / 2), fallbackPathProperties(source), getAbsoluteLinePoints(element.x, element.y, element.points) ); const record = metadata.slides.find((candidate) => candidate.id === slideId); if (!record) throw new Error("The selected line slide no longer exists."); if (excluded) record.excluded = true; else delete record.excluded; writeSlideshowMetadata(ea2, element.id, metadata); await commitWorkbench(ea2); } async function setLinePresentationPathHidden(ea2, pathId, hidden) { const source = ea2.getViewElements().find((element2) => element2.id === pathId); if (!isLinearPathElement(source)) throw new Error("The presentation path no longer exists."); ea2.clear(); ea2.copyViewElementsToEAforEditing([source]); const element = ea2.getElement(pathId); if (!element) throw new Error("The presentation path could not be edited."); const metadata = upgradeLineSlideshowData( element.customData, element.id, Math.floor(element.points.length / 2), fallbackPathProperties(source), getAbsoluteLinePoints(element.x, element.y, element.points) ); metadata.hidden = hidden; if (hidden) { element.strokeColor = "transparent"; element.backgroundColor = "transparent"; element.locked = true; } else { element.strokeColor = metadata.originalProps.strokeColor; element.backgroundColor = metadata.originalProps.backgroundColor; element.locked = metadata.originalProps.locked; } writeSlideshowMetadata(ea2, element.id, metadata); await commitWorkbench(ea2); } async function renameLineSlide(ea2, pathId, slideId, name) { const source = ea2.getViewElements().find((element2) => element2.id === pathId); if (!isLinearPathElement(source)) throw new Error("The presentation path no longer exists."); ea2.clear(); ea2.copyViewElementsToEAforEditing([source]); const element = ea2.getElement(pathId); if (!element) throw new Error("The presentation path could not be edited."); const metadata = upgradeLineSlideshowData( element.customData, element.id, Math.floor(element.points.length / 2), fallbackPathProperties(source), getAbsoluteLinePoints(element.x, element.y, element.points) ); const record = metadata.slides.find((candidate) => candidate.id === slideId); if (!record) throw new Error("The selected line slide no longer exists."); const normalized = normalizeNotes2(name); if (normalized === void 0) delete record.title; else record.title = normalized; writeSlideshowMetadata(ea2, element.id, metadata); await commitWorkbench(ea2); } async function saveLineAnimationSteps(ea2, pathId, slideId, steps) { const source = ea2.getViewElements().find((element2) => element2.id === pathId); if (!isLinearPathElement(source)) throw new Error("The presentation path no longer exists."); ea2.clear(); ea2.copyViewElementsToEAforEditing([source]); const element = ea2.getElement(pathId); if (!element) throw new Error("The presentation path could not be edited."); const metadata = upgradeLineSlideshowData( element.customData, element.id, Math.floor(element.points.length / 2), fallbackPathProperties(source), getAbsoluteLinePoints(element.x, element.y, element.points) ); const record = metadata.slides.find((candidate) => candidate.id === slideId); if (!record) throw new Error("The selected line slide no longer exists."); if (steps.length === 0) delete record.animation; else record.animation = { steps: steps.map((step) => structuredClone(step)) }; writeSlideshowMetadata(ea2, element.id, metadata); await commitWorkbench(ea2); } async function renameFramePresentation(ea2, name) { const frames = getFrameElements(ea2); const orderedIds = buildFrameSlideDeck(frames).slides.map((slide) => slide.id); const normalized = normalizeNotes2(name); ea2.clear(); ea2.copyViewElementsToEAforEditing(frames); orderedIds.forEach((frameId, order) => { const source = frames.find((frame) => frame.id === frameId); if (!source) return; const data = withNormalizedFrameOrder(source.customData, order); if (normalized === void 0) delete data.deckName; else data.deckName = normalized; writeSlideshowMetadata(ea2, frameId, data); }); await commitWorkbench(ea2); } async function resizeFrameToPresentationAspect(ea2, frameId, config) { const source = ea2.getViewElements().find((element) => element.id === frameId); if (!isFrameElement(source)) throw new Error("The selected frame no longer exists."); const rect = expandSlideRectToAspectRatio( { x1: source.x, y1: source.y, x2: source.x + source.width, y2: source.y + source.height }, { width: config.printSlideWidth, height: config.printSlideHeight } ); ea2.clear(); ea2.copyViewElementsToEAforEditing([source]); const frame = ea2.getElement(frameId); if (!frame) throw new Error("The selected frame could not be edited."); frame.x = Math.min(rect.x1, rect.x2); frame.y = Math.min(rect.y1, rect.y2); frame.width = Math.abs(rect.x2 - rect.x1); frame.height = Math.abs(rect.y2 - rect.y1); await commitWorkbench(ea2); } function convertedDeckName(name, sourceRetained, suffix) { if (!name) return null; return sourceRetained ? `${name} (${suffix})` : name; } async function convertLinePresentationToFrames(ea2, pathId, config, options) { if (getFrameElements(ea2).length > 0) throw new Error("FRAME_SLIDESHOW_EXISTS"); const source = ea2.getViewElements().find((element) => element.id === pathId); if (!isLinearPathElement(source)) throw new Error("The presentation path no longer exists."); const deck = buildLineSlideDeck(source); if (deck.slides.length === 0) throw new Error("The line slideshow has no slides."); const normalizedOptions = typeof options === "boolean" ? { correctAspectRatio: options, deleteLine: false, frameKind: "marker" } : { correctAspectRatio: options.correctAspectRatio, deleteLine: options.deleteLine ?? false, frameKind: options.frameKind ?? "marker" }; const sceneElements = ea2.getViewElements(); const frameSpecs = deck.slides.map((slide) => { const rect = normalizedOptions.correctAspectRatio ? expandSlideRectToAspectRatio(slide.rect, { width: config.printSlideWidth, height: config.printSlideHeight }) : slide.rect; return { slide, left: Math.min(rect.x1, rect.x2), top: Math.min(rect.y1, rect.y2), width: Math.abs(rect.x2 - rect.x1), height: Math.abs(rect.y2 - rect.y1) }; }); const memberIdsByFrame = normalizedOptions.frameKind === "normal" ? frameSpecs.map( (spec) => ea2.getElementsInArea( sceneElements, { x: spec.left, y: spec.top, width: spec.width, height: spec.height }, { includeMarkerFrames: false, includeBoundElements: true } ).filter( (element) => element.id !== source.id && !isFrameElement(element) && !element.isDeleted && element.frameId === null ).map((element) => element.id) ) : frameSpecs.map(() => []); const memberIds = new Set(memberIdsByFrame.flat()); const members = sceneElements.filter((element) => memberIds.has(element.id)); ea2.clear(); if (members.length > 0 || normalizedOptions.deleteLine) { ea2.copyViewElementsToEAforEditing( normalizedOptions.deleteLine ? [source, ...members] : members ); } const assignedIds = /* @__PURE__ */ new Set(); const deckName = convertedDeckName(deck.name, !normalizedOptions.deleteLine, "frames"); frameSpecs.forEach((spec, order) => { const id = ea2.addFrame(spec.left, spec.top, spec.width, spec.height, spec.slide.title); const frame = ea2.getElement(id); if (!frame) throw new Error("The converted frame could not be created."); if (normalizedOptions.frameKind === "marker") frame.frameRole = "marker"; else delete frame.frameRole; const data = withNormalizedFrameOrder(void 0, order); if (deckName) data.deckName = deckName; if (spec.slide.notes) data.notes = spec.slide.notes; if (spec.slide.excluded) data.excluded = true; if (spec.slide.animationSteps.length > 0) { data.animation = { steps: spec.slide.animationSteps.map((step) => structuredClone(step)) }; } writeSlideshowMetadata(ea2, id, data); if (normalizedOptions.frameKind === "normal") { for (const memberId of memberIdsByFrame[order] ?? []) { if (assignedIds.has(memberId)) continue; const member = ea2.getElement(memberId); if (!member || member.frameId !== null) continue; member.frameId = id; assignedIds.add(memberId); } } }); if (normalizedOptions.deleteLine) { const path = ea2.getElement(source.id); if (path) path.isDeleted = true; } await commitWorkbench(ea2); } async function convertFramePresentationToLine(ea2, options = {}) { const frames = getFrameElements(ea2); const deck = buildFrameSlideDeck(frames); if (deck.slides.length === 0) throw new Error("The frame slideshow has no slides."); const slides = options.visibleSlidesOnly ? deck.visibleSlides : deck.slides; if (slides.length === 0) throw new Error("The frame slideshow has no visible slides."); const frameIds = new Set(deck.slides.map((slide) => slide.id)); const framedElements = ea2.getViewElements().filter((element) => element.frameId !== null && frameIds.has(element.frameId)); const points = []; for (const slide of slides) { points.push( [Math.min(slide.rect.x1, slide.rect.x2), Math.min(slide.rect.y1, slide.rect.y2)], [Math.max(slide.rect.x1, slide.rect.x2), Math.max(slide.rect.y1, slide.rect.y2)] ); } ea2.clear(); const editableSources = options.deleteFrames ? [...framedElements, ...frames] : framedElements; if (editableSources.length > 0) ea2.copyViewElementsToEAforEditing(editableSources); for (const source of framedElements) { const element = ea2.getElement(source.id); if (element) element.frameId = null; } if (options.deleteFrames) { for (const frame of frames) { const element = ea2.getElement(frame.id); if (element) element.isDeleted = true; } } const lineId = ea2.addLine(points); const line = ea2.getElement(lineId); if (!line) throw new Error("The line slideshow could not be created."); const metadata = { schemaVersion: 2, kind: "path", hidden: false, originalProps: fallbackPathProperties(line), slides: slides.map((slide, index) => { const first = line.points[index * 2]; const second = line.points[index * 2 + 1]; return { id: `slideshow-${lineId}-${index + 1}`, title: slide.title, ...slide.notes ? { notes: slide.notes } : {}, ...!options.visibleSlidesOnly && slide.excluded ? { excluded: true } : {}, ...slide.animationSteps.length > 0 ? { animation: { steps: slide.animationSteps.map((step) => structuredClone(step)) } } : {}, ...first && second ? { pair: [ [line.x + first[0], line.y + first[1]], [line.x + second[0], line.y + second[1]] ] } : {} }; }) }; const name = convertedDeckName(deck.name, !options.deleteFrames, "line"); if (name) metadata.name = name; writeSlideshowMetadata(ea2, lineId, metadata); await commitWorkbench(ea2); return lineId; } // src/scripts/slideshow/AnimationEditor.ts function targetKey(target) { return `${target.type}:${target.id}:${target.scope ?? "slide"}`; } function sameTargets(left, right) { if (left.length !== right.length) return false; const keys = new Set(right.map(targetKey)); return left.every((target) => keys.has(targetKey(target))); } function uniqueStepId(steps) { const used = new Set(steps.map((step) => step.id)); const base = `animation-${Date.now().toString(36)}`; let id = base; let suffix = 2; while (used.has(id)) { id = `${base}-${suffix}`; suffix += 1; } return id; } function moveStep(steps, fromIndex, toIndex) { if (fromIndex < 0 || toIndex < 0 || fromIndex >= steps.length || toIndex >= steps.length) return; const [step] = steps.splice(fromIndex, 1); if (step) steps.splice(toIndex, 0, step); } var AnimationEditor = class { constructor(options) { this.options = options; this.steps = options.slide.animationSteps.map((step) => structuredClone(step)); this.drawingFile = options.hostView.file; this.targetPreviews = new AnimationTargetPreviewService(options.ea, options.api); this.previewRuntime = new AnimationRuntime({ ea: options.ea, api: options.api, hostView: options.hostView, config: options.config }); } options; steps; selectedStepId = null; targets = []; ignoredSelectionCount = 0; effect = "appear"; trigger = "advance"; delayMs = 1e3; durationMs = 350; direction = "left"; newStepDefaults = { effect: this.effect, trigger: this.trigger, delayMs: this.delayMs, durationMs: this.durationMs, direction: this.direction }; lastSelectionTargets = null; destroyed = false; saving = false; selectingStep = false; recycleTimer = 0; pendingRecycleElements = null; previewRuntime; targetPreviews; drawingFile; targetPreviewBindings = /* @__PURE__ */ new Map(); previewAppearanceKey = ""; previewGeneration = 0; /** Renders the editor into its current sidepanel container. */ render() { if (this.destroyed) return; const { container, icons, t } = this.options; const doc = container.ownerDocument; this.targetPreviewBindings.clear(); this.previewGeneration += 1; this.previewAppearanceKey = getPreviewAppearance(this.options.api.getAppState()).key; container.replaceChildren(); container.className = "slideshow-animation-editor"; const instructions = doc.createElement("div"); instructions.className = "slideshow-animation-editor__hint"; instructions.textContent = t("animationSelectionHint"); container.appendChild(instructions); if (this.ignoredSelectionCount > 0) { const warning = doc.createElement("div"); warning.className = "slideshow-warning"; warning.textContent = t("animationOutsideSlideIgnored", { count: this.ignoredSelectionCount }); container.appendChild(warning); } const targetSection = doc.createElement("div"); targetSection.className = "slideshow-animation-editor__section"; const targetHeading = doc.createElement("div"); targetHeading.className = "slideshow-animation-editor__section-title"; targetHeading.textContent = t("animationTargets"); targetSection.appendChild(targetHeading); const chips = doc.createElement("div"); chips.className = "slideshow-animation-editor__targets"; if (this.targets.length === 0) { const empty = doc.createElement("span"); empty.className = "slideshow-animation-editor__muted"; empty.textContent = t("animationNoTargets"); chips.appendChild(empty); } else { this.targets.forEach((target, index) => { const chip = doc.createElement("span"); chip.className = "slideshow-animation-editor__target"; const preview = this.createTargetPreview(doc, [target], "slideshow-animation-editor__target-preview"); preview.setAttribute("role", "img"); preview.setAttribute("aria-label", this.getTargetLabel(target)); chip.appendChild(preview); const remove = this.iconButton(doc, icons.close, t("removeAnimationTarget"), false, () => { this.targets.splice(index, 1); this.render(); }); chip.appendChild(remove); chips.appendChild(chip); }); } targetSection.appendChild(chips); container.appendChild(targetSection); const form = doc.createElement("div"); form.className = "slideshow-animation-editor__form"; const effectSelect = this.createChoices(doc, t("animationEffect"), [ ["appear", t("animationEffectAppear")], ["fade", t("animationEffectFade")], ["slide", t("animationEffectSlide")], ["zoom", t("animationEffectZoom")], ["disappear", t("animationEffectDisappear")], ["fade-out", t("animationEffectFadeOut")], ["slide-out", t("animationEffectSlideOut")], ["zoom-out", t("animationEffectZoomOut")] ], this.effect, (value) => { this.effect = value; this.rememberFormDefaults(); this.render(); }); form.appendChild(effectSelect); const triggerSelect = this.createChoices(doc, t("animationTrigger"), [ ["advance", t("animationTriggerAdvance")], ["after-delay", t("animationTriggerDelay")] ], this.trigger, (value) => { this.trigger = value; this.rememberFormDefaults(); this.render(); }); form.appendChild(triggerSelect); if (this.trigger === "after-delay") { form.appendChild( this.numberField(doc, t("animationDelayMs"), this.delayMs, 0, (value) => { this.delayMs = value; this.rememberFormDefaults(); }) ); } if (!isInstantAnimationEffect(this.effect)) { form.appendChild( this.numberField(doc, t("animationDurationMs"), this.durationMs, 0, (value) => { this.durationMs = value; this.rememberFormDefaults(); }) ); } if (this.effect === "slide" || this.effect === "slide-out") { const directionOptions = isExitAnimationEffect(this.effect) ? [ ["left", t("animationDirectionOutLeft")], ["right", t("animationDirectionOutRight")], ["up", t("animationDirectionOutUp")], ["down", t("animationDirectionOutDown")] ] : [ ["left", t("animationDirectionLeft")], ["right", t("animationDirectionRight")], ["up", t("animationDirectionUp")], ["down", t("animationDirectionDown")] ]; form.appendChild( this.createChoices(doc, t("animationDirection"), directionOptions, this.direction, (value) => { this.direction = value; this.rememberFormDefaults(); this.render(); }) ); } container.appendChild(form); const formActions = doc.createElement("div"); formActions.className = "slideshow-animation-editor__form-actions"; const saveLabel = this.selectedStepId ? t("updateAnimationStep") : t("addAnimationStep"); const saveButton = doc.createElement("button"); saveButton.type = "button"; saveButton.disabled = this.saving || this.targets.length === 0; saveButton.innerHTML = `${icons.plus}${saveLabel}`; saveButton.addEventListener("click", () => void this.saveCurrentStep()); formActions.appendChild(saveButton); const previewButton = doc.createElement("button"); previewButton.type = "button"; previewButton.disabled = this.targets.length === 0; previewButton.innerHTML = `${icons.play}${t("previewAnimation")}`; previewButton.addEventListener("click", () => void this.previewCurrentStep()); formActions.appendChild(previewButton); if (this.selectedStepId) { const cancelButton = doc.createElement("button"); cancelButton.type = "button"; cancelButton.textContent = t("newAnimationStep"); cancelButton.addEventListener("click", () => { this.startNewStep(); this.render(); }); formActions.appendChild(cancelButton); } container.appendChild(formActions); const stepHeading = doc.createElement("div"); stepHeading.className = "slideshow-animation-editor__section-title"; stepHeading.textContent = t("animationSequence", { count: this.steps.length }); container.appendChild(stepHeading); const stepList = doc.createElement("div"); stepList.className = "slideshow-animation-editor__steps"; if (this.steps.length === 0) { const empty = doc.createElement("div"); empty.className = "slideshow-animation-editor__muted"; empty.textContent = t("animationNoSteps"); stepList.appendChild(empty); } this.steps.forEach((step, index) => stepList.appendChild(this.renderStep(doc, step, index))); container.appendChild(stepList); } /** Processes live scene changes while animation editing is active. */ handleSceneChange(elements, appState) { if (this.destroyed || !this.isCurrentDrawing()) return; const appearanceKey = getPreviewAppearance(this.options.api.getAppState()).key; if (appearanceKey !== this.previewAppearanceKey) { this.previewAppearanceKey = appearanceKey; this.previewGeneration += 1; for (const [preview, targets] of this.targetPreviewBindings) this.loadTargetPreview(preview, targets); } this.captureSelection(elements, appState); this.scheduleMissingTargetRecycle(elements); } /** Captures the live canvas selection while animation editing is active. */ captureSelection(elements, appState) { if (this.destroyed || !this.isCurrentDrawing() || this.selectingStep) { return; } const captured = captureAnimationTargets( this.getSlideScope(), elements, appState.selectedElementIds, appState.selectedGroupIds ); if (this.lastSelectionTargets !== null && sameTargets(captured.targets, this.lastSelectionTargets) && captured.ignoredSelectionCount === this.ignoredSelectionCount) { return; } const selectionChanged = this.lastSelectionTargets === null || !sameTargets(captured.targets, this.lastSelectionTargets); this.lastSelectionTargets = captured.targets; if (selectionChanged) { const ids = new Set(resolveAnimationTargetElementIds(this.getSlideScope(), captured.targets, elements)); const firstStep = this.steps.find( (step) => resolveAnimationTargetElementIds(this.getSlideScope(), step.targets, elements).some((id) => ids.has(id)) ); if (firstStep) this.loadStepForm(firstStep); else { this.startNewStep(); this.targets = captured.targets; } } this.ignoredSelectionCount = captured.ignoredSelectionCount; this.render(); } /** Restores preview state and releases editor-owned resources. */ async destroy() { if (this.destroyed) return; this.destroyed = true; if (this.recycleTimer) this.options.hostView.ownerWindow.clearTimeout(this.recycleTimer); this.recycleTimer = 0; this.pendingRecycleElements = null; this.targetPreviewBindings.clear(); this.previewGeneration += 1; this.targetPreviews.destroy(); if (this.isCurrentDrawing()) await this.previewRuntime.leaveSlide(); else this.previewRuntime.abandonActiveSlide(); } scheduleMissingTargetRecycle(elements) { if (this.destroyed || !this.isCurrentDrawing()) return; this.pendingRecycleElements = elements; const ownerWindow = this.options.hostView.ownerWindow; if (this.recycleTimer) ownerWindow.clearTimeout(this.recycleTimer); this.recycleTimer = ownerWindow.setTimeout(() => { this.recycleTimer = 0; void this.recycleMissingTargets(); }, 160); } async recycleMissingTargets() { if (this.destroyed || !this.isCurrentDrawing()) return; const elements = this.pendingRecycleElements ?? this.options.ea.getViewElements(); this.pendingRecycleElements = null; if (this.saving) { this.scheduleMissingTargetRecycle(elements); return; } const steps = recycleMissingAnimationTargets(this.steps, elements); if (JSON.stringify(steps) === JSON.stringify(this.steps)) return; this.saving = true; try { await this.saveAnimationSteps(steps); if (!this.isCurrentDrawing()) return; this.steps = steps; if (this.selectedStepId) { const selectedStep = steps.find((step) => step.id === this.selectedStepId); if (selectedStep) { this.targets = selectedStep.targets.map((target) => structuredClone(target)); } else { this.selectedStepId = null; this.targets = []; this.startNewStep(); } } this.options.onSaved(this.steps); } catch (error) { console.error("Slideshow stale animation cleanup failed", error); new Notice(this.options.t("animationSaveFailed")); } finally { this.saving = false; this.render(); } } renderStep(doc, step, index) { const { icons, t } = this.options; const row = doc.createElement("div"); row.className = "slideshow-animation-editor__step"; if (step.id === this.selectedStepId) row.classList.add("is-selected"); row.tabIndex = 0; row.draggable = this.options.ea.DEVICE.isDesktop; const summary = doc.createElement("button"); summary.type = "button"; summary.className = "slideshow-animation-editor__step-summary"; const label = doc.createElement("span"); label.textContent = t("animationStepSummary", { number: index + 1, effect: this.effectLabel(step.effect), targets: step.targets.length }); const preview = this.createTargetPreview(doc, step.targets, "slideshow-animation-editor__step-preview"); summary.append(preview, label); summary.addEventListener("click", () => this.selectStep(step)); row.appendChild(summary); const actions = doc.createElement("div"); actions.className = "slideshow-animation-editor__step-actions"; actions.appendChild( this.iconButton(doc, icons.chevronUp, t("moveAnimationStepUp"), index === 0, () => { void this.reorderStep(index, index - 1); }) ); actions.appendChild( this.iconButton( doc, icons.chevronDown, t("moveAnimationStepDown"), index === this.steps.length - 1, () => void this.reorderStep(index, index + 1) ) ); actions.appendChild( this.iconButton(doc, icons.play, t("previewAnimationStep"), false, () => { void this.previewRuntime.previewStep(this.getSlideScope(), step); }) ); actions.appendChild( this.iconButton(doc, icons.trash, t("deleteAnimationStep"), false, () => { void this.deleteStep(step.id); }) ); row.appendChild(actions); if (this.options.ea.DEVICE.isDesktop) { row.addEventListener("dragstart", (event) => { event.dataTransfer?.setData("text/plain", String(index)); if (event.dataTransfer) event.dataTransfer.effectAllowed = "move"; }); row.addEventListener("dragover", (event) => { event.preventDefault(); if (event.dataTransfer) event.dataTransfer.dropEffect = "move"; }); row.addEventListener("drop", (event) => { event.preventDefault(); const fromIndex = Number.parseInt(event.dataTransfer?.getData("text/plain") ?? "", 10); if (Number.isInteger(fromIndex) && fromIndex !== index) void this.reorderStep(fromIndex, index); }); } row.addEventListener("keydown", (event) => { if (!event.altKey || event.key !== "ArrowUp" && event.key !== "ArrowDown") return; event.preventDefault(); const target = event.key === "ArrowUp" ? index - 1 : index + 1; void this.reorderStep(index, target); }); return row; } /** Loads a saved step without changing the user's defaults for the next new step. */ loadStepForm(step) { this.selectedStepId = step.id; this.targets = step.targets.map((target) => structuredClone(target)); this.effect = step.effect; this.trigger = step.trigger; this.delayMs = step.delayMs ?? 1e3; this.durationMs = step.durationMs ?? 350; this.direction = step.direction ?? "left"; this.ignoredSelectionCount = 0; } /** Shares the bounded thumbnail cache between selected-target cards and sequence rows. */ createTargetPreview(doc, targets, className) { const preview = doc.createElement("span"); preview.className = className; this.targetPreviewBindings.set(preview, targets); this.loadTargetPreview(preview, targets); return preview; } /** Updates image content in place so appearance changes preserve the mounted form controls. */ loadTargetPreview(preview, targets) { const generation = this.previewGeneration; void this.targetPreviews.createPreview( this.getSlideScope(), targets, preview.ownerDocument, () => !this.destroyed && generation === this.previewGeneration && preview.isConnected && this.isCurrentDrawing(), this.previewRuntime.getOriginalOpacities() ).then((image) => { if (image && !this.destroyed && generation === this.previewGeneration && preview.isConnected) preview.replaceChildren(image); }).catch((error) => console.error("Slideshow animation thumbnail failed", error)); } selectStep(step) { this.loadStepForm(step); const ids = resolveAnimationTargetElementIds( this.getSlideScope(), step.targets, this.options.ea.getViewElements() ); const elements = this.options.ea.getViewElements().filter((element) => ids.includes(element.id)); this.selectingStep = true; try { if (elements.length > 0) this.options.ea.selectElementsInView(elements); this.options.api.updateScene({ appState: { selectedGroupIds: Object.fromEntries(step.targets.filter((target) => target.type === "group").map((target) => [target.id, true])) }, captureUpdate: "NEVER", forceFlushSync: true }); const state = this.options.api.getAppState(); this.lastSelectionTargets = captureAnimationTargets( this.getSlideScope(), this.options.ea.getViewElements(), state.selectedElementIds, state.selectedGroupIds ).targets; } finally { this.selectingStep = false; } this.render(); } async saveCurrentStep() { if (this.saving || this.targets.length === 0 || !this.isCurrentDrawing()) return; this.saving = true; this.render(); try { const selectedId = this.selectedStepId; const steps = this.steps.map((step2) => structuredClone(step2)); const step = this.buildFormStep(selectedId ?? uniqueStepId(steps)); this.rememberFormDefaults(); if (selectedId) { const index = steps.findIndex((candidate) => candidate.id === selectedId); if (index >= 0) steps[index] = step; else steps.push(step); } else { steps.push(step); } await this.saveAnimationSteps(steps); if (!this.isCurrentDrawing()) return; this.steps = steps; if (!selectedId && this.selectedStepId === null && sameTargets(this.targets, step.targets)) { this.startNewStep(); } this.options.onSaved(this.steps); } catch (error) { console.error("Slideshow animation metadata save failed", error); new Notice(this.options.t("animationSaveFailed")); } finally { this.saving = false; this.render(); } } async reorderStep(fromIndex, toIndex) { if (toIndex < 0 || toIndex >= this.steps.length || this.saving) return; const steps = this.steps.map((step) => structuredClone(step)); moveStep(steps, fromIndex, toIndex); await this.persistSteps(steps); } async deleteStep(stepId) { if (this.saving) return; const steps = this.steps.filter((step) => step.id !== stepId); await this.persistSteps(steps); if (this.selectedStepId === stepId) { this.selectedStepId = null; this.targets = []; this.startNewStep(); } this.render(); } async persistSteps(steps) { if (!this.isCurrentDrawing()) return; this.saving = true; try { await this.saveAnimationSteps(steps); if (!this.isCurrentDrawing()) return; this.steps = steps; this.options.onSaved(this.steps); } catch (error) { console.error("Slideshow animation sequence save failed", error); new Notice(this.options.t("animationSaveFailed")); } finally { this.saving = false; this.render(); } } async previewCurrentStep() { if (this.targets.length === 0 || !this.isCurrentDrawing()) return; await this.previewRuntime.previewStep( this.getSlideScope(), this.buildFormStep(this.selectedStepId ?? "preview") ); } saveAnimationSteps(steps) { if (!this.isCurrentDrawing()) return Promise.resolve(); const { slide, ea: ea2 } = this.options; return slide.kind === "frame" ? saveFrameAnimationSteps(ea2, slide.frameId, steps) : saveLineAnimationSteps(ea2, slide.pathId, slide.id, steps); } buildFormStep(id) { const step = { id, targets: this.targets.map((target) => structuredClone(target)), effect: this.effect, trigger: this.trigger }; if (this.trigger === "after-delay") step.delayMs = this.delayMs; if (!isInstantAnimationEffect(this.effect)) step.durationMs = this.durationMs; if (this.effect === "slide" || this.effect === "slide-out") step.direction = this.direction; return step; } startNewStep() { this.selectedStepId = null; Object.assign(this, this.newStepDefaults); } getSlideScope() { const appState = this.options.api.getAppState(); return getAnimationSlideScope(this.options.slide, this.options.config, { width: appState.width, height: appState.height }); } isCurrentDrawing() { return this.options.hostView.file === this.drawingFile; } /** Remembers explicit form choices independently of saved-step selection. */ rememberFormDefaults() { this.newStepDefaults = { effect: this.effect, trigger: this.trigger, delayMs: this.delayMs, durationMs: this.durationMs, direction: this.direction }; } getTargetLabel(target) { if (target.type === "group") { return this.options.t("animationGroupTarget", { id: target.id.slice(0, 8) }); } const element = this.options.ea.getViewElements().find((candidate) => candidate.id === target.id); return this.options.t("animationElementTarget", { type: element?.type ?? "?", id: target.id.slice(0, 8) }); } effectLabel(effect) { const { t } = this.options; switch (effect) { case "fade": return t("animationEffectFade"); case "slide": return t("animationEffectSlide"); case "zoom": return t("animationEffectZoom"); case "disappear": return t("animationEffectDisappear"); case "fade-out": return t("animationEffectFadeOut"); case "slide-out": return t("animationEffectSlideOut"); case "zoom-out": return t("animationEffectZoomOut"); default: return t("animationEffectAppear"); } } iconButton(doc, icon, label, disabled, callback) { const button = doc.createElement("button"); button.type = "button"; button.innerHTML = icon; button.disabled = disabled; button.setAttribute("aria-label", label); button.addEventListener("click", callback); return button; } /** Renders accessible effect/direction buttons using the same form state as timing controls. */ createChoices(doc, labelText, choices, value, onChange) { const section = doc.createElement("div"); section.className = "slideshow-animation-editor__choices-section"; const heading = doc.createElement("span"); heading.textContent = labelText; const buttons = doc.createElement("div"); buttons.className = "slideshow-animation-editor__choices"; buttons.setAttribute("role", "group"); buttons.setAttribute("aria-label", labelText); for (const [choice, label] of choices) { const button = doc.createElement("button"); button.type = "button"; const icon = doc.createElement("span"); icon.className = "slideshow-animation-editor__choice-icon"; icon.setAttribute("aria-hidden", "true"); icon.innerHTML = getAnimationEditorIcon(this.options.ea, choice, isExitAnimationEffect(this.effect)); const text = doc.createElement("span"); text.textContent = label; button.append(icon, text); button.setAttribute("aria-pressed", String(choice === value)); button.addEventListener("click", () => onChange(choice)); buttons.appendChild(button); } section.append(heading, buttons); return section; } numberField(doc, labelText, value, min, onChange) { const label = doc.createElement("label"); const text = doc.createElement("span"); text.textContent = labelText; label.appendChild(text); const input = doc.createElement("input"); input.type = "number"; input.min = String(min); input.step = "50"; input.value = String(value); input.addEventListener("change", () => { const parsed = Number(input.value); onChange(Number.isFinite(parsed) ? Math.max(min, parsed) : value); }); label.appendChild(input); return label; } }; // src/scripts/slideshow/SlideSorter.ts function isSingleColumnSorterLayout(rowRects) { if (rowRects.length <= 1) return true; const firstLeft = rowRects[0]?.left ?? 0; return rowRects.every((rect) => Math.abs(rect.left - firstLeft) <= 8); } function getDropIndicatorPlacement(rowRects, insertionIndex) { const singleColumn = isSingleColumnSorterLayout(rowRects); if (rowRects.length === 0) { return { beforeIndex: null, afterIndex: null, singleColumn }; } if (insertionIndex >= rowRects.length) { return { beforeIndex: null, afterIndex: rowRects.length - 1, singleColumn }; } const wrapsRow = !singleColumn && insertionIndex > 0 && Math.abs( (rowRects[insertionIndex - 1]?.top ?? 0) - (rowRects[insertionIndex]?.top ?? 0) ) > 8; return { beforeIndex: insertionIndex, afterIndex: wrapsRow ? insertionIndex - 1 : null, singleColumn }; } function getDropInsertionIndexFromRects(rowRects, pointerX, pointerY) { if (rowRects.length === 0) return 0; const groups = []; rowRects.forEach((rect, index) => { const group = groups.find((candidate) => { const first = candidate[0]?.rect; return Boolean(first && Math.abs(first.top - rect.top) <= 8); }); if (group) group.push({ rect, index }); else groups.push([{ rect, index }]); }); const targetGroup = groups.find((group) => { const top = Math.min(...group.map((entry) => entry.rect.top)); const bottom = Math.max(...group.map((entry) => entry.rect.bottom)); return pointerY < (top + bottom) / 2; }); if (!targetGroup) return rowRects.length; const ordered = [...targetGroup].sort((a, b) => a.rect.left - b.rect.left); const target = ordered.find((entry) => pointerX < (entry.rect.left + entry.rect.right) / 2); return target?.index ?? (ordered[ordered.length - 1]?.index ?? -1) + 1; } function getDropMoveTarget(fromIndex, insertionIndex, slideCount) { if (fromIndex < 0 || fromIndex >= slideCount || insertionIndex < 0 || insertionIndex > slideCount) { return null; } const target = insertionIndex > fromIndex ? insertionIndex - 1 : insertionIndex; return target === fromIndex ? null : target; } function getDragAutoScrollVelocity(pointerY, containerTop, containerBottom, edgeSize = 72, maximumSpeed = 18) { const availableHeight = Math.max(containerBottom - containerTop, 0); const edge = Math.min(edgeSize, availableHeight / 2); if (edge <= 0) return 0; if (pointerY < containerTop + edge) { const strength = Math.min(Math.max((containerTop + edge - pointerY) / edge, 0), 1); return -maximumSpeed * strength; } if (pointerY > containerBottom - edge) { const strength = Math.min(Math.max((pointerY - (containerBottom - edge)) / edge, 0), 1); return maximumSpeed * strength; } return 0; } function getFinalPreviewAnimationFingerprint(steps) { if (!steps.some((step) => isExitAnimationEffect(step.effect))) return "all-visible"; return JSON.stringify( steps.map((step) => ({ phase: isExitAnimationEffect(step.effect) ? "exit" : "enter", targets: step.targets })) ); } var SlideSorter = class { constructor(options) { this.options = options; this.ownerWindow = options.container.ownerDocument.defaultView ?? window; this.previewRenderingEnabled = options.previewRenderingEnabled ?? true; this.selectedSlideId = options.deck.slides[0]?.id ?? null; options.container.addEventListener?.("dragover", this.handleContainerDragOver); options.container.addEventListener?.("dragleave", this.handleContainerDragLeave); options.container.addEventListener?.("drop", this.handleContainerDrop); } options; selectedSlideId = null; expandedNotesSlideId = null; notesTextarea = null; notesTimer = 0; ownerWindow; renderGeneration = 0; draggedIndex = null; dropTargetIndex = null; dropIndicatorKey = null; dragPointerX = null; dragPointerY = null; autoScrollVelocity = 0; autoScrollFrame = 0; notesSaveInFlight = null; previewObserver = null; previewRenderingEnabled; /** Rebinds timer behavior after the sidepanel DOM migrates between windows. */ onWindowMigrated(ownerWindow) { if (this.notesTimer) { this.ownerWindow.clearTimeout(this.notesTimer); this.notesTimer = 0; this.scheduleNotesSave(); } this.stopAutoScroll(); this.previewObserver?.disconnect(); this.previewObserver = null; this.ownerWindow = ownerWindow; this.render(); } /** Enables or suspends sorter thumbnail work without rebuilding slide rows. */ setPreviewRenderingEnabled(enabled) { if (enabled === this.previewRenderingEnabled) return; this.previewRenderingEnabled = enabled; this.renderGeneration += 1; this.previewObserver?.disconnect(); this.previewObserver = null; } /** Refreshes visible/nearby thumbnails when preview rendering is enabled. */ refreshPreviews() { if (!this.previewRenderingEnabled) return; this.renderGeneration += 1; const generation = this.renderGeneration; this.previewObserver?.disconnect(); this.previewObserver = this.createPreviewObserver(generation); const hosts = Array.from( this.options.container.querySelectorAll(".slideshow-sorter__preview") ); for (const host of hosts) { const slide = this.options.deck.slides.find( (candidate) => candidate.id === host.dataset.slideId ); if (!slide) continue; if (this.previewObserver) this.previewObserver.observe(host); else this.renderPreview(host, slide, generation); } } /** Marks appearance changes for a fresh export even while ordinary scene refreshes are paused. */ invalidatePreviewAppearance() { this.options.container.querySelectorAll(".slideshow-sorter__preview").forEach((host) => { host.dataset.previewDirty = "true"; }); this.refreshPreviews(); } /** Re-establishes lazy loading after focus returns, without touching already-populated thumbnails. */ resumePreviewRendering() { if (!this.previewRenderingEnabled) return; this.renderGeneration += 1; const generation = this.renderGeneration; this.previewObserver?.disconnect(); this.previewObserver = this.createPreviewObserver(generation); const hosts = Array.from( this.options.container.querySelectorAll(".slideshow-sorter__preview") ).filter( (host) => !host.firstElementChild || host.dataset.previewDirty === "true" ); for (const host of hosts) { const slide = this.options.deck.slides.find( (candidate) => candidate.id === host.dataset.slideId ); if (!slide) continue; if (this.previewObserver) this.previewObserver.observe(host); else this.renderPreview(host, slide, generation); } } /** * Reconciles deck metadata/ordering into the existing rows when slide identity is unchanged. * Returns false when the sorter must be rebuilt because slides were added, removed, or changed kind. */ syncDeck(nextDeck, refreshChangedPreviews = true) { const deck = this.options.deck; if (deck.kind !== nextDeck.kind || deck.slides.length !== nextDeck.slides.length) return false; const currentById = new Map(deck.slides.map((slide) => [slide.id, slide])); if (nextDeck.slides.some((slide) => { const current = currentById.get(slide.id); return !current || current.kind !== slide.kind; })) { return false; } const previousOrder = deck.slides.map((slide) => slide.id).join("\0"); const nextOrder = nextDeck.slides.map((slide) => slide.id).join("\0"); const previewRefreshIds = /* @__PURE__ */ new Set(); const nextSlides = []; for (const incoming of nextDeck.slides) { const current = currentById.get(incoming.id); if (!current) return false; const rectChanged = current.rect.x1 !== incoming.rect.x1 || current.rect.y1 !== incoming.rect.y1 || current.rect.x2 !== incoming.rect.x2 || current.rect.y2 !== incoming.rect.y2; const animationChanged = getFinalPreviewAnimationFingerprint(current.animationSteps) !== getFinalPreviewAnimationFingerprint(incoming.animationSteps); if (rectChanged || animationChanged) previewRefreshIds.add(current.id); Object.assign(current, { ...incoming, rect: { ...incoming.rect }, animationSteps: incoming.animationSteps.map((step) => structuredClone(step)) }); nextSlides.push(current); } deck.name = nextDeck.name; deck.slides = nextSlides; deck.visibleSlides = nextSlides.filter((slide) => !slide.excluded); deck.hasExplicitFrameOrder = nextDeck.hasExplicitFrameOrder; const rowsById = new Map( Array.from(this.options.container.querySelectorAll(".slideshow-sorter__row")).map( (row) => [row.dataset.slideId ?? "", row] ) ); if (previousOrder !== nextOrder) { for (const slide of deck.slides) { const row = rowsById.get(slide.id); if (row) this.options.container.appendChild(row); } } deck.slides.forEach((slide, index) => { const row = rowsById.get(slide.id); if (!row) return; this.updateRowOrderState(row, slide, index); this.updateRowInclusion(row, slide); this.updateNotesBadge(row, slide); this.updateAnimationBadge(row, slide); }); if (this.expandedNotesSlideId && this.notesTextarea && this.notesTextarea.ownerDocument.activeElement !== this.notesTextarea) { const slide = deck.slides.find((candidate) => candidate.id === this.expandedNotesSlideId); if (slide) this.notesTextarea.value = slide.notes ?? ""; } if (this.selectedSlideId && !currentById.has(this.selectedSlideId)) { this.selectedSlideId = deck.slides[0]?.id ?? null; this.updateSelectedRows(); } if (refreshChangedPreviews) { for (const slideId of previewRefreshIds) this.refreshSlidePreview(slideId); } return true; } /** Captures mounted preview nodes so a rare full sidepanel rebuild can reuse them without blinking. */ capturePreviewContents() { const result = /* @__PURE__ */ new Map(); this.options.container.querySelectorAll(".slideshow-sorter__preview").forEach((host) => { const slideId = host.dataset.slideId; if (slideId && host.childNodes.length > 0) result.set(slideId, Array.from(host.childNodes)); }); return result; } /** Restores previously mounted preview nodes into matching slide hosts after a full UI rebuild. */ restorePreviewContents(contents, refreshRestored = true) { this.options.container.querySelectorAll(".slideshow-sorter__preview").forEach((host) => { const slideId = host.dataset.slideId; const nodes = slideId ? contents.get(slideId) : void 0; if (!nodes || nodes.length === 0) return; host.replaceChildren(...nodes); if (!refreshRestored) this.previewObserver?.unobserve(host); }); } /** Performs one lazy preview pass without enabling background thumbnail refreshes. */ refreshPreviewsOnce() { this.renderGeneration += 1; const generation = this.renderGeneration; const hosts = Array.from( this.options.container.querySelectorAll(".slideshow-sorter__preview") ).filter( (host) => !host.firstElementChild || host.dataset.previewDirty === "true" ); if (hosts.length === 0) return; const observer = this.createPreviewObserver(generation, true, true); if (observer) { for (const host of hosts) observer.observe(host); return; } const selectedHost = hosts.find((host) => host.dataset.slideId === this.selectedSlideId); const fallbackHosts = Array.from( /* @__PURE__ */ new Set([...selectedHost ? [selectedHost] : [], ...hosts.slice(0, 8)]) ); for (const host of fallbackHosts) { const slide = this.options.deck.slides.find( (candidate) => candidate.id === host.dataset.slideId ); if (slide) this.renderPreview(host, slide, generation, true); } } /** Expands or collapses one animation editor without rebuilding unaffected slide rows. */ setAnimationEditingSlideId(slideId) { const previousSlideId = this.options.animationEditingSlideId ?? null; if (previousSlideId === slideId) return; const affected = /* @__PURE__ */ new Set(); if (previousSlideId) affected.add(previousSlideId); if (slideId) { affected.add(slideId); this.selectedSlideId = slideId; if (this.expandedNotesSlideId && this.expandedNotesSlideId !== slideId) { affected.add(this.expandedNotesSlideId); this.expandedNotesSlideId = null; this.notesTextarea = null; } } this.options.animationEditingSlideId = slideId; this.options.container.classList.toggle( "has-expanded-editor", Boolean(this.expandedNotesSlideId || slideId) ); this.updateSelectedRows(); for (const affectedSlideId of affected) this.replaceRowPreservingPreview(affectedSlideId); } /** Applies one include/exclude change in place; preview pixels are deliberately untouched. */ applyInclusion(slideId, excluded) { const slide = this.options.deck.slides.find((candidate) => candidate.id === slideId); if (!slide) return; slide.excluded = excluded; this.options.deck.visibleSlides = this.options.deck.slides.filter((candidate) => !candidate.excluded); if (this.options.deck.kind === "frame") this.options.deck.hasExplicitFrameOrder = true; const row = this.getRow(slideId); if (row) this.updateRowInclusion(row, slide); } /** Applies a persisted reorder by moving existing row nodes rather than recreating them. */ applyReorder(fromIndex, toIndex) { const { deck, container } = this.options; if (fromIndex < 0 || toIndex < 0 || fromIndex >= deck.slides.length || toIndex >= deck.slides.length || fromIndex === toIndex) { return; } const [moved] = deck.slides.splice(fromIndex, 1); if (!moved) return; deck.slides.splice(toIndex, 0, moved); deck.slides.forEach((slide, index) => { if (slide.kind === "frame") slide.order = index; else slide.pairIndex = index; }); deck.visibleSlides = deck.slides.filter((slide) => !slide.excluded); if (deck.kind === "frame") deck.hasExplicitFrameOrder = true; const rowsById = new Map( Array.from(container.querySelectorAll(".slideshow-sorter__row")).map((row) => [ row.dataset.slideId ?? "", row ]) ); const movedRow = rowsById.get(moved.id); const nextSlide = deck.slides[toIndex + 1]; const nextRow = nextSlide ? rowsById.get(nextSlide.id) : void 0; if (movedRow) { if (nextRow) container.insertBefore(movedRow, nextRow); else container.appendChild(movedRow); } deck.slides.forEach((slide, index) => { const row = rowsById.get(slide.id); if (row) this.updateRowOrderState(row, slide, index); }); } /** Updates one slide's animation badge/model and refreshes only that preview when requested. */ updateAnimationSteps(slideId, steps, refreshPreview = true) { const slide = this.options.deck.slides.find((candidate) => candidate.id === slideId); if (!slide) return; const previewChanged = getFinalPreviewAnimationFingerprint(slide.animationSteps) !== getFinalPreviewAnimationFingerprint(steps); Object.assign(slide, { animationSteps: steps.map((step) => structuredClone(step)) }); const row = this.getRow(slideId); if (row) this.updateAnimationBadge(row, slide); if (refreshPreview && previewChanged) this.refreshSlidePreview(slideId); } /** Refreshes only one slide image, retaining the existing bitmap until its replacement is ready. */ refreshSlidePreview(slideId) { const row = this.getRow(slideId); const host = row?.querySelector(".slideshow-sorter__preview") ?? null; const slide = this.options.deck.slides.find((candidate) => candidate.id === slideId); if (!host || !slide) return; if (!this.previewRenderingEnabled) { host.dataset.previewDirty = "true"; return; } this.renderPreview(host, slide, this.renderGeneration); } /** Returns the currently selected stable slide id. */ getSelectedSlideId() { return this.selectedSlideId; } /** Returns the slide whose inline notes editor is expanded, if any. */ getExpandedNotesSlideId() { return this.expandedNotesSlideId; } /** Returns the current vertical sorter position for preservation across deck refreshes. */ getScrollTop() { return this.options.container.scrollTop ?? 0; } /** Restores a vertical sorter position after its rows have been rebuilt. */ restoreScrollTop(scrollTop) { this.options.container.scrollTop = scrollTop; } /** Scrolls the requested slide row into the visible sorter viewport. */ scrollToSlide(slideId, focus = true, block = "center") { const row = Array.from( this.options.container.querySelectorAll(".slideshow-sorter__row") ).find((candidate) => candidate.dataset.slideId === slideId); if (!row) return; if (focus) row.focus({ preventScroll: true }); row.scrollIntoView({ block }); this.ownerWindow.setTimeout(() => { if (row.isConnected) row.scrollIntoView({ block }); }, 50); } /** Returns whether notes currently have keyboard focus. */ isEditingNotes() { return this.notesTextarea?.ownerDocument.activeElement === this.notesTextarea; } /** Mirrors an unambiguous canvas selection without taking keyboard focus from the drawing. */ async selectFromScene(slideId) { if (this.options.animationEditingSlideId || this.isEditingNotes()) return; if (!this.options.deck.slides.some((slide) => slide.id === slideId)) return; if (slideId !== this.selectedSlideId) { await this.flushNotes(); const previousNotesSlideId = this.expandedNotesSlideId; this.selectedSlideId = slideId; this.expandedNotesSlideId = null; this.notesTextarea = null; this.options.container.classList.toggle( "has-expanded-editor", Boolean(this.options.animationEditingSlideId) ); this.updateSelectedRows(); if (previousNotesSlideId) this.replaceRowPreservingPreview(previousNotesSlideId); } this.scrollToSlide(slideId, false); } /** Selects prior stable ids when still present, then renders the sorter. */ render(preferredSlideId = this.selectedSlideId, preferredNotesSlideId = this.expandedNotesSlideId) { this.renderGeneration += 1; const generation = this.renderGeneration; const { container, deck } = this.options; const scrollTop = container.scrollTop; this.previewObserver?.disconnect(); this.previewObserver = this.previewRenderingEnabled ? this.createPreviewObserver(generation) : null; container.replaceChildren(); this.notesTextarea = null; if (deck.slides.length === 0) return; this.selectedSlideId = preferredSlideId && deck.slides.some((slide) => slide.id === preferredSlideId) ? preferredSlideId : deck.slides[0]?.id ?? null; this.expandedNotesSlideId = preferredNotesSlideId && preferredNotesSlideId === this.selectedSlideId && deck.slides.some((slide) => slide.id === preferredNotesSlideId) ? preferredNotesSlideId : null; container.classList.toggle( "has-expanded-editor", Boolean(this.expandedNotesSlideId || this.options.animationEditingSlideId) ); deck.slides.forEach((slide, index) => { const row = this.createRow(slide, index); container.appendChild(row); const previewHost = row.querySelector(".slideshow-sorter__preview"); if (previewHost) { previewHost.dataset.slideId = slide.id; if (this.previewRenderingEnabled) { if (this.previewObserver) this.previewObserver.observe(previewHost); else this.renderPreview(previewHost, slide, generation); } } }); container.scrollTop = scrollTop; } createPreviewObserver(generation, allowWhileSuspended = false, disconnectAfterCallback = false) { const Observer = this.ownerWindow.IntersectionObserver; if (typeof Observer !== "function") return null; return new Observer( (entries, observer) => { for (const entry of entries) { if (!entry.isIntersecting) continue; observer.unobserve(entry.target); const host = entry.target; const slide = this.options.deck.slides.find( (candidate) => candidate.id === host.dataset.slideId ); if (slide) this.renderPreview(host, slide, generation, allowWhileSuspended); } if (disconnectAfterCallback) observer.disconnect(); }, { root: this.options.container, rootMargin: "240px 0px" } ); } renderPreview(previewHost, slide, generation, allowWhileSuspended = false) { if (!this.previewRenderingEnabled && !allowWhileSuspended) return; void this.options.previewService.createPreview(slide, previewHost.ownerDocument, { targetWidth: 480 }).then((preview) => { if (!preview || !this.previewRenderingEnabled && !allowWhileSuspended || generation !== this.renderGeneration || !previewHost.isConnected) return; const current = previewHost.querySelector("img"); delete previewHost.dataset.previewDirty; if (current?.src === preview.src) return; previewHost.replaceChildren(preview); }).catch(() => void 0); } getRow(slideId) { return Array.from( this.options.container.querySelectorAll(".slideshow-sorter__row") ).find((row) => row.dataset.slideId === slideId) ?? null; } getSlideIndex(slideId) { return this.options.deck.slides.findIndex((slide) => slide.id === slideId); } updateSelectedRows() { this.options.container.querySelectorAll(".slideshow-sorter__row").forEach((row) => row.classList.toggle("is-selected", row.dataset.slideId === this.selectedSlideId)); } replaceRowPreservingPreview(slideId) { const row = this.getRow(slideId); const index = this.getSlideIndex(slideId); const slide = this.options.deck.slides[index]; if (!row || !slide || index < 0) return; const existingPreview = row.querySelector(".slideshow-sorter__preview"); if (existingPreview) this.previewObserver?.unobserve(existingPreview); const previewChildren = existingPreview ? Array.from(existingPreview.childNodes) : []; const replacement = this.createRow(slide, index); const replacementPreview = replacement.querySelector(".slideshow-sorter__preview"); if (replacementPreview && previewChildren.length > 0) { replacementPreview.replaceChildren(...previewChildren); } row.replaceWith(replacement); if (replacementPreview && previewChildren.length === 0 && this.previewRenderingEnabled) { if (this.previewObserver) this.previewObserver.observe(replacementPreview); else this.renderPreview(replacementPreview, slide, this.renderGeneration); } } updateRowInclusion(row, slide) { row.classList.toggle("is-excluded", slide.excluded); const button = row.querySelector(".slideshow-sorter__toggle-inclusion"); if (!button) return; const label = this.options.t(slide.excluded ? "includeSlide" : "excludeSlide"); button.innerHTML = slide.excluded ? this.options.icons.eyeOff : this.options.icons.eye; button.setAttribute("aria-label", label); } updateRowOrderState(row, slide, index) { const title = row.querySelector(".slideshow-sorter__title"); if (title) { const titleText = this.options.t("slideNumberAndTitle", { number: index + 1, title: slide.title }); title.textContent = titleText; title.title = titleText; } const up = row.querySelector(".slideshow-sorter__move-up"); const down = row.querySelector(".slideshow-sorter__move-down"); if (up) up.disabled = !this.options.reorderEnabled || index === 0; if (down) { down.disabled = !this.options.reorderEnabled || index === this.options.deck.slides.length - 1; } } updateAnimationBadge(row, slide) { const badges = row.querySelector(".slideshow-sorter__badges"); if (!badges) return; badges.querySelector(".slideshow-sorter__badge--animation")?.remove(); if (slide.animationSteps.length === 0) return; const badge = row.ownerDocument.createElement("span"); const count = slide.animationSteps.length; const label = this.options.t("animationCount", { count }); badge.className = "slideshow-sorter__badge slideshow-sorter__badge--animation"; badge.title = label; badge.setAttribute("aria-label", label); badge.innerHTML = `${this.options.icons.sparkles}${label}`; badges.appendChild(badge); } updateNotesBadge(row, slide) { const badges = row.querySelector(".slideshow-sorter__badges"); if (!badges) return; badges.querySelector(".slideshow-sorter__badge--notes")?.remove(); if (!slide.notes) return; const badge = row.ownerDocument.createElement("span"); const label = this.options.t("notesPresent"); badge.className = "slideshow-sorter__badge slideshow-sorter__badge--notes"; badge.title = label; badge.setAttribute("aria-label", label); badge.innerHTML = `${this.options.icons.notebookPen}${label}`; badges.prepend(badge); } createIconButton(ownerDocument, icon, label, disabled, onClick) { const button = ownerDocument.createElement("button"); button.type = "button"; button.innerHTML = icon; button.setAttribute("aria-label", label); button.disabled = disabled; button.addEventListener("click", (event) => { event.stopPropagation(); onClick(); }); return button; } createRow(slide, index) { const { deck, icons, t, reorderEnabled, ea: ea2 } = this.options; const doc = this.options.container.ownerDocument; const row = doc.createElement("div"); row.className = "slideshow-sorter__row"; if (slide.id === this.selectedSlideId) row.classList.add("is-selected"); if (slide.excluded) row.classList.add("is-excluded"); row.tabIndex = 0; row.dataset.slideId = slide.id; row.setAttribute("role", "listitem"); row.addEventListener("click", () => void this.selectSlide(slide.id)); row.addEventListener("dblclick", () => this.options.callbacks.zoomToSlide(slide)); row.addEventListener("keydown", (event) => this.handleRowKeydown(event, slide)); const top = doc.createElement("div"); top.className = "slideshow-sorter__top"; const titleRow = doc.createElement("div"); titleRow.className = "slideshow-sorter__title-row"; const title = doc.createElement("div"); title.className = "slideshow-sorter__title"; const titleText = t("slideNumberAndTitle", { number: index + 1, title: slide.title }); title.textContent = titleText; title.title = titleText; titleRow.appendChild(title); const editTitleButton = this.createIconButton( doc, icons.edit, t("editSlideName"), false, () => this.options.callbacks.editSlideName?.(slide) ); editTitleButton.className = "slideshow-sorter__title-edit"; editTitleButton.draggable = false; editTitleButton.addEventListener("dragstart", (event) => event.preventDefault()); titleRow.appendChild(editTitleButton); top.appendChild(titleRow); const badges = doc.createElement("div"); badges.className = "slideshow-sorter__badges"; if (slide.notes) { const badge = doc.createElement("span"); const label = t("notesPresent"); badge.className = "slideshow-sorter__badge slideshow-sorter__badge--notes"; badge.title = label; badge.setAttribute("aria-label", label); badge.innerHTML = `${icons.notebookPen}${label}`; badges.appendChild(badge); } if (slide.animationSteps.length > 0) { const badge = doc.createElement("span"); const count = slide.animationSteps.length; const label = t("animationCount", { count }); badge.className = "slideshow-sorter__badge slideshow-sorter__badge--animation"; badge.title = label; badge.setAttribute("aria-label", label); badge.innerHTML = `${icons.sparkles}${label}`; badges.appendChild(badge); } top.appendChild(badges); row.appendChild(top); if (ea2.DEVICE.isDesktop && reorderEnabled) { top.draggable = true; top.classList.add("is-draggable"); top.setAttribute("aria-label", t("dragSlide")); top.addEventListener("dragstart", (event) => { this.selectedSlideId = slide.id; this.options.container.querySelectorAll(".slideshow-sorter__row.is-selected").forEach((selectedRow) => selectedRow.classList.remove("is-selected")); row.classList.add("is-selected"); this.draggedIndex = this.getSlideIndex(slide.id); row.classList.add("is-dragging"); event.dataTransfer?.setData("text/plain", String(index)); if (event.dataTransfer) event.dataTransfer.effectAllowed = "move"; }); top.addEventListener("dragend", () => { this.finishDrag(); }); } const content = doc.createElement("div"); content.className = "slideshow-sorter__content"; row.appendChild(content); const preview = doc.createElement("div"); preview.className = "slideshow-sorter__preview"; preview.dataset.slideId = slide.id; preview.style.backgroundColor = this.options.previewService.getBackgroundColor(); preview.style.aspectRatio = this.options.previewService.getAspectRatio(); content.appendChild(preview); const actions = doc.createElement("div"); actions.className = "slideshow-sorter__actions"; const moveUpButton = this.createIconButton( doc, icons.chevronUp, t("moveSlideUp"), !reorderEnabled || index === 0, () => { const currentIndex = this.getSlideIndex(slide.id); if (currentIndex > 0) void this.options.callbacks.move(currentIndex, currentIndex - 1); } ); moveUpButton.classList.add("slideshow-sorter__move-up"); actions.appendChild(moveUpButton); const moveDownButton = this.createIconButton( doc, icons.chevronDown, t("moveSlideDown"), !reorderEnabled || index === deck.slides.length - 1, () => { const currentIndex = this.getSlideIndex(slide.id); if (currentIndex >= 0 && currentIndex < this.options.deck.slides.length - 1) { void this.options.callbacks.move(currentIndex, currentIndex + 1); } } ); moveDownButton.classList.add("slideshow-sorter__move-down"); actions.appendChild(moveDownButton); const inclusionButton = this.createIconButton( doc, slide.excluded ? icons.eyeOff : icons.eye, slide.excluded ? t("includeSlide") : t("excludeSlide"), false, () => void this.options.callbacks.toggleInclusion(slide, !slide.excluded) ); inclusionButton.classList.add("slideshow-sorter__toggle-inclusion"); actions.appendChild(inclusionButton); const animationExpanded = this.options.animationEditingSlideId === slide.id; const animationButton = this.createIconButton( doc, icons.sparkles, t("editAnimations"), false, () => this.options.callbacks.requestAnimationEditor(slide) ); animationButton.classList.toggle("is-active", animationExpanded); animationButton.setAttribute("aria-expanded", String(animationExpanded)); actions.appendChild(animationButton); if (slide.kind === "path") { actions.appendChild( this.createIconButton(doc, icons.edit, t("editLineSlide"), false, () => { const currentIndex = this.getSlideIndex(slide.id); if (currentIndex >= 0) void this.options.callbacks.editLineSlide(slide, currentIndex); }) ); } const notesExpanded = this.expandedNotesSlideId === slide.id; const notesButton = this.createIconButton( doc, icons.notebookPen, notesExpanded ? t("hidePresenterNotes") : t("showPresenterNotes"), false, () => void this.toggleNotes(slide.id) ); notesButton.classList.toggle("is-active", notesExpanded); notesButton.setAttribute("aria-expanded", String(notesExpanded)); actions.appendChild(notesButton); content.appendChild(actions); if (notesExpanded) this.renderNotesEditor(slide, row); if (this.options.animationEditingSlideId === slide.id) { const animationHost = doc.createElement("div"); animationHost.className = "slideshow-sorter__animation"; row.appendChild(animationHost); this.options.callbacks.mountAnimationEditor?.(slide, animationHost); } return row; } handleRowKeydown(event, slide) { const index = this.getSlideIndex(slide.id); if (index < 0) return; const rows = Array.from( this.options.container.querySelectorAll(".slideshow-sorter__row") ); if (event.altKey && (event.key === "ArrowUp" || event.key === "ArrowDown")) { event.preventDefault(); if (!this.options.reorderEnabled) return; const target = event.key === "ArrowUp" ? index - 1 : index + 1; if (target >= 0 && target < this.options.deck.slides.length) { void this.options.callbacks.move(index, target); } return; } switch (event.key) { case "ArrowUp": case "ArrowDown": { event.preventDefault(); const target = event.key === "ArrowUp" ? index - 1 : index + 1; rows[target]?.focus(); break; } case "Enter": event.preventDefault(); this.options.callbacks.zoomToSlide(slide); break; case " ": case "Spacebar": event.preventDefault(); void this.options.callbacks.toggleInclusion(slide, !slide.excluded); break; case "n": case "N": event.preventDefault(); void this.openNotes(slide.id, true); break; case "a": case "A": event.preventDefault(); this.options.callbacks.requestAnimationEditor(slide); break; } } async selectSlide(slideId) { if (slideId === this.selectedSlideId) return; await this.flushNotes(); const previousNotesSlideId = this.expandedNotesSlideId; this.selectedSlideId = slideId; this.expandedNotesSlideId = null; this.notesTextarea = null; this.options.container.classList.toggle( "has-expanded-editor", Boolean(this.options.animationEditingSlideId) ); this.updateSelectedRows(); if (previousNotesSlideId) this.replaceRowPreservingPreview(previousNotesSlideId); } async toggleNotes(slideId) { if (this.expandedNotesSlideId === slideId) { await this.flushNotes(); this.expandedNotesSlideId = null; this.notesTextarea = null; this.options.container.classList.toggle( "has-expanded-editor", Boolean(this.options.animationEditingSlideId) ); this.replaceRowPreservingPreview(slideId); return; } await this.openNotes(slideId, false); } async openNotes(slideId, focusNotes) { await this.flushNotes(); const previousNotesSlideId = this.expandedNotesSlideId; this.selectedSlideId = slideId; this.expandedNotesSlideId = slideId; this.notesTextarea = null; this.options.container.classList.add("has-expanded-editor"); this.updateSelectedRows(); if (previousNotesSlideId && previousNotesSlideId !== slideId) { this.replaceRowPreservingPreview(previousNotesSlideId); } this.replaceRowPreservingPreview(slideId); this.scrollToSlide(slideId, false, "start"); if (focusNotes) this.notesTextarea?.focus(); } renderNotesEditor(slide, row) { const doc = this.options.container.ownerDocument; const notes = doc.createElement("div"); notes.className = "slideshow-notes"; notes.addEventListener("click", (event) => event.stopPropagation()); const heading = doc.createElement("strong"); heading.textContent = this.options.t("notesHeading"); notes.appendChild(heading); const textarea = doc.createElement("textarea"); textarea.placeholder = this.options.t("notesPlaceholder"); textarea.value = slide.notes ?? ""; textarea.addEventListener("click", (event) => event.stopPropagation()); textarea.addEventListener("keydown", (event) => this.handleNotesKeydown(event)); textarea.addEventListener("input", () => this.scheduleNotesSave()); textarea.addEventListener("blur", () => { void this.flushNotes().finally(() => this.options.callbacks.notesBlurred()); }); notes.appendChild(textarea); const hint = doc.createElement("div"); hint.className = "slideshow-notes__hint"; hint.textContent = this.options.t("notesHint"); notes.appendChild(hint); row.appendChild(notes); this.notesTextarea = textarea; } handleNotesKeydown(event) { event.stopPropagation(); if (!event.defaultPrevented || event.key.length !== 1 || event.metaKey || event.ctrlKey || event.altKey) { return; } const textarea = event.currentTarget; if (!textarea) return; const start = textarea.selectionStart ?? textarea.value.length; const end = textarea.selectionEnd ?? start; textarea.setRangeText(event.key, start, end, "end"); this.scheduleNotesSave(); } handleContainerDragOver = (event) => { if (this.draggedIndex === null) return; event.preventDefault(); if (event.dataTransfer) event.dataTransfer.dropEffect = "move"; this.dragPointerX = event.clientX; this.dragPointerY = event.clientY; this.updateDropTarget(event.clientX, event.clientY); this.updateAutoScroll(event.clientY); }; handleContainerDragLeave = (event) => { const relatedTarget = event.relatedTarget; if (relatedTarget && this.options.container.contains(relatedTarget)) return; this.clearDropIndicator(); this.stopAutoScroll(); }; handleContainerDrop = (event) => { if (this.draggedIndex === null) return; event.preventDefault(); const fromIndex = this.draggedIndex; const insertionIndex = this.dropTargetIndex; this.finishDrag(); if (insertionIndex === null) return; const target = getDropMoveTarget(fromIndex, insertionIndex, this.options.deck.slides.length); if (target !== null) void this.options.callbacks.move(fromIndex, target); }; updateDropTarget(pointerX, pointerY) { const rows = Array.from( this.options.container.querySelectorAll(".slideshow-sorter__row") ); const rowRects = rows.map((row) => row.getBoundingClientRect()); const insertionIndex = getDropInsertionIndexFromRects(rowRects, pointerX, pointerY); const placement = getDropIndicatorPlacement(rowRects, insertionIndex); const indicatorKey = [ insertionIndex, placement.beforeIndex ?? "none", placement.afterIndex ?? "none", placement.singleColumn ? 1 : 0 ].join(":"); this.options.container.classList.toggle("is-single-column", placement.singleColumn); if (indicatorKey === this.dropIndicatorKey) return; this.clearDropIndicator(); this.dropTargetIndex = insertionIndex; this.dropIndicatorKey = indicatorKey; if (placement.beforeIndex !== null) { rows[placement.beforeIndex]?.classList.add("is-drop-before"); } if (placement.afterIndex !== null) { rows[placement.afterIndex]?.classList.add("is-drop-after"); } } clearDropIndicator() { const rows = this.options.container.querySelectorAll?.(".is-drop-before, .is-drop-after") ?? []; rows.forEach((row) => row.classList.remove("is-drop-before", "is-drop-after")); this.dropTargetIndex = null; this.dropIndicatorKey = null; } updateAutoScroll(pointerY) { const rect = this.options.container.getBoundingClientRect(); this.autoScrollVelocity = getDragAutoScrollVelocity(pointerY, rect.top, rect.bottom); if (this.autoScrollVelocity === 0) { this.stopAutoScroll(); return; } if (!this.autoScrollFrame) { this.autoScrollFrame = this.ownerWindow.requestAnimationFrame(this.runAutoScroll); } } runAutoScroll = () => { this.autoScrollFrame = 0; if (this.draggedIndex === null || this.autoScrollVelocity === 0) return; const previousScrollTop = this.options.container.scrollTop; this.options.container.scrollTop += this.autoScrollVelocity; if (this.options.container.scrollTop === previousScrollTop) { this.autoScrollVelocity = 0; return; } if (this.dragPointerX !== null && this.dragPointerY !== null) { this.updateDropTarget(this.dragPointerX, this.dragPointerY); } this.autoScrollFrame = this.ownerWindow.requestAnimationFrame(this.runAutoScroll); }; stopAutoScroll() { if (this.autoScrollFrame) this.ownerWindow.cancelAnimationFrame(this.autoScrollFrame); this.autoScrollFrame = 0; this.autoScrollVelocity = 0; } finishDrag() { this.stopAutoScroll(); this.clearDropIndicator(); const rows = this.options.container.querySelectorAll?.( ".slideshow-sorter__row.is-dragging" ) ?? []; rows.forEach((row) => row.classList.remove("is-dragging")); this.draggedIndex = null; this.dragPointerX = null; this.dragPointerY = null; } scheduleNotesSave() { if (!this.notesTextarea || !this.expandedNotesSlideId) return; if (this.notesTimer) this.ownerWindow.clearTimeout(this.notesTimer); this.notesTimer = this.ownerWindow.setTimeout(() => { this.notesTimer = 0; void this.flushNotes(); }, 500); } /** Flushes a pending notes edit before slide changes, panel close, or presentation start. */ async flushNotes() { if (this.notesTimer) { this.ownerWindow.clearTimeout(this.notesTimer); this.notesTimer = 0; } const slideId = this.expandedNotesSlideId; const current = this.notesTextarea?.value; if (!slideId || current === void 0) return; const previousSave = this.notesSaveInFlight; const save = (async () => { await previousSave?.catch(() => void 0); const slide = this.options.deck.slides.find((candidate) => candidate.id === slideId); if (!slide || current === (slide.notes ?? "")) return; await this.options.callbacks.saveNotes(slide, current); if (current.trim().length === 0) delete slide.notes; else slide.notes = current; const row = this.getRow(slideId); if (row) this.updateNotesBadge(row, slide); })(); this.notesSaveInFlight = save; try { await save; } finally { if (this.notesSaveInFlight === save) this.notesSaveInFlight = null; } } /** Cancels timers and invalidates asynchronous preview insertions. */ destroy() { this.renderGeneration += 1; this.previewObserver?.disconnect(); this.previewObserver = null; if (this.notesTimer) this.ownerWindow.clearTimeout(this.notesTimer); this.notesTimer = 0; this.notesTextarea = null; this.finishDrag(); this.options.container.removeEventListener?.("dragover", this.handleContainerDragOver); this.options.container.removeEventListener?.("dragleave", this.handleContainerDragLeave); this.options.container.removeEventListener?.("drop", this.handleContainerDrop); } }; // src/scripts/slideshow/slideshowQuickGuide.ts var SLIDESHOW_VIDEO_URL = "https://youtu.be/7DDY8rRDzdU"; var SLIDESHOW_VIDEO_THUMBNAIL_URL = "https://img.youtube.com/vi/7DDY8rRDzdU/maxresdefault.jpg"; var SLIDESHOW_COURSE_THUMBNAIL_URL = "https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/logo-slideshow-v4.png"; var SLIDESHOW_COURSE_URL = "https://community.sketch-your-mind.com/slideshow"; function openSlideshowQuickGuideModal(ea2, t) { const modal = new ea2.obsidian.Modal(app); modal.titleEl.setText(t("quickGuideTitle")); modal.contentEl.createEl("h3", { text: t("quickGuideShortcutsTitle") }); const shortcuts = modal.contentEl.createEl("ul"); for (const key of [ "quickGuideClick", "quickGuideWindowed", "quickGuideEditor", "quickGuideResumeFullscreen", "quickGuideResumeWindowed" ]) { shortcuts.createEl("li", { text: t(key) }); } modal.contentEl.createEl("h3", { text: t("quickGuideAuthoringTitle") }); for (const key of [ "quickGuideFrameSlides", "quickGuideLineSlides", "quickGuideMarkerFrames", "quickGuideAnimations", "quickGuideNotes" ]) { modal.contentEl.createEl("p", { text: t(key) }); } modal.contentEl.createEl("h3", { text: t("quickGuideLearnMoreTitle") }); const videoLink = modal.contentEl.createEl("a"); videoLink.href = SLIDESHOW_VIDEO_URL; videoLink.target = "_blank"; videoLink.rel = "noopener noreferrer"; videoLink.style.display = "inline-flex"; videoLink.style.alignItems = "center"; videoLink.style.gap = "10px"; videoLink.style.marginBottom = "8px"; const videoThumbnail = videoLink.createEl("img"); videoThumbnail.src = SLIDESHOW_VIDEO_THUMBNAIL_URL; videoThumbnail.alt = t("quickGuideVideoThumbnailAlt"); videoThumbnail.width = 112; videoThumbnail.style.width = "112px"; videoThumbnail.style.height = "63px"; videoThumbnail.style.objectFit = "cover"; videoThumbnail.style.borderRadius = "6px"; videoThumbnail.style.flex = "0 0 auto"; videoLink.createSpan({ text: t("quickGuideVideo") }); modal.contentEl.createEl("br"); const courseLink = modal.contentEl.createEl("a"); courseLink.href = SLIDESHOW_COURSE_URL; courseLink.target = "_blank"; courseLink.rel = "noopener noreferrer"; courseLink.style.display = "inline-flex"; courseLink.style.alignItems = "center"; courseLink.style.gap = "10px"; const courseThumbnail = courseLink.createEl("img"); courseThumbnail.src = SLIDESHOW_COURSE_THUMBNAIL_URL; courseThumbnail.alt = t("quickGuideCourse"); courseThumbnail.width = 112; courseThumbnail.style.width = "112px"; courseThumbnail.style.objectFit = "cover"; courseThumbnail.style.borderRadius = "6px"; courseThumbnail.style.flex = "0 0 auto"; courseLink.createSpan({ text: t("quickGuideCourse") }); modal.open(); } // src/scripts/slideshow/slideshowRuntime.ts var RUNTIME_PROPERTY = "__excalidrawAutomateSlideshowRuntimeV1"; function getSlideshowRuntime() { const host = app; host[RUNTIME_PROPERTY] ??= { contexts: /* @__PURE__ */ new WeakMap(), progress: /* @__PURE__ */ new WeakMap(), progressType: /* @__PURE__ */ new WeakMap(), progressSource: /* @__PURE__ */ new WeakMap(), progressBySource: /* @__PURE__ */ new WeakMap(), presentations: /* @__PURE__ */ new WeakMap(), sidepanel: null }; const runtime = host[RUNTIME_PROPERTY]; if (!("progressType" in runtime) || !runtime.progressType) { Object.assign(runtime, { progressType: /* @__PURE__ */ new WeakMap() }); } if (!("progressSource" in runtime) || !runtime.progressSource) { Object.assign(runtime, { progressSource: /* @__PURE__ */ new WeakMap() }); } if (!("progressBySource" in runtime) || !runtime.progressBySource) { Object.assign(runtime, { progressBySource: /* @__PURE__ */ new WeakMap() }); } return runtime; } function registerSlideshowViewContext(context) { const runtime = getSlideshowRuntime(); const wasKnown = runtime.contexts.has(context.view); runtime.contexts.set(context.view, context); return wasKnown; } function getSlideshowViewContext(view) { return getSlideshowRuntime().contexts.get(view); } function setSlideshowProgress(view, slide, presentationSource) { const runtime = getSlideshowRuntime(); runtime.progress.set(view, slide); if (presentationSource) { const type = presentationSource === "frame" ? "frame" : "line"; runtime.progressType.set(view, type); if (presentationSource === "frame" || presentationSource.startsWith("line:")) { const source = presentationSource; runtime.progressSource.set(view, source); let bySource = runtime.progressBySource.get(view); if (!bySource) { bySource = /* @__PURE__ */ new Map(); runtime.progressBySource.set(view, bySource); } bySource.set(source, slide); } } } function getSlideshowProgress(view) { return getSlideshowRuntime().progress.get(view); } function getSlideshowProgressType(view) { return getSlideshowRuntime().progressType.get(view); } function getSlideshowProgressSource(view) { return getSlideshowRuntime().progressSource.get(view); } function getSlideshowProgressForSource(view, source) { const runtime = getSlideshowRuntime(); const exact = runtime.progressBySource.get(view)?.get(source); if (exact !== void 0) return exact; return runtime.progressSource.get(view) === source ? runtime.progress.get(view) : void 0; } // src/scripts/slideshow/SlideshowSidepanel.ts function getDeckFingerprint(resolved) { if (!resolved) return "none"; return JSON.stringify({ kind: resolved.deck.kind, name: resolved.deck.name, pathId: resolved.pathElement?.id ?? null, slides: resolved.deck.slides.map((slide) => ({ id: slide.id, title: slide.title, rect: slide.rect, notes: slide.notes ?? null, excluded: slide.excluded, animationSteps: slide.animationSteps })) }); } function getSidepanelChromeFingerprint(choices, presentationSourceKey) { return JSON.stringify({ sources: [ ...choices.frame ? ["frame"] : [], ...choices.lines.map((line) => line.key) ], presentationSourceKey }); } function getPreviewFingerprint(appState, sceneVisualFingerprint, elements, resolved) { const previewSceneFingerprint = resolved?.pathElement ? getSceneVisualFingerprint( elements.filter((element) => element.id !== resolved.pathElement?.id) ) : sceneVisualFingerprint; return `${appState.theme}|${appState.viewBackgroundColor}|${previewSceneFingerprint}`; } function getSidepanelFingerprint(ea2, choices, presentationSourceKey, appState, sceneVisualFingerprint = getSceneVisualFingerprint(ea2.getViewElements())) { const lineFingerprint = choices.lines.map((line) => `${line.key}:${line.name ?? ""}:${getDeckFingerprint(line.resolved)}`).join("|"); const convertibleId = getConvertibleSelectedLine(ea2)?.id ?? "none"; const declarableFrameId = getDeclarableSelectedFrame(ea2)?.id ?? "none"; return `${presentationSourceKey ?? "none"}|${getDeckFingerprint(choices.frame)}|${lineFingerprint}|candidate=${convertibleId}|frameCandidate=${declarableFrameId}|${appState.theme}|${appState.viewBackgroundColor}|${sceneVisualFingerprint}`; } function chooseSidepanelPresentationSourceKey(choices, storedSource, preferredType) { if (storedSource && hasPresentationSource(choices, storedSource)) return storedSource; if (preferredType === "frame" && choices.frame) return "frame"; if (preferredType === "line" && choices.lines.length > 0) return choices.lines[0]?.key ?? null; return choices.defaultSourceKey; } function getConvertibleSelectedLine(ea2) { const selected = ea2.getViewSelectedElement(); if (!isLinearPathElement(selected) || Math.floor(selected.points.length / 2) <= 0) return null; return getLinePresentationSourceKey(selected) ? null : selected; } function getDeclarableSelectedFrame(ea2) { const selected = ea2.getViewSelectedElement(); if (!isFrameElement(selected)) return null; const alreadyDeclared = ea2.getViewElements().some((element) => isFrameElement(element) && hasFrameSlideshowDeclaration(element.customData)); return alreadyDeclared ? null : selected; } function getLineSourceByKey(choices, sourceKey) { if (!sourceKey || sourceKey === "frame") return null; return choices.lines.find((line) => line.key === sourceKey) ?? null; } function getSorterSceneSelectionSignature(appState) { const selectedElementIds = Object.keys(appState.selectedElementIds).filter((id) => appState.selectedElementIds[id]).sort(); const editor = appState.selectedLinearElement; return JSON.stringify({ selectedElementIds, selectedLinearElement: editor ? { elementId: editor.elementId, isEditing: editor.isEditing, selectedPointsIndices: editor.selectedPointsIndices ? [...editor.selectedPointsIndices].sort((a, b) => a - b) : null } : null }); } function getSceneSelectedSlideId(resolved, appState) { if (!resolved) return null; if (resolved.deck.kind === "frame") { const selectedSlides = resolved.deck.slides.filter( (slide) => slide.kind === "frame" && appState.selectedElementIds[slide.frameId] ); return selectedSlides.length === 1 ? selectedSlides[0]?.id ?? null : null; } const editor = appState.selectedLinearElement; if (!editor?.isEditing || editor.elementId !== resolved.pathElement?.id) return null; const pointIndices = editor.selectedPointsIndices; if (!pointIndices || pointIndices.length === 0) return null; const pairIndices = new Set(pointIndices.map((pointIndex) => Math.floor(pointIndex / 2))); if (pairIndices.size !== 1) return null; const pairIndex = pairIndices.values().next().value; return pairIndex === void 0 ? null : resolved.deck.slides[pairIndex]?.id ?? null; } function getResumeSlideForPresentation(progress, progressType, presentationType, visibleSlideCount, progressSource, presentationSource) { if (progress === void 0 || presentationType === null || visibleSlideCount <= 0) return null; if (progressType && progressType !== presentationType) return null; if (progressSource && presentationSource && progressSource !== presentationSource) return null; return Math.min(Math.max(progress, 0), visibleSlideCount - 1); } function resolveDeviceLaunchModes(isMobile, windowMode, notesMode, hasSecondaryDisplay) { return { startFullscreen: isMobile || windowMode === "fullscreen", openPresenterView: !isMobile && notesMode === "presenter" && hasSecondaryDisplay }; } function styleModalActions(actions) { actions.style.display = "flex"; actions.style.justifyContent = "flex-end"; actions.style.gap = "0.5rem"; actions.style.flexWrap = "wrap"; } function bindEnterToSave(input, saveButton) { input.addEventListener("keydown", (event) => { if (event.key !== "Enter" || event.isComposing) return; event.preventDefault(); saveButton.click(); }); } function addCheckboxOption(container, label) { const doc = container.ownerDocument; const row = doc.createElement("label"); row.style.display = "flex"; row.style.alignItems = "center"; row.style.gap = "0.5rem"; row.style.marginBottom = "0.5rem"; const input = doc.createElement("input"); input.type = "checkbox"; const text = doc.createElement("span"); text.textContent = label; row.append(input, text); container.appendChild(row); return input; } function addSelectOption(container, label, options) { const doc = container.ownerDocument; const row = doc.createElement("label"); row.style.display = "flex"; row.style.alignItems = "center"; row.style.justifyContent = "space-between"; row.style.gap = "1rem"; row.style.marginBottom = "0.5rem"; const text = doc.createElement("span"); text.textContent = label; const select = doc.createElement("select"); for (const [value, optionText] of options) { const option = doc.createElement("option"); option.value = value; option.textContent = optionText; select.appendChild(option); } row.append(text, select); container.appendChild(row); return select; } var SlideshowSidepanel = class { constructor(options) { this.options = options; this.ownerWindow = options.tab.contentEl.ownerDocument.defaultView ?? window; this.boundView = null; const launchPreferences = loadSlideshowLaunchPreferences(options.ea); this.startMode = launchPreferences.startMode; this.windowMode = launchPreferences.windowMode; this.notesMode = launchPreferences.notesMode; this.preferredPresentationType = launchPreferences.presentationType; this.sorterThumbnailMaxWidth = loadSorterThumbnailMaxWidth(options.ea); this.deviceKey = getSlideshowDeviceKey(this.ownerWindow); } options; sorter = null; previewService = null; resolved = null; choices = { frame: null, lines: [], line: null, defaultSourceKey: null, defaultType: null }; presentationSourceKey = null; presentationSourceByDrawing = /* @__PURE__ */ new Map(); refreshTimer = 0; ownerWindow; lastFingerprint = ""; lastPreviewFingerprint = ""; lastPreviewAppearanceKey = ""; lastChromeFingerprint = ""; pendingRefresh = false; sorterMutationDepth = 0; sceneSelectionSignature = null; pendingSceneSlideId = null; closed = false; bindGeneration = 0; activeLeafChangeRef = null; boundView; boundDrawingFile = null; requestedSlideId = null; animationEditor = null; animationEditingSlideId = null; startMode = "beginning"; windowMode = "fullscreen"; notesMode = "slides"; launchSettingsExpanded = false; preferredPresentationType; displays = []; presentationDisplayId = null; presenterDisplayId = null; displayConfigurationKey = null; deviceKey; settingsWriteQueue = Promise.resolve(); removeDisplayChangeListener = null; displayRefreshTimer = 0; previewOnceScheduled = false; sorterThumbnailMaxWidth; /** Returns the drawing currently edited by this sidepanel. */ getBoundView() { return this.boundView; } isSidepanelFocused() { const sidepanelLeaf = this.options.ea.getSidepanelLeaf(); const { tab } = this.options; const activeElement = tab.contentEl.ownerDocument.activeElement; const hasDomFocus = Boolean(activeElement && tab.contentEl.contains?.(activeElement)); return Boolean( sidepanelLeaf && (app.workspace.activeLeaf === sidepanelLeaf || hasDomFocus) && tab.isVisible() && tab.isActiveTab() ); } syncPreviewFocusState() { const focused = this.isSidepanelFocused(); this.sorter?.setPreviewRenderingEnabled(focused); if (!focused) { this.previewService?.cancelPending(); return; } if (this.pendingRefresh) { void this.refresh(); return; } this.sorter?.resumePreviewRendering(); } /** Loads the currently visible thumbnails once without enabling background refreshes. */ refreshPreviewsOnce() { if (this.closed || this.previewOnceScheduled) return; this.previewOnceScheduled = true; const run = () => { this.previewOnceScheduled = false; if (!this.closed) this.sorter?.refreshPreviewsOnce(); }; if (typeof this.ownerWindow.requestAnimationFrame === "function") { this.ownerWindow.requestAnimationFrame(() => run()); } else { this.ownerWindow.setTimeout(run, 0); } } /** Focuses and reveals the slide requested by an element action after the tab is visible. */ revealRequestedSlide() { const slideId = this.requestedSlideId; if (!slideId) return; this.sorter?.scrollToSlide(slideId); this.ownerWindow.setTimeout(() => { if (this.requestedSlideId === slideId) this.requestedSlideId = null; }, 500); } /** Rebinds the panel to a concrete view and optionally selects its deck type. */ async activate(view, preferredSource, preferredSlideId) { if (preferredSource) { const sourceKey = preferredSource === "line" ? null : preferredSource; if (sourceKey) this.presentationSourceByDrawing.set(view.file.path, sourceKey); else this.preferredPresentationType = "line"; } if (preferredSlideId) this.requestedSlideId = preferredSlideId; const drawingChanged = view === this.boundView && view.file !== this.boundDrawingFile; if (view === this.boundView && !drawingChanged) { this.options.ea.setView(view); await this.refresh(); return; } const generation = ++this.bindGeneration; await this.applyViewBinding(view, generation, drawingChanged); } /** Installs lifecycle hooks, workspace focus tracking, and scene-change tracking. */ initialize() { const { ea: ea2, tab } = this.options; tab.onOpen = () => { void this.refresh(true).then(() => this.refreshPreviewsOnce()); }; tab.onFocus = (view) => { this.bindView(view); this.ownerWindow.setTimeout(() => this.syncPreviewFocusState(), 0); }; tab.onWindowMigrated = (win) => { if (this.displayRefreshTimer) this.ownerWindow.clearTimeout(this.displayRefreshTimer); this.displayRefreshTimer = 0; this.removeDisplayChangeListener?.(); this.removeDisplayChangeListener = null; this.ownerWindow = win; this.bindDisplayChangeListener(); this.sorter?.onWindowMigrated(win); void this.animationEditor?.destroy(); this.animationEditor = null; this.animationEditingSlideId = null; this.previewService?.clear(); this.lastFingerprint = ""; this.lastPreviewFingerprint = ""; void this.refresh(true); }; tab.onExcalidrawViewClosed = () => this.bindView(null); tab.onClose = () => { this.closed = true; if (this.refreshTimer) this.ownerWindow.clearTimeout(this.refreshTimer); this.refreshTimer = 0; if (this.displayRefreshTimer) this.ownerWindow.clearTimeout(this.displayRefreshTimer); this.displayRefreshTimer = 0; this.removeDisplayChangeListener?.(); this.removeDisplayChangeListener = null; const sorter = this.sorter; this.sorter = null; void sorter?.flushNotes().finally(() => sorter.destroy()); void this.animationEditor?.destroy(); this.animationEditor = null; this.animationEditingSlideId = null; this.previewService?.clear(); this.previewService = null; ea2.onSceneChangeHook = null; if (this.activeLeafChangeRef) { app.workspace.offref(this.activeLeafChangeRef); this.activeLeafChangeRef = null; } this.options.onClosed(); }; this.activeLeafChangeRef = app.workspace.on( "active-leaf-change", (leaf) => { if (this.closed) return; if (leaf === ea2.getSidepanelLeaf()) { this.syncPreviewFocusState(); return; } this.syncPreviewFocusState(); if (leaf && ea2.isExcalidrawView(leaf.view)) { this.bindView(leaf.view); return; } if (leaf?.view.getViewType?.() === "empty") return; this.bindView(null); } ); ea2.onSceneChangeHook = { appStateKeys: [ "selectedElementIds", "selectedGroupIds", "selectedLinearElement", "viewBackgroundColor", "theme" ], trackElements: true, triggerWhenInvisible: false, callback: (elements, appState, _files, view) => { if (!this.boundView || view !== this.boundView) return; if (view.file !== this.boundDrawingFile) { this.bindView(view); return; } const appearanceKey = getPreviewAppearance(appState).key; if (appearanceKey !== this.lastPreviewAppearanceKey) { this.lastPreviewAppearanceKey = appearanceKey; this.sorter?.invalidatePreviewAppearance(); this.refreshPreviewsOnce(); } if (this.sorterMutationDepth > 0) { this.pendingRefresh = true; return; } if (this.sorter?.isEditingNotes()) { this.pendingRefresh = true; return; } if (this.animationEditor) { this.animationEditor.handleSceneChange(elements, appState); return; } const selectionSignature = getSorterSceneSelectionSignature(appState); if (selectionSignature !== this.sceneSelectionSignature) { this.sceneSelectionSignature = selectionSignature; const selectedSlideId = getSceneSelectedSlideId(this.resolved, appState); this.pendingSceneSlideId = selectedSlideId; if (selectedSlideId) void this.sorter?.selectFromScene(selectedSlideId); } this.scheduleRefresh(); } }; this.bindDisplayChangeListener(); if (this.boundView) void this.refresh(true); else this.renderUnavailable(); } bindView(view) { if (this.closed) return; const drawingChanged = view !== null && view === this.boundView && view.file !== this.boundDrawingFile; if (view === this.boundView && !drawingChanged) { if (view) void this.refresh(); else this.renderUnavailable(); return; } const generation = ++this.bindGeneration; void this.applyViewBinding(view, generation, drawingChanged); } async applyViewBinding(view, generation, discardUnsaved = false) { const previousSorter = this.sorter; const previousEditor = this.animationEditor; if (discardUnsaved) { previousSorter?.destroy(); if (this.sorter === previousSorter) this.sorter = null; this.animationEditor = null; this.animationEditingSlideId = null; await previousEditor?.destroy(); } else { await previousSorter?.flushNotes(); if (this.closed || generation !== this.bindGeneration) return; previousSorter?.destroy(); if (this.sorter === previousSorter) this.sorter = null; await previousEditor?.destroy(); if (this.animationEditor === previousEditor) this.animationEditor = null; this.animationEditingSlideId = null; } if (this.closed || generation !== this.bindGeneration) return; this.previewService?.clear(); this.previewService = null; this.resolved = null; this.choices = { frame: null, lines: [], line: null, defaultSourceKey: null, defaultType: null }; this.presentationSourceKey = null; this.sceneSelectionSignature = null; this.pendingSceneSlideId = null; this.lastFingerprint = ""; this.lastPreviewFingerprint = ""; this.lastChromeFingerprint = ""; this.boundView = view; this.boundDrawingFile = view?.file ?? null; this.options.ea.setView(view); this.options.ea.clear(); if (!view) { this.renderUnavailable(); return; } await this.refresh(true); } scheduleRefresh() { if (this.closed) return; if (this.sorter?.isEditingNotes()) { this.pendingRefresh = true; return; } if (this.refreshTimer) this.ownerWindow.clearTimeout(this.refreshTimer); this.refreshTimer = this.ownerWindow.setTimeout(() => { this.refreshTimer = 0; void this.refresh(); }, 180); } appendSupportLine(root, doc) { const support = doc.createElement("div"); support.className = "slideshow-sidepanel__support"; const prefix = doc.createElement("span"); prefix.textContent = `${this.options.t("supportPrompt")} `; support.appendChild(prefix); const link = doc.createElement("a"); link.href = "https://ko-fi.com/zsolt"; link.target = "_blank"; link.rel = "noopener noreferrer"; link.textContent = this.options.t("supportLink"); support.appendChild(link); root.appendChild(support); } appendSettingsButton(header, doc) { const { ea: ea2, icons, t } = this.options; const settingsButton = doc.createElement("button"); settingsButton.type = "button"; settingsButton.className = "slideshow-sidepanel__icon-button"; settingsButton.setAttribute("aria-label", t("settingsTitle")); settingsButton.innerHTML = icons.settings; settingsButton.addEventListener("click", () => { void (async () => { await this.sorter?.flushNotes(); openSlideshowSettingsModal(ea2, this.options.config, t, () => { this.previewService?.clear(); this.lastFingerprint = ""; this.lastPreviewFingerprint = ""; void this.refresh(true); }); })(); }); header.appendChild(settingsButton); } /** Builds the selection/source-specific header action without rebuilding the sidepanel. */ createHeaderContextAction(doc) { const { ea: ea2, icons, t } = this.options; const button = doc.createElement("button"); button.type = "button"; button.className = "slideshow-sidepanel__icon-button slideshow-sidepanel__source-action"; if (getDeclarableSelectedFrame(ea2)) { button.setAttribute("aria-label", t("declareFrameSlideshow")); button.innerHTML = icons.plus; button.addEventListener("click", () => void this.declareSelectedFrameSlideshow()); return button; } if (getConvertibleSelectedLine(ea2)) { button.setAttribute("aria-label", t("createLinePresentation")); button.innerHTML = icons.plus; button.addEventListener("click", () => void this.convertSelectedLineToPresentation()); return button; } if (this.presentationSourceKey !== "frame" && this.resolved?.pathElement) { const pathHidden = isPresentationPathHidden(this.resolved.pathElement); button.setAttribute( "aria-label", t(pathHidden ? "showPresentationPath" : "hidePresentationPath") ); button.innerHTML = pathHidden ? icons.eyeOff : icons.eye; button.addEventListener("click", () => void this.togglePresentationPathVisibility()); return button; } return null; } /** Reconciles only the selection/source-specific header action. */ updateHeaderContextAction() { const header = this.options.tab.contentEl.querySelector(".slideshow-sidepanel__header"); if (!header) return; const current = header.querySelector(".slideshow-sidepanel__source-action"); const next = this.createHeaderContextAction(header.ownerDocument); if (current && next) { current.replaceWith(next); return; } if (current) { current.remove(); return; } if (!next) return; const anchor = header.querySelector(".slideshow-sidepanel__info-button"); header.insertBefore(next, anchor); } appendInfoButton(header, doc) { const { ea: ea2, icons, t } = this.options; const infoButton = doc.createElement("button"); infoButton.type = "button"; infoButton.className = "slideshow-sidepanel__icon-button slideshow-sidepanel__info-button"; infoButton.setAttribute("aria-label", t("quickGuideButton")); infoButton.innerHTML = icons.info; infoButton.addEventListener("click", () => openSlideshowQuickGuideModal(ea2, t)); header.appendChild(infoButton); } bindDisplayChangeListener() { this.removeDisplayChangeListener?.(); this.removeDisplayChangeListener = onDisplayConfigurationChanged(this.ownerWindow, () => { if (this.closed) return; if (this.displayRefreshTimer) this.ownerWindow.clearTimeout(this.displayRefreshTimer); this.displayRefreshTimer = this.ownerWindow.setTimeout(() => { this.displayRefreshTimer = 0; this.lastFingerprint = ""; void this.refresh(true); }, 120); }); } renderUnavailable() { const { tab, t } = this.options; tab.setDisabled(false); tab.contentEl.replaceChildren(); const style = tab.contentEl.ownerDocument.createElement("style"); style.textContent = SLIDESHOW_SIDEPANEL_STYLES; tab.contentEl.appendChild(style); const root = tab.contentEl.ownerDocument.createElement("div"); root.className = "slideshow-sidepanel"; tab.contentEl.appendChild(root); const doc = tab.contentEl.ownerDocument; this.appendSupportLine(root, doc); const header = doc.createElement("div"); header.className = "slideshow-sidepanel__header"; root.appendChild(header); this.appendInfoButton(header, doc); this.appendSettingsButton(header, doc); const empty = tab.contentEl.ownerDocument.createElement("div"); empty.className = "slideshow-empty"; empty.textContent = t("noEligibleSlides"); root.appendChild(empty); } /** Refreshes deck data and previews only when the debounced scene fingerprint changes. */ async refresh(force = false) { const { ea: ea2 } = this.options; const view = this.boundView; if (this.closed || !view) { this.renderUnavailable(); return; } if (view.file !== this.boundDrawingFile) { const generation = ++this.bindGeneration; await this.applyViewBinding(view, generation, true); return; } if (this.sorter?.isEditingNotes()) { this.pendingRefresh = true; return; } const previewFocused = this.isSidepanelFocused(); this.sorter?.setPreviewRenderingEnabled(previewFocused); if (!force && !previewFocused && !this.animationEditor) { this.pendingRefresh = true; return; } if (ea2.targetView !== view) ea2.setView(view); const api = ea2.getExcalidrawAPI(); if (!api) { this.renderUnavailable(); return; } const choices = resolveSlideDeckChoices(ea2); const drawingKey = view.file.path; const storedSource = this.presentationSourceByDrawing.get(drawingKey) ?? loadSlideshowPresentationSource(ea2, drawingKey); const presentationSourceKey = chooseSidepanelPresentationSourceKey( choices, storedSource, this.preferredPresentationType ); if (presentationSourceKey) this.presentationSourceByDrawing.set(drawingKey, presentationSourceKey); const resolved = resolvePresentationSource(choices, presentationSourceKey); const appState = api.getAppState(); const elements = ea2.getViewElements(); const sceneVisualFingerprint = getSceneVisualFingerprint(elements); const previewFingerprint = getPreviewFingerprint( appState, sceneVisualFingerprint, elements, resolved ); const chromeFingerprint = getSidepanelChromeFingerprint(choices, presentationSourceKey); const compositeFingerprint = getSidepanelFingerprint( ea2, choices, presentationSourceKey, appState, sceneVisualFingerprint ); if (!force && compositeFingerprint === this.lastFingerprint) return; const previewContentChanged = previewFingerprint !== this.lastPreviewFingerprint; const canPatchExistingUi = !force && Boolean(this.sorter && this.resolved && resolved) && presentationSourceKey === this.presentationSourceKey && chromeFingerprint === this.lastChromeFingerprint; if (canPatchExistingUi && resolved && this.sorter?.syncDeck(resolved.deck, !previewContentChanged)) { this.choices = choices; this.presentationSourceKey = presentationSourceKey; this.resolved = resolved; this.lastFingerprint = compositeFingerprint; this.lastPreviewFingerprint = previewFingerprint; this.lastChromeFingerprint = chromeFingerprint; this.pendingRefresh = false; this.updatePresentationSourceUi(); if (previewContentChanged) this.sorter.refreshPreviews(); this.pendingSceneSlideId = null; return; } const requestedSlideId = this.requestedSlideId; if (this.sceneSelectionSignature === null) { this.sceneSelectionSignature = getSorterSceneSelectionSignature(appState); this.pendingSceneSlideId = getSceneSelectedSlideId(resolved, appState); } const selectedId = this.animationEditingSlideId ?? requestedSlideId ?? this.pendingSceneSlideId ?? this.sorter?.getSelectedSlideId() ?? null; const expandedNotesId = this.sorter?.getExpandedNotesSlideId() ?? null; const sorterScrollTop = this.sorter?.getScrollTop() ?? 0; const preservedPreviews = presentationSourceKey === this.presentationSourceKey ? this.sorter?.capturePreviewContents() : void 0; this.previewService?.cancelPending(); this.sorter?.destroy(); this.sorter = null; this.choices = choices; this.presentationSourceKey = presentationSourceKey; this.resolved = resolved; this.lastFingerprint = compositeFingerprint; this.lastPreviewFingerprint = previewFingerprint; this.lastChromeFingerprint = chromeFingerprint; this.pendingRefresh = false; this.previewService ??= new SlidePreviewService(ea2, api, this.options.config); const renderedSorter = this.render(selectedId, expandedNotesId); if (preservedPreviews) { renderedSorter?.restorePreviewContents(preservedPreviews, previewContentChanged); } this.pendingSceneSlideId = null; if (requestedSlideId) { renderedSorter?.scrollToSlide(requestedSlideId); } else { renderedSorter?.restoreScrollTop(sorterScrollTop); } } /** Updates presentation labels/counts without rebuilding sorter rows or thumbnail hosts. */ updatePresentationSourceUi() { const deck = this.resolved?.deck; if (!deck) return; const sourceOptions = getPresentationSourceLabels( this.choices, this.options.t("frameDeck"), this.options.t("linePresentationDefaultName") ); const sourceSelect = this.options.tab.contentEl.querySelector( ".slideshow-sidepanel__presentation-source-select" ); if (sourceSelect && sourceSelect.options.length === sourceOptions.length) { sourceOptions.forEach((definition, index) => { const option = sourceSelect.options.item(index); if (option && option.value === definition.key) option.textContent = definition.label; }); } const summary = this.options.tab.contentEl.querySelector(".slideshow-sidepanel__summary"); if (summary) { const activeSourceLabel = sourceOptions.find((option) => option.key === this.presentationSourceKey)?.label ?? (deck.kind === "frame" ? this.options.t("frameDeck") : this.options.t("linePresentationDefaultName")); summary.dataset.sourceLabel = activeSourceLabel; } this.updateHeaderContextAction(); this.updateDeckSummaryAndAvailability(); } render(preferredSlideId, preferredNotesSlideId) { const { tab, t, icons, ea: ea2 } = this.options; tab.setDisabled(false); tab.contentEl.replaceChildren(); const style = tab.contentEl.ownerDocument.createElement("style"); style.textContent = SLIDESHOW_SIDEPANEL_STYLES; tab.contentEl.appendChild(style); const doc = tab.contentEl.ownerDocument; const root = doc.createElement("div"); root.className = "slideshow-sidepanel"; root.style.setProperty( "--slideshow-sorter-thumbnail-max-width", `${this.sorterThumbnailMaxWidth}px` ); tab.contentEl.appendChild(root); this.appendSupportLine(root, doc); const header = doc.createElement("div"); header.className = "slideshow-sidepanel__header"; root.appendChild(header); const noVisibleSlides = Boolean(this.resolved && this.resolved.deck.visibleSlides.length === 0); const exactResumeProgress = this.boundView && this.presentationSourceKey ? getSlideshowProgressForSource(this.boundView, this.presentationSourceKey) : void 0; const resumeSlide = this.boundView && this.resolved ? getResumeSlideForPresentation( exactResumeProgress ?? getSlideshowProgress(this.boundView), exactResumeProgress !== void 0 && this.presentationSourceKey ? getPresentationSourceType(this.presentationSourceKey) : getSlideshowProgressType(this.boundView), this.presentationSourceKey ? getPresentationSourceType(this.presentationSourceKey) : null, this.resolved.deck.visibleSlides.length, exactResumeProgress !== void 0 ? this.presentationSourceKey ?? void 0 : getSlideshowProgressSource(this.boundView), this.presentationSourceKey ) : null; const selectedSlideId = this.sorter?.getSelectedSlideId() ?? preferredSlideId ?? this.resolved?.deck.slides[0]?.id ?? null; const selectedVisibleIndex = this.resolved ? getVisibleSlideIndex(this.resolved.deck, selectedSlideId) : null; this.refreshDisplayTargets(); const startButton = doc.createElement("button"); startButton.type = "button"; startButton.className = "slideshow-sidepanel__icon-button slideshow-sidepanel__launch-main"; startButton.setAttribute("aria-label", t("startPresentation")); startButton.innerHTML = icons.play; startButton.disabled = !this.resolved || noVisibleSlides; header.appendChild(startButton); startButton.addEventListener("click", () => void this.launchPresentation()); const printButton = doc.createElement("button"); printButton.type = "button"; printButton.className = "slideshow-sidepanel__icon-button slideshow-sidepanel__print-button"; const printLabel = t("printDialogTitle"); printButton.setAttribute("aria-label", printLabel); printButton.innerHTML = icons.printer; printButton.disabled = !this.resolved; header.appendChild(printButton); printButton.addEventListener("click", (event) => { void this.printPresentation(event); }); if (this.resolved?.deck.kind === "frame") { const exportButton = header.createEl("button", { cls: "slideshow-sidepanel__icon-button slideshow-sidepanel__export-markdown", attr: { type: "button", "aria-label": t("exportMarkdown") } }); exportButton.innerHTML = icons.fileDown; exportButton.addEventListener("click", () => { void this.exportMarkdown(); }); } const contextAction = this.createHeaderContextAction(doc); if (contextAction) header.appendChild(contextAction); this.appendInfoButton(header, doc); this.appendSettingsButton(header, doc); if (!this.resolved || !this.previewService) { const empty = doc.createElement("div"); empty.className = "slideshow-empty"; empty.textContent = t("noEligibleSlides"); root.appendChild(empty); return null; } const launchSettings = doc.createElement("details"); launchSettings.className = "slideshow-sidepanel__launch-settings"; launchSettings.open = this.launchSettingsExpanded; launchSettings.addEventListener("toggle", () => { this.launchSettingsExpanded = launchSettings.open; }); const launchSummary = doc.createElement("summary"); launchSummary.className = "slideshow-sidepanel__launch-settings-summary"; launchSummary.textContent = t("presentationSettings"); launchSettings.appendChild(launchSummary); root.appendChild(launchSettings); const launchOptions = doc.createElement("div"); launchOptions.className = "slideshow-sidepanel__launch-options"; launchSettings.appendChild(launchOptions); const appendSelect = (labelText, value, options, onChange) => { const label = doc.createElement("label"); label.className = "slideshow-sidepanel__launch-option"; const select = doc.createElement("select"); select.setAttribute("aria-label", labelText); for (const optionDefinition of options) { const option = doc.createElement("option"); option.value = optionDefinition.value; option.textContent = optionDefinition.label; option.disabled = optionDefinition.disabled ?? false; select.appendChild(option); } select.value = value; select.addEventListener("change", () => onChange(select.value)); label.appendChild(select); launchOptions.appendChild(label); return select; }; const sourceOptions = getPresentationSourceLabels( this.choices, t("frameDeck"), t("linePresentationDefaultName") ); if (sourceOptions.length > 1 && this.presentationSourceKey) { const sourceSelect = appendSelect( t("presentationType"), this.presentationSourceKey, sourceOptions.map((option) => ({ value: option.key, label: option.label })), (nextSource) => void this.selectPresentationSource(nextSource) ); sourceSelect.classList.add("slideshow-sidepanel__presentation-source-select"); } const effectiveStartMode = this.startMode === "resume" && resumeSlide === null ? "beginning" : this.startMode === "current" && selectedVisibleIndex === null ? "beginning" : this.startMode; appendSelect( t("startMode"), effectiveStartMode, [ { value: "beginning", label: t("startModeStart") }, { value: "resume", label: t("startModeResume"), disabled: resumeSlide === null }, { value: "current", label: t("startModeCurrent"), disabled: selectedVisibleIndex === null } ], (mode) => { this.startMode = mode; void this.persistLaunchPreferences(); } ); if (!ea2.DEVICE.isMobile) { appendSelect( t("windowMode"), this.windowMode, [ { value: "fullscreen", label: t("windowModeFullscreen") }, { value: "window", label: t("windowModeWindowed") } ], (mode) => { this.windowMode = mode; void this.persistLaunchPreferences(); } ); const hasSecondaryDisplay = this.displays.length > 1; appendSelect( t("notesMode"), hasSecondaryDisplay ? this.notesMode : "slides", [ { value: "slides", label: t("notesModeSlidesOnly") }, { value: "presenter", label: t("notesModeWithNotes"), disabled: !hasSecondaryDisplay } ], (mode) => { this.notesMode = mode; void this.persistLaunchPreferences(); this.lastFingerprint = ""; void this.refresh(true); } ); } if (!ea2.DEVICE.isMobile && this.notesMode === "presenter" && this.displays.length > 1) { const displayControls = doc.createElement("div"); displayControls.className = "slideshow-sidepanel__display-controls"; launchSettings.appendChild(displayControls); const appendDisplayPicker = (labelText, selectedId, onChange) => { const label = doc.createElement("label"); const caption = doc.createElement("span"); caption.textContent = labelText; label.appendChild(caption); const select = doc.createElement("select"); select.setAttribute("aria-label", labelText); for (const display of this.displays) { const option = doc.createElement("option"); option.value = String(display.id); option.textContent = this.getDisplayLabel(display); select.appendChild(option); } if (selectedId !== null) select.value = String(selectedId); select.addEventListener("change", () => onChange(Number(select.value))); label.appendChild(select); displayControls.appendChild(label); }; appendDisplayPicker(t("presentationDisplay"), this.presentationDisplayId, (id) => { this.presentationDisplayId = id; void this.persistDisplayPreferences(); }); appendDisplayPicker(t("presenterDisplay"), this.presenterDisplayId, (id) => { this.presenterDisplayId = id; void this.persistDisplayPreferences(); }); } const deck = this.resolved.deck; const summaryRow = doc.createElement("div"); summaryRow.className = "slideshow-sidepanel__summary-row"; root.appendChild(summaryRow); const summary = doc.createElement("div"); summary.className = "slideshow-sidepanel__summary"; summaryRow.appendChild(summary); const activeSourceLabel = sourceOptions.find((option) => option.key === this.presentationSourceKey)?.label ?? (deck.kind === "frame" ? t("frameDeck") : t("linePresentationDefaultName")); summary.dataset.sourceLabel = activeSourceLabel; summary.textContent = `${activeSourceLabel} \xB7 ${t("visibleSlideCount", { visible: deck.visibleSlides.length, total: deck.slides.length })}`; const thumbnailSizeControl = doc.createElement("label"); thumbnailSizeControl.className = "slideshow-sidepanel__thumbnail-size-control"; thumbnailSizeControl.setAttribute("aria-label", t("sorterThumbnailSize")); thumbnailSizeControl.title = t("sorterThumbnailSize"); const thumbnailSizeSlider = doc.createElement("input"); thumbnailSizeSlider.type = "range"; thumbnailSizeSlider.min = "140"; thumbnailSizeSlider.max = "520"; thumbnailSizeSlider.step = "20"; thumbnailSizeSlider.value = String(this.sorterThumbnailMaxWidth); thumbnailSizeSlider.setAttribute("aria-label", t("sorterThumbnailSize")); thumbnailSizeSlider.addEventListener("input", () => { this.sorterThumbnailMaxWidth = Number(thumbnailSizeSlider.value); root.style.setProperty( "--slideshow-sorter-thumbnail-max-width", `${this.sorterThumbnailMaxWidth}px` ); }); thumbnailSizeSlider.addEventListener("change", () => { void this.persistSorterThumbnailMaxWidth(); }); thumbnailSizeControl.appendChild(thumbnailSizeSlider); summaryRow.appendChild(thumbnailSizeControl); const presentationSettingsButton = doc.createElement("button"); presentationSettingsButton.type = "button"; presentationSettingsButton.className = "slideshow-sidepanel__icon-button slideshow-sidepanel__presentation-settings"; presentationSettingsButton.setAttribute( "aria-label", t(deck.kind === "frame" ? "framePresentationSettings" : "linePresentationSettings") ); presentationSettingsButton.innerHTML = icons.moreHorizontal; presentationSettingsButton.addEventListener( "click", () => deck.kind === "frame" ? this.openFramePresentationSettings() : this.openLinePresentationSettings() ); summaryRow.appendChild(presentationSettingsButton); const reorderEnabled = !this.resolved.pathElement || !hasBoundLineEndpoint(this.resolved.pathElement); if (!reorderEnabled) { const warning = doc.createElement("div"); warning.className = "slideshow-warning"; warning.textContent = t("lineReorderBound"); root.appendChild(warning); } const sorterContainer = doc.createElement("div"); sorterContainer.className = "slideshow-sorter"; sorterContainer.setAttribute("role", "list"); root.appendChild(sorterContainer); this.sorter = new SlideSorter({ ea: ea2, container: sorterContainer, deck, previewService: this.previewService, icons, t, reorderEnabled, animationEditingSlideId: this.animationEditingSlideId, previewRenderingEnabled: this.isSidepanelFocused(), callbacks: { move: (fromIndex, toIndex) => this.moveSlide(fromIndex, toIndex), toggleInclusion: (slide, excluded) => this.toggleInclusion(slide, excluded), zoomToSlide: (slide) => this.zoomToSlide(slide), saveNotes: (slide, notes) => this.saveNotes(slide, notes), requestAnimationEditor: (slide) => this.requestAnimationEditor(slide), mountAnimationEditor: (slide, container) => this.mountAnimationEditor(slide, container), editSlideName: (slide) => this.openSlideNameEditor(slide), editLineSlide: (slide, index) => this.editLineSlide(slide, index), notesBlurred: () => { if (this.pendingRefresh) this.scheduleRefresh(); } } }); this.sorter.render(preferredSlideId, preferredNotesSlideId); return this.sorter; } refreshDisplayTargets() { const hostWindow = this.boundView?.ownerWindow ?? this.ownerWindow; const displays = getAvailableDisplays(hostWindow); const configurationKey = getSlideshowDisplayConfigurationKey(displays); const configurationChanged = configurationKey !== this.displayConfigurationKey; this.displays = displays; this.displayConfigurationKey = configurationKey; if (displays.length === 0) { this.presentationDisplayId = null; this.presenterDisplayId = null; return; } const defaults = chooseDefaultDisplayTargets(displays, getCurrentDisplayId(hostWindow)); const saved = loadSlideshowDisplayPreferences( this.options.ea, this.deviceKey, configurationKey ); const savedPresentationId = saved ? resolveSlideshowDisplayTarget( displays, saved.presentationDisplayId, saved.presentationDisplayIdentity ) : null; const savedPresenterId = saved ? resolveSlideshowDisplayTarget( displays, saved.presenterDisplayId, saved.presenterDisplayIdentity ) : null; if (configurationChanged) { this.presentationDisplayId = savedPresentationId ?? defaults.presentationDisplayId; this.presenterDisplayId = savedPresenterId ?? defaults.presenterDisplayId; return; } const presentationValid = displays.some( (display) => display.id === this.presentationDisplayId ); const presenterValid = displays.some((display) => display.id === this.presenterDisplayId); if (!presentationValid) { this.presentationDisplayId = savedPresentationId ?? defaults.presentationDisplayId; } if (!presenterValid) { this.presenterDisplayId = savedPresenterId ?? defaults.presenterDisplayId; } } getDisplayLabel(display) { const resolution = `${display.bounds.width}\xD7${display.bounds.height}`; const primary = display.primary ? ` \xB7 ${this.options.t("primaryDisplay")}` : ""; const name = display.label || this.options.t("displayLabel", { number: display.index + 1 }); return `${name} \xB7 ${resolution}${primary}`; } persistLaunchPreferences() { const source = this.presentationSourceKey; const drawingPath = this.boundView?.file.path; const preferences = { startMode: this.startMode, windowMode: this.windowMode, notesMode: this.notesMode, ...source ? { presentationType: getPresentationSourceType(source) } : {} }; this.settingsWriteQueue = this.settingsWriteQueue.then(async () => { await saveSlideshowLaunchPreferences(this.options.ea, preferences); if (source && drawingPath) { await saveSlideshowPresentationSource(this.options.ea, drawingPath, source); } }).catch((error) => console.error("Slideshow launch preference save failed", error)); return this.settingsWriteQueue; } persistDisplayPreferences() { const presentationDisplay = this.displays.find( (display) => display.id === this.presentationDisplayId ); const presenterDisplay = this.displays.find( (display) => display.id === this.presenterDisplayId ); const preferences = { presentationDisplayId: this.presentationDisplayId, presenterDisplayId: this.presenterDisplayId, presentationDisplayIdentity: presentationDisplay ? getSlideshowDisplayIdentity(presentationDisplay) : null, presenterDisplayIdentity: presenterDisplay ? getSlideshowDisplayIdentity(presenterDisplay) : null }; const configurationKey = this.displayConfigurationKey ?? getSlideshowDisplayConfigurationKey(this.displays); this.settingsWriteQueue = this.settingsWriteQueue.then( () => saveSlideshowDisplayPreferences( this.options.ea, this.deviceKey, preferences, configurationKey ) ).catch((error) => console.error("Slideshow display preference save failed", error)); return this.settingsWriteQueue; } /** Persists the sorter thumbnail cap through the sidepanel's serialized settings queue. */ persistSorterThumbnailMaxWidth() { const width = this.sorterThumbnailMaxWidth; this.settingsWriteQueue = this.settingsWriteQueue.then(() => saveSorterThumbnailMaxWidth(this.options.ea, width)).catch((error) => console.error("Slideshow thumbnail-size save failed", error)); return this.settingsWriteQueue; } async prepareWindowedPresentation(view) { const sidepanelLeaf = this.options.ea.getSidepanelLeaf(); const container = sidepanelLeaf?.view.containerEl; const sidepanelWindow = container?.ownerDocument.defaultView ?? null; const requestFrame = view.ownerWindow.requestAnimationFrame?.bind(view.ownerWindow); const nextFrame = () => requestFrame ? new Promise((resolve) => requestFrame(() => resolve())) : new Promise((resolve) => view.ownerWindow.setTimeout(resolve, 0)); if (sidepanelWindow && sidepanelWindow !== view.ownerWindow) { await app.workspace.setActiveLeaf(view.leaf, { focus: true }); return; } if (container) { const isVisible = () => { const rect = container.getBoundingClientRect(); return container.isConnected && rect.width > 1 && rect.height > 1 && view.ownerWindow.getComputedStyle(container).display !== "none"; }; if (isVisible()) { this.options.ea.toggleSidepanelView(); for (let frame = 0; frame < 20 && isVisible(); frame += 1) await nextFrame(); } } await app.workspace.setActiveLeaf(view.leaf, { focus: true }); await nextFrame(); } async launchPresentation() { const view = this.boundView; const resolved = this.resolved; const presentationSourceKey = this.presentationSourceKey; if (!view || !resolved || !presentationSourceKey || resolved.deck.visibleSlides.length === 0) return; const presentationType = getPresentationSourceType(presentationSourceKey); await this.persistLaunchPreferences(); const exactResumeProgress = getSlideshowProgressForSource(view, presentationSourceKey); const resume = getResumeSlideForPresentation( exactResumeProgress ?? getSlideshowProgress(view), exactResumeProgress !== void 0 ? presentationType : getSlideshowProgressType(view), presentationType, resolved.deck.visibleSlides.length, exactResumeProgress !== void 0 ? presentationSourceKey : getSlideshowProgressSource(view), presentationSourceKey ); const selectedId = this.sorter?.getSelectedSlideId() ?? null; const selectedIndex = getVisibleSlideIndex(resolved.deck, selectedId); const effectiveStartMode = this.startMode === "resume" && resume === null ? "beginning" : this.startMode === "current" && selectedIndex === null ? "beginning" : this.startMode; let initialSlide; if (effectiveStartMode === "resume") { initialSlide = resume ?? 0; } else if (effectiveStartMode === "current") { if (selectedIndex === null) { new Notice(this.options.t("selectedSlideNotPresentable")); return; } initialSlide = selectedIndex; } else { initialSlide = 0; } await this.sorter?.flushNotes(); await this.animationEditor?.destroy(); this.animationEditor = null; this.animationEditingSlideId = null; this.refreshDisplayTargets(); await this.persistDisplayPreferences(); const { startFullscreen, openPresenterView } = resolveDeviceLaunchModes( this.options.ea.DEVICE.isMobile, this.windowMode, this.notesMode, this.displays.length > 1 ); const launchOptions = { initialSlide, startFullscreen, openPresenterView, ...openPresenterView && this.presentationDisplayId !== null ? { presentationDisplayId: this.presentationDisplayId } : {}, ...openPresenterView && this.presenterDisplayId !== null ? { presenterDisplayId: this.presenterDisplayId } : {} }; await this.prepareWindowedPresentation(view); await this.options.startPresentation(presentationSourceKey, launchOptions); } async printPresentation(event) { try { await this.sorter?.flushNotes(); if (this.animationEditor) await this.closeAnimationEditor(); if (this.presentationSourceKey) { await this.options.printPresentation(this.presentationSourceKey, event); } } catch (error) { console.error("Slideshow PDF export failed", error); new this.options.ea.obsidian.Notice(this.options.t("printFailed")); } } async exportMarkdown() { try { await this.sorter?.flushNotes(); if (this.animationEditor) await this.closeAnimationEditor(); await this.options.exportMarkdown(); } catch (error) { console.error("Slideshow Markdown export failed", error); new this.options.ea.obsidian.Notice(this.options.t("exportMarkdownFailed")); } } async selectPresentationSource(sourceKey) { if (!hasPresentationSource(this.choices, sourceKey) || sourceKey === this.presentationSourceKey) return; await this.sorter?.flushNotes(); await this.animationEditor?.destroy(); this.animationEditor = null; this.animationEditingSlideId = null; const view = this.boundView; if (!view) return; this.presentationSourceByDrawing.set(view.file.path, sourceKey); this.preferredPresentationType = getPresentationSourceType(sourceKey); this.presentationSourceKey = sourceKey; await this.persistLaunchPreferences(); this.lastFingerprint = ""; await this.refresh(true); } async convertSelectedLineToPresentation() { const view = this.boundView; const path = getConvertibleSelectedLine(this.options.ea); if (!view || !path) return; try { await this.sorter?.flushNotes(); await createLinePresentation( this.options.ea, path.id, this.options.t("linePresentationDefaultName") ); await view.forceSave(true); const sourceKey = `line:${path.id}`; this.presentationSourceByDrawing.set(view.file.path, sourceKey); this.presentationSourceKey = sourceKey; this.preferredPresentationType = "line"; await this.persistLaunchPreferences(); this.lastFingerprint = ""; await this.refresh(true); } catch (error) { console.error("Slideshow line presentation creation failed", error); new Notice(this.options.t("metadataSaveFailed")); } } async declareSelectedFrameSlideshow() { const view = this.boundView; const frame = getDeclarableSelectedFrame(this.options.ea); if (!view || !frame) return; try { await this.sorter?.flushNotes(); await declareFrameSlideshow(this.options.ea, frame.id); await view.forceSave(true); this.presentationSourceByDrawing.set(view.file.path, "frame"); this.presentationSourceKey = "frame"; this.preferredPresentationType = "frame"; await this.persistLaunchPreferences(); this.lastFingerprint = ""; await this.refresh(true); } catch (error) { console.error("Slideshow frame presentation declaration failed", error); new Notice(this.options.t("metadataSaveFailed")); } } openSlideNameEditor(slide) { const view = this.boundView; if (!view) return; const { ea: ea2, t } = this.options; const modal = new ea2.obsidian.Modal(app); modal.titleEl.setText(t("editSlideName")); const input = modal.contentEl.createEl("input", { type: "text", value: slide.title, attr: { "aria-label": t("slideName") } }); input.style.width = "100%"; input.style.marginBottom = "1rem"; const actions = modal.contentEl.createDiv({ cls: "modal-button-container" }); styleModalActions(actions); const cancel = actions.createEl("button", { text: t("settingsCancel") }); cancel.addEventListener("click", () => modal.close()); const save = actions.createEl("button", { text: t("settingsSave"), cls: "mod-cta" }); save.addEventListener("click", () => { void (async () => { try { if (slide.kind === "frame") await renameFrameSlide(ea2, slide.frameId, input.value); else await renameLineSlide(ea2, slide.pathId, slide.id, input.value); await view.forceSave(true); modal.close(); await this.refresh(); } catch (error) { console.error("Slideshow slide rename failed", error); new Notice(t("metadataSaveFailed")); } })(); }); bindEnterToSave(input, save); modal.open(); input.focus(); input.select(); } chooseFrameToLineOptions() { const { ea: ea2, t } = this.options; return new Promise((resolve) => { const modal = new ea2.obsidian.Modal(app); let settled = false; const finish = (choice) => { if (settled) return; settled = true; resolve(choice); modal.close(); }; modal.titleEl.setText(t("convertFrameToLine")); modal.contentEl.createEl("p", { text: t("convertFrameToLinePrompt") }); const deleteFrames = addCheckboxOption(modal.contentEl, t("conversionDeleteFrames")); const visibleSlidesOnly = addCheckboxOption( modal.contentEl, t("conversionVisibleSlidesOnly") ); const actions = modal.contentEl.createDiv({ cls: "modal-button-container" }); styleModalActions(actions); const cancel = actions.createEl("button", { text: t("settingsCancel") }); cancel.addEventListener("click", () => finish(null)); const create = actions.createEl("button", { text: t("conversionCreate"), cls: "mod-cta" }); create.addEventListener( "click", () => finish({ deleteFrames: deleteFrames.checked, visibleSlidesOnly: visibleSlidesOnly.checked }) ); modal.onClose = () => { if (!settled) { settled = true; resolve(null); } }; modal.open(); }); } chooseLineToFrameOptions() { const { ea: ea2, t } = this.options; return new Promise((resolve) => { const modal = new ea2.obsidian.Modal(app); let settled = false; const finish = (choice) => { if (settled) return; settled = true; resolve(choice); modal.close(); }; modal.titleEl.setText(t("convertLineToFrame")); modal.contentEl.createEl("p", { text: t("convertLineToFramePrompt") }); const deleteLine = addCheckboxOption(modal.contentEl, t("conversionDeleteLine")); const frameKind = addSelectOption(modal.contentEl, t("convertLineToFrameKind"), [ ["marker", t("convertLineToFrameMarker")], ["normal", t("convertLineToFrameNormal")] ]); const geometry = addSelectOption(modal.contentEl, t("convertLineToFrameGeometryTitle"), [ ["aspect", t("convertLineToFrameAspect")], ["exact", t("convertLineToFrameExact")] ]); const actions = modal.contentEl.createDiv({ cls: "modal-button-container" }); styleModalActions(actions); const cancel = actions.createEl("button", { text: t("settingsCancel") }); cancel.addEventListener("click", () => finish(null)); const create = actions.createEl("button", { text: t("conversionCreate"), cls: "mod-cta" }); create.addEventListener( "click", () => finish({ deleteLine: deleteLine.checked, frameKind: frameKind.value === "normal" ? "normal" : "marker", correctAspectRatio: geometry.value === "aspect" }) ); modal.onClose = () => { if (!settled) { settled = true; resolve(null); } }; modal.open(); }); } openFramePresentationSettings() { const view = this.boundView; const deck = this.choices.frame?.deck; if (!view || !deck) return; const { ea: ea2, t } = this.options; const modal = new ea2.obsidian.Modal(app); modal.titleEl.setText(t("framePresentationSettings")); const input = modal.contentEl.createEl("input", { type: "text", value: deck.name ?? "", attr: { "aria-label": t("framePresentationName") } }); input.style.width = "100%"; input.style.marginBottom = "1rem"; const actions = modal.contentEl.createDiv({ cls: "modal-button-container" }); styleModalActions(actions); const save = actions.createEl("button", { text: t("settingsSave"), cls: "mod-cta" }); save.addEventListener("click", () => { void (async () => { try { await renameFramePresentation(ea2, input.value); await view.forceSave(true); modal.close(); await this.refresh(); } catch (error) { console.error("Slideshow frame presentation rename failed", error); new Notice(t("metadataSaveFailed")); } })(); }); const convert = actions.createEl("button", { text: t("convertFrameToLine") }); convert.addEventListener("click", () => { void (async () => { const conversionOptions = await this.chooseFrameToLineOptions(); if (!conversionOptions) return; try { await this.sorter?.flushNotes(); const pathId = await convertFramePresentationToLine(ea2, conversionOptions); await view.forceSave(true); modal.close(); const sourceKey = `line:${pathId}`; this.presentationSourceKey = sourceKey; this.presentationSourceByDrawing.set(view.file.path, sourceKey); this.preferredPresentationType = "line"; await this.persistLaunchPreferences(); this.lastFingerprint = ""; await this.refresh(true); } catch (error) { console.error("Slideshow frame-to-line conversion failed", error); new Notice(t("conversionFailed")); } })(); }); bindEnterToSave(input, save); modal.open(); input.focus(); input.select(); } openLinePresentationSettings() { const source = getLineSourceByKey(this.choices, this.presentationSourceKey); const view = this.boundView; if (!source || !view) return; const { ea: ea2, t } = this.options; const modal = new ea2.obsidian.Modal(app); modal.titleEl.setText(t("linePresentationSettings")); const input = modal.contentEl.createEl("input", { type: "text", value: source.name ?? t("linePresentationDefaultName"), attr: { "aria-label": t("linePresentationName") } }); input.style.width = "100%"; input.style.marginBottom = "1rem"; const actions = modal.contentEl.createDiv({ cls: "modal-button-container slideshow-line-presentation-settings__actions" }); styleModalActions(actions); const save = actions.createEl("button", { text: t("settingsSave"), cls: "mod-cta" }); save.addEventListener("click", () => { void (async () => { try { await renameLinePresentation(ea2, source.pathId, input.value); await view.forceSave(true); modal.close(); await this.refresh(); } catch (error) { console.error("Slideshow line presentation rename failed", error); new Notice(t("metadataSaveFailed")); } })(); }); const remove = actions.createEl("button", { text: t("removeLinePresentation") }); remove.style.color = "var(--text-error)"; remove.addEventListener("click", () => { void (async () => { const confirmed = await openConfirmationModal(ea2, app, { title: t("removeLinePresentation"), message: t("removeLinePresentationConfirm"), confirmText: t("removeLinePresentation"), cancelText: t("settingsCancel") }); if (!confirmed) return; try { await removeLinePresentation(ea2, source.pathId); await view.forceSave(true); modal.close(); this.presentationSourceByDrawing.delete(view.file.path); this.presentationSourceKey = null; this.lastFingerprint = ""; await this.refresh(true); } catch (error) { console.error("Slideshow line presentation removal failed", error); new Notice(t("metadataSaveFailed")); } })(); }); if (!this.choices.frame) { const convert = actions.createEl("button", { text: t("convertLineToFrame") }); convert.addEventListener("click", () => { void (async () => { const conversionOptions = await this.chooseLineToFrameOptions(); if (!conversionOptions) return; try { await this.sorter?.flushNotes(); await convertLinePresentationToFrames( ea2, source.pathId, this.options.config, conversionOptions ); await view.forceSave(true); modal.close(); this.presentationSourceKey = "frame"; this.presentationSourceByDrawing.set(view.file.path, "frame"); this.preferredPresentationType = "frame"; await this.persistLaunchPreferences(); this.lastFingerprint = ""; await this.refresh(true); } catch (error) { console.error("Slideshow line-to-frame conversion failed", error); new Notice(t("conversionFailed")); } })(); }); } bindEnterToSave(input, save); modal.open(); input.focus(); input.select(); } async togglePresentationPathVisibility() { const path = this.resolved?.pathElement; if (!path) return; try { await this.sorter?.flushNotes(); await setLinePresentationPathHidden( this.options.ea, path.id, !isPresentationPathHidden(path) ); await this.refresh(); } catch (error) { console.error("Slideshow presentation path visibility update failed", error); new Notice(this.options.t("metadataSaveFailed")); } } updateDeckSummaryAndAvailability() { const deck = this.resolved?.deck; if (!deck) return; const summary = this.options.tab.contentEl.querySelector(".slideshow-sidepanel__summary"); if (summary) { const sourceLabel = summary.dataset.sourceLabel ?? ""; summary.textContent = `${sourceLabel} \xB7 ${this.options.t("visibleSlideCount", { visible: deck.visibleSlides.length, total: deck.slides.length })}`; } const disabled = deck.visibleSlides.length === 0; const startButton = this.options.tab.contentEl.querySelector( ".slideshow-sidepanel__launch-main" ); const printButton = this.options.tab.contentEl.querySelector( ".slideshow-sidepanel__print-button" ); if (startButton) startButton.disabled = disabled; if (printButton) printButton.disabled = false; } updateLastFingerprintFromCurrentState() { const view = this.boundView; if (!view || view.file !== this.boundDrawingFile) { this.lastFingerprint = ""; this.lastPreviewFingerprint = ""; this.lastChromeFingerprint = ""; return; } if (this.options.ea.targetView !== view) this.options.ea.setView(view); const api = this.options.ea.getExcalidrawAPI(); if (!api) { this.lastFingerprint = ""; this.lastPreviewFingerprint = ""; this.lastChromeFingerprint = ""; return; } const appState = api.getAppState(); const elements = this.options.ea.getViewElements(); const sceneVisualFingerprint = getSceneVisualFingerprint(elements); this.lastFingerprint = getSidepanelFingerprint( this.options.ea, this.choices, this.presentationSourceKey, appState, sceneVisualFingerprint ); this.lastPreviewFingerprint = getPreviewFingerprint( appState, sceneVisualFingerprint, elements, this.resolved ); this.lastChromeFingerprint = getSidepanelChromeFingerprint( this.choices, this.presentationSourceKey ); this.pendingRefresh = false; } async moveSlide(fromIndex, toIndex) { if (!this.resolved) return; this.sorterMutationDepth += 1; try { await this.sorter?.flushNotes(); if (this.resolved.deck.kind === "frame") { await reorderFrameSlides(this.options.ea, fromIndex, toIndex); } else if (this.resolved.pathElement) { await reorderLineSlides(this.options.ea, this.resolved.pathElement.id, fromIndex, toIndex); } this.sorter?.applyReorder(fromIndex, toIndex); this.updateLastFingerprintFromCurrentState(); } catch (error) { if (error instanceof Error && error.message === "BOUND_PRESENTATION_PATH") { new Notice(this.options.t("lineReorderBound")); } else { console.error("Slideshow sorter reorder failed", error); new Notice(this.options.t("reorderFailed")); } } finally { this.sorterMutationDepth = Math.max(this.sorterMutationDepth - 1, 0); if (this.sorterMutationDepth === 0 && this.pendingRefresh) this.scheduleRefresh(); } } async toggleInclusion(slide, excluded) { this.sorterMutationDepth += 1; try { await this.sorter?.flushNotes(); if (slide.kind === "frame") { await setFrameExcluded(this.options.ea, slide.frameId, excluded); } else { await setLineSlideExcluded(this.options.ea, slide.pathId, slide.id, excluded); } this.sorter?.applyInclusion(slide.id, excluded); this.updateDeckSummaryAndAvailability(); this.updateLastFingerprintFromCurrentState(); } catch (error) { console.error("Slideshow inclusion update failed", error); new Notice(this.options.t("metadataSaveFailed")); } finally { this.sorterMutationDepth = Math.max(this.sorterMutationDepth - 1, 0); if (this.sorterMutationDepth === 0 && this.pendingRefresh) this.scheduleRefresh(); } } async saveNotes(slide, notes) { try { const view = this.boundView; if (!view) throw new Error("The slideshow sidepanel is not bound to a drawing."); if (this.options.ea.targetView !== view) this.options.ea.setView(view); if (slide.kind === "frame") { await saveFrameNotes(this.options.ea, slide.frameId, notes); } else { await saveLineNotes(this.options.ea, slide.pathId, slide.id, notes); } await view.forceSave(true); if (notes.trim().length === 0) delete slide.notes; else slide.notes = notes; this.updateLastFingerprintFromCurrentState(); } catch (error) { console.error("Slideshow notes update failed", error); new Notice(this.options.t("metadataSaveFailed")); } } zoomToSlide(slide) { const api = this.options.ea.getExcalidrawAPI(); const view = this.boundView; if (!api || !view) return; view.preventAutozoom(); const appState = api.getAppState(); const rect = getNavigationRect( slide.rect, { width: appState.width, height: appState.height }, this.options.config.maxZoom ); api.updateScene({ appState: { scrollX: -rect.left, scrollY: -rect.top, zoom: { value: rect.nextZoom } } }); } async editLineSlide(slide, index) { if (slide.kind !== "path") return; const { ea: ea2 } = this.options; const api = ea2.getExcalidrawAPI(); const view = this.boundView; if (!api || !view) return; try { await this.sorter?.flushNotes(); const currentPath = ea2.getViewElements().find((element) => element.id === slide.pathId); if (!isLinearPathElement(currentPath)) return; if (isPresentationPathHidden(currentPath)) { await setLinePresentationPathHidden(ea2, currentPath.id, false); } const path = ea2.getViewElements().find((element) => element.id === slide.pathId); if (!isLinearPathElement(path)) return; app.workspace.setActiveLeaf(view.leaf, { focus: true }); view.preventAutozoom(); ea2.selectElementsInView([path]); const appState = api.getAppState(); let rect = getNavigationRect( slide.rect, { width: appState.width, height: appState.height }, this.options.config.maxZoom ); const offsetWidth = (rect.right - rect.left) * (1 - this.options.config.editZoomOut) / 2; const offsetHeight = (rect.bottom - rect.top) * (1 - this.options.config.editZoomOut) / 2; rect = { left: rect.left - offsetWidth, right: rect.right + offsetWidth, top: rect.top - offsetHeight, bottom: rect.bottom + offsetHeight, nextZoom: Math.max(rect.nextZoom * this.options.config.editZoomOut, 0.1) }; api.updateScene({ appState: { scrollX: -rect.left, scrollY: -rect.top, zoom: { value: rect.nextZoom } } }); api.setActiveTool({ type: "selection" }); api.startLineEditor(path, [index * 2, index * 2 + 1]); this.lastFingerprint = ""; } catch (error) { console.error("Slideshow line-slide editing failed", error); new Notice(this.options.t("editLineSlideFailed")); } } requestAnimationEditor(slide) { void (async () => { await this.sorter?.flushNotes(); if (this.animationEditingSlideId === slide.id) { await this.closeAnimationEditor(); return; } await this.animationEditor?.destroy(); this.animationEditor = null; this.animationEditingSlideId = slide.id; if (this.sorter) this.sorter.setAnimationEditingSlideId(slide.id); else this.render(slide.id, null); this.selectAndZoomAnimationSlide(slide); this.sorter?.scrollToSlide(slide.id, false, "start"); this.refreshPreviewsOnce(); })(); } mountAnimationEditor(slide, container) { const api = this.options.ea.getExcalidrawAPI(); const view = this.boundView; if (!api || !view || slide.id !== this.animationEditingSlideId) return; const previousEditor = this.animationEditor; this.animationEditor = null; void previousEditor?.destroy(); this.animationEditor = new AnimationEditor({ ea: this.options.ea, api, hostView: view, container, slide, config: this.options.config, icons: this.options.icons, t: this.options.t, onSaved: (steps) => { this.sorter?.updateAnimationSteps(slide.id, steps); this.updateLastFingerprintFromCurrentState(); } }); this.animationEditor.render(); this.animationEditor.handleSceneChange(this.options.ea.getViewElements(), api.getAppState()); } selectAndZoomAnimationSlide(slide) { const view = this.boundView; if (!view) return; if (slide.kind === "frame") { const frame = this.options.ea.getViewElements().find((element) => element.id === slide.frameId); if (frame) this.options.ea.selectElementsInView([frame]); } else { const path = this.options.ea.getViewElements().find((element) => element.id === slide.pathId); if (path) this.options.ea.selectElementsInView([path]); } this.zoomToSlide(slide); app.workspace.setActiveLeaf(view.leaf, { focus: true }); } async closeAnimationEditor() { await this.animationEditor?.destroy(); this.animationEditor = null; const slideId = this.animationEditingSlideId; this.animationEditingSlideId = null; this.sorter?.setAnimationEditingSlideId(null); this.updateLastFingerprintFromCurrentState(); if (slideId) this.sorter?.scrollToSlide(slideId); this.refreshPreviewsOnce(); } }; // src/scripts/slideshow/exportMarkdown.ts function getMarkdownExportPath(drawingPath, filename) { const name = filename.trim().replace(/\.md$/i, ""); if (!name || /^\.+$/.test(name) || /[\\/:*?"<>|#\[\]\r\n]/.test(name) || /[. ]$/.test(name)) return null; const folder = drawingPath.slice(0, Math.max(0, drawingPath.lastIndexOf("/") + 1)); return `${folder}${name}.md`; } function buildSlideshowMarkdown(drawingPath, deck, frames) { return deck.slides.filter((slide) => slide.kind === "frame").map((slide) => { const frame = frames.find((candidate) => candidate.id === slide.frameId); const name = frame?.name; const unique = name && frames.filter((candidate) => candidate.name === name || candidate.id === name).length === 1; const target = unique && !/[|#\^\[\]\r\n]/.test(name) && !/,padding=\d/.test(name) ? name : slide.frameId; const heading = slide.title.replace(/[\r\n]+/g, " ").replace(/([\\`*_{}\[\]<>#])/g, "\\$1"); return `## ${heading} ![[${drawingPath}#^frame=${target}]] ${slide.notes ?? ""}`.trimEnd(); }).join("\n\n") + "\n"; } async function exportSlideshowMarkdown(context, deck) { const { ea: ea2, view, utils: utils2, t } = context; const drawing = view.file; if (view.isDirty()) await view.forceSave(true); if (view.file !== drawing) return; const frames = ea2.getViewElements().filter((element) => element.type === "frame"); const markdown = buildSlideshowMarkdown(drawing.path, deck, frames); const filename = await utils2.inputPrompt( t("exportMarkdownFilename"), "", t("exportMarkdownDefaultFilename", { name: drawing.basename }) ).catch((error) => { if (error === "No input given.") return void 0; throw error; }); if (filename === void 0) return; const path = getMarkdownExportPath(drawing.path, filename); if (!path) { new ea2.obsidian.Notice(t("exportMarkdownInvalidFilename")); return; } if (app.vault.getFileByPath(path)) { new ea2.obsidian.Notice(t("exportMarkdownExists")); return; } const file = await app.vault.create(path, markdown); await app.workspace.getLeaf("tab").openFile(file); } // src/scripts/slideshow/slideshowLauncher.ts async function ensureManualSlideshowDeclaration(context) { const { ea: ea2, view } = context; ea2.setView(view); const selected = ea2.getViewSelectedElement(); if (isLinearPathElement(selected)) { const existingSourceKey = getLinePresentationSourceKey(selected); if (existingSourceKey) return existingSourceKey; if (Math.floor(selected.points.length / 2) > 0) { await createLinePresentation(ea2, selected.id); return `line:${selected.id}`; } return void 0; } if (!isFrameElement(selected)) return void 0; const frames = ea2.getViewElements().filter(isFrameElement); const alreadyDeclared = frames.some((frame) => hasFrameSlideshowDeclaration(frame.customData)); if (!alreadyDeclared) await declareFrameSlideshow(ea2, selected.id); return "frame"; } function resolveManualInvocationIntent(modifiers) { return { openSidepanel: modifiers.ctrlKey || modifiers.metaKey, resume: modifiers.shiftKey, startFullscreen: !modifiers.altKey }; } function chooseManualPresentationSourceKey(choices, selectedSource, savedSource, preferredType) { if (selectedSource && resolvePresentationSource(choices, selectedSource)) return selectedSource; if (savedSource && resolvePresentationSource(choices, savedSource)) return savedSource; if (preferredType === "frame" && choices.frame) return "frame"; if (preferredType === "line" && choices.lines[0]) return choices.lines[0].key; return choices.defaultSourceKey ?? void 0; } function resolveLaunchModifiers(view) { return { startFullscreen: !view.modifierKeyDown.altKey }; } function getElementPresentationSourceKey(element) { if (isFrameElement(element) && hasFrameSlideshowDeclaration(element.customData)) return "frame"; if (isLinearPathElement(element)) return getLinePresentationSourceKey(element); return null; } function registerSlideshowElementActionProvider(context) { return context.ea.registerElementActionProvider((element) => { const latestContext = getSlideshowViewContext(context.view) ?? context; const presentationSourceKey = getElementPresentationSourceKey(element) ?? (isFrameElement(element) && latestContext.ea.getViewElements().some( (candidate) => isFrameElement(candidate) && hasFrameSlideshowDeclaration(candidate.customData) ) ? "frame" : null); if (!presentationSourceKey) return []; const actions = [ { id: "edit-slideshow", title: latestContext.t("editSlideshow"), icon: "pencil", action: () => { latestContext.ea.setView(latestContext.view); void openSlideshowSidepanel( latestContext, presentationSourceKey, presentationSourceKey === "frame" ? element.id : void 0, true ); } } ]; if (presentationSourceKey === "frame" && isFrameElement(element)) { actions.push({ id: "fit-frame-to-slideshow-aspect", title: latestContext.t("fitFrameToPresentationAspect"), icon: "ratio", action: () => { latestContext.ea.setView(latestContext.view); void resizeFrameToPresentationAspect( latestContext.ea, element.id, loadSlideshowConfig(latestContext.ea) ).catch((error) => { console.error("Slideshow frame aspect-ratio resize failed", error); new Notice(latestContext.t("resizeFrameFailed")); }); } }); } return actions; }); } async function startSlideshowPresentation(context, launch = {}) { const { ea: ea2, view, config, t } = context; ea2.setView(view); if (view.isDirty()) await view.forceSave(true); const api = ea2.getExcalidrawAPI(); if (!api) { new Notice(t("cannotAccessView")); return; } const runtime = getSlideshowRuntime(); const previous = runtime.presentations.get(view); if (previous) await previous.exit(); const choices = resolveSlideDeckChoices(ea2); const requestedSource = launch.presentationSourceKey ?? launch.presentationType ?? choices.defaultSourceKey ?? void 0; const setup = resolvePresentationSetup(ea2, api, t, requestedSource); if (!setup || setup.slides.length === 0) return; app.workspace.setActiveLeaf(view.leaf, { focus: true }); const modifierDefaults = resolveLaunchModifiers(view); const savedProgressType = getSlideshowProgressType(view); const savedProgressSource = getSlideshowProgressSource(view); const exactProgress = getSlideshowProgressForSource(view, setup.sourceKey); const resumedSlide = launch.resume && (exactProgress !== void 0 || (!savedProgressType || savedProgressType === setup.pathType) && (!savedProgressSource || savedProgressSource === setup.sourceKey)) ? exactProgress ?? getSlideshowProgress(view) : void 0; const initialSlide = launch.initialSlide ?? resumedSlide ?? 0; const controller = new SlideshowController({ ea: ea2, api, hostView: view, statusBarElement: view.ownerDocument.querySelector("div.status-bar"), setup, config, icons: getSlideshowIcons(ea2), initialSlide, startFullscreen: launch.startFullscreen ?? modifierDefaults.startFullscreen, ...launch.openPresenterView === void 0 ? {} : { openPresenterViewOnStart: launch.openPresenterView }, ...launch.presentationDisplayId === void 0 ? {} : { presentationDisplayId: launch.presentationDisplayId }, ...launch.presenterDisplayId === void 0 ? {} : { presenterDisplayId: launch.presenterDisplayId }, t, onSlideChange: (slide) => setSlideshowProgress(view, slide, setup.sourceKey), onExit: () => { if (runtime.presentations.get(view) === controller) { runtime.presentations.delete(view); } }, openSidepanel: () => openSlideshowSidepanel(context, setup.sourceKey) }); runtime.presentations.set(view, controller); setSlideshowProgress(view, initialSlide, setup.sourceKey); try { await controller.start(); } catch (error) { if (runtime.presentations.get(view) === controller) { runtime.presentations.delete(view); } throw error; } } async function printSlideshowPresentation(context, presentationSource, event) { const { ea: ea2, view, config, t } = context; ea2.setView(view); if (view.isDirty()) await view.forceSave(true); const api = ea2.getExcalidrawAPI(); if (!api) { new Notice(t("cannotAccessView")); return; } const choices = resolveSlideDeckChoices(ea2); const resolved = presentationSource === "line" ? choices.line : presentationSource === "frame" ? choices.frame : resolvePresentationSource(choices, presentationSource); if (!resolved) { new Notice(t("allSlidesExcluded")); return; } await printSlideshowToPdf({ event, ea: ea2, api, choices, sourceKey: presentationSource === "line" ? choices.lines[0].key : presentationSource, printSlideWidth: config.printSlideWidth, printSlideHeight: config.printSlideHeight, maxZoom: config.maxZoom, t }); } async function openSlideshowSidepanel(context, preferredSource, preferredSlideId, reassertActiveTab = false) { const runtime = getSlideshowRuntime(); await runtime.presentations.get(context.view)?.exit(); if (runtime.sidepanel) { await runtime.sidepanel.activate( context.view, preferredSource, preferredSlideId, reassertActiveTab ); return; } const existing = context.ea.checkForActiveSidepanelTabForScript(); if (existing) { existing.close(); } context.ea.setView(context.view); const tab = await context.ea.createSidepanelTab(context.t("sidepanelTitle"), false, true); if (!tab) return; const sidepanel = new SlideshowSidepanel({ ea: context.ea, tab, t: context.t, icons: getSlideshowIcons(context.ea), config: context.config, onClosed: () => { if (runtime.sidepanel?.activate === handle.activate) runtime.sidepanel = null; }, startPresentation: async (presentationSourceKey, launchOptions) => { const boundView = sidepanel.getBoundView(); if (!boundView) return; const boundContext = getSlideshowViewContext(boundView); if (!boundContext) return; Object.assign(boundContext.config, context.config); await startSlideshowPresentation(boundContext, { presentationSourceKey, ...launchOptions }); }, printPresentation: async (presentationSourceKey, event) => { const boundView = sidepanel.getBoundView(); if (!boundView) return; const boundContext = getSlideshowViewContext(boundView); if (!boundContext) return; Object.assign(boundContext.config, context.config); await printSlideshowPresentation(boundContext, presentationSourceKey, event); }, exportMarkdown: async () => { const boundView = sidepanel.getBoundView(); if (!boundView) return; const boundContext = getSlideshowViewContext(boundView); if (!boundContext) return; boundContext.ea.setView(boundView); const deck = resolveSlideDeckChoices(boundContext.ea).frame?.deck; if (deck) await exportSlideshowMarkdown(boundContext, deck); } }); const handle = { activate: async (view, source, slideId, shouldReassertActiveTab = false) => { await sidepanel.activate(view, source, slideId); tab.open(); sidepanel.revealRequestedSlide(); sidepanel.refreshPreviewsOnce(); if (!shouldReassertActiveTab) return; await sleepInWindow(view.ownerWindow, 250); if (runtime.sidepanel?.activate !== handle.activate || tab.isActiveTab()) return; tab.focus(); sidepanel.revealRequestedSlide(); } }; runtime.sidepanel = handle; sidepanel.initialize(); await handle.activate( context.view, preferredSource, preferredSlideId, reassertActiveTab ); } async function runManualSlideshowInvocation(context, modifiers = context.view.modifierKeyDown) { const active = getSlideshowRuntime().presentations.get(context.view); const intent = resolveManualInvocationIntent(modifiers); if (active && !intent.resume && !intent.openSidepanel) { active.advance(); return; } const selectedSourceKey = await ensureManualSlideshowDeclaration(context); if (intent.openSidepanel) { await openSlideshowSidepanel(context, selectedSourceKey); return; } context.ea.setView(context.view); const preferences = loadSlideshowLaunchPreferences(context.ea); const choices = resolveSlideDeckChoices(context.ea); const savedSource = loadSlideshowPresentationSource(context.ea, context.view.file.path); const preferredSourceKey = chooseManualPresentationSourceKey( choices, selectedSourceKey, savedSource, preferences.presentationType ); const ownerWindow = context.view.ownerWindow; const displays = context.ea.DEVICE.isMobile ? [] : getAvailableDisplays(ownerWindow); const openPresenterView = !context.ea.DEVICE.isMobile && preferences.notesMode === "presenter" && displays.length > 1; const launch = { resume: intent.resume, startFullscreen: intent.startFullscreen, openPresenterView, ...preferredSourceKey === void 0 ? {} : { presentationSourceKey: preferredSourceKey } }; if (openPresenterView) { const deviceKey = getSlideshowDeviceKey(ownerWindow); const configurationKey = getSlideshowDisplayConfigurationKey(displays); const savedDisplays = loadSlideshowDisplayPreferences( context.ea, deviceKey, configurationKey ); const defaults = chooseDefaultDisplayTargets(displays, getCurrentDisplayId(ownerWindow)); const presentationDisplayId = savedDisplays ? resolveSlideshowDisplayTarget( displays, savedDisplays.presentationDisplayId, savedDisplays.presentationDisplayIdentity ) ?? defaults.presentationDisplayId : defaults.presentationDisplayId; const presenterDisplayId = savedDisplays ? resolveSlideshowDisplayTarget( displays, savedDisplays.presenterDisplayId, savedDisplays.presenterDisplayIdentity ) ?? defaults.presenterDisplayId : defaults.presenterDisplayId; if (presentationDisplayId !== null) launch.presentationDisplayId = presentationDisplayId; if (presenterDisplayId !== null) launch.presenterDisplayId = presenterDisplayId; } await startSlideshowPresentation(context, launch); } // src/scripts/slideshow/run.ts async function runSlideshow(scriptEa, scriptUtils, config) { const t = createSlideshowTranslator(scriptEa.obsidian.moment.locale()); if (!scriptEa.verifyMinimumPluginVersion("2.27.0")) { new Notice(t("requiresNewerVersion")); return; } const targetView = scriptEa.targetView; if (!targetView) return; const manualModifiers = scriptUtils.executionSource === "manual" ? { ...targetView.modifierKeyDown } : void 0; const context = { ea: scriptEa, utils: scriptUtils, view: targetView, config, t }; const wasKnown = registerSlideshowViewContext(context); if (!wasKnown) registerSlideshowElementActionProvider(context); await scriptEa.registerAutostart(t("autostartExplanation")); if (scriptUtils.executionSource !== "manual") return; await runManualSlideshowInvocation(context, manualModifiers); } // src/scripts/slideshow/main.ts void runSlideshow(ea, utils, loadSlideshowConfig(ea)); })(); /* end of bundle */