File size: 2,542 Bytes
fc93158 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | import type { Block, KnownBlock } from "@slack/web-api";
type PlainTextObject = { text?: string };
type SlackBlockWithFields = {
type?: string;
text?: PlainTextObject & { type?: string };
title?: PlainTextObject;
alt_text?: string;
elements?: Array<{ text?: string; type?: string }>;
};
function cleanCandidate(value: string | undefined): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const normalized = value.replace(/\s+/g, " ").trim();
return normalized.length > 0 ? normalized : undefined;
}
function readSectionText(block: SlackBlockWithFields): string | undefined {
return cleanCandidate(block.text?.text);
}
function readHeaderText(block: SlackBlockWithFields): string | undefined {
return cleanCandidate(block.text?.text);
}
function readImageText(block: SlackBlockWithFields): string | undefined {
return cleanCandidate(block.alt_text) ?? cleanCandidate(block.title?.text);
}
function readVideoText(block: SlackBlockWithFields): string | undefined {
return cleanCandidate(block.title?.text) ?? cleanCandidate(block.alt_text);
}
function readContextText(block: SlackBlockWithFields): string | undefined {
if (!Array.isArray(block.elements)) {
return undefined;
}
const textParts = block.elements
.map((element) => cleanCandidate(element.text))
.filter((value): value is string => Boolean(value));
return textParts.length > 0 ? textParts.join(" ") : undefined;
}
export function buildSlackBlocksFallbackText(blocks: (Block | KnownBlock)[]): string {
for (const raw of blocks) {
const block = raw as SlackBlockWithFields;
switch (block.type) {
case "header": {
const text = readHeaderText(block);
if (text) {
return text;
}
break;
}
case "section": {
const text = readSectionText(block);
if (text) {
return text;
}
break;
}
case "image": {
const text = readImageText(block);
if (text) {
return text;
}
return "Shared an image";
}
case "video": {
const text = readVideoText(block);
if (text) {
return text;
}
return "Shared a video";
}
case "file": {
return "Shared a file";
}
case "context": {
const text = readContextText(block);
if (text) {
return text;
}
break;
}
default:
break;
}
}
return "Shared a Block Kit message";
}
|