@widgetic/chat 0.1.37 → 0.1.39
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.
- package/dist/components/AttachmentDisplay.svelte +14 -4
- package/dist/components/Chat.svelte +155 -116
- package/dist/components/Chat.svelte.d.ts +4 -0
- package/dist/components/ChatComposer.svelte +63 -0
- package/dist/components/ChatComposer.svelte.d.ts +2 -0
- package/dist/components/ChatMessages.svelte +129 -20
- package/dist/components/ChatMessages.svelte.d.ts +2 -0
- package/dist/components/CodeBlock.svelte +9 -1
- package/dist/components/ComposerAttachmentsTray.svelte +64 -0
- package/dist/components/ComposerAttachmentsTray.svelte.d.ts +11 -0
- package/dist/components/PanelChatHeader.svelte +26 -6
- package/dist/components/PanelChatHeader.svelte.d.ts +1 -0
- package/dist/components/PanelFollowUpSuggestions.svelte +2 -2
- package/dist/components/PanelSuggestionButtons.svelte +2 -1
- package/dist/i18n/index.d.ts +1 -0
- package/dist/i18n/index.js +1 -0
- package/dist/i18n/messages.d.ts +4 -1
- package/dist/i18n/messages.js +4 -1
- package/dist/i18n/publishNudgeLocales.d.ts +18 -0
- package/dist/i18n/publishNudgeLocales.js +17 -0
- package/dist/sendNudgeState.d.ts +5 -0
- package/dist/sendNudgeState.js +18 -0
- package/dist/types/attachment.d.ts +5 -0
- package/dist/utils/attachmentPreviewUrl.d.ts +21 -0
- package/dist/utils/attachmentPreviewUrl.js +39 -0
- package/dist/utils/chatImageUploadPrep.d.ts +22 -0
- package/dist/utils/chatImageUploadPrep.js +90 -0
- package/dist/utils/generationArchiveStore.d.ts +10 -0
- package/dist/utils/generationArchiveStore.js +88 -0
- package/dist/utils/imageTransform.d.ts +12 -0
- package/dist/utils/imageTransform.js +45 -0
- package/dist/utils/linkifyText.d.ts +16 -0
- package/dist/utils/linkifyText.js +57 -0
- package/dist/utils/suggestionDraft.d.ts +5 -0
- package/dist/utils/suggestionDraft.js +15 -0
- package/package.json +3 -3
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Host-facing translations for `chat.input.publishNudge` (one row per ui-sdk module locale). */
|
|
2
|
+
export const PUBLISH_NUDGE_ENGLISH = 'First generate your widget, then you can publish it.';
|
|
3
|
+
export const PUBLISH_NUDGE_BY_LOCALE = {
|
|
4
|
+
en: PUBLISH_NUDGE_ENGLISH,
|
|
5
|
+
ar: 'أنشئ الويدجت أولاً، ثم يمكنك نشره.',
|
|
6
|
+
da: 'Generér din widget først, og udgiv den derefter.',
|
|
7
|
+
de: 'Erzeuge zuerst dein Widget, danach kannst du es veröffentlichen.',
|
|
8
|
+
es: 'Primero genera tu widget y luego podrás publicarlo.',
|
|
9
|
+
fa: 'اول ویجت را تولید کنید، بعد میتوانید آن را منتشر کنید.',
|
|
10
|
+
fr: "Générez d'abord votre widget, puis vous pourrez le publier.",
|
|
11
|
+
he: 'תחילה צור את הווידג׳ט, ואז תוכל לפרסם אותו.',
|
|
12
|
+
nl: 'Genereer eerst je widget; daarna kun je publiceren.',
|
|
13
|
+
'pt-BR': 'Primeiro gere o seu widget; depois você poderá publicá-lo.',
|
|
14
|
+
sv: 'Generera widgeten först, sedan kan du publicera den.',
|
|
15
|
+
ur: 'پہلے اپنا ویجٹ بنائیں، پھر آپ اسے شائع کر سکتے ہیں۔',
|
|
16
|
+
'zh-CN': '请先生成小组件,然后再发布。',
|
|
17
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type SendNudgePhase = 'idle' | 'active' | 'cleared';
|
|
2
|
+
export type SendNudgeEvent = 'trigger' | 'autoHide' | 'userInteract' | 'reset';
|
|
3
|
+
/** Small state machine for the Send-button publish nudge (bounce + tooltip). */
|
|
4
|
+
export declare function reduceSendNudge(phase: SendNudgePhase, event: SendNudgeEvent): SendNudgePhase;
|
|
5
|
+
export declare const SEND_NUDGE_VISIBLE_MS = 4000;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Small state machine for the Send-button publish nudge (bounce + tooltip). */
|
|
2
|
+
export function reduceSendNudge(phase, event) {
|
|
3
|
+
switch (phase) {
|
|
4
|
+
case 'idle':
|
|
5
|
+
return event === 'trigger' ? 'active' : 'idle';
|
|
6
|
+
case 'active':
|
|
7
|
+
if (event === 'autoHide' || event === 'userInteract')
|
|
8
|
+
return 'cleared';
|
|
9
|
+
if (event === 'trigger')
|
|
10
|
+
return 'active';
|
|
11
|
+
return phase;
|
|
12
|
+
case 'cleared':
|
|
13
|
+
return event === 'reset' ? 'idle' : event === 'trigger' ? 'active' : 'cleared';
|
|
14
|
+
default:
|
|
15
|
+
return 'idle';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export const SEND_NUDGE_VISIBLE_MS = 4000;
|
|
@@ -43,6 +43,11 @@ export interface AttachmentInput {
|
|
|
43
43
|
uploadedUrl?: string;
|
|
44
44
|
/** Widgetic uploads row id (for codegen attachmentIds) */
|
|
45
45
|
uploadId?: string;
|
|
46
|
+
/**
|
|
47
|
+
* An image as a `data:` URL, read when it is attached. A `blob:` preview and a CDN address do not come back after a
|
|
48
|
+
* refresh (the first dies with the page, the second is not an image the draft can rebuild a File from), so the draft keeps this.
|
|
49
|
+
*/
|
|
50
|
+
persistedDataUrl?: string;
|
|
46
51
|
uploadProgress?: number;
|
|
47
52
|
}
|
|
48
53
|
/**
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { AttachmentInput } from '../types/attachment.js';
|
|
2
|
+
/**
|
|
3
|
+
* Makes the address the composer tray draws a picked file with — a `blob:` address of the file on this page.
|
|
4
|
+
*
|
|
5
|
+
* It is made once, when the file is attached, and not while the tray draws: the tray reads the address inside a derived
|
|
6
|
+
* value, and Svelte does not allow a write to state there (the picture of a tile used to stay empty for that reason).
|
|
7
|
+
* The page gives the address back when the attachment is removed or the draft is cleared.
|
|
8
|
+
*
|
|
9
|
+
* @param file The file the person picked.
|
|
10
|
+
* @returns The `blob:` address, or `undefined` for a file that has no picture to show (a text file, say) or when the browser refuses.
|
|
11
|
+
*/
|
|
12
|
+
export declare function createLocalPreviewUrl(file: File | null | undefined): string | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* The address the tray draws an attachment with, in the order of what is best known: the preview of the page, the CDN
|
|
15
|
+
* address of the upload, then the `data:` copy the draft keeps. It only reads: it never writes to the attachment, so it
|
|
16
|
+
* is safe to call from a template or a derived value.
|
|
17
|
+
*
|
|
18
|
+
* @param attachment The attachment of the composer tray.
|
|
19
|
+
* @returns An address a picture can be drawn from, or '' when the attachment has none yet.
|
|
20
|
+
*/
|
|
21
|
+
export declare function readAttachmentPreviewUrl(attachment: Pick<AttachmentInput, 'preview' | 'uploadedUrl' | 'persistedDataUrl'> | null | undefined): string;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Kinds of file that have a picture to draw in the composer tray: images, videos and PDFs. */
|
|
2
|
+
function fileTypeHasLocalPreview(fileType) {
|
|
3
|
+
const type = (fileType || '').toLowerCase();
|
|
4
|
+
return type.startsWith('image/') || type.startsWith('video/') || type === 'application/pdf';
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Makes the address the composer tray draws a picked file with — a `blob:` address of the file on this page.
|
|
8
|
+
*
|
|
9
|
+
* It is made once, when the file is attached, and not while the tray draws: the tray reads the address inside a derived
|
|
10
|
+
* value, and Svelte does not allow a write to state there (the picture of a tile used to stay empty for that reason).
|
|
11
|
+
* The page gives the address back when the attachment is removed or the draft is cleared.
|
|
12
|
+
*
|
|
13
|
+
* @param file The file the person picked.
|
|
14
|
+
* @returns The `blob:` address, or `undefined` for a file that has no picture to show (a text file, say) or when the browser refuses.
|
|
15
|
+
*/
|
|
16
|
+
export function createLocalPreviewUrl(file) {
|
|
17
|
+
if (!file || !fileTypeHasLocalPreview(file.type))
|
|
18
|
+
return undefined;
|
|
19
|
+
try {
|
|
20
|
+
return URL.createObjectURL(file);
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
console.warn('[Chat] Could not make a local preview of the attached file:', error);
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The address the tray draws an attachment with, in the order of what is best known: the preview of the page, the CDN
|
|
29
|
+
* address of the upload, then the `data:` copy the draft keeps. It only reads: it never writes to the attachment, so it
|
|
30
|
+
* is safe to call from a template or a derived value.
|
|
31
|
+
*
|
|
32
|
+
* @param attachment The attachment of the composer tray.
|
|
33
|
+
* @returns An address a picture can be drawn from, or '' when the attachment has none yet.
|
|
34
|
+
*/
|
|
35
|
+
export function readAttachmentPreviewUrl(attachment) {
|
|
36
|
+
if (!attachment)
|
|
37
|
+
return '';
|
|
38
|
+
return attachment.preview || attachment.uploadedUrl || attachment.persistedDataUrl || '';
|
|
39
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-side downscale before chat upload / codegen attachment IDs.
|
|
3
|
+
* Aligns with gateway JEV/Claude standard tier (long edge ≤ 1568 px, ~1.15 MP).
|
|
4
|
+
*/
|
|
5
|
+
export declare const CHAT_AGENT_IMAGE_MAX_LONG_EDGE = 1568;
|
|
6
|
+
export declare const CHAT_AGENT_IMAGE_MAX_PIXELS: number;
|
|
7
|
+
export declare const CHAT_AGENT_IMAGE_TARGET_BYTES = 1500000;
|
|
8
|
+
export declare const CHAT_AGENT_JPEG_QUALITY = 0.85;
|
|
9
|
+
export type ChatImagePrepDecision = {
|
|
10
|
+
action: 'passthrough';
|
|
11
|
+
} | {
|
|
12
|
+
action: 'resize';
|
|
13
|
+
maxLongEdge: number;
|
|
14
|
+
quality: number;
|
|
15
|
+
targetBytes: number;
|
|
16
|
+
};
|
|
17
|
+
/** Pure policy: whether and how to resize before upload. */
|
|
18
|
+
export declare function decideChatImagePrep(width: number, height: number, byteLength: number, mimeType: string): ChatImagePrepDecision;
|
|
19
|
+
/**
|
|
20
|
+
* Downscales raster images for the agent; returns the original file on any skip or failure.
|
|
21
|
+
*/
|
|
22
|
+
export declare function prepareChatImageFileForUpload(file: File): Promise<File>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-side downscale before chat upload / codegen attachment IDs.
|
|
3
|
+
* Aligns with gateway JEV/Claude standard tier (long edge ≤ 1568 px, ~1.15 MP).
|
|
4
|
+
*/
|
|
5
|
+
export const CHAT_AGENT_IMAGE_MAX_LONG_EDGE = 1568;
|
|
6
|
+
export const CHAT_AGENT_IMAGE_MAX_PIXELS = 1_568 * 1_568;
|
|
7
|
+
export const CHAT_AGENT_IMAGE_TARGET_BYTES = 1_500_000;
|
|
8
|
+
export const CHAT_AGENT_JPEG_QUALITY = 0.85;
|
|
9
|
+
/** Pure policy: whether and how to resize before upload. */
|
|
10
|
+
export function decideChatImagePrep(width, height, byteLength, mimeType) {
|
|
11
|
+
if (!mimeType.startsWith('image/'))
|
|
12
|
+
return { action: 'passthrough' };
|
|
13
|
+
if (mimeType === 'image/svg+xml' || mimeType === 'image/gif')
|
|
14
|
+
return { action: 'passthrough' };
|
|
15
|
+
const longEdge = Math.max(width, height);
|
|
16
|
+
const pixels = width * height;
|
|
17
|
+
if (longEdge <= CHAT_AGENT_IMAGE_MAX_LONG_EDGE &&
|
|
18
|
+
pixels <= CHAT_AGENT_IMAGE_MAX_PIXELS &&
|
|
19
|
+
byteLength <= CHAT_AGENT_IMAGE_TARGET_BYTES) {
|
|
20
|
+
return { action: 'passthrough' };
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
action: 'resize',
|
|
24
|
+
maxLongEdge: CHAT_AGENT_IMAGE_MAX_LONG_EDGE,
|
|
25
|
+
quality: CHAT_AGENT_JPEG_QUALITY,
|
|
26
|
+
targetBytes: CHAT_AGENT_IMAGE_TARGET_BYTES,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function loadImageFromFile(file) {
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
const url = URL.createObjectURL(file);
|
|
32
|
+
const img = new Image();
|
|
33
|
+
img.onload = () => {
|
|
34
|
+
URL.revokeObjectURL(url);
|
|
35
|
+
resolve(img);
|
|
36
|
+
};
|
|
37
|
+
img.onerror = () => {
|
|
38
|
+
URL.revokeObjectURL(url);
|
|
39
|
+
reject(new Error('Could not decode image'));
|
|
40
|
+
};
|
|
41
|
+
img.src = url;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function canvasToBlob(canvas, type, quality) {
|
|
45
|
+
return new Promise((resolve) => {
|
|
46
|
+
canvas.toBlob((blob) => resolve(blob), type, quality);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Downscales raster images for the agent; returns the original file on any skip or failure.
|
|
51
|
+
*/
|
|
52
|
+
export async function prepareChatImageFileForUpload(file) {
|
|
53
|
+
if (!file.type.startsWith('image/'))
|
|
54
|
+
return file;
|
|
55
|
+
if (file.type === 'image/svg+xml' || file.type === 'image/gif')
|
|
56
|
+
return file;
|
|
57
|
+
try {
|
|
58
|
+
const img = await loadImageFromFile(file);
|
|
59
|
+
const decision = decideChatImagePrep(img.naturalWidth, img.naturalHeight, file.size, file.type);
|
|
60
|
+
if (decision.action === 'passthrough')
|
|
61
|
+
return file;
|
|
62
|
+
const scale = Math.min(1, decision.maxLongEdge / Math.max(img.naturalWidth, img.naturalHeight));
|
|
63
|
+
const width = Math.max(1, Math.round(img.naturalWidth * scale));
|
|
64
|
+
const height = Math.max(1, Math.round(img.naturalHeight * scale));
|
|
65
|
+
const canvas = document.createElement('canvas');
|
|
66
|
+
canvas.width = width;
|
|
67
|
+
canvas.height = height;
|
|
68
|
+
const ctx = canvas.getContext('2d');
|
|
69
|
+
if (!ctx)
|
|
70
|
+
return file;
|
|
71
|
+
ctx.drawImage(img, 0, 0, width, height);
|
|
72
|
+
const preferPng = file.type === 'image/png' && file.size < 400_000;
|
|
73
|
+
const mime = preferPng ? 'image/png' : 'image/jpeg';
|
|
74
|
+
let quality = decision.quality;
|
|
75
|
+
let blob = await canvasToBlob(canvas, mime, quality);
|
|
76
|
+
if (!blob)
|
|
77
|
+
return file;
|
|
78
|
+
while (blob.size > decision.targetBytes && quality > 0.5 && mime === 'image/jpeg') {
|
|
79
|
+
quality -= 0.08;
|
|
80
|
+
blob = (await canvasToBlob(canvas, mime, quality)) ?? blob;
|
|
81
|
+
}
|
|
82
|
+
const baseName = file.name.replace(/\.[^.]+$/, '') || 'image';
|
|
83
|
+
const ext = mime === 'image/png' ? 'png' : 'jpg';
|
|
84
|
+
return new File([blob], `${baseName}.${ext}`, { type: mime, lastModified: file.lastModified });
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
console.warn('[Chat] Image prep failed; sending original file', error);
|
|
88
|
+
return file;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Local persistence for panel generation archive (thinking + code tails), keyed by conversation. */
|
|
2
|
+
export type GenerationArchiveRecord = {
|
|
3
|
+
thinking: string;
|
|
4
|
+
code: string;
|
|
5
|
+
thoughtSeconds: number | null;
|
|
6
|
+
updatedAt: number;
|
|
7
|
+
};
|
|
8
|
+
export declare function loadGenerationArchive(conversationId: string | null | undefined): Promise<GenerationArchiveRecord | null>;
|
|
9
|
+
export declare function saveGenerationArchive(conversationId: string | null | undefined, record: Omit<GenerationArchiveRecord, 'updatedAt'>): Promise<void>;
|
|
10
|
+
export declare function clearGenerationArchive(conversationId: string | null | undefined): Promise<void>;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/** Local persistence for panel generation archive (thinking + code tails), keyed by conversation. */
|
|
2
|
+
const DB_NAME = 'widgetic-chat-generation-archive';
|
|
3
|
+
const STORE = 'byConversation';
|
|
4
|
+
const DB_VERSION = 1;
|
|
5
|
+
function openDb() {
|
|
6
|
+
return new Promise((resolve, reject) => {
|
|
7
|
+
if (typeof indexedDB === 'undefined') {
|
|
8
|
+
reject(new Error('indexedDB unavailable'));
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
|
12
|
+
request.onerror = () => reject(request.error ?? new Error('idb open failed'));
|
|
13
|
+
request.onsuccess = () => resolve(request.result);
|
|
14
|
+
request.onupgradeneeded = () => {
|
|
15
|
+
const db = request.result;
|
|
16
|
+
if (!db.objectStoreNames.contains(STORE)) {
|
|
17
|
+
db.createObjectStore(STORE, { keyPath: 'conversationId' });
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
export async function loadGenerationArchive(conversationId) {
|
|
23
|
+
if (!conversationId)
|
|
24
|
+
return null;
|
|
25
|
+
try {
|
|
26
|
+
const db = await openDb();
|
|
27
|
+
return await new Promise((resolve, reject) => {
|
|
28
|
+
const tx = db.transaction(STORE, 'readonly');
|
|
29
|
+
const req = tx.objectStore(STORE).get(conversationId);
|
|
30
|
+
req.onsuccess = () => {
|
|
31
|
+
const row = req.result;
|
|
32
|
+
if (!row?.thinking?.trim() && !row?.code?.trim()) {
|
|
33
|
+
resolve(null);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
resolve({
|
|
37
|
+
thinking: row.thinking ?? '',
|
|
38
|
+
code: row.code ?? '',
|
|
39
|
+
thoughtSeconds: row.thoughtSeconds ?? null,
|
|
40
|
+
updatedAt: row.updatedAt ?? 0,
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
req.onerror = () => reject(req.error);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
console.debug('[generationArchiveStore] load skipped', error);
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export async function saveGenerationArchive(conversationId, record) {
|
|
52
|
+
if (!conversationId)
|
|
53
|
+
return;
|
|
54
|
+
if (!record.thinking.trim() && !record.code.trim())
|
|
55
|
+
return;
|
|
56
|
+
try {
|
|
57
|
+
const db = await openDb();
|
|
58
|
+
await new Promise((resolve, reject) => {
|
|
59
|
+
const tx = db.transaction(STORE, 'readwrite');
|
|
60
|
+
tx.objectStore(STORE).put({
|
|
61
|
+
conversationId,
|
|
62
|
+
...record,
|
|
63
|
+
updatedAt: Date.now(),
|
|
64
|
+
});
|
|
65
|
+
tx.oncomplete = () => resolve();
|
|
66
|
+
tx.onerror = () => reject(tx.error);
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
console.warn('[generationArchiveStore] save failed', error);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export async function clearGenerationArchive(conversationId) {
|
|
74
|
+
if (!conversationId)
|
|
75
|
+
return;
|
|
76
|
+
try {
|
|
77
|
+
const db = await openDb();
|
|
78
|
+
await new Promise((resolve, reject) => {
|
|
79
|
+
const tx = db.transaction(STORE, 'readwrite');
|
|
80
|
+
tx.objectStore(STORE).delete(conversationId);
|
|
81
|
+
tx.oncomplete = () => resolve();
|
|
82
|
+
tx.onerror = () => reject(tx.error);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
/* ignore */
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare Image Transformations for chat attachment previews (display only).
|
|
3
|
+
*/
|
|
4
|
+
export type ImageTransformOptions = {
|
|
5
|
+
width: number;
|
|
6
|
+
height?: number;
|
|
7
|
+
fit?: 'cover' | 'contain' | 'crop' | 'scale-down';
|
|
8
|
+
quality?: number;
|
|
9
|
+
};
|
|
10
|
+
/** Path-style Cloudflare transform URL, or the original when not on an allowlisted host. */
|
|
11
|
+
export declare function buildTransformedUrl(url: string | null | undefined, options: ImageTransformOptions): string;
|
|
12
|
+
export declare function buildImageThumbnailUrl(url: string | null | undefined, renderedCssPx: number): string;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare Image Transformations for chat attachment previews (display only).
|
|
3
|
+
*/
|
|
4
|
+
/** Matches site `PUBLIC_IMAGE_TRANSFORM_HOSTS` defaults (library build cannot read Vite env). */
|
|
5
|
+
const TRANSFORM_HOSTS = 'static.widgetic.com,cdn.widgetic.com'
|
|
6
|
+
.split(',')
|
|
7
|
+
.map((host) => host.trim().toLowerCase())
|
|
8
|
+
.filter(Boolean);
|
|
9
|
+
const ENABLED = true;
|
|
10
|
+
function isTransformable(url) {
|
|
11
|
+
if (!ENABLED || !url)
|
|
12
|
+
return false;
|
|
13
|
+
if (url.startsWith('blob:') || url.startsWith('data:'))
|
|
14
|
+
return false;
|
|
15
|
+
try {
|
|
16
|
+
const parsed = new URL(url);
|
|
17
|
+
if (parsed.protocol !== 'https:')
|
|
18
|
+
return false;
|
|
19
|
+
return TRANSFORM_HOSTS.includes(parsed.hostname.toLowerCase());
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** Path-style Cloudflare transform URL, or the original when not on an allowlisted host. */
|
|
26
|
+
export function buildTransformedUrl(url, options) {
|
|
27
|
+
const source = url ?? '';
|
|
28
|
+
if (!isTransformable(source))
|
|
29
|
+
return source;
|
|
30
|
+
const parts = [`width=${options.width}`];
|
|
31
|
+
if (options.height)
|
|
32
|
+
parts.push(`height=${options.height}`);
|
|
33
|
+
else if (options.fit === 'cover')
|
|
34
|
+
parts.push(`height=${options.width}`);
|
|
35
|
+
if (options.fit)
|
|
36
|
+
parts.push(`fit=${options.fit}`);
|
|
37
|
+
parts.push(`quality=${options.quality ?? 75}`);
|
|
38
|
+
parts.push('format=auto');
|
|
39
|
+
const parsed = new URL(source);
|
|
40
|
+
return `${parsed.origin}/cdn-cgi/image/${parts.join(',')}/${source}`;
|
|
41
|
+
}
|
|
42
|
+
export function buildImageThumbnailUrl(url, renderedCssPx) {
|
|
43
|
+
const width = Math.min(Math.round(renderedCssPx * 2), 640);
|
|
44
|
+
return buildTransformedUrl(url, { width, fit: 'cover', quality: 80 });
|
|
45
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits a line of chat text into plain text and web links, so a message can show an address as a link a person can
|
|
3
|
+
* click, and let the long address wrap inside the message instead of running out of the panel.
|
|
4
|
+
*
|
|
5
|
+
* Only `http://` and `https://` addresses become links: a `javascript:` or `data:` address in a message is plain text.
|
|
6
|
+
*/
|
|
7
|
+
export type LinkifiedSegment = {
|
|
8
|
+
type: 'text';
|
|
9
|
+
text: string;
|
|
10
|
+
} | {
|
|
11
|
+
type: 'link';
|
|
12
|
+
text: string;
|
|
13
|
+
href: string;
|
|
14
|
+
};
|
|
15
|
+
/** The segments of `text` in order; joining their `text` gives `text` back. */
|
|
16
|
+
export declare function splitTextIntoLinks(text: string): LinkifiedSegment[];
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits a line of chat text into plain text and web links, so a message can show an address as a link a person can
|
|
3
|
+
* click, and let the long address wrap inside the message instead of running out of the panel.
|
|
4
|
+
*
|
|
5
|
+
* Only `http://` and `https://` addresses become links: a `javascript:` or `data:` address in a message is plain text.
|
|
6
|
+
*/
|
|
7
|
+
/** An address runs until a space or a character that cannot be part of one in running text. */
|
|
8
|
+
const ADDRESS_PATTERN = /https?:\/\/[^\s<>"'`]+/gi;
|
|
9
|
+
/** Punctuation that ends a sentence rather than an address ("see https://a.com/x."). */
|
|
10
|
+
const SENTENCE_END = /[.,;:!?]+$/;
|
|
11
|
+
/**
|
|
12
|
+
* Where the address in `candidate` really ends: trailing sentence punctuation is not part of it, and neither is a closing
|
|
13
|
+
* bracket without an opening one inside the address ("(see https://a.com/x)").
|
|
14
|
+
*/
|
|
15
|
+
function trimAddressEnd(candidate) {
|
|
16
|
+
let address = candidate;
|
|
17
|
+
let changed = true;
|
|
18
|
+
while (changed && address.length > 0) {
|
|
19
|
+
changed = false;
|
|
20
|
+
const withoutPunctuation = address.replace(SENTENCE_END, '');
|
|
21
|
+
if (withoutPunctuation !== address) {
|
|
22
|
+
address = withoutPunctuation;
|
|
23
|
+
changed = true;
|
|
24
|
+
}
|
|
25
|
+
const last = address.at(-1);
|
|
26
|
+
const opener = last === ')' ? '(' : last === ']' ? '[' : last === '}' ? '{' : null;
|
|
27
|
+
if (opener && last) {
|
|
28
|
+
const opens = address.split(opener).length - 1;
|
|
29
|
+
const closes = address.split(last).length - 1;
|
|
30
|
+
if (closes > opens) {
|
|
31
|
+
address = address.slice(0, -1);
|
|
32
|
+
changed = true;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return address;
|
|
37
|
+
}
|
|
38
|
+
/** The segments of `text` in order; joining their `text` gives `text` back. */
|
|
39
|
+
export function splitTextIntoLinks(text) {
|
|
40
|
+
const source = String(text ?? '');
|
|
41
|
+
const segments = [];
|
|
42
|
+
let cursor = 0;
|
|
43
|
+
for (const match of source.matchAll(ADDRESS_PATTERN)) {
|
|
44
|
+
const start = match.index ?? 0;
|
|
45
|
+
const address = trimAddressEnd(match[0]);
|
|
46
|
+
// "https://" alone is not an address
|
|
47
|
+
if (!/^https?:\/\/[^\s/?#]+/i.test(address))
|
|
48
|
+
continue;
|
|
49
|
+
if (start > cursor)
|
|
50
|
+
segments.push({ type: 'text', text: source.slice(cursor, start) });
|
|
51
|
+
segments.push({ type: 'link', text: address, href: address });
|
|
52
|
+
cursor = start + address.length;
|
|
53
|
+
}
|
|
54
|
+
if (cursor < source.length)
|
|
55
|
+
segments.push({ type: 'text', text: source.slice(cursor) });
|
|
56
|
+
return segments;
|
|
57
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Merges a suggestion label into the composer draft without sending.
|
|
3
|
+
* Empty draft: replace. Nonempty: append after a single space (one line, caret at end).
|
|
4
|
+
*/
|
|
5
|
+
export function mergeSuggestionIntoDraft(currentDraft, suggestion) {
|
|
6
|
+
const trimmed = suggestion.trim();
|
|
7
|
+
if (!trimmed)
|
|
8
|
+
return currentDraft;
|
|
9
|
+
const draft = currentDraft;
|
|
10
|
+
if (!draft.trim())
|
|
11
|
+
return trimmed;
|
|
12
|
+
if (draft.endsWith(' ') || draft.endsWith('\n'))
|
|
13
|
+
return `${draft}${trimmed}`;
|
|
14
|
+
return `${draft} ${trimmed}`;
|
|
15
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@widgetic/chat",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.39",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
},
|
|
58
58
|
"peerDependencies": {
|
|
59
59
|
"@widgetic/api-sdk": "*",
|
|
60
|
-
"@widgetic/design-system": ">=0.5.
|
|
60
|
+
"@widgetic/design-system": ">=0.5.36",
|
|
61
61
|
"svelte": "^5.25.6"
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
"@tailwindcss/postcss": "^4.1.4",
|
|
74
74
|
"@types/node": "^26.4.1",
|
|
75
75
|
"@widgetic/api-sdk": "^1.0.10",
|
|
76
|
-
"@widgetic/design-system": "^0.5.
|
|
76
|
+
"@widgetic/design-system": "^0.5.39",
|
|
77
77
|
"@widgetic/dev-tools": "^0.2.0",
|
|
78
78
|
"autoprefixer": "^10.4.20",
|
|
79
79
|
"eslint": "^9.0.0",
|