File size: 2,242 Bytes
87fc763
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Format utilities for Nextcloud Talk messages.
 *
 * Nextcloud Talk supports markdown natively, so most formatting passes through.
 * This module handles any edge cases or transformations needed.
 */

/**
 * Convert markdown to Nextcloud Talk compatible format.
 * Nextcloud Talk supports standard markdown, so minimal transformation needed.
 */
export function markdownToNextcloudTalk(text: string): string {
  return text.trim();
}

/**
 * Escape special characters in text to prevent markdown interpretation.
 */
export function escapeNextcloudTalkMarkdown(text: string): string {
  return text.replace(/([*_`~[\]()#>+\-=|{}!\\])/g, "\\$1");
}

/**
 * Format a mention for a Nextcloud user.
 * Nextcloud Talk uses @user format for mentions.
 */
export function formatNextcloudTalkMention(userId: string): string {
  return `@${userId.replace(/^@/, "")}`;
}

/**
 * Format a code block for Nextcloud Talk.
 */
export function formatNextcloudTalkCodeBlock(code: string, language?: string): string {
  const lang = language ?? "";
  return `\`\`\`${lang}\n${code}\n\`\`\``;
}

/**
 * Format inline code for Nextcloud Talk.
 */
export function formatNextcloudTalkInlineCode(code: string): string {
  if (code.includes("`")) {
    return `\`\` ${code} \`\``;
  }
  return `\`${code}\``;
}

/**
 * Strip Nextcloud Talk specific formatting from text.
 * Useful for extracting plain text content.
 */
export function stripNextcloudTalkFormatting(text: string): string {
  return text
    .replace(/```[\s\S]*?```/g, "")
    .replace(/`[^`]+`/g, "")
    .replace(/\*\*([^*]+)\*\*/g, "$1")
    .replace(/\*([^*]+)\*/g, "$1")
    .replace(/_([^_]+)_/g, "$1")
    .replace(/~~([^~]+)~~/g, "$1")
    .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
    .replace(/\s+/g, " ")
    .trim();
}

/**
 * Truncate text to a maximum length, preserving word boundaries.
 */
export function truncateNextcloudTalkText(text: string, maxLength: number, suffix = "..."): string {
  if (text.length <= maxLength) {
    return text;
  }
  const truncated = text.slice(0, maxLength - suffix.length);
  const lastSpace = truncated.lastIndexOf(" ");
  if (lastSpace > maxLength * 0.7) {
    return truncated.slice(0, lastSpace) + suffix;
  }
  return truncated + suffix;
}