@widgetic/chat 0.1.44 → 0.1.47

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 (75) hide show
  1. package/README.md +162 -20
  2. package/dist/components/ActionBar.svelte +14 -1
  3. package/dist/components/ActionBar.svelte.d.ts +6 -0
  4. package/dist/components/AttachmentDisplay.svelte +22 -130
  5. package/dist/components/AttachmentPreviewDialog.svelte +428 -0
  6. package/dist/components/AttachmentPreviewDialog.svelte.d.ts +14 -0
  7. package/dist/components/Chat.svelte +556 -121
  8. package/dist/components/Chat.svelte.d.ts +15 -2
  9. package/dist/components/ChatComposer.svelte +63 -69
  10. package/dist/components/ChatComposer.svelte.d.ts +8 -3
  11. package/dist/components/ChatDropOverlay.svelte +58 -0
  12. package/dist/components/ChatDropOverlay.svelte.d.ts +8 -0
  13. package/dist/components/ChatMessages.svelte +322 -98
  14. package/dist/components/ChatMessages.svelte.d.ts +11 -2
  15. package/dist/components/ComposerAttachmentsTray.svelte +144 -56
  16. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +11 -1
  17. package/dist/components/FileGlyphIcon.svelte +34 -0
  18. package/dist/components/FileGlyphIcon.svelte.d.ts +8 -0
  19. package/dist/components/PanelSuggestionButtons.svelte +67 -19
  20. package/dist/components/PanelSuggestionButtons.svelte.d.ts +3 -1
  21. package/dist/components/RestoreCheckpointDialog.svelte +66 -0
  22. package/dist/components/RestoreCheckpointDialog.svelte.d.ts +11 -0
  23. package/dist/components/SentAttachments.svelte +118 -0
  24. package/dist/components/SentAttachments.svelte.d.ts +12 -0
  25. package/dist/components/agent/AgentTurn.svelte +17 -2
  26. package/dist/components/agent/CodeCard.svelte +9 -3
  27. package/dist/i18n/index.d.ts +1 -1
  28. package/dist/i18n/index.js +1 -1
  29. package/dist/i18n/messages.d.ts +52 -4
  30. package/dist/i18n/messages.js +58 -6
  31. package/dist/i18n/suggestions.d.ts +17 -2
  32. package/dist/i18n/suggestions.js +11 -12
  33. package/dist/services/index.d.ts +4 -2
  34. package/dist/services/index.js +2 -1
  35. package/dist/services/limitRefusal.d.ts +42 -0
  36. package/dist/services/limitRefusal.js +60 -0
  37. package/dist/services/sketchAssistantClient.d.ts +11 -3
  38. package/dist/services/sketchAssistantClient.js +37 -10
  39. package/dist/services/sketchAssistantErrors.d.ts +16 -1
  40. package/dist/services/sketchAssistantErrors.js +25 -4
  41. package/dist/services/sketchAssistantOrchestrator.d.ts +7 -1
  42. package/dist/services/sketchAssistantOrchestrator.js +2 -2
  43. package/dist/types/attachment.d.ts +11 -0
  44. package/dist/utils/agentTurn.d.ts +32 -1
  45. package/dist/utils/agentTurn.js +46 -3
  46. package/dist/utils/attachmentDuplicates.d.ts +48 -0
  47. package/dist/utils/attachmentDuplicates.js +70 -0
  48. package/dist/utils/attachmentPolicy.d.ts +88 -0
  49. package/dist/utils/attachmentPolicy.js +135 -0
  50. package/dist/utils/attachmentPreview.d.ts +146 -0
  51. package/dist/utils/attachmentPreview.js +224 -0
  52. package/dist/utils/attachmentTray.d.ts +35 -0
  53. package/dist/utils/attachmentTray.js +27 -0
  54. package/dist/utils/chatFileDrag.d.ts +39 -0
  55. package/dist/utils/chatFileDrag.js +29 -0
  56. package/dist/utils/composerPreview.d.ts +33 -0
  57. package/dist/utils/composerPreview.js +31 -0
  58. package/dist/utils/generationArchiveStore.d.ts +5 -1
  59. package/dist/utils/generationArchiveStore.js +9 -4
  60. package/dist/utils/index.d.ts +1 -1
  61. package/dist/utils/index.js +1 -1
  62. package/dist/utils/limitFailureLine.d.ts +20 -0
  63. package/dist/utils/limitFailureLine.js +40 -0
  64. package/dist/utils/panelListPadding.d.ts +20 -0
  65. package/dist/utils/panelListPadding.js +31 -0
  66. package/dist/utils/pasteInsertion.d.ts +43 -0
  67. package/dist/utils/pasteInsertion.js +94 -0
  68. package/dist/utils/pastedContent.d.ts +13 -0
  69. package/dist/utils/pastedContent.js +18 -1
  70. package/dist/utils/referenceItems.js +11 -3
  71. package/dist/utils/sentAttachments.d.ts +43 -0
  72. package/dist/utils/sentAttachments.js +38 -0
  73. package/dist/utils/sentReferenceBadges.d.ts +11 -1
  74. package/dist/utils/sentReferenceBadges.js +47 -2
  75. package/package.json +3 -3
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Which files the message box takes, and how large. Kept apart from the components so Node can test it.
3
+ *
4
+ * It answers two questions, with the same rules: while files are dragged over the chat (only the types are known then, the
5
+ * browser tells nothing of the sizes until they are dropped), and when they are dropped, picked or pasted (the sizes are known).
6
+ *
7
+ * The kinds are the ones the "+" says it adds: images, video, PDF, CSV and text. Whether the builder can read them all is another
8
+ * matter (it reads pictures, CSV and text; see the creator's `codegenAttachments`): a file that is kept but not read is told so
9
+ * after it is sent, and the tooltip of the "+" says so before.
10
+ */
11
+ /** The kind of a file the box takes. */
12
+ export type AttachmentKind = 'image' | 'video' | 'document';
13
+ /** Why a file was left out. */
14
+ export type AttachmentRefusalReason = 'type' | 'size' | 'folder';
15
+ /** A file that was left out, and why. `limitBytes` is the size it went over, for the sentence that says so. */
16
+ export interface RefusedAttachment {
17
+ file: File;
18
+ reason: AttachmentRefusalReason;
19
+ limitBytes?: number;
20
+ }
21
+ /** The largest file of each kind. A picture is made smaller before it is sent when it is large (see `prepareChatImageFileForUpload`), so the limit is checked on the picture that is sent. */
22
+ export declare const ATTACHMENT_SIZE_LIMITS_BYTES: Record<AttachmentKind, number>;
23
+ /**
24
+ * The kind of a file by its type, and by its extension when the type says nothing. Nothing (null) for a file the box does not
25
+ * take: a zip, an executable, a font, a sound, a Word file.
26
+ */
27
+ export declare function attachmentKindOf(file: {
28
+ name?: string;
29
+ type?: string;
30
+ }): AttachmentKind | null;
31
+ /** Whether something dragged looks like a folder (it has no name, no type and no size: a file with those is empty, which nothing attaches). */
32
+ export declare function looksLikeFolder(file: {
33
+ size: number;
34
+ type?: string;
35
+ }): boolean;
36
+ /** What `checkAttachmentFile` found: the file is taken, or it is left out for a reason. */
37
+ export type AttachmentCheck = {
38
+ ok: true;
39
+ kind: AttachmentKind;
40
+ } | {
41
+ ok: false;
42
+ reason: AttachmentRefusalReason;
43
+ limitBytes?: number;
44
+ };
45
+ /** How a check is made. */
46
+ export interface AttachmentCheckOptions {
47
+ /**
48
+ * Leave the size of a picture unchecked. A large picture is made smaller before it is sent (see `prepareChatImageFileForUpload`),
49
+ * so a file that arrives too large may still go; the picture that is sent is checked, once it is made.
50
+ */
51
+ skipPictureSize?: boolean;
52
+ }
53
+ /** Whether one file is taken: a kind the box takes, and not larger than that kind's limit. */
54
+ export declare function checkAttachmentFile(file: File, options?: AttachmentCheckOptions): AttachmentCheck;
55
+ /** The files that are taken (in the order they came) and the ones that were left out, each with its reason. */
56
+ export declare function partitionAttachmentFiles(files: readonly File[], options?: AttachmentCheckOptions): {
57
+ accepted: File[];
58
+ refused: RefusedAttachment[];
59
+ };
60
+ /** What the file chooser of the "+" offers: the kinds the box takes (a person is not invited to pick what would be refused). */
61
+ export declare const ATTACHMENT_ACCEPT_ATTRIBUTE = "image/*,video/*,text/*,application/pdf,application/json,.pdf,.txt,.md,.markdown,.csv,.tsv,.json,.mermaid,.mmd";
62
+ /** One thing that is dragged: what the browser tells of it before the drop (`DataTransferItem`: its kind and its type, never its size or name). */
63
+ export interface DraggedItem {
64
+ kind: string;
65
+ type: string;
66
+ }
67
+ /** What a drag over the chat says about what is dragged. */
68
+ export type DragVerdict = 'accept' | 'refuse' | 'none';
69
+ /**
70
+ * Whether the files being dragged are ones the box takes, from what the browser tells while they are over the page: their types.
71
+ * 'none' when no file is dragged (text, a link: the chat is not a drop target for them); 'refuse' when every file is of a kind the
72
+ * box does not take; 'accept' otherwise: a file whose type the system does not tell (a `.md`, a `.mmd`) gets the benefit of the
73
+ * doubt, and the drop says what could not be taken. A mixed drag is 'accept': the files that can be taken are attached.
74
+ */
75
+ export declare function judgeDraggedItems(items: ReadonlyArray<DraggedItem>): DragVerdict;
76
+ /** What a drag event says of what is dragged (`event.dataTransfer`): the kinds of data it holds and, per item, its kind and type. */
77
+ export interface DragTransferInfo {
78
+ types?: ArrayLike<string> | null;
79
+ items?: ArrayLike<DraggedItem> | null;
80
+ }
81
+ /** Whether files (and not a text or a link) are being dragged: the browser lists `Files` among the types of the drag. */
82
+ export declare function dragCarriesFiles(transfer: DragTransferInfo | null | undefined): boolean;
83
+ /**
84
+ * The verdict on a drag event: 'none' when no file is dragged, otherwise what `judgeDraggedItems` says of the items. A browser that
85
+ * lists no items before the drop (Safari does not) says nothing that refuses the files, so the drag gets the benefit of the doubt
86
+ * and the drop says what could not be taken.
87
+ */
88
+ export declare function judgeDragTransfer(transfer: DragTransferInfo | null | undefined): DragVerdict;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Which files the message box takes, and how large. Kept apart from the components so Node can test it.
3
+ *
4
+ * It answers two questions, with the same rules: while files are dragged over the chat (only the types are known then, the
5
+ * browser tells nothing of the sizes until they are dropped), and when they are dropped, picked or pasted (the sizes are known).
6
+ *
7
+ * The kinds are the ones the "+" says it adds: images, video, PDF, CSV and text. Whether the builder can read them all is another
8
+ * matter (it reads pictures, CSV and text; see the creator's `codegenAttachments`): a file that is kept but not read is told so
9
+ * after it is sent, and the tooltip of the "+" says so before.
10
+ */
11
+ /** The largest file of each kind. A picture is made smaller before it is sent when it is large (see `prepareChatImageFileForUpload`), so the limit is checked on the picture that is sent. */
12
+ export const ATTACHMENT_SIZE_LIMITS_BYTES = {
13
+ image: 10 * 1024 * 1024,
14
+ video: 100 * 1024 * 1024,
15
+ document: 25 * 1024 * 1024,
16
+ };
17
+ /** The extensions that make a file a document when its type does not say (a browser gives `.md` and `.mmd` no type on some systems). */
18
+ const DOCUMENT_EXTENSIONS = new Set(['pdf', 'txt', 'md', 'markdown', 'csv', 'tsv', 'json', 'mermaid', 'mmd']);
19
+ /** The extensions of the pictures and videos, for a file whose type is empty. */
20
+ const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'avif', 'bmp']);
21
+ const VIDEO_EXTENSIONS = new Set(['mp4', 'webm', 'mov', 'm4v']);
22
+ /** The documents the box takes besides every `text/*`. */
23
+ const DOCUMENT_MIME_TYPES = new Set([
24
+ 'application/pdf',
25
+ 'application/json',
26
+ 'application/csv',
27
+ 'application/vnd.ms-excel', // what some systems call a CSV
28
+ ]);
29
+ /** The extension of a file name in lower case, or '' when it has none. */
30
+ function extensionOf(fileName) {
31
+ const lastDotIndex = (fileName ?? '').lastIndexOf('.');
32
+ return lastDotIndex > 0 && lastDotIndex < fileName.length - 1
33
+ ? fileName.slice(lastDotIndex + 1).toLowerCase()
34
+ : '';
35
+ }
36
+ /**
37
+ * The kind of a file by its type, and by its extension when the type says nothing. Nothing (null) for a file the box does not
38
+ * take: a zip, an executable, a font, a sound, a Word file.
39
+ */
40
+ export function attachmentKindOf(file) {
41
+ const type = (file.type ?? '').toLowerCase();
42
+ const extension = extensionOf(file.name ?? '');
43
+ if (type.startsWith('image/'))
44
+ return 'image';
45
+ if (type.startsWith('video/'))
46
+ return 'video';
47
+ if (type.startsWith('text/') || DOCUMENT_MIME_TYPES.has(type))
48
+ return 'document';
49
+ // A type that says nothing (or says "binary") is judged by the name; a type that names another kind of file is left out
50
+ if (type === '' || type === 'application/octet-stream') {
51
+ if (IMAGE_EXTENSIONS.has(extension))
52
+ return 'image';
53
+ if (VIDEO_EXTENSIONS.has(extension))
54
+ return 'video';
55
+ if (DOCUMENT_EXTENSIONS.has(extension))
56
+ return 'document';
57
+ }
58
+ // A `.csv` or `.md` that a system types as something else (an Excel type, a markdown type of its own)
59
+ if (DOCUMENT_EXTENSIONS.has(extension) && extension !== 'json' && extension !== 'pdf' && /^(application|text)\//.test(type)) {
60
+ return 'document';
61
+ }
62
+ return null;
63
+ }
64
+ /** Whether something dragged looks like a folder (it has no name, no type and no size: a file with those is empty, which nothing attaches). */
65
+ export function looksLikeFolder(file) {
66
+ return file.size === 0 && (file.type ?? '') === '';
67
+ }
68
+ /** Whether one file is taken: a kind the box takes, and not larger than that kind's limit. */
69
+ export function checkAttachmentFile(file, options = {}) {
70
+ if (looksLikeFolder(file))
71
+ return { ok: false, reason: 'folder' };
72
+ const kind = attachmentKindOf(file);
73
+ if (!kind)
74
+ return { ok: false, reason: 'type' };
75
+ if (kind === 'image' && options.skipPictureSize)
76
+ return { ok: true, kind };
77
+ const limitBytes = ATTACHMENT_SIZE_LIMITS_BYTES[kind];
78
+ if (file.size > limitBytes)
79
+ return { ok: false, reason: 'size', limitBytes };
80
+ return { ok: true, kind };
81
+ }
82
+ /** The files that are taken (in the order they came) and the ones that were left out, each with its reason. */
83
+ export function partitionAttachmentFiles(files, options = {}) {
84
+ const accepted = [];
85
+ const refused = [];
86
+ for (const file of files) {
87
+ const check = checkAttachmentFile(file, options);
88
+ if (check.ok)
89
+ accepted.push(file);
90
+ else
91
+ refused.push({ file, reason: check.reason, limitBytes: check.limitBytes });
92
+ }
93
+ return { accepted, refused };
94
+ }
95
+ /** What the file chooser of the "+" offers: the kinds the box takes (a person is not invited to pick what would be refused). */
96
+ export const ATTACHMENT_ACCEPT_ATTRIBUTE = 'image/*,video/*,text/*,application/pdf,application/json,.pdf,.txt,.md,.markdown,.csv,.tsv,.json,.mermaid,.mmd';
97
+ /**
98
+ * Whether the files being dragged are ones the box takes, from what the browser tells while they are over the page: their types.
99
+ * 'none' when no file is dragged (text, a link: the chat is not a drop target for them); 'refuse' when every file is of a kind the
100
+ * box does not take; 'accept' otherwise: a file whose type the system does not tell (a `.md`, a `.mmd`) gets the benefit of the
101
+ * doubt, and the drop says what could not be taken. A mixed drag is 'accept': the files that can be taken are attached.
102
+ */
103
+ export function judgeDraggedItems(items) {
104
+ const files = items.filter((item) => item.kind === 'file');
105
+ if (files.length === 0)
106
+ return 'none';
107
+ const everyFileIsRefused = files.every((item) => {
108
+ const type = (item.type ?? '').toLowerCase();
109
+ if (type === '' || type === 'application/octet-stream')
110
+ return false;
111
+ return attachmentKindOf({ type, name: '' }) === null;
112
+ });
113
+ return everyFileIsRefused ? 'refuse' : 'accept';
114
+ }
115
+ /** Whether files (and not a text or a link) are being dragged: the browser lists `Files` among the types of the drag. */
116
+ export function dragCarriesFiles(transfer) {
117
+ if (!transfer?.types)
118
+ return false;
119
+ return Array.from(transfer.types).includes('Files');
120
+ }
121
+ /**
122
+ * The verdict on a drag event: 'none' when no file is dragged, otherwise what `judgeDraggedItems` says of the items. A browser that
123
+ * lists no items before the drop (Safari does not) says nothing that refuses the files, so the drag gets the benefit of the doubt
124
+ * and the drop says what could not be taken.
125
+ */
126
+ export function judgeDragTransfer(transfer) {
127
+ if (!dragCarriesFiles(transfer))
128
+ return 'none';
129
+ const items = Array.from(transfer?.items ?? []);
130
+ if (items.length === 0)
131
+ return 'accept';
132
+ const verdict = judgeDraggedItems(items);
133
+ // The types say files while the items do not list any as one (a browser that lists them in its own way): still files
134
+ return verdict === 'none' ? 'accept' : verdict;
135
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * What the preview of an attached file shows, and how big its card is. Kept apart from the components so Node can test it.
3
+ *
4
+ * Pressing a thumbnail or a file chip (in the message box, or in a sent message) opens the file in a card that looks and moves like
5
+ * the File Browser's preview: the name and the details of the file on top with the arrows to the file before and after it and the
6
+ * close button, and the file itself below. This file holds the rules of that card that do not need a screen: which kind of preview a
7
+ * file gets, the size of the card for a picture, a video, a PDF or a text, and what the arrow keys do. (The numbers of the card come
8
+ * from the File Browser's own `imagePreviewFrame`, so a picture opened from the chat has the room it has there.)
9
+ */
10
+ import type { ContentItemOutput } from '../types/message.js';
11
+ /** The kinds of file that open in the preview. Any other file has no preview (a chip of it only names it). */
12
+ export type PreviewKind = 'image' | 'video' | 'pdf' | 'text';
13
+ /** The glyph a file chip carries in front of its name. */
14
+ export type FileGlyph = 'pdf' | 'video' | 'sheet' | 'text' | 'file';
15
+ /** What the preview needs to know about a file. */
16
+ export interface PreviewableFile {
17
+ /** Where the file can be read from (an address on the web, or a `blob:` address for a file that is still on this device). */
18
+ url: string;
19
+ /** The name the person sees on top of the card. */
20
+ name: string;
21
+ /** The type the file was saved with (`image/png`); empty when it is not known. */
22
+ type: string;
23
+ /** The size in bytes, or null when it is not known. */
24
+ size: number | null;
25
+ }
26
+ /** The facts the kind of a file is worked out from. */
27
+ export interface PreviewFacts {
28
+ url?: string | null;
29
+ name?: string | null;
30
+ type?: string | null;
31
+ }
32
+ /** The extension of a file name in lower case, or '' when the name has none (`archive.tar.gz` is `gz`; `.env` has none). */
33
+ export declare function extensionOf(name: string | null | undefined): string;
34
+ /** The extension as the details line of the card writes it (`PNG`), or '' when the name has none. */
35
+ export declare function extensionLabelOf(name: string | null | undefined): string;
36
+ /**
37
+ * Which kind of preview a file gets, or null when it gets none. The type of the file decides; when the type says nothing (an empty
38
+ * type, or the catch-all `application/octet-stream`) the extension of the name does; a picture is also known by its address.
39
+ */
40
+ export declare function previewKindOf(facts: PreviewFacts): PreviewKind | null;
41
+ /** The glyph a file chip carries: it says at a glance what the file is, whether or not the file has a preview. */
42
+ export declare function fileGlyphOf(facts: PreviewFacts): FileGlyph;
43
+ /**
44
+ * A file of a sent message as the preview takes it, or null when it has none: a file without an address cannot be read, and a kind
45
+ * the preview does not show (a spreadsheet, an archive) has no card.
46
+ */
47
+ export declare function previewFileOfAttachment(attachment: ContentItemOutput): PreviewableFile | null;
48
+ /** The files of one place (a message, the message box) that the preview can step through, and where each of them stands. */
49
+ export interface PreviewGroup {
50
+ /** The files the card steps through with its arrows, in the order they are drawn. */
51
+ files: PreviewableFile[];
52
+ /** The place of an attachment in `files`, or -1 when that attachment has no preview. */
53
+ indexOf: (attachment: ContentItemOutput) => number;
54
+ }
55
+ /**
56
+ * The files a card steps through when one of them is pressed: those that have a preview, in the order the screen draws them (so the
57
+ * right arrow goes to the file drawn after this one). The files that have none are left out; `indexOf` says so with -1.
58
+ */
59
+ export declare function previewGroupOf(attachmentsInDrawnOrder: readonly ContentItemOutput[]): PreviewGroup;
60
+ /** What a key press does in the card: go to the file before this one, or to the file after it. */
61
+ export type PreviewKeyAction = 'previous' | 'next';
62
+ /**
63
+ * What an arrow key does in the card, or null for any other key. The arrow keys follow the reading direction: the key that points
64
+ * toward the start of the line goes to the previous file and the key that points toward the end goes to the next one. On a left to
65
+ * right screen that is the left arrow and the right arrow; on a right to left screen the two swap, so the arrow points the way the
66
+ * files are laid out.
67
+ */
68
+ export declare function previewKeyAction(key: string, direction: 'ltr' | 'rtl'): PreviewKeyAction | null;
69
+ /**
70
+ * The place of the file an arrow leads to, or null when there is none (the first file has no one before it, the last none after it;
71
+ * the card does not wrap around, so the arrow is disabled at the ends).
72
+ */
73
+ export declare function steppedPreviewIndex(currentIndex: number, direction: PreviewKeyAction, fileCount: number): number | null;
74
+ /** The room the card has to fit in: the window the chat is in. */
75
+ export interface PreviewHost {
76
+ width: number;
77
+ height: number;
78
+ }
79
+ /** The size of a card in px, and (for a picture or a video) of the file inside it. */
80
+ export interface PreviewFrame {
81
+ width: number;
82
+ height: number;
83
+ pictureWidth: number;
84
+ pictureHeight: number;
85
+ }
86
+ /** What the card takes for itself around the file, in px: the same numbers as the File Browser's card (the padding, the header row). */
87
+ export declare const PREVIEW_CARD: {
88
+ /** The room between the card and the edge of the window, at each side. */
89
+ readonly sideMargin: 24;
90
+ /** The padding of the card at both sides (24 each) and its two 1 px borders. */
91
+ readonly horizontalPad: 50;
92
+ /** The top row of the card (the name and details, 36 px) and the gap below it (16 px). */
93
+ readonly headerBlock: 52;
94
+ /** The padding of the card at the top and the bottom and its two borders. */
95
+ readonly verticalPad: 50;
96
+ /** The air kept between the file and the edge of the window. */
97
+ readonly contentVerticalGutter: 48;
98
+ /** The narrowest card: the name, the two arrows and the close button need this much. */
99
+ readonly minWidth: 320;
100
+ /** The most of the window a card takes. */
101
+ readonly maxHostFraction: 0.92;
102
+ /** The smallest side a picture is drawn at. */
103
+ readonly minPictureSide: 68;
104
+ };
105
+ /**
106
+ * The card of a picture (or of a video, once the video tells its size): as big as the picture is, and no bigger than the window
107
+ * leaves room for. A small picture is never made larger. A picture that tells no size is drawn as a 4:3 one.
108
+ */
109
+ export declare function computePictureFrame(naturalWidth: number, naturalHeight: number, hostSize: PreviewHost): PreviewFrame;
110
+ /** The cards that are not a picture: a file that cannot be shown, one that is on its way, a PDF, a text. */
111
+ export type DocumentCardKind = 'error' | 'loading' | 'pdf' | 'text';
112
+ /** The card of a file that is not a picture: a fixed size for a message or a text, the whole window for a PDF (which needs the room). */
113
+ export declare function computeDocumentFrame(kind: DocumentCardKind, hostSize: PreviewHost): {
114
+ width: number;
115
+ height: number;
116
+ };
117
+ /** The most characters of a text the card reads: the card shows a part of a very long text and says so, instead of freezing on it. */
118
+ export declare const PREVIEW_TEXT_MAX_CHARACTERS = 200000;
119
+ /** A text as the card shows it. */
120
+ export interface PreviewText {
121
+ text: string;
122
+ /** Whether the text was longer than the card reads, so the card says that the rest is not shown. */
123
+ truncated: boolean;
124
+ }
125
+ /**
126
+ * The text of a file as the card shows it: a JSON file is indented so it can be read (a text that is not valid JSON stays as it is),
127
+ * the line ends of a Windows file are the line ends of any other, and a text longer than `PREVIEW_TEXT_MAX_CHARACTERS` is cut.
128
+ */
129
+ export declare function formatPreviewText(rawText: string, name: string | null | undefined): PreviewText;
130
+ /** A length of time as `m:ss` (a video of 75 seconds is `1:15`), or '' when it is not known. */
131
+ export declare function durationText(seconds: number | null | undefined): string;
132
+ /** What the details line of the card is made of, in its order: the extension, the size of a picture, the length of a video, the weight. */
133
+ export interface PreviewDetails {
134
+ name: string;
135
+ kind: PreviewKind | null;
136
+ size: number | null;
137
+ /** The size in px of a picture or a video, once it is known. */
138
+ dimensions?: {
139
+ width: number;
140
+ height: number;
141
+ } | null;
142
+ /** The length of a video in seconds, once it is known. */
143
+ durationSeconds?: number | null;
144
+ }
145
+ /** The parts of the details line (`PNG`, `1024 × 1280`, `1.2 MB`); the card joins them with a dot. A part that is not known is left out. */
146
+ export declare function previewDetailParts(details: PreviewDetails, sizeText: (bytes: number) => string): string[];
@@ -0,0 +1,224 @@
1
+ import { isPictureOfMessage } from './sentReferenceBadges.js';
2
+ /** The extensions of the files that are read as text when their type says nothing (a browser gives `.md` and `.csv` odd types). */
3
+ const TEXT_EXTENSIONS = new Set(['txt', 'md', 'markdown', 'csv', 'tsv', 'json', 'mermaid', 'mmd']);
4
+ /** The extensions of the files that are sheets: they get the glyph of a sheet. */
5
+ const SHEET_EXTENSIONS = new Set(['csv', 'tsv', 'xls', 'xlsx']);
6
+ /** The extensions of the videos a browser plays, for the case their type says nothing. */
7
+ const VIDEO_EXTENSIONS = new Set(['mp4', 'webm', 'mov', 'm4v', 'ogv']);
8
+ /** The extension of a file name in lower case, or '' when the name has none (`archive.tar.gz` is `gz`; `.env` has none). */
9
+ export function extensionOf(name) {
10
+ if (typeof name !== 'string')
11
+ return '';
12
+ const dotIndex = name.lastIndexOf('.');
13
+ if (dotIndex <= 0 || dotIndex === name.length - 1)
14
+ return '';
15
+ return name.slice(dotIndex + 1).toLowerCase();
16
+ }
17
+ /** The extension as the details line of the card writes it (`PNG`), or '' when the name has none. */
18
+ export function extensionLabelOf(name) {
19
+ return extensionOf(name).toUpperCase();
20
+ }
21
+ /** The type of a file with its parameters cut off and in lower case (`text/plain; charset=utf-8` is `text/plain`). */
22
+ function bareTypeOf(type) {
23
+ return typeof type === 'string' ? type.split(';')[0].trim().toLowerCase() : '';
24
+ }
25
+ /**
26
+ * Which kind of preview a file gets, or null when it gets none. The type of the file decides; when the type says nothing (an empty
27
+ * type, or the catch-all `application/octet-stream`) the extension of the name does; a picture is also known by its address.
28
+ */
29
+ export function previewKindOf(facts) {
30
+ const type = bareTypeOf(facts.type);
31
+ const extension = extensionOf(facts.name);
32
+ const typeSaysNothing = type === '' || type === 'application/octet-stream';
33
+ if (isPictureOfMessage({ file_type: type, url: facts.url ?? '' }))
34
+ return 'image';
35
+ if (type.startsWith('video/') || (typeSaysNothing && VIDEO_EXTENSIONS.has(extension)))
36
+ return 'video';
37
+ if (type === 'application/pdf' || (typeSaysNothing && extension === 'pdf'))
38
+ return 'pdf';
39
+ if (type.startsWith('text/') ||
40
+ type === 'application/json' ||
41
+ type === 'application/csv' ||
42
+ (typeSaysNothing && TEXT_EXTENSIONS.has(extension))) {
43
+ return 'text';
44
+ }
45
+ return null;
46
+ }
47
+ /** The glyph a file chip carries: it says at a glance what the file is, whether or not the file has a preview. */
48
+ export function fileGlyphOf(facts) {
49
+ const type = bareTypeOf(facts.type);
50
+ const extension = extensionOf(facts.name);
51
+ const kind = previewKindOf(facts);
52
+ if (kind === 'pdf')
53
+ return 'pdf';
54
+ if (kind === 'video')
55
+ return 'video';
56
+ if (type === 'text/csv' || type === 'application/csv' || SHEET_EXTENSIONS.has(extension))
57
+ return 'sheet';
58
+ if (kind === 'text')
59
+ return 'text';
60
+ return 'file';
61
+ }
62
+ /**
63
+ * A file of a sent message as the preview takes it, or null when it has none: a file without an address cannot be read, and a kind
64
+ * the preview does not show (a spreadsheet, an archive) has no card.
65
+ */
66
+ export function previewFileOfAttachment(attachment) {
67
+ const url = typeof attachment.url === 'string' ? attachment.url : '';
68
+ if (url === '')
69
+ return null;
70
+ const facts = { url, name: attachment.file_name, type: attachment.file_type };
71
+ if (previewKindOf(facts) === null)
72
+ return null;
73
+ return {
74
+ url,
75
+ name: attachment.file_name?.trim() || '',
76
+ type: attachment.file_type ?? '',
77
+ size: typeof attachment.file_size === 'number' && attachment.file_size > 0 ? attachment.file_size : null
78
+ };
79
+ }
80
+ /**
81
+ * The files a card steps through when one of them is pressed: those that have a preview, in the order the screen draws them (so the
82
+ * right arrow goes to the file drawn after this one). The files that have none are left out; `indexOf` says so with -1.
83
+ */
84
+ export function previewGroupOf(attachmentsInDrawnOrder) {
85
+ const files = [];
86
+ const placeByAttachment = new Map();
87
+ for (const attachment of attachmentsInDrawnOrder) {
88
+ const file = previewFileOfAttachment(attachment);
89
+ if (!file)
90
+ continue;
91
+ placeByAttachment.set(attachment, files.length);
92
+ files.push(file);
93
+ }
94
+ return { files, indexOf: (attachment) => placeByAttachment.get(attachment) ?? -1 };
95
+ }
96
+ /**
97
+ * What an arrow key does in the card, or null for any other key. The arrow keys follow the reading direction: the key that points
98
+ * toward the start of the line goes to the previous file and the key that points toward the end goes to the next one. On a left to
99
+ * right screen that is the left arrow and the right arrow; on a right to left screen the two swap, so the arrow points the way the
100
+ * files are laid out.
101
+ */
102
+ export function previewKeyAction(key, direction) {
103
+ if (key !== 'ArrowLeft' && key !== 'ArrowRight')
104
+ return null;
105
+ const keyPointsToStart = (key === 'ArrowLeft') === (direction !== 'rtl');
106
+ return keyPointsToStart ? 'previous' : 'next';
107
+ }
108
+ /**
109
+ * The place of the file an arrow leads to, or null when there is none (the first file has no one before it, the last none after it;
110
+ * the card does not wrap around, so the arrow is disabled at the ends).
111
+ */
112
+ export function steppedPreviewIndex(currentIndex, direction, fileCount) {
113
+ if (!Number.isInteger(currentIndex) || currentIndex < 0 || currentIndex >= fileCount)
114
+ return null;
115
+ const nextIndex = direction === 'previous' ? currentIndex - 1 : currentIndex + 1;
116
+ return nextIndex >= 0 && nextIndex < fileCount ? nextIndex : null;
117
+ }
118
+ /** What the card takes for itself around the file, in px: the same numbers as the File Browser's card (the padding, the header row). */
119
+ export const PREVIEW_CARD = {
120
+ /** The room between the card and the edge of the window, at each side. */
121
+ sideMargin: 24,
122
+ /** The padding of the card at both sides (24 each) and its two 1 px borders. */
123
+ horizontalPad: 50,
124
+ /** The top row of the card (the name and details, 36 px) and the gap below it (16 px). */
125
+ headerBlock: 52,
126
+ /** The padding of the card at the top and the bottom and its two borders. */
127
+ verticalPad: 50,
128
+ /** The air kept between the file and the edge of the window. */
129
+ contentVerticalGutter: 48,
130
+ /** The narrowest card: the name, the two arrows and the close button need this much. */
131
+ minWidth: 320,
132
+ /** The most of the window a card takes. */
133
+ maxHostFraction: 0.92,
134
+ /** The smallest side a picture is drawn at. */
135
+ minPictureSide: 68
136
+ };
137
+ const TOTAL_VERTICAL_SPACE = PREVIEW_CARD.verticalPad + PREVIEW_CARD.headerBlock;
138
+ /** A host with no size (a window that is not measured yet) gets the size of a common laptop screen, so the card is never 0 px. */
139
+ function usableHost(host) {
140
+ const width = Number.isFinite(host.width) && host.width > 0 ? host.width : 1280;
141
+ const height = Number.isFinite(host.height) && host.height > 0 ? host.height : 720;
142
+ return { width, height };
143
+ }
144
+ /**
145
+ * The card of a picture (or of a video, once the video tells its size): as big as the picture is, and no bigger than the window
146
+ * leaves room for. A small picture is never made larger. A picture that tells no size is drawn as a 4:3 one.
147
+ */
148
+ export function computePictureFrame(naturalWidth, naturalHeight, hostSize) {
149
+ const host = usableHost(hostSize);
150
+ const knownSize = Number.isFinite(naturalWidth) && Number.isFinite(naturalHeight) && naturalWidth > 0 && naturalHeight > 0;
151
+ const width = knownSize ? naturalWidth : 640;
152
+ const height = knownSize ? naturalHeight : 480;
153
+ const maxPictureWidth = Math.max(100, host.width * PREVIEW_CARD.maxHostFraction - 2 * PREVIEW_CARD.sideMargin - PREVIEW_CARD.horizontalPad);
154
+ const maxPictureHeight = Math.max(100, host.height * PREVIEW_CARD.maxHostFraction - TOTAL_VERTICAL_SPACE - PREVIEW_CARD.contentVerticalGutter);
155
+ const scale = Math.min(1, maxPictureWidth / width, maxPictureHeight / height);
156
+ const pictureWidth = Math.max(PREVIEW_CARD.minPictureSide, Math.round(width * scale));
157
+ const pictureHeight = Math.max(PREVIEW_CARD.minPictureSide, Math.round(height * scale));
158
+ const cardWidth = Math.min(Math.max(PREVIEW_CARD.minWidth, pictureWidth + PREVIEW_CARD.horizontalPad), Math.max(pictureWidth + PREVIEW_CARD.horizontalPad, host.width * PREVIEW_CARD.maxHostFraction - 2 * PREVIEW_CARD.sideMargin));
159
+ return { width: cardWidth, height: pictureHeight + TOTAL_VERTICAL_SPACE, pictureWidth, pictureHeight };
160
+ }
161
+ /** The card of a file that is not a picture: a fixed size for a message or a text, the whole window for a PDF (which needs the room). */
162
+ export function computeDocumentFrame(kind, hostSize) {
163
+ const host = usableHost(hostSize);
164
+ const maxWidth = Math.max(PREVIEW_CARD.minWidth, host.width - 2 * PREVIEW_CARD.sideMargin);
165
+ switch (kind) {
166
+ case 'error':
167
+ case 'loading':
168
+ return { width: Math.min(410, maxWidth), height: 256 };
169
+ case 'text':
170
+ return { width: Math.min(566, maxWidth), height: 460 };
171
+ case 'pdf': {
172
+ const maxAvailableHeight = host.height - TOTAL_VERTICAL_SPACE - PREVIEW_CARD.contentVerticalGutter;
173
+ const contentHeight = Math.max(200, Math.min(maxAvailableHeight, maxWidth * 0.75));
174
+ return { width: maxWidth, height: Math.round(contentHeight + TOTAL_VERTICAL_SPACE) };
175
+ }
176
+ }
177
+ }
178
+ /** The most characters of a text the card reads: the card shows a part of a very long text and says so, instead of freezing on it. */
179
+ export const PREVIEW_TEXT_MAX_CHARACTERS = 200_000;
180
+ /**
181
+ * The text of a file as the card shows it: a JSON file is indented so it can be read (a text that is not valid JSON stays as it is),
182
+ * the line ends of a Windows file are the line ends of any other, and a text longer than `PREVIEW_TEXT_MAX_CHARACTERS` is cut.
183
+ */
184
+ export function formatPreviewText(rawText, name) {
185
+ const normalized = rawText.replace(/\r\n?/g, '\n');
186
+ if (normalized.length > PREVIEW_TEXT_MAX_CHARACTERS) {
187
+ return { text: normalized.slice(0, PREVIEW_TEXT_MAX_CHARACTERS), truncated: true };
188
+ }
189
+ if (extensionOf(name) === 'json') {
190
+ try {
191
+ return { text: JSON.stringify(JSON.parse(normalized), null, 2), truncated: false };
192
+ }
193
+ catch {
194
+ // Not valid JSON (a file with a comment in it, or one that was cut): it is shown as it was written
195
+ }
196
+ }
197
+ return { text: normalized, truncated: false };
198
+ }
199
+ /** A length of time as `m:ss` (a video of 75 seconds is `1:15`), or '' when it is not known. */
200
+ export function durationText(seconds) {
201
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
202
+ return '';
203
+ const wholeSeconds = Math.floor(seconds);
204
+ return `${Math.floor(wholeSeconds / 60)}:${String(wholeSeconds % 60).padStart(2, '0')}`;
205
+ }
206
+ /** The parts of the details line (`PNG`, `1024 × 1280`, `1.2 MB`); the card joins them with a dot. A part that is not known is left out. */
207
+ export function previewDetailParts(details, sizeText) {
208
+ const parts = [];
209
+ const extension = extensionLabelOf(details.name);
210
+ if (extension)
211
+ parts.push(extension);
212
+ const dimensions = details.dimensions;
213
+ if ((details.kind === 'image' || details.kind === 'video') && dimensions && dimensions.width > 0 && dimensions.height > 0) {
214
+ parts.push(`${Math.round(dimensions.width)} × ${Math.round(dimensions.height)}`);
215
+ }
216
+ if (details.kind === 'video') {
217
+ const length = durationText(details.durationSeconds);
218
+ if (length)
219
+ parts.push(length);
220
+ }
221
+ if (typeof details.size === 'number' && details.size > 0)
222
+ parts.push(sizeText(details.size));
223
+ return parts;
224
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Which of the attached files the tray above the text draws, and in what order. Kept apart from the components so Node can test it.
3
+ *
4
+ * The tray lives inside the message box, over the text. Its order does not follow the order the files were added in: the files that
5
+ * are not pictures come first, each as a chip, and the pictures come after them, one after the other, as small thumbnails. So a
6
+ * picture dropped before a PDF, and another dropped after it, still stand together below the PDF.
7
+ *
8
+ * A text that was pasted is not in the tray at all: it is in the words of the message, as a badge where the caret was.
9
+ */
10
+ import type { AttachmentInput } from '../types/attachment.js';
11
+ /** One file of the tray, with its place in the full list of attached files (what removing it needs). */
12
+ export interface TrayEntry {
13
+ attachment: AttachmentInput;
14
+ /** The place of the file in the list the page keeps: `onRemove` is given it, so a tray that shows the files in another order still removes the right one. */
15
+ index: number;
16
+ }
17
+ /** The tray as it is drawn, top to bottom. */
18
+ export interface TrayArrangement {
19
+ /** The files that are not pictures, in the order they were attached: each is a chip. */
20
+ chips: TrayEntry[];
21
+ /** The pictures, in the order they were attached: each is a thumbnail, and they follow one another below the chips. */
22
+ pictures: TrayEntry[];
23
+ }
24
+ /**
25
+ * Whether a file is a text pasted into the box (see `AttachmentInput.excerpt`): it stands in the words of the message, as a badge,
26
+ * so the tray has no tile for it.
27
+ */
28
+ export declare function isPastedTextAttachment(attachment: Pick<AttachmentInput, 'excerpt'>): boolean;
29
+ /**
30
+ * The files of the tray in the order they are drawn. A pasted text is left out (it has its place in the message). Two lists are
31
+ * given back, the chips and the pictures; each keeps the order in which its files were attached.
32
+ */
33
+ export declare function arrangeTrayAttachments(attachments: readonly AttachmentInput[], isPicture: (attachment: AttachmentInput) => boolean): TrayArrangement;
34
+ /** Whether the tray has anything to draw: some file that is not a pasted text. */
35
+ export declare function trayHasTiles(attachments: readonly AttachmentInput[]): boolean;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Whether a file is a text pasted into the box (see `AttachmentInput.excerpt`): it stands in the words of the message, as a badge,
3
+ * so the tray has no tile for it.
4
+ */
5
+ export function isPastedTextAttachment(attachment) {
6
+ return typeof attachment.excerpt === 'string';
7
+ }
8
+ /**
9
+ * The files of the tray in the order they are drawn. A pasted text is left out (it has its place in the message). Two lists are
10
+ * given back, the chips and the pictures; each keeps the order in which its files were attached.
11
+ */
12
+ export function arrangeTrayAttachments(attachments, isPicture) {
13
+ const arrangement = { chips: [], pictures: [] };
14
+ attachments.forEach((attachment, index) => {
15
+ if (isPastedTextAttachment(attachment))
16
+ return;
17
+ if (isPicture(attachment))
18
+ arrangement.pictures.push({ attachment, index });
19
+ else
20
+ arrangement.chips.push({ attachment, index });
21
+ });
22
+ return arrangement;
23
+ }
24
+ /** Whether the tray has anything to draw: some file that is not a pasted text. */
25
+ export function trayHasTiles(attachments) {
26
+ return attachments.some((attachment) => !isPastedTextAttachment(attachment));
27
+ }