2025-09-02 09:21:55 -07:00
|
|
|
/**
|
|
|
|
|
* @license
|
|
|
|
|
* Copyright 2025 Google LLC
|
|
|
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
export type HighlightToken = {
|
|
|
|
|
text: string;
|
|
|
|
|
type: 'default' | 'command' | 'file';
|
|
|
|
|
};
|
|
|
|
|
|
2025-09-05 15:29:54 -07:00
|
|
|
const HIGHLIGHT_REGEX = /(^\/[a-zA-Z0-9_-]+|@(?:\\ |[a-zA-Z0-9_./-])+)/g;
|
2025-09-02 09:21:55 -07:00
|
|
|
|
|
|
|
|
export function parseInputForHighlighting(
|
|
|
|
|
text: string,
|
2025-09-05 15:29:54 -07:00
|
|
|
index: number,
|
2025-09-02 09:21:55 -07:00
|
|
|
): readonly HighlightToken[] {
|
|
|
|
|
if (!text) {
|
|
|
|
|
return [{ text: '', type: 'default' }];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const tokens: HighlightToken[] = [];
|
|
|
|
|
let lastIndex = 0;
|
|
|
|
|
let match;
|
|
|
|
|
|
|
|
|
|
while ((match = HIGHLIGHT_REGEX.exec(text)) !== null) {
|
|
|
|
|
const [fullMatch] = match;
|
|
|
|
|
const matchIndex = match.index;
|
|
|
|
|
|
|
|
|
|
// Add the text before the match as a default token
|
|
|
|
|
if (matchIndex > lastIndex) {
|
|
|
|
|
tokens.push({
|
|
|
|
|
text: text.slice(lastIndex, matchIndex),
|
|
|
|
|
type: 'default',
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Add the matched token
|
|
|
|
|
const type = fullMatch.startsWith('/') ? 'command' : 'file';
|
2025-09-05 15:29:54 -07:00
|
|
|
// Only highlight slash commands if the index is 0.
|
|
|
|
|
if (type === 'command' && index !== 0) {
|
|
|
|
|
tokens.push({
|
|
|
|
|
text: fullMatch,
|
|
|
|
|
type: 'default',
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
tokens.push({
|
|
|
|
|
text: fullMatch,
|
|
|
|
|
type,
|
|
|
|
|
});
|
|
|
|
|
}
|
2025-09-02 09:21:55 -07:00
|
|
|
|
|
|
|
|
lastIndex = matchIndex + fullMatch.length;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Add any remaining text after the last match
|
|
|
|
|
if (lastIndex < text.length) {
|
|
|
|
|
tokens.push({
|
|
|
|
|
text: text.slice(lastIndex),
|
|
|
|
|
type: 'default',
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return tokens;
|
|
|
|
|
}
|