@kortix/ui 0.15.8 → 0.15.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/_vendor/kortix-shared.js +4 -1
  2. package/dist/access/access/access-dialog-share.js +12 -6
  3. package/dist/access/access/share-selection.d.ts +9 -0
  4. package/dist/access/access/share-selection.js +64 -0
  5. package/dist/customize/connectors/connector-identity.js +3 -3
  6. package/dist/customize/connectors/detail/app-page.js +2 -2
  7. package/dist/customize/connectors/detail/connector-accounts.d.ts +3 -1
  8. package/dist/customize/connectors/detail/connector-accounts.js +2 -2
  9. package/dist/customize/connectors/detail/connector-notice-view.d.ts +4 -0
  10. package/dist/customize/connectors/detail/connector-notice-view.js +4 -0
  11. package/dist/customize/connectors/detail/connector-notice.d.ts +31 -4
  12. package/dist/customize/connectors/detail/connector-notice.js +23 -4
  13. package/dist/customize/connectors/detail/connector-page.js +27 -7
  14. package/dist/customize/connectors/detail/connector-status.d.ts +12 -1
  15. package/dist/customize/connectors/detail/connector-status.js +11 -0
  16. package/dist/customize/connectors/detail/status-badge.d.ts +3 -3
  17. package/dist/customize/connectors/detail/status-badge.js +2 -1
  18. package/dist/customize/connectors/detail/use-connector-detail.js +10 -2
  19. package/dist/customize/connectors/detail/use-mcp-oauth-sign-in.d.ts +13 -0
  20. package/dist/customize/connectors/detail/use-mcp-oauth-sign-in.js +29 -0
  21. package/dist/customize/providers/provider-accordion.js +5 -4
  22. package/dist/customize/providers/provider-connect.js +3 -1
  23. package/dist/customize/providers/provider-sheet.js +9 -4
  24. package/dist/customize/sections/component/email-connect-form.js +4 -2
  25. package/dist/customize/sections/connectors-view.d.ts +4 -1
  26. package/dist/customize/sections/connectors-view.js +42 -7
  27. package/dist/customize/sections/view/account-secret-resources-panel.d.ts +15 -0
  28. package/dist/customize/sections/view/account-secret-resources-panel.js +44 -5
  29. package/dist/customize/sections/view/secret-delivery.d.ts +9 -2
  30. package/dist/customize/sections/view/secret-delivery.js +14 -4
  31. package/dist/customize/sections/view/secrets-view.js +21 -5
  32. package/dist/customize/triggers/schedule/schedule-builder.js +1 -1
  33. package/dist/customize/triggers/schedule/schedule-copy.js +4 -0
  34. package/dist/customize/triggers/schedule/schedule-detail-sheet.js +14 -3
  35. package/dist/customize/triggers/schedule/then-fields.d.ts +3 -1
  36. package/dist/customize/triggers/schedule/then-fields.js +8 -4
  37. package/dist/customize/triggers/schedule/trigger-composer.js +1 -1
  38. package/dist/customize/triggers/schedule/trigger-list.d.ts +3 -1
  39. package/dist/customize/triggers/schedule/trigger-list.js +18 -2
  40. package/dist/customize/triggers/schedule/trigger-runs-logic.js +4 -2
  41. package/dist/customize/triggers/schedule/trigger-runs-panel.js +4 -1
  42. package/dist/files/renderers/pptx-renderer.js +5 -20
  43. package/dist/files/renderers/presentation/FullScreenPresentationViewer.d.ts +3 -2
  44. package/dist/files/renderers/presentation/FullScreenPresentationViewer.js +23 -304
  45. package/dist/files/renderers/presentation/presentation-export-menu.d.ts +14 -0
  46. package/dist/files/renderers/presentation/presentation-export-menu.js +44 -0
  47. package/dist/files/renderers/presentation/presentation-utils.d.ts +1 -0
  48. package/dist/files/renderers/presentation/presentation-utils.js +4 -0
  49. package/dist/files/renderers/presentation/slide-iframe.d.ts +23 -0
  50. package/dist/files/renderers/presentation/slide-iframe.js +61 -0
  51. package/dist/files/renderers/presentation/use-presentation-metadata.d.ts +39 -0
  52. package/dist/files/renderers/presentation/use-presentation-metadata.js +137 -0
  53. package/dist/files/renderers/presentation/use-slide-navigation.d.ts +17 -0
  54. package/dist/files/renderers/presentation/use-slide-navigation.js +82 -0
  55. package/dist/files/renderers/shared/use-stage-fit-scale.d.ts +19 -0
  56. package/dist/files/renderers/shared/use-stage-fit-scale.js +41 -0
  57. package/dist/files/renderers/show-content-renderer.js +16 -11
  58. package/dist/files/renderers/xlsx/xlsx-renderer.d.ts +4 -13
  59. package/dist/files/renderers/xlsx/xlsx-renderer.js +6 -63
  60. package/dist/files/renderers/xlsx/xlsx-viewer.d.ts +4 -2
  61. package/dist/files/renderers/xlsx/xlsx-viewer.js +28 -34
  62. package/dist/files/viewer/file-content-renderer.js +1 -4
  63. package/dist/files/viewer/use-file-content-state.js +10 -9
  64. package/dist/i18n/en.d.ts +48 -0
  65. package/dist/i18n/en.js +51 -3
  66. package/dist/internal/chrome/use-chrome-offered.d.ts +2 -1
  67. package/dist/internal/chrome/use-chrome-offered.js +4 -2
  68. package/dist/internal/hooks/connectors/use-finish-sign-in.d.ts +13 -0
  69. package/dist/internal/hooks/connectors/use-finish-sign-in.js +33 -0
  70. package/dist/internal/hooks/connectors/use-pipedream-connect-member.js +6 -1
  71. package/dist/internal/hooks/connectors/use-pipedream-connect-project.js +6 -1
  72. package/dist/internal/lib/error-handler.js +33 -0
  73. package/dist/internal/lib/trigger-clock.d.ts +7 -2
  74. package/dist/internal/lib/trigger-clock.js +17 -3
  75. package/dist/lib/z-stack.d.ts +5 -1
  76. package/dist/lib/z-stack.js +12 -2
  77. package/dist/session/models/model-connection-gate.js +16 -3
  78. package/dist/session/models/model-picker-panel.js +6 -2
  79. package/dist/session/models/provider-key-action.d.ts +10 -0
  80. package/dist/session/models/provider-key-action.js +35 -0
  81. package/dist/session/models/provider-key-slot.d.ts +9 -0
  82. package/dist/session/models/provider-key-slot.js +19 -0
  83. package/dist/session/prompts/session-connect-prompt.d.ts +40 -0
  84. package/dist/session/prompts/session-connect-prompt.js +126 -0
  85. package/dist/session/status/session-error-banner.d.ts +1 -1
  86. package/dist/session/status/session-error-banner.js +12 -4
  87. package/dist/session/thread/session-chat.js +7 -2
  88. package/dist/session/thread/transcript.js +31 -7
  89. package/dist/test-utils/intl.d.ts +48 -0
  90. package/package.json +3 -3
@@ -0,0 +1,137 @@
1
+ 'use client';
2
+ import { buildStaticFilePreviewUrl as constructHtmlPreviewUrl } from '@kortix/sdk';
3
+ import { useCallback, useEffect, useRef, useState } from 'react';
4
+ import { useSandboxProxy } from '../../../internal/hooks/use-sandbox-proxy.js';
5
+ import { sanitizeFilename } from './presentation-utils.js';
6
+ /**
7
+ * The fullscreen viewer's metadata lifecycle: the fetch (with cache busting),
8
+ * its unbounded retry with exponential backoff, the reload when the modal
9
+ * opens and when the editor closes, and the cleanup of a pending retry.
10
+ */
11
+ export function usePresentationMetadata({ isOpen, presentationName, sandboxUrl, showEditor, }) {
12
+ const { subdomainOpts } = useSandboxProxy();
13
+ const [metadata, setMetadata] = useState(null);
14
+ const [isLoading, setIsLoading] = useState(false);
15
+ const [retryAttempt, setRetryAttempt] = useState(0);
16
+ const retryTimeoutRef = useRef(null);
17
+ const hasLoadedRef = useRef(false);
18
+ // Track the previous isOpen state to detect when modal opens
19
+ const wasOpenRef = useRef(false);
20
+ // Load metadata with retry logic
21
+ const loadMetadata = useCallback(async (retryCount = 0, maxRetries = Infinity) => {
22
+ // Don't load if we already successfully loaded metadata
23
+ if (hasLoadedRef.current) {
24
+ return;
25
+ }
26
+ // If sandbox URL isn't available yet, wait and don't set loading state
27
+ if (!presentationName || !sandboxUrl) {
28
+ setIsLoading(false);
29
+ return;
30
+ }
31
+ setIsLoading(true);
32
+ setRetryAttempt(retryCount);
33
+ try {
34
+ // Sanitize the presentation name to match backend directory creation
35
+ const sanitizedPresentationName = sanitizeFilename(presentationName);
36
+ const metadataUrl = constructHtmlPreviewUrl(`presentations/${sanitizedPresentationName}/metadata.json`, subdomainOpts);
37
+ const urlWithCacheBust = `${metadataUrl}?t=${Date.now()}`;
38
+ console.log(`Loading presentation metadata (attempt ${retryCount + 1}):`, urlWithCacheBust);
39
+ const response = await fetch(urlWithCacheBust, {
40
+ cache: 'no-cache',
41
+ headers: { 'Cache-Control': 'no-cache' },
42
+ });
43
+ if (response.ok) {
44
+ const data = await response.json();
45
+ setMetadata(data);
46
+ hasLoadedRef.current = true; // Mark as successfully loaded
47
+ console.log('Successfully loaded presentation metadata:', data);
48
+ setIsLoading(false);
49
+ // Clear any pending retry timeout on success
50
+ if (retryTimeoutRef.current) {
51
+ clearTimeout(retryTimeoutRef.current);
52
+ retryTimeoutRef.current = null;
53
+ }
54
+ return; // Success, exit early
55
+ }
56
+ else {
57
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
58
+ }
59
+ }
60
+ catch (err) {
61
+ console.error(`Error loading metadata (attempt ${retryCount + 1}):`, err);
62
+ // Calculate delay with exponential backoff, capped at 10 seconds
63
+ // For early attempts, use shorter delays. After 5 attempts, use consistent 5 second intervals
64
+ const delay = retryCount < 5
65
+ ? Math.min(1000 * Math.pow(2, retryCount), 10000) // Exponential backoff for first 5 attempts
66
+ : 5000; // Consistent 5 second intervals after that
67
+ console.log(`Retrying in ${delay}ms... (attempt ${retryCount + 1})`);
68
+ // Keep retrying indefinitely - don't set error state
69
+ retryTimeoutRef.current = setTimeout(() => {
70
+ loadMetadata(retryCount + 1, maxRetries);
71
+ }, delay);
72
+ return; // Keep loading state, don't set error
73
+ }
74
+ }, [presentationName, sandboxUrl, subdomainOpts]);
75
+ // Sync metadata with the modal state: an open resets the loaded flag and
76
+ // starts (or restarts) the load, a close stops a pending retry.
77
+ useEffect(() => {
78
+ const justOpened = isOpen && !wasOpenRef.current;
79
+ wasOpenRef.current = isOpen;
80
+ if (justOpened) {
81
+ // Reset loaded flag when opening (so we can reload if needed)
82
+ hasLoadedRef.current = false;
83
+ // Clear any existing retry timeout when opening
84
+ if (retryTimeoutRef.current) {
85
+ clearTimeout(retryTimeoutRef.current);
86
+ retryTimeoutRef.current = null;
87
+ }
88
+ // Only start loading if we have the required data
89
+ if (presentationName && sandboxUrl) {
90
+ loadMetadata();
91
+ }
92
+ else {
93
+ setIsLoading(false);
94
+ }
95
+ }
96
+ else if (!isOpen) {
97
+ // Clear retry timeout when closing
98
+ if (retryTimeoutRef.current) {
99
+ clearTimeout(retryTimeoutRef.current);
100
+ retryTimeoutRef.current = null;
101
+ }
102
+ }
103
+ }, [isOpen, presentationName, sandboxUrl, loadMetadata]);
104
+ // Cleanup retry timeout on unmount
105
+ useEffect(() => {
106
+ return () => {
107
+ if (retryTimeoutRef.current) {
108
+ clearTimeout(retryTimeoutRef.current);
109
+ }
110
+ };
111
+ }, []);
112
+ // The slide list, ordered by slide number, as the pager and the stage read it
113
+ const slides = metadata
114
+ ? Object.entries(metadata.slides)
115
+ .map(([num, slide]) => ({ number: parseInt(num), ...slide }))
116
+ .sort((a, b) => a.number - b.number)
117
+ : [];
118
+ // Reload metadata when exiting editor mode to refresh with latest changes
119
+ useEffect(() => {
120
+ let timeoutId;
121
+ if (!showEditor && isOpen) {
122
+ // Reset loaded flag so we can reload after editor changes
123
+ hasLoadedRef.current = false;
124
+ // Add a small delay to allow the editor to save changes
125
+ timeoutId = setTimeout(() => {
126
+ loadMetadata();
127
+ }, 300);
128
+ }
129
+ return () => {
130
+ if (timeoutId) {
131
+ clearTimeout(timeoutId);
132
+ }
133
+ };
134
+ // eslint-disable-next-line react-hooks/exhaustive-deps
135
+ }, [showEditor, isOpen]);
136
+ return { metadata, slides, isLoading, retryAttempt, subdomainOpts };
137
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Which slide is showing and how it changes: the initial-slide sync on open,
3
+ * the pager transitions, and the fullscreen keyboard map.
4
+ */
5
+ export declare function useSlideNavigation({ isOpen, initialSlide, totalSlides, showEditor, onExitEditor, onClose, }: {
6
+ isOpen: boolean;
7
+ initialSlide: number;
8
+ totalSlides: number;
9
+ showEditor: boolean;
10
+ onExitEditor: () => void;
11
+ onClose: () => void;
12
+ }): {
13
+ currentSlide: number;
14
+ setCurrentSlide: import("react").Dispatch<import("react").SetStateAction<number>>;
15
+ goToNextSlide: () => void;
16
+ goToPreviousSlide: () => void;
17
+ };
@@ -0,0 +1,82 @@
1
+ 'use client';
2
+ import { useCallback, useEffect, useRef, useState } from 'react';
3
+ /**
4
+ * Which slide is showing and how it changes: the initial-slide sync on open,
5
+ * the pager transitions, and the fullscreen keyboard map.
6
+ */
7
+ export function useSlideNavigation({ isOpen, initialSlide, totalSlides, showEditor, onExitEditor, onClose, }) {
8
+ const [currentSlide, setCurrentSlide] = useState(initialSlide);
9
+ // Track the previous isOpen state to detect when modal opens
10
+ const wasOpenRef = useRef(false);
11
+ // Sync currentSlide with initialSlide when modal opens (not on every initialSlide change)
12
+ useEffect(() => {
13
+ const justOpened = isOpen && !wasOpenRef.current;
14
+ wasOpenRef.current = isOpen;
15
+ if (justOpened) {
16
+ // Modal just opened - set the slide to the requested initial slide
17
+ setCurrentSlide(initialSlide);
18
+ }
19
+ }, [isOpen, initialSlide]);
20
+ // Navigation functions
21
+ const goToNextSlide = useCallback(() => {
22
+ if (currentSlide < totalSlides) {
23
+ setCurrentSlide((prev) => prev + 1);
24
+ }
25
+ }, [currentSlide, totalSlides]);
26
+ const goToPreviousSlide = useCallback(() => {
27
+ if (currentSlide > 1) {
28
+ setCurrentSlide((prev) => prev - 1);
29
+ }
30
+ }, [currentSlide]);
31
+ // Keyboard navigation
32
+ useEffect(() => {
33
+ if (!isOpen)
34
+ return;
35
+ const handleKeyDown = (e) => {
36
+ // Prevent default for all our handled keys
37
+ const handledKeys = [
38
+ 'ArrowLeft',
39
+ 'ArrowRight',
40
+ 'ArrowUp',
41
+ 'ArrowDown',
42
+ ' ',
43
+ 'Home',
44
+ 'End',
45
+ 'Escape',
46
+ ];
47
+ if (handledKeys.includes(e.key)) {
48
+ e.preventDefault();
49
+ e.stopPropagation();
50
+ }
51
+ switch (e.key) {
52
+ case 'ArrowLeft':
53
+ case 'ArrowUp':
54
+ goToPreviousSlide();
55
+ break;
56
+ case 'ArrowRight':
57
+ case 'ArrowDown':
58
+ case ' ':
59
+ goToNextSlide();
60
+ break;
61
+ case 'Home':
62
+ setCurrentSlide(1);
63
+ break;
64
+ case 'End':
65
+ setCurrentSlide(totalSlides);
66
+ break;
67
+ case 'Escape':
68
+ if (showEditor) {
69
+ onExitEditor();
70
+ }
71
+ else {
72
+ onClose();
73
+ }
74
+ break;
75
+ }
76
+ };
77
+ // Add event listener to document with capture to ensure we get the events first
78
+ document.addEventListener('keydown', handleKeyDown, true);
79
+ return () => document.removeEventListener('keydown', handleKeyDown, true);
80
+ }, [isOpen, goToNextSlide, goToPreviousSlide, totalSlides, onClose, showEditor, onExitEditor]);
81
+ return { currentSlide, setCurrentSlide, goToNextSlide, goToPreviousSlide };
82
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Scales a fixed-size stage to fit the element this is bound to, keeping the
3
+ * stage's aspect ratio: the smaller of the width and height ratios (width
4
+ * only, when the stage has no fixed height), capped at 1 unless
5
+ * `allowUpscale` is set.
6
+ */
7
+ export declare function fitScale(containerWidth: number, containerHeight: number, stageWidth: number, stageHeight: number | undefined, allowUpscale: boolean): number;
8
+ /**
9
+ * Scales the fixed-size stage down to fit a narrower viewport — never up,
10
+ * unless `allowUpscale` is set (the presentation slide follows its container
11
+ * in both directions; the pptx desktop stage only shrinks).
12
+ * Uses a callback ref (rather than a plain `useRef`) so the observer
13
+ * attaches exactly when the viewport element mounts — it doesn't exist yet on
14
+ * first render, since the viewer only appears once the file bytes finish
15
+ * loading.
16
+ */
17
+ export declare function useStageFitScale(stageWidth: number, stageHeight: number | undefined, options: {
18
+ allowUpscale: boolean;
19
+ }): [(node: HTMLDivElement | null) => void, number];
@@ -0,0 +1,41 @@
1
+ import { useLayoutEffect, useState } from 'react';
2
+ /**
3
+ * Scales a fixed-size stage to fit the element this is bound to, keeping the
4
+ * stage's aspect ratio: the smaller of the width and height ratios (width
5
+ * only, when the stage has no fixed height), capped at 1 unless
6
+ * `allowUpscale` is set.
7
+ */
8
+ export function fitScale(containerWidth, containerHeight, stageWidth, stageHeight, allowUpscale) {
9
+ // Calculate scale to fit the stage into the container while maintaining
10
+ // aspect ratio
11
+ const scale = stageHeight === undefined
12
+ ? containerWidth / stageWidth
13
+ : Math.min(containerWidth / stageWidth, containerHeight / stageHeight);
14
+ return allowUpscale ? scale : Math.min(1, scale);
15
+ }
16
+ /**
17
+ * Scales the fixed-size stage down to fit a narrower viewport — never up,
18
+ * unless `allowUpscale` is set (the presentation slide follows its container
19
+ * in both directions; the pptx desktop stage only shrinks).
20
+ * Uses a callback ref (rather than a plain `useRef`) so the observer
21
+ * attaches exactly when the viewport element mounts — it doesn't exist yet on
22
+ * first render, since the viewer only appears once the file bytes finish
23
+ * loading.
24
+ */
25
+ export function useStageFitScale(stageWidth, stageHeight, options) {
26
+ const { allowUpscale } = options;
27
+ const [node, setNode] = useState(null);
28
+ const [scale, setScale] = useState(1);
29
+ useLayoutEffect(() => {
30
+ if (!node || typeof ResizeObserver === 'undefined')
31
+ return;
32
+ const observer = new ResizeObserver((entries) => {
33
+ const width = entries[0]?.contentRect.width ?? node.clientWidth;
34
+ const height = stageHeight === undefined ? undefined : (entries[0]?.contentRect.height ?? node.clientHeight);
35
+ setScale(fitScale(width, height ?? 0, stageWidth, stageHeight, allowUpscale));
36
+ });
37
+ observer.observe(node);
38
+ return () => observer.disconnect();
39
+ }, [node, stageWidth, stageHeight, allowUpscale]);
40
+ return [setNode, scale];
41
+ }
@@ -6,7 +6,7 @@ import { useTranslations } from '../../i18n/index.js';
6
6
  * show tool content inline in the session chat and side panel.
7
7
  *
8
8
  * Architecture:
9
- * Binary files (image, video, audio, docx, pptx)
9
+ * Binary files (image, video, audio, docx, pptx, xlsx)
10
10
  * → loaded via useBinaryBlob (/file/raw endpoint, direct binary fetch)
11
11
  * → rendered with shared leaf renderers (ImageRenderer, PdfRenderer, etc.)
12
12
  *
@@ -14,9 +14,6 @@ import { useTranslations } from '../../i18n/index.js';
14
14
  * → loaded via useFileContent (SDK text read)
15
15
  * → rendered with CsvRenderer
16
16
  *
17
- * Self-loading (xlsx)
18
- * → XlsxRenderer handles its own data loading
19
- *
20
17
  * Generic file (json, yaml, ts, py, etc.)
21
18
  * → delegated to FileContentRenderer (handles text/code rendering)
22
19
  *
@@ -136,7 +133,7 @@ function isLocalSandboxFilePath(value) {
136
133
  return value.startsWith('/') || sessionDriveMountPath(value) !== null;
137
134
  }
138
135
  /** Types loaded via useBinaryBlob (/file/raw, direct binary fetch) */
139
- const BLOB_TYPES = new Set(['image', 'video', 'audio', 'docx', 'pptx']);
136
+ const BLOB_TYPES = new Set(['image', 'video', 'audio', 'docx', 'pptx', 'xlsx']);
140
137
  /**
141
138
  * Where a show's binary viewer reads its bytes from, or null for no blob read.
142
139
  *
@@ -328,7 +325,8 @@ export function ShowContentRenderer({ type, title = '', description = '', path:
328
325
  return null;
329
326
  // Binary/media types backed by useBinaryBlob — and a PDF whose stored copy
330
327
  // is read the same way.
331
- if ((isImage || isVideo || isAudio || isDocx || isPptx || (isPdf && storedCopy)) && path) {
328
+ if ((isImage || isVideo || isAudio || isDocx || isPptx || isXlsx || (isPdf && storedCopy)) &&
329
+ path) {
332
330
  if (blobError)
333
331
  return 'error';
334
332
  if (blobLoading || (isImage && heicConverting))
@@ -346,8 +344,8 @@ export function ShowContentRenderer({ type, title = '', description = '', path:
346
344
  // CSV backed by useFileContent (text).
347
345
  if (isCsv && path)
348
346
  return csvLoading ? 'loading' : 'ready';
349
- // Everything else (url link, xlsx self-loading, code/markdown/text/html/
350
- // error, localhost/html iframe, fallback) renders without a fetch we track.
347
+ // Everything else (url link, code/markdown/text/html/error, localhost/html
348
+ // iframe, fallback) renders without a fetch we track.
351
349
  return 'ready';
352
350
  }, [
353
351
  effectiveType,
@@ -489,10 +487,17 @@ export function ShowContentRenderer({ type, title = '', description = '', path:
489
487
  return _jsx(FileCard, { title: title, fileName: fileName, path: path });
490
488
  }
491
489
  // ═════════════════════════════════════════════════════════════════════════
492
- // XLSX — XlsxRenderer (self-loading via filePath prop)
490
+ // XLSX — loaded via useBinaryBlob → rawBlob → XlsxRenderer
493
491
  // ═════════════════════════════════════════════════════════════════════════
494
- if (isXlsx && path && sandboxPath) {
495
- return (_jsx(Suspense, { fallback: _jsx(RendererFallback, { className: mediaH }), children: _jsx("div", { className: cn(mediaH, 'overflow-hidden'), children: framed(_jsx(XlsxRenderer, { filePath: sandboxPath, fileName: fileName, className: "h-full", ...viewerChrome })) }) }));
492
+ if (isXlsx && path) {
493
+ if (blobLoading)
494
+ return _jsx(RendererFallback, { className: mediaH });
495
+ if (blobError)
496
+ return _jsx(LoadError, { message: blobError });
497
+ if (rawBlob) {
498
+ return (_jsx(Suspense, { fallback: _jsx(RendererFallback, { className: mediaH }), children: _jsx("div", { className: cn(mediaH, 'overflow-hidden'), children: framed(_jsx(XlsxRenderer, { blob: rawBlob, fileName: fileName, className: "h-full", ...viewerChrome })) }) }));
499
+ }
500
+ return (_jsx(FileCard, { title: title || tI18nComplete.raw('text1931491100e0'), fileName: fileName, path: path }));
496
501
  }
497
502
  // ═════════════════════════════════════════════════════════════════════════
498
503
  // DOCX — loaded via useBinaryBlob → rawBlob → DocxRenderer
@@ -1,25 +1,16 @@
1
- export declare function isBlobUrl(path: string): boolean;
2
1
  interface XlsxRendererProps {
3
- content?: string | null;
4
- filePath?: string;
2
+ /** The workbook bytes. The parent owns the read (useBinaryBlob), like it
3
+ * does for the docx and pptx viewers — this renderer never reads a path. */
4
+ blob?: Blob | null;
5
5
  fileName: string;
6
6
  /** Extra controls for the viewer's own toolbar, rendered after zoom and
7
7
  * before the file menu. */
8
8
  compact?: boolean;
9
9
  toolbarActions?: React.ReactNode;
10
10
  className?: string;
11
- sandboxId?: string;
12
- project?: {
13
- sandbox?: {
14
- id?: string;
15
- sandbox_url?: string;
16
- };
17
- };
18
- onDownload?: () => void;
19
- isDownloading?: boolean;
20
11
  /** False when the host's own toolbar already has the Download button, so the
21
12
  * viewer does not show a second one. */
22
13
  showDownload?: boolean;
23
14
  }
24
- export declare function XlsxRenderer({ filePath, fileName, className, compact, toolbarActions, showDownload, }: XlsxRendererProps): import("react").JSX.Element;
15
+ export declare function XlsxRenderer({ blob, fileName, className, compact, toolbarActions, showDownload, }: XlsxRendererProps): import("react").JSX.Element;
25
16
  export {};
@@ -1,72 +1,15 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { Button } from '../../../primitives/button.js';
4
- import { KortixLoader } from '../../../primitives/kortix-loader.js';
5
- import { readRuntimeFileWithRetry } from '../../../internal/files/runtime-file-read.js';
6
- import { cn } from '../../../lib/utils.js';
7
- import { FileXlsIcon as FileSpreadsheet, ArrowClockwiseIcon as RefreshCw, } from '@phosphor-icons/react';
3
+ import { FileXlsIcon as FileSpreadsheet } from '@phosphor-icons/react';
8
4
  import { useTranslations } from '../../../i18n/index.js';
9
5
  import { useIsDark } from '../../../hooks/use-is-dark.js';
10
- import { useCallback, useEffect, useState } from 'react';
6
+ import { cn } from '../../../lib/utils.js';
11
7
  import { XlsxViewerPreview } from './xlsx-viewer.js';
12
- export function isBlobUrl(path) {
13
- return path.startsWith('blob:');
14
- }
15
- export function XlsxRenderer({ filePath, fileName, className, compact = false, toolbarActions, showDownload = true, }) {
8
+ export function XlsxRenderer({ blob, fileName, className, compact = false, toolbarActions, showDownload = true, }) {
16
9
  const tI18nComplete = useTranslations('hardcodedUi.i18nComplete');
17
10
  const isDark = useIsDark();
18
- const [src, setSrc] = useState(null);
19
- const [error, setError] = useState(null);
20
- const [attempt, setAttempt] = useState(0);
21
- const xlsxPath = filePath || fileName;
22
- useEffect(() => {
23
- if (!xlsxPath)
24
- return;
25
- let cancelled = false;
26
- let objectUrl = null;
27
- const abortController = new AbortController();
28
- setSrc(null);
29
- setError(null);
30
- (async () => {
31
- try {
32
- if (isBlobUrl(xlsxPath)) {
33
- if (!cancelled)
34
- setSrc(xlsxPath);
35
- return;
36
- }
37
- const { readFileAsBlob } = await import('../../../internal/files/runtime-files.js');
38
- const blob = await readRuntimeFileWithRetry(xlsxPath, async () => {
39
- const blob = await readFileAsBlob(xlsxPath);
40
- if (!blob || blob.size === 0)
41
- throw new Error('Empty file received');
42
- return blob;
43
- }, undefined, abortController.signal);
44
- if (cancelled)
45
- return;
46
- objectUrl = URL.createObjectURL(blob);
47
- setSrc(objectUrl);
48
- }
49
- catch (e) {
50
- if (abortController.signal.aborted)
51
- return;
52
- console.error('[XlsxRenderer] Error:', e);
53
- if (!cancelled)
54
- setError(e instanceof Error ? e.message : 'Failed to load spreadsheet');
55
- }
56
- })();
57
- return () => {
58
- cancelled = true;
59
- abortController.abort();
60
- if (objectUrl)
61
- URL.revokeObjectURL(objectUrl);
62
- };
63
- }, [xlsxPath, attempt]);
64
- const handleRetry = useCallback(() => setAttempt((n) => n + 1), []);
65
- if (error) {
66
- return (_jsx("div", { className: cn('flex h-full w-full items-center justify-center', className), children: _jsxs("div", { className: "space-y-3 text-center", children: [_jsx("div", { className: "bg-muted mx-auto flex h-16 w-16 items-center justify-center rounded-full", children: _jsx(FileSpreadsheet, { className: "text-muted-foreground h-8 w-8" }) }), _jsxs("div", { children: [_jsx("h3", { className: "text-foreground text-lg font-medium", children: tI18nComplete.raw('text29f7878c46b4') }), _jsx("p", { className: "text-muted-foreground mt-1 text-xs", children: error })] }), _jsxs(Button, { onClick: handleRetry, variant: "outline", size: "sm", children: [_jsx(RefreshCw, { className: "mr-2 h-3 w-3" }), tI18nComplete.raw('text942087cc2d41')] })] }) }));
67
- }
68
- if (!src) {
69
- return (_jsx("div", { className: cn('flex h-full w-full items-center justify-center', className), children: _jsx(KortixLoader, { size: "medium" }) }));
11
+ if (!blob) {
12
+ return (_jsx("div", { className: cn('flex h-full w-full items-center justify-center', className), children: _jsxs("div", { className: "space-y-3 text-center", children: [_jsx("div", { className: "bg-muted mx-auto flex h-16 w-16 items-center justify-center rounded-full", children: _jsx(FileSpreadsheet, { className: "text-muted-foreground h-8 w-8" }) }), _jsx("div", { children: _jsx("h3", { className: "text-foreground text-lg font-medium", children: tI18nComplete.raw('text29f7878c46b4') }) })] }) }));
70
13
  }
71
- return (_jsx(XlsxViewerPreview, { src: src, fileName: fileName, isDark: isDark, onIsDarkChange: () => { }, showToolbar: !compact, showDownload: showDownload, showUpload: false, className: cn('h-full w-full', className), toolbarActions: toolbarActions }));
14
+ return (_jsx(XlsxViewerPreview, { workbook: blob, fileName: fileName, isDark: isDark, onIsDarkChange: () => { }, showToolbar: !compact, showDownload: showDownload, showUpload: false, className: cn('h-full w-full', className), toolbarActions: toolbarActions }));
72
15
  }
@@ -26,7 +26,7 @@ export declare function XlsxWorkbookSurface({ className, fileName, isDark, onDow
26
26
  toolbarActions?: React.ReactNode;
27
27
  workbookIdentity: string;
28
28
  }): React.JSX.Element;
29
- export declare function XlsxViewerPreview({ className, fileName, isDark, onIsDarkChange, showDownload, showToolbar, showUpload, src, toolbarActions, }: {
29
+ export declare function XlsxViewerPreview({ className, fileName, isDark, onIsDarkChange, showDownload, showToolbar, showUpload, workbook, toolbarActions, }: {
30
30
  className?: string;
31
31
  fileName?: string;
32
32
  isDark: boolean;
@@ -34,6 +34,8 @@ export declare function XlsxViewerPreview({ className, fileName, isDark, onIsDar
34
34
  showDownload?: boolean;
35
35
  showToolbar?: boolean;
36
36
  showUpload?: boolean;
37
- src?: string;
37
+ /** The workbook bytes. The parent owns the read (useBinaryBlob); the viewer
38
+ * only decodes them. */
39
+ workbook?: Blob | null;
38
40
  toolbarActions?: React.ReactNode;
39
41
  }): React.JSX.Element;
@@ -5,6 +5,7 @@ import { setWasmSource, useXlsxViewer, useXlsxViewerController, useXlsxViewerThu
5
5
  import { CaretLeftIcon as ChevronLeft, CaretRightIcon as ChevronRight, MinusCircleIcon as CircleMinus, PlusCircleIcon as CirclePlus, DotsThreeIcon as Ellipsis, MagnifyingGlassIcon as Search, UploadIcon as Upload, } from '@phosphor-icons/react';
6
6
  import * as React from 'react';
7
7
  import { createPortal } from 'react-dom';
8
+ import { downloadBlob } from '../../../internal/lib/utils/download.js';
8
9
  import { Button } from '../../../primitives/button.js';
9
10
  import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger, } from '../../../primitives/dropdown-menu.js';
10
11
  import { Input } from '../../../primitives/input.js';
@@ -51,17 +52,22 @@ const XLSX_SHEET_TAB_THUMBNAIL_OPTIONS = {
51
52
  maxWidth: 560,
52
53
  },
53
54
  };
54
- function formatWorkbookName(fileName, url) {
55
- if (fileName?.trim())
56
- return fileName;
57
- const pathname = url.split('?')[0] ?? '';
58
- const rawName = pathname.split('/').pop() ?? 'workbook.xlsx';
59
- try {
60
- return decodeURIComponent(rawName);
61
- }
62
- catch {
63
- return rawName;
55
+ /** The workbook Blob's own identity: the same object keeps one id, a fresh
56
+ * read (an edited file, a refetch) gets the next one, so per-workbook state
57
+ * (search, sheet tabs, zoom) resets exactly when the bytes change — the same
58
+ * remount-on-change the blob URL gave this identity before the workbook
59
+ * arrived as a Blob instead of a URL. */
60
+ const workbookIds = new WeakMap();
61
+ let nextWorkbookId = 1;
62
+ function workbookIdentity(blob) {
63
+ if (!blob)
64
+ return 'empty';
65
+ let id = workbookIds.get(blob);
66
+ if (id === undefined) {
67
+ id = nextWorkbookId++;
68
+ workbookIds.set(blob, id);
64
69
  }
70
+ return `blob-${id}`;
65
71
  }
66
72
  function ensureWorkbookExtension(fileName) {
67
73
  const lowerFileName = fileName.toLowerCase();
@@ -76,15 +82,7 @@ function downloadWorkbookBuffer(buffer, fileName) {
76
82
  ? 'application/vnd.ms-excel'
77
83
  : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
78
84
  });
79
- const url = URL.createObjectURL(blob);
80
- const anchor = document.createElement('a');
81
- anchor.href = url;
82
- anchor.download = resolvedFileName;
83
- anchor.rel = 'noopener';
84
- document.body.append(anchor);
85
- anchor.click();
86
- anchor.remove();
87
- setTimeout(() => URL.revokeObjectURL(url), 0);
85
+ downloadBlob(blob, resolvedFileName);
88
86
  }
89
87
  function normalizeSearchText(value) {
90
88
  return typeof value === 'string'
@@ -634,26 +632,26 @@ export function XlsxWorkbookSurface({ className, fileName, isDark, onDownload, o
634
632
  }, [copySelection]);
635
633
  return (_jsxs("div", { className: cn('bg-background flex h-[640px] min-h-0 flex-col overflow-hidden', className), children: [showToolbar ? (_jsx(WorkbookToolbar, { fileName: fileName, isDark: isDark, onDownload: onDownload, onIsDarkChange: onIsDarkChange, onUploadClick: onUploadClick, showDownloadButton: showDownloadButton, showNightRenderToggle: showNightRenderToggle, showUploadButton: showUploadButton, toolbarActions: toolbarActions, viewportRef: viewportRef, workbookIdentity: workbookIdentity })) : null, _jsxs("div", { className: "flex min-h-0 flex-1 flex-col", children: [_jsx(ViewerCopyMenu, { onCopy: copySelection, children: _jsx("div", { className: "bg-muted/20 min-h-0 flex-1", children: _jsx(XlsxViewer, { experimentalCanvas: true, allowResizeInReadOnly: true, className: "h-full min-h-0 min-w-0", height: "100%", isDark: isDark, readOnly: true, rounded: false, showDefaultToolbar: false, showImages: true, fileTooLargeState: _jsx("div", { className: "grid h-full w-full min-w-full place-items-center p-6", children: _jsxs("div", { className: "bg-background max-w-sm rounded-lg border p-4 text-sm", children: [_jsx("p", { className: "font-medium", children: tI18nComplete.raw('text8a2819cae213') }), _jsx("p", { className: "text-muted-foreground mt-1", children: tI18nComplete.raw('textd3821f7d63f3') })] }) }), loadingState: _jsx(ViewerLoadingSurface, {}), renderScroller: renderSearchableScroller, errorState: _jsx("div", { className: "text-destructive grid h-full w-full min-w-full place-items-center p-6 text-sm", children: error?.message ?? tI18nComplete.raw('text8d75c18adecc') }), renderTableHeaderMenu: renderTableHeaderMenu }) }) }), _jsx(WorkbookSheetTabs, { workbookIdentity: workbookIdentity })] })] }));
636
634
  }
637
- export function XlsxViewerPreview({ className, fileName, isDark, onIsDarkChange, showDownload = true, showToolbar = true, showUpload = true, src, toolbarActions, }) {
638
- return (_jsx(XlsxViewerContent, { className: className, effectiveIsDark: isDark, fileName: fileName, setNightRenderEnabled: onIsDarkChange, shouldRenderNightMode: true, showDownload: showDownload, showToolbar: showToolbar, showUpload: showUpload, toolbarActions: toolbarActions, url: src }));
635
+ export function XlsxViewerPreview({ className, fileName, isDark, onIsDarkChange, showDownload = true, showToolbar = true, showUpload = true, workbook, toolbarActions, }) {
636
+ return (_jsx(XlsxViewerContent, { className: className, effectiveIsDark: isDark, fileName: fileName, setNightRenderEnabled: onIsDarkChange, shouldRenderNightMode: true, showDownload: showDownload, showToolbar: showToolbar, showUpload: showUpload, toolbarActions: toolbarActions, workbook: workbook }));
639
637
  }
640
- function XlsxViewerContent({ className, effectiveIsDark, fileName, setNightRenderEnabled, shouldRenderNightMode, showDownload, showToolbar = true, showUpload, toolbarActions, url, }) {
638
+ function XlsxViewerContent({ className, effectiveIsDark, fileName, setNightRenderEnabled, shouldRenderNightMode, showDownload, showToolbar = true, showUpload, toolbarActions, workbook, }) {
641
639
  const tI18nComplete = useTranslations('hardcodedUi.i18nComplete');
642
640
  const fileInputRef = React.useRef(null);
643
641
  const [uploadedWorkbook, setUploadedWorkbook] = React.useState(null);
644
- const sourceFileName = React.useMemo(() => (url ? formatWorkbookName(fileName, url) : (fileName ?? 'workbook.xlsx')), [fileName, url]);
642
+ const sourceFileName = React.useMemo(() => fileName?.trim() || 'workbook.xlsx', [fileName]);
645
643
  const displayFileName = React.useMemo(() => uploadedWorkbook?.fileName ?? sourceFileName, [sourceFileName, uploadedWorkbook?.fileName]);
646
- const workbookIdentity = React.useMemo(() => uploadedWorkbook?.identity ?? `${url ?? 'empty'}::${displayFileName}`, [displayFileName, uploadedWorkbook?.identity, url]);
644
+ const identity = React.useMemo(() => uploadedWorkbook?.identity ?? workbookIdentity(workbook), [uploadedWorkbook?.identity, workbook]);
647
645
  const [workbookBuffer, setWorkbookBuffer] = React.useState(null);
648
646
  const [loadError, setLoadError] = React.useState();
649
647
  const shouldShowLoadingSpinner = useDelayedLoadingIndicator(!workbookBuffer && !loadError && !uploadedWorkbook, XLSX_LOADING_INDICATOR_DELAY_MS);
650
648
  React.useEffect(() => {
651
649
  let isCurrent = true;
652
- if (url) {
650
+ if (workbook) {
653
651
  setUploadedWorkbook(null);
654
652
  }
655
653
  async function loadWorkbook() {
656
- if (!url) {
654
+ if (!workbook) {
657
655
  setWorkbookBuffer(null);
658
656
  setLoadError(undefined);
659
657
  return;
@@ -661,11 +659,7 @@ function XlsxViewerContent({ className, effectiveIsDark, fileName, setNightRende
661
659
  setWorkbookBuffer(null);
662
660
  setLoadError(undefined);
663
661
  try {
664
- const response = await fetch(url);
665
- if (!response.ok) {
666
- throw new Error(`Failed to fetch XLSX (${response.status})`);
667
- }
668
- const nextWorkbookBuffer = await response.arrayBuffer();
662
+ const nextWorkbookBuffer = await workbook.arrayBuffer();
669
663
  if (!isCurrent)
670
664
  return;
671
665
  setWorkbookBuffer(nextWorkbookBuffer);
@@ -680,7 +674,7 @@ function XlsxViewerContent({ className, effectiveIsDark, fileName, setNightRende
680
674
  return () => {
681
675
  isCurrent = false;
682
676
  };
683
- }, [url]);
677
+ }, [workbook]);
684
678
  async function handleUpload(event) {
685
679
  const file = event.target.files?.[0];
686
680
  event.target.value = '';
@@ -696,8 +690,8 @@ function XlsxViewerContent({ className, effectiveIsDark, fileName, setNightRende
696
690
  }
697
691
  const activeBuffer = uploadedWorkbook?.buffer ?? workbookBuffer;
698
692
  const activeFileName = uploadedWorkbook?.fileName ?? displayFileName;
699
- const activeIdentity = workbookIdentity;
700
- if (!url && !uploadedWorkbook) {
693
+ const activeIdentity = identity;
694
+ if (!workbook && !uploadedWorkbook) {
701
695
  return (_jsxs("div", { className: cn('bg-background flex h-[640px] min-h-0 flex-col overflow-hidden', className), children: [_jsx("input", { ref: fileInputRef, type: "file", accept: ".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel", className: "hidden", onChange: handleUpload }), _jsx(WorkbookStandaloneToolbar, { onUploadClick: () => fileInputRef.current?.click(), showUploadButton: showUpload, toolbarActions: toolbarActions }), _jsx("div", { className: "bg-muted/30 grid min-h-0 flex-1 place-items-center p-4", children: _jsxs("div", { className: "bg-background max-w-md rounded-lg border p-4 text-center text-sm shadow-xs", children: [_jsx("p", { className: "font-medium", children: tI18nComplete.raw('text2e15b5a6e45a') }), _jsxs("p", { className: "text-muted-foreground mt-1", children: [tI18nComplete.raw('text27acc1f81d66'), " ", _jsx("code", { children: "src" }), ' ', tI18nComplete.raw('text37056f2381e2')] }), _jsxs(Button, { type: "button", variant: "outline", size: "sm", className: "mt-4", onClick: () => fileInputRef.current?.click(), children: [_jsx(Upload, { className: "size-4" }), tI18nComplete.raw('text522d6e41c020')] })] }) })] }));
702
696
  }
703
697
  if (loadError && !activeBuffer) {