@widgetic/chat 0.1.42 → 0.1.43

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 (83) hide show
  1. package/README.md +461 -6
  2. package/dist/components/Chat.svelte +1078 -87
  3. package/dist/components/Chat.svelte.d.ts +102 -2
  4. package/dist/components/ChatComposer.svelte +382 -9
  5. package/dist/components/ChatComposer.svelte.d.ts +66 -3
  6. package/dist/components/ChatMessageQueue.svelte +56 -0
  7. package/dist/components/ChatMessageQueue.svelte.d.ts +20 -0
  8. package/dist/components/ChatMessages.svelte +477 -46
  9. package/dist/components/ChatMessages.svelte.d.ts +45 -2
  10. package/dist/components/ComposerAttachmentsTray.svelte +42 -10
  11. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +5 -0
  12. package/dist/components/ComposerMentionChips.svelte +53 -0
  13. package/dist/components/ComposerMentionChips.svelte.d.ts +15 -0
  14. package/dist/components/FollowUpCard.svelte +134 -0
  15. package/dist/components/FollowUpCard.svelte.d.ts +17 -0
  16. package/dist/components/MentionChip.svelte +41 -0
  17. package/dist/components/MentionChip.svelte.d.ts +12 -0
  18. package/dist/components/MentionMenu.svelte +114 -0
  19. package/dist/components/MentionMenu.svelte.d.ts +19 -0
  20. package/dist/components/agent/AgentAvatar.svelte +6 -4
  21. package/dist/components/agent/AgentAvatar.svelte.d.ts +1 -1
  22. package/dist/components/agent/CodeCard.svelte +122 -27
  23. package/dist/components/agent/CodeCard.svelte.d.ts +3 -0
  24. package/dist/components/agent/CodeDiff.svelte +180 -0
  25. package/dist/components/agent/CodeDiff.svelte.d.ts +10 -0
  26. package/dist/components/agent/GenerationModule.svelte +13 -2
  27. package/dist/components/agent/GenerationModule.svelte.d.ts +3 -0
  28. package/dist/components/index.d.ts +4 -0
  29. package/dist/components/index.js +9 -0
  30. package/dist/errors/logTechnicalUserError.d.ts +1 -0
  31. package/dist/errors/logTechnicalUserError.js +37 -0
  32. package/dist/i18n/messages.d.ts +106 -1
  33. package/dist/i18n/messages.js +112 -1
  34. package/dist/i18n/sketchLocales.js +8 -8
  35. package/dist/messageQueue.d.ts +83 -0
  36. package/dist/messageQueue.js +84 -0
  37. package/dist/services/sketchAssistantClient.js +6 -2
  38. package/dist/services/sketchAssistantErrors.d.ts +4 -0
  39. package/dist/services/sketchAssistantErrors.js +22 -0
  40. package/dist/services/sketchAssistantOrchestrator.d.ts +1 -6
  41. package/dist/services/sketchAssistantOrchestrator.js +10 -24
  42. package/dist/services/sketchAssistantReply.js +3 -1
  43. package/dist/stores/chatStore.d.ts +5 -0
  44. package/dist/stores/chatStore.js +21 -0
  45. package/dist/types/agent.d.ts +4 -3
  46. package/dist/types/attachment.d.ts +16 -0
  47. package/dist/types/config.d.ts +6 -0
  48. package/dist/types/index.d.ts +1 -0
  49. package/dist/types/index.js +2 -0
  50. package/dist/types/mention.d.ts +40 -0
  51. package/dist/types/mention.js +8 -0
  52. package/dist/types/message.d.ts +60 -1
  53. package/dist/utils/agentTurn.d.ts +40 -9
  54. package/dist/utils/agentTurn.js +43 -11
  55. package/dist/utils/attachmentProgress.d.ts +12 -0
  56. package/dist/utils/attachmentProgress.js +18 -0
  57. package/dist/utils/bubbleRichFit.d.ts +68 -0
  58. package/dist/utils/bubbleRichFit.js +45 -0
  59. package/dist/utils/bubbleShrinkWrap.d.ts +8 -1
  60. package/dist/utils/bubbleShrinkWrap.js +113 -17
  61. package/dist/utils/codeChanges.d.ts +103 -0
  62. package/dist/utils/codeChanges.js +226 -0
  63. package/dist/utils/codeHighlight.js +1 -0
  64. package/dist/utils/codeStreamFormat.d.ts +5 -2
  65. package/dist/utils/composerMentions.d.ts +96 -0
  66. package/dist/utils/composerMentions.js +217 -0
  67. package/dist/utils/followUps.d.ts +74 -0
  68. package/dist/utils/followUps.js +116 -0
  69. package/dist/utils/generationArchiveStore.d.ts +6 -0
  70. package/dist/utils/generationArchiveStore.js +11 -3
  71. package/dist/utils/index.d.ts +12 -0
  72. package/dist/utils/index.js +20 -0
  73. package/dist/utils/orderedLine.d.ts +29 -0
  74. package/dist/utils/orderedLine.js +17 -0
  75. package/dist/utils/pastedContent.d.ts +99 -0
  76. package/dist/utils/pastedContent.js +258 -0
  77. package/dist/utils/questionCards.d.ts +131 -0
  78. package/dist/utils/questionCards.js +287 -0
  79. package/dist/utils/referenceItems.d.ts +36 -0
  80. package/dist/utils/referenceItems.js +56 -0
  81. package/dist/utils/sentReferenceBadges.d.ts +26 -0
  82. package/dist/utils/sentReferenceBadges.js +32 -0
  83. package/package.json +1 -1
@@ -0,0 +1,116 @@
1
+ /** The most words a pill shows. The gateway writes titles of at most this; a longer one is cut when read. */
2
+ export const FOLLOW_UP_TITLE_WORDS = 5;
3
+ /** The most characters a pill shows (a language with no spaces has no words to count, so this is what holds it). */
4
+ export const FOLLOW_UP_TITLE_CHARS = 40;
5
+ /** The most pills one card draws, whatever the reply carries. */
6
+ export const FOLLOW_UP_MAX_PILLS = 5;
7
+ /** A text as one line, compared without regard to case or spacing: the key of a request. */
8
+ export function normalizeRequest(text) {
9
+ return text.normalize('NFC').replace(/\s+/g, ' ').trim().toLowerCase();
10
+ }
11
+ /** A title cut to what a pill shows: at most `FOLLOW_UP_TITLE_WORDS` words and `FOLLOW_UP_TITLE_CHARS` characters. */
12
+ function cutTitle(text) {
13
+ const words = text.replace(/\s+/g, ' ').trim().split(' ').filter((word) => word !== '');
14
+ const byWords = words.slice(0, FOLLOW_UP_TITLE_WORDS).join(' ');
15
+ return byWords.length > FOLLOW_UP_TITLE_CHARS ? byWords.slice(0, FOLLOW_UP_TITLE_CHARS).trim() : byWords;
16
+ }
17
+ /** The title of a chip as a pill shows it, or '' when the chip has none (it is then an option of a question). */
18
+ export function followUpTitleOf(suggestion) {
19
+ const title = suggestion?.title;
20
+ return typeof title === 'string' ? cutTitle(title) : '';
21
+ }
22
+ /**
23
+ * Whether a chip is a follow-up pill: a plain `refine` chip with words to ask and a title. The sketch's undo chip and the
24
+ * "generate anyway" chip of a question are never pills, and a chip with no title is an option of a question.
25
+ */
26
+ export function isFollowUpSuggestion(suggestion) {
27
+ if (!suggestion || suggestion.undoSketch)
28
+ return false;
29
+ if (suggestion.intent !== 'refine')
30
+ return false;
31
+ if (typeof suggestion.label !== 'string' || suggestion.label.trim() === '')
32
+ return false;
33
+ return followUpTitleOf(suggestion) !== '';
34
+ }
35
+ /** The chips of a reply that are options of a question: everything that is not a follow-up pill. */
36
+ export function questionOptionsOf(suggestions) {
37
+ return (suggestions ?? []).filter((suggestion) => !isFollowUpSuggestion(suggestion));
38
+ }
39
+ /**
40
+ * The options of the question card a reply shows now: those of `questionOptionsOf`, or none once the person pressed Skip on
41
+ * that reply's card (`skippedReplyIds`, kept with `withQuestionSkipped`). Without options there is no card: the words of the
42
+ * question are then drawn as a plain message, and the turn no longer waits for an answer.
43
+ */
44
+ export function openQuestionOptionsOf(suggestions, replyId, skippedReplyIds) {
45
+ return skippedReplyIds.includes(replyId) ? [] : questionOptionsOf(suggestions);
46
+ }
47
+ /**
48
+ * The replies whose question card was skipped, with one more: each reply is named once, in the order the cards were skipped.
49
+ * A new list every time (nothing is changed in place), so a `$state` that holds it notices the change. An empty id is not a reply.
50
+ */
51
+ export function withQuestionSkipped(skippedReplyIds, replyId) {
52
+ if (!replyId || skippedReplyIds.includes(replyId))
53
+ return [...skippedReplyIds];
54
+ return [...skippedReplyIds, replyId];
55
+ }
56
+ /** The pills a reply makes: its follow-up chips, one for each request (a repeat is left out), at most `FOLLOW_UP_MAX_PILLS`. */
57
+ export function followUpPillsOf(suggestions) {
58
+ const pills = [];
59
+ const seen = new Set();
60
+ for (const suggestion of suggestions ?? []) {
61
+ if (!isFollowUpSuggestion(suggestion))
62
+ continue;
63
+ const request = suggestion.label.trim();
64
+ const id = normalizeRequest(request);
65
+ if (seen.has(id))
66
+ continue;
67
+ seen.add(id);
68
+ pills.push({ id, title: followUpTitleOf(suggestion), request });
69
+ if (pills.length >= FOLLOW_UP_MAX_PILLS)
70
+ break;
71
+ }
72
+ return pills;
73
+ }
74
+ /**
75
+ * The card the conversation shows now, or null. It is made from the newest reply that has follow-ups, looking back from the end
76
+ * of the conversation and stopping at the first message of the person: a message sent takes the card away, and an older turn's
77
+ * ideas never come back. The reply need not be one the chat shows: the chips of a build ride on the saved summary of it ("Updated
78
+ * 2 files"), which the chat keeps out of sight. A reply that was rolled back by a restore, and one the host marked with
79
+ * `metadata.panelFollowUp === false`, are skipped.
80
+ */
81
+ export function findFollowUpCard(messages) {
82
+ for (let index = messages.length - 1; index >= 0; index--) {
83
+ const message = messages[index];
84
+ if (message.messageType === 'user')
85
+ return null;
86
+ if (message.messageType !== 'assistant' || message.rolledBackAt)
87
+ continue;
88
+ if (message.metadata?.panelFollowUp === false)
89
+ continue;
90
+ const pills = followUpPillsOf(message.suggestions);
91
+ if (pills.length > 0)
92
+ return { replyId: message.id, pills };
93
+ }
94
+ return null;
95
+ }
96
+ /** Whether a pill's request is in the message box: what makes the pill show as checked (and refuse a second pick). */
97
+ export function isRequestInDraft(draftText, request) {
98
+ const needle = normalizeRequest(request);
99
+ if (needle === '' || typeof draftText !== 'string')
100
+ return false;
101
+ return normalizeRequest(draftText).includes(needle);
102
+ }
103
+ /** What a dismissed pill is remembered by: the reply it was offered under and its request. */
104
+ export function followUpDismissKey(replyId, pill) {
105
+ return `${replyId}\u0000${pill.id}`;
106
+ }
107
+ /** The card with the pills the person took out left out; null when none is left (the card goes with its last pill). */
108
+ export function withoutDismissedPills(card, dismissedKeys) {
109
+ if (!card)
110
+ return null;
111
+ if (dismissedKeys.length === 0)
112
+ return card;
113
+ const hidden = new Set(dismissedKeys);
114
+ const pills = card.pills.filter((pill) => !hidden.has(followUpDismissKey(card.replyId, pill)));
115
+ return pills.length > 0 ? { replyId: card.replyId, pills } : null;
116
+ }
@@ -1,4 +1,5 @@
1
1
  /** Local persistence for panel generation archive (thinking + code tails), keyed by conversation. */
2
+ import { type CodeChanges } from './codeChanges.js';
2
3
  export type GenerationArchiveRecord = {
3
4
  thinking: string;
4
5
  code: string;
@@ -8,6 +9,11 @@ export type GenerationArchiveRecord = {
8
9
  * last run of a conversation, which is not always the turn that is newest now). Records saved before this was kept have none.
9
10
  */
10
11
  prompt?: string;
12
+ /**
13
+ * What the run changed in the widget's files (the diff the code card shows under its conclusion), when the host gave it.
14
+ * Records saved before this was kept have none.
15
+ */
16
+ changes?: CodeChanges | null;
11
17
  updatedAt: number;
12
18
  };
13
19
  export declare function loadGenerationArchive(conversationId: string | null | undefined): Promise<GenerationArchiveRecord | null>;
@@ -1,4 +1,5 @@
1
1
  /** Local persistence for panel generation archive (thinking + code tails), keyed by conversation. */
2
+ import { readCodeChanges } from './codeChanges.js';
2
3
  const DB_NAME = 'widgetic-chat-generation-archive';
3
4
  const STORE = 'byConversation';
4
5
  const DB_VERSION = 1;
@@ -29,7 +30,9 @@ export async function loadGenerationArchive(conversationId) {
29
30
  const req = tx.objectStore(STORE).get(conversationId);
30
31
  req.onsuccess = () => {
31
32
  const row = req.result;
32
- if (!row?.thinking?.trim() && !row?.code?.trim()) {
33
+ // Read again, not trusted: what is in the browser's storage is data of a past version, or of no version at all
34
+ const savedChanges = readCodeChanges(row?.changes);
35
+ if (!row || (!row.thinking?.trim() && !row.code?.trim() && savedChanges === null)) {
33
36
  resolve(null);
34
37
  return;
35
38
  }
@@ -38,6 +41,7 @@ export async function loadGenerationArchive(conversationId) {
38
41
  code: row.code ?? '',
39
42
  thoughtSeconds: row.thoughtSeconds ?? null,
40
43
  prompt: typeof row.prompt === 'string' ? row.prompt : '',
44
+ changes: savedChanges,
41
45
  updatedAt: row.updatedAt ?? 0,
42
46
  });
43
47
  };
@@ -52,15 +56,19 @@ export async function loadGenerationArchive(conversationId) {
52
56
  export async function saveGenerationArchive(conversationId, record) {
53
57
  if (!conversationId)
54
58
  return;
55
- if (!record.thinking.trim() && !record.code.trim())
56
- return;
57
59
  try {
60
+ // Read again into plain data: IndexedDB cannot copy a proxy, and a record that fails to copy would lose the thinking and the
61
+ // code with it. The read also keeps what is written inside the bounds of `readCodeChanges`.
62
+ const changesToSave = readCodeChanges(record.changes);
63
+ if (!record.thinking.trim() && !record.code.trim() && changesToSave === null)
64
+ return;
58
65
  const db = await openDb();
59
66
  await new Promise((resolve, reject) => {
60
67
  const tx = db.transaction(STORE, 'readwrite');
61
68
  tx.objectStore(STORE).put({
62
69
  conversationId,
63
70
  ...record,
71
+ changes: changesToSave,
64
72
  updatedAt: Date.now(),
65
73
  });
66
74
  tx.oncomplete = () => resolve();
@@ -1,4 +1,8 @@
1
1
  export { fileTypeConfig, detectFileType, validateFile, validateFiles, formatFileSize, getFileExtension, generateFileId, createFilePreview, createPendingAttachment, getAcceptString, supportsPreview, getFileIcon, compressImage } from './fileUtils.js';
2
+ export { PASTED_TEXT_MIN_CHARACTERS, PASTED_TEXT_MIN_LINES, PASTED_TEXT_FILE_NAME, PASTED_TEXT_LABEL_MAX_CHARACTERS, DEFAULT_PASTED_TEXT_THRESHOLDS, attachmentsFromPaste, isLongPastedText, pastedTextLabel, textAsFile, uniqueFileName, withUniqueFileNames, prepareImagesOfPaste } from './pastedContent.js';
3
+ export type { PastedAttachment, PastedTextThresholds, PasteSource, PasteSourceItem } from './pastedContent.js';
4
+ export { createOrderedLine } from './orderedLine.js';
5
+ export type { OrderedLine, PlaceInLine } from './orderedLine.js';
2
6
  export { VERSION_RATINGS, ratingAfterPress, ratingOfVersion, isRatableVersionReply } from './versionRatings.js';
3
7
  export type { VersionThumb } from './versionRatings.js';
4
8
  export { setLogsEnabled, chatLog, chatWarn, chatError } from './logger.js';
@@ -6,8 +10,16 @@ export { readThinkingTail, readCodegenStreamTail, generationActivityPhase, thoug
6
10
  export type { GenerationActivityPhase } from './generationActivity.js';
7
11
  export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './generationPlan.js';
8
12
  export type { GenerationPlanWire, MappedGenerationPlanCard, WidgetPlanTaskStatusWire, } from './generationPlan.js';
13
+ export { readCodeChanges, readCodeChangesFromMetadata } from './codeChanges.js';
14
+ export type { CodeChangeFile, CodeChangeStatus, CodeChanges } from './codeChanges.js';
9
15
  export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, pageNamesPeople, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
10
16
  export { CHIP_NOTE_MAX_CHARACTERS, CHIP_NOTE_MAX_WORDS, firstWords, selectedElementChipLabel, selectedElementChipTitle, selectedElementName, } from './selectedElementChip.js';
11
17
  export type { SelectedElementChipSource } from './selectedElementChip.js';
18
+ export { FOLLOW_UP_MAX_PILLS, FOLLOW_UP_TITLE_CHARS, FOLLOW_UP_TITLE_WORDS, findFollowUpCard, followUpPillsOf, followUpTitleOf, isFollowUpSuggestion, isRequestInDraft, questionOptionsOf } from './followUps.js';
19
+ export type { FollowUpCardModel, FollowUpPill } from './followUps.js';
20
+ export { QUESTION_ANSWER_LINE_SEPARATOR, QUESTION_CARD_MAX_OPTIONS, QUESTION_CARD_MAX_QUESTIONS, answersFromPicks, areAllAnswersSkipped, chipQuestionOutcomeOf, isSkippedAnswer, keepLocalQuestionCards, openQuestionCardOf, picksOfAnswer, questionCardFromClarification, questionCardOf, questionCardPlainText, questionCardStateOf, skippedAnswersOf, skippedRowsOf, summaryRowsOf, withoutRecommendedWord } from './questionCards.js';
21
+ export type { ChipQuestionOutcome, QuestionCardState, QuestionCardSummaryRow } from './questionCards.js';
22
+ export { DEFAULT_MENTION_LIMIT, MAX_MENTION_LINK_HINTS, addMention, buildMentionRows, caretAfterMentionInsert, findActiveMentionTrigger, findMentionLinkHints, firstSelectableRowIndex, hasMention, insertMentionText, linkHostsOfText, mentionItemMatches, mentionKey, mentionOptionId, mentionRowsHaveSeveralKinds, nextSelectableRowIndex, registrableDomain, removeMention, } from './composerMentions.js';
23
+ export type { ActiveMentionTrigger, MentionLinkHint, MentionRow, MentionRowUnavailable } from './composerMentions.js';
12
24
  export type { AgentAvatarSize, AgentLook, AvatarStart, FinishedGeneration, GenerationModulesView, SoundStateInput, TurnOutcome, TurnReplyFacts } from './agentTurn.js';
13
25
  export type { AttachmentType, AttachmentValidation, PendingAttachment, UploadStatus } from '../types/index.js';
@@ -1,13 +1,33 @@
1
1
  // File utilities
2
2
  export { fileTypeConfig, detectFileType, validateFile, validateFiles, formatFileSize, getFileExtension, generateFileId, createFilePreview, createPendingAttachment, getAcceptString, supportsPreview, getFileIcon, compressImage } from './fileUtils.js';
3
+ // What a paste into the message box brings in: a screenshot or a file becomes an attachment, and so does a long text (as a text file).
4
+ // Every paste is an attachment of its own: `withUniqueFileNames` gives it a name no other file of the message has, and
5
+ // `prepareImagesOfPaste` makes its pictures ready for upload (made smaller, in the chat) all at once, in the order of the paste.
6
+ export { PASTED_TEXT_MIN_CHARACTERS, PASTED_TEXT_MIN_LINES, PASTED_TEXT_FILE_NAME, PASTED_TEXT_LABEL_MAX_CHARACTERS, DEFAULT_PASTED_TEXT_THRESHOLDS, attachmentsFromPaste, isLongPastedText, pastedTextLabel, textAsFile, uniqueFileName, withUniqueFileNames, prepareImagesOfPaste } from './pastedContent.js';
7
+ // A line for things that start together but have to come out in the order they started (the tiles of pictures read at once)
8
+ export { createOrderedLine } from './orderedLine.js';
3
9
  // The thumbs next to a version
4
10
  export { VERSION_RATINGS, ratingAfterPress, ratingOfVersion, isRatableVersionReply } from './versionRatings.js';
5
11
  // Logger
6
12
  export { setLogsEnabled, chatLog, chatWarn, chatError } from './logger.js';
7
13
  export { readThinkingTail, readCodegenStreamTail, generationActivityPhase, thoughtDurationSeconds, generationActivityAriaKey, } from './generationActivity.js';
8
14
  export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './generationPlan.js';
15
+ // What a round changed in the widget's files, for the "Changes" view of the code card: the gateway sends it in the metadata of the
16
+ // completed operation (`metadata.codeChanges`); a page reads it with `readCodeChangesFromMetadata` and gives it to `Chat` as
17
+ // `generationChanges`.
18
+ export { readCodeChanges, readCodeChangesFromMetadata } from './codeChanges.js';
9
19
  // The assistant's turn: its avatar's looks, the judgement of a finished turn, who wrote a message, what is kept of the work.
10
20
  // A page that is not the chat (the workflows assistant) follows the same choreography through these.
11
21
  export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, pageNamesPeople, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
12
22
  // What the chip of a picked part says: the first words of its note, or its name while the note is empty.
13
23
  export { CHIP_NOTE_MAX_CHARACTERS, CHIP_NOTE_MAX_WORDS, firstWords, selectedElementChipLabel, selectedElementChipTitle, selectedElementName, } from './selectedElementChip.js';
24
+ // The follow-up card (ideas for what to improve next, as pills under the last reply): which chips are pills (the ones with a
25
+ // title), the card a conversation makes, and "checked" read from the message box. For a page that keeps its own list of messages.
26
+ export { FOLLOW_UP_MAX_PILLS, FOLLOW_UP_TITLE_CHARS, FOLLOW_UP_TITLE_WORDS, findFollowUpCard, followUpPillsOf, followUpTitleOf, isFollowUpSuggestion, isRequestInDraft, questionOptionsOf } from './followUps.js';
27
+ // The card of questions the assistant puts to the person before it builds: each question says on its own whether one option or
28
+ // several can be picked, Next with nothing picked skips that question (the assistant decides it), and a message written in the chat
29
+ // instead of answering skips them all. For a page that keeps its own list of messages, or that turns the gateway's card into one.
30
+ export { QUESTION_ANSWER_LINE_SEPARATOR, QUESTION_CARD_MAX_OPTIONS, QUESTION_CARD_MAX_QUESTIONS, answersFromPicks, areAllAnswersSkipped, chipQuestionOutcomeOf, isSkippedAnswer, keepLocalQuestionCards, openQuestionCardOf, picksOfAnswer, questionCardFromClarification, questionCardOf, questionCardPlainText, questionCardStateOf, skippedAnswersOf, skippedRowsOf, summaryRowsOf, withoutRecommendedWord } from './questionCards.js';
31
+ // The rules of the @ menu in the message box: when the caret is inside a mention, the rows to show, what a pick writes, the picks of a
32
+ // message, and the links that are offered as a pick. A page that builds its own message box follows the same rules through these.
33
+ export { DEFAULT_MENTION_LIMIT, MAX_MENTION_LINK_HINTS, addMention, buildMentionRows, caretAfterMentionInsert, findActiveMentionTrigger, findMentionLinkHints, firstSelectableRowIndex, hasMention, insertMentionText, linkHostsOfText, mentionItemMatches, mentionKey, mentionOptionId, mentionRowsHaveSeveralKinds, nextSelectableRowIndex, registrableDomain, removeMention, } from './composerMentions.js';
@@ -0,0 +1,29 @@
1
+ /**
2
+ * A line for things that start together but have to come out in the order they started.
3
+ *
4
+ * The chat uses it for the pictures it is handed (a pasted screenshot, a restored draft): all of them are read at once, as
5
+ * reading is the slow part, but each one's tile is added only after the tile of the picture handed in before it. Without
6
+ * the line, a big screenshot pasted just before a small one would get its tile after it.
7
+ *
8
+ * ```ts
9
+ * const place = line.takePlace(); // at once, in the order the things come
10
+ * try {
11
+ * const picture = await readPicture(); // all of them wait for this together
12
+ * await place.untilReached; // until the ones before it have had their turn
13
+ * addTile(picture);
14
+ * } finally {
15
+ * place.leave(); // always, also when reading failed
16
+ * }
17
+ * ```
18
+ */
19
+ export interface PlaceInLine {
20
+ /** Ends when every place taken before this one has been left. It never fails, so it needs no `catch`. */
21
+ untilReached: Promise<void>;
22
+ /** Leaves the place, so the places after it can be reached. Calling it again does nothing more. */
23
+ leave: () => void;
24
+ }
25
+ export interface OrderedLine {
26
+ /** Takes the next place in the line. It is taken at once: the order is that of the calls, not of what ends first. */
27
+ takePlace: () => PlaceInLine;
28
+ }
29
+ export declare function createOrderedLine(): OrderedLine;
@@ -0,0 +1,17 @@
1
+ export function createOrderedLine() {
2
+ // Ends when every place taken so far has been left.
3
+ let everyPlaceTakenSoFarLeft = Promise.resolve();
4
+ return {
5
+ takePlace() {
6
+ const placesBeforeLeft = everyPlaceTakenSoFarLeft;
7
+ let leave = () => { };
8
+ const thisPlaceLeft = new Promise((resolve) => {
9
+ leave = resolve;
10
+ });
11
+ // The line goes on only when this place AND the ones before it have been left. A place left early (a picture that could
12
+ // not be read, so it does not wait) therefore cannot let the places after it be reached before the ones ahead of it.
13
+ everyPlaceTakenSoFarLeft = Promise.all([placesBeforeLeft, thisPlaceLeft]).then(() => undefined);
14
+ return { untilReached: placesBeforeLeft, leave };
15
+ },
16
+ };
17
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * What a paste into the message box brings in. A picture on the clipboard (a screenshot, an image copied from a page), a
3
+ * file copied in the file manager, or a long text becomes an attachment, the way a file dropped on the box would. A short
4
+ * text is no attachment: the browser types it into the box, as it always did.
5
+ *
6
+ * Pure rules, no DOM and no Svelte: `attachmentsFromPaste` reads what `ClipboardEvent.clipboardData` offers (the tests give
7
+ * it a plain object), so a page with a composer of its own (the workflows assistant) can follow the same rules.
8
+ */
9
+ /** A pasted text of at least this many characters is attached as a text file instead of being typed into the box. */
10
+ export declare const PASTED_TEXT_MIN_CHARACTERS = 500;
11
+ /** A pasted text of at least this many lines is attached as a text file, even when its lines are short. */
12
+ export declare const PASTED_TEXT_MIN_LINES = 12;
13
+ /**
14
+ * The name a pasted text is attached under. It is the name the server stores the file under (and puts in the address of the
15
+ * stored file), so it says nothing of the text: the first words of the text are the label of the chip, which stays on screen.
16
+ */
17
+ export declare const PASTED_TEXT_FILE_NAME = "pasted-text.txt";
18
+ /** The name given to a pasted picture that came without one (the extension is added from its type). */
19
+ export declare const PASTED_IMAGE_FILE_NAME = "pasted-image";
20
+ /** The name given to a pasted file, that is not a picture, that came without one. */
21
+ export declare const PASTED_FILE_NAME = "pasted-file";
22
+ /** Longest label of a pasted text, in characters. The chip cuts it again with an ellipsis where it has less room. */
23
+ export declare const PASTED_TEXT_LABEL_MAX_CHARACTERS = 60;
24
+ /** How long a text must be to be attached as a file instead of typed into the box. */
25
+ export interface PastedTextThresholds {
26
+ minCharacters: number;
27
+ minLines: number;
28
+ }
29
+ /** The thresholds a page gets when it gives none of its own. */
30
+ export declare const DEFAULT_PASTED_TEXT_THRESHOLDS: PastedTextThresholds;
31
+ /** One file made by a paste, with the words its chip may say in place of the name of the file. */
32
+ export interface PastedAttachment {
33
+ file: File;
34
+ /** The first words of a pasted text. It is for the screen only: it is never sent anywhere, the name of the file is. */
35
+ label?: string;
36
+ }
37
+ /** One entry of `clipboardData.items`, as much as the rules read of it. */
38
+ export interface PasteSourceItem {
39
+ readonly kind: string;
40
+ getAsFile(): File | null;
41
+ }
42
+ /** What the rules read of a clipboard: `ClipboardEvent.clipboardData` fits it, and so does a plain object in a test. */
43
+ export interface PasteSource {
44
+ readonly files?: ArrayLike<File> | null;
45
+ readonly items?: ArrayLike<PasteSourceItem> | null;
46
+ getData(format: string): string;
47
+ }
48
+ /** Whether a text is long enough to be attached as a file instead of typed into the box. */
49
+ export declare function isLongPastedText(text: string, thresholds?: Partial<PastedTextThresholds>): boolean;
50
+ /**
51
+ * The first words of a text, on one line, for the chip of the file made from it: "Great direction — a sketch of ...".
52
+ * Undefined when the text has no word at all. A line that is too long is cut between two words, when there is a space in its
53
+ * second half to cut at, and else where it reaches the limit (a text with no spaces, like Chinese). Cut by characters a
54
+ * person sees: an emoji is never cut in half.
55
+ */
56
+ export declare function pastedTextLabel(text: string): string | undefined;
57
+ /** A text as the file a person could have dropped on the box. The type is the plain one a text file has, with no charset. */
58
+ export declare function textAsFile(text: string): File;
59
+ /**
60
+ * `name`, or when someone has it already (`takenNames`, compared the way a file manager does, without regard to case) the first
61
+ * of "name-2", "name-3", … that nobody has. The number goes before the extension. A name that is free is returned as it is.
62
+ */
63
+ export declare function uniqueFileName(name: string, takenNames: Iterable<string>): string;
64
+ /**
65
+ * What a paste brought in, each file under a name that differs from the others of the paste and from `takenNames` (the files
66
+ * already attached to the message). A browser calls every screenshot "image.png" and a long text is always attached as
67
+ * "pasted-text.txt": the builder is told the text files it reads by name, and the person is told by name which of them it
68
+ * could not read, so two pastes that share a name cannot be told apart. A paste whose name is free is returned as it is; one
69
+ * that is renamed is a new file with the same bytes, type and date. The list given is not changed.
70
+ */
71
+ export declare function withUniqueFileNames(pastedAttachments: PastedAttachment[], takenNames?: Iterable<string>): PastedAttachment[];
72
+ /**
73
+ * How long a picture may take to be made ready before it is attached as it came. The pastes of the chat stand in a line (a
74
+ * paste gets its tile after the paste before it), so a picture that is never made ready, because the browser never finishes
75
+ * reading it, would hold up every paste after it. A big picture takes a second or two; this is far beyond that.
76
+ */
77
+ export declare const PASTED_IMAGE_PREPARATION_TIME_LIMIT_MS = 15000;
78
+ /**
79
+ * One picture made ready by `prepareImage`, or the picture as it came when that fails, hands nothing back, or takes longer
80
+ * than `timeLimitMilliseconds`: a paste is never lost, and never held up for ever, because of how its picture was prepared.
81
+ * What is not ready in time is left to finish on its own; its result is not used.
82
+ */
83
+ export declare function prepareImageWithTimeLimit(file: File, prepareImage: (file: File) => Promise<File>, timeLimitMilliseconds?: number): Promise<File>;
84
+ /**
85
+ * What a paste brought in, with each picture made ready for upload by `prepareImage` (in the chat: made smaller when it is
86
+ * large, see `prepareChatImageFileForUpload`), the way a dropped picture is. The pictures of a paste are prepared all at once,
87
+ * so a paste of several does not take the longer for it. The result keeps the order and the length of the list; a text or any
88
+ * other file is handed back as it is, label and all, and so is a picture that `prepareImage` left as it was. A picture that
89
+ * cannot be prepared (`prepareImage` threw, or took longer than the time limit) stays as it came: a paste is never lost for
90
+ * that, see `prepareImageWithTimeLimit`. The list given is not changed. The function that prepares is given by the caller, so
91
+ * these rules still need no DOM.
92
+ */
93
+ export declare function prepareImagesOfPaste(pastedAttachments: PastedAttachment[], prepareImage: (file: File) => Promise<File>, timeLimitMilliseconds?: number): Promise<PastedAttachment[]>;
94
+ /**
95
+ * What a paste brings in as attachments, in the order of the list: the pictures and files that were pasted, or one text file
96
+ * made from a long pasted text. An empty list means "nothing to attach": the paste is an ordinary one and the browser types
97
+ * the text into the box.
98
+ */
99
+ export declare function attachmentsFromPaste(source: PasteSource | null | undefined, thresholds?: Partial<PastedTextThresholds>): PastedAttachment[];