mirror of
https://github.com/Shik3i/KoalaSync.git
synced 2026-08-30 04:19:27 +00:00
fix(extension): harden chat and target tab lifecycle
This commit is contained in:
@@ -29,5 +29,41 @@
|
||||
return tokens;
|
||||
}
|
||||
|
||||
root.KoalaSyncChatFormat = Object.freeze({ escapeChatHtml, formatChatText, tokenizeChatText });
|
||||
function splitChatText(value, maxCodePoints = 500, maxChunks = 10) {
|
||||
if (!Number.isInteger(maxCodePoints) || maxCodePoints < 1 || !Number.isInteger(maxChunks) || maxChunks < 1) {
|
||||
throw new TypeError('Chat chunk limits must be positive integers');
|
||||
}
|
||||
let remaining = [...String(value ?? '').trim()];
|
||||
if (remaining.length === 0) return [];
|
||||
if (remaining.length > maxCodePoints * maxChunks) {
|
||||
throw new RangeError('Chat composer text exceeds the chunk limit');
|
||||
}
|
||||
|
||||
const chunks = [];
|
||||
while (remaining.length > 0) {
|
||||
if (remaining.length <= maxCodePoints) {
|
||||
chunks.push(remaining.join('').trim());
|
||||
break;
|
||||
}
|
||||
|
||||
const remainingSlots = maxChunks - chunks.length;
|
||||
const minimumSplit = Math.max(1, remaining.length - (remainingSlots - 1) * maxCodePoints);
|
||||
let splitAt = maxCodePoints;
|
||||
for (let index = maxCodePoints - 1; index >= minimumSplit; index--) {
|
||||
if (/\s/u.test(remaining[index])) {
|
||||
splitAt = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const chunk = remaining.slice(0, splitAt).join('').trim();
|
||||
remaining = remaining.slice(splitAt);
|
||||
while (remaining.length > 0 && /\s/u.test(remaining[0])) remaining.shift();
|
||||
if (chunk) chunks.push(chunk);
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
root.KoalaSyncChatFormat = Object.freeze({ escapeChatHtml, formatChatText, tokenizeChatText, splitChatText });
|
||||
})(globalThis);
|
||||
|
||||
Reference in New Issue
Block a user