← Files ItalicARCHIVED FILE
ui/recording-text.js
6.98 KB · Nov 25, 2026 · 00:20 UTC
/** How Home and a recording's page word a recording, as the web app does
* (apps/web/src/lib/markdown.ts, recordings.ts, recording-search.ts). */
/** Notes as one line: Markdown marks dropped, lines joined with a middle dot. */
export function markdownPreviewText(md) {
return String(md || '')
.split(/\r?\n/)
.map((line) =>
line
.replace(/^\s{0,3}#{1,6}\s+/, '')
.replace(/^\s*(?:[-*+•]|\d+[.)])\s+/, '')
.replace(/^\[( |x)\]\s+/i, '')
.replace(/^\[([^\]]+)]\s+/, '')
.replace(/\[([^\]]+)]\([^\s)]+(?:\s+"[^"]*")?\)/g, '$1')
.replace(/\*\*|__|`/g, '')
.trim(),
)
.filter(Boolean)
.join(' · ');
}
const COUNT_FORMAT = new Intl.NumberFormat();
/** "19 words", or characters for Chinese text. Nothing for no text. */
export function recordingLengthLabel(transcript) {
const text = String(transcript || '').trim();
if (!text) return undefined;
const characters = text.match(/[一-鿿]/g)?.length ?? 0;
if (characters > 0) return characters === 1 ? '1 character' : `${COUNT_FORMAT.format(characters)} characters`;
const words = text.split(/[ \n\t]+/).filter(Boolean).length;
return words === 1 ? '1 word' : `${COUNT_FORMAT.format(words)} words`;
}
const startOfDay = (value) => {
const day = new Date(value);
day.setHours(0, 0, 0, 0);
return day.getTime();
};
/** "Today", "Yesterday", "Nov 6", or "Nov 6, 2025" in another year. */
export function dayTitle(ms, now = Date.now(), locale) {
const day = startOfDay(ms), today = startOfDay(now);
if (day === today) return 'Today';
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
if (day === yesterday.getTime()) return 'Yesterday';
const withYear = new Date(day).getFullYear() !== new Date(today).getFullYear();
return new Date(day).toLocaleDateString(locale, {month: 'short', day: 'numeric', ...(withYear ? {year: 'numeric'} : {})});
}
/** "Today, 4:55 PM": a recording's page. */
export function recordingTime(ms, now = Date.now(), locale) {
return `${dayTitle(ms, now, locale)}, ${new Date(ms).toLocaleTimeString(locale, {hour: 'numeric', minute: '2-digit'})}`;
}
/** A row's time: the reader's clock, with AM or PM apart so it can be set smaller. */
export function clockParts(ms, locale) {
const parts = new Intl.DateTimeFormat(locale, {hour: 'numeric', minute: '2-digit'}).formatToParts(new Date(ms));
return {
time: parts.filter((part) => part.type !== 'dayPeriod').map((part) => part.value).join('').trim(),
meridiem: parts.find((part) => part.type === 'dayPeriod')?.value,
};
}
const WIDE = [[0x1100, 0x115f], [0x2e80, 0x303e], [0x3041, 0x33ff], [0x3400, 0x4dbf], [0x4e00, 0x9fff], [0xa000, 0xa4cf],
[0xac00, 0xd7a3], [0xf900, 0xfaff], [0xfe30, 0xfe4f], [0xff00, 0xff60], [0xffe0, 0xffe6], [0x1f300, 0x1faff], [0x20000, 0x3fffd]];
/** The design tokens' length step for `text` (typography.lengthSteps), by its
* characters alone: a run of whitespace counts once, a wide character twice.
* The web also measures lines; a widget can't before it draws. */
export function lengthStep(text, steps, floor = 'body') {
const collapsed = String(text || '').replace(/\s+/g, ' ').trim();
let length = 0;
for (const character of collapsed) {
const code = character.codePointAt(0) ?? 0;
length += WIDE.some(([low, high]) => code >= low && code <= high) ? 2 : 1;
}
const last = Math.max(0, steps.findIndex((step) => step.name === floor));
const index = steps.findIndex((step) => step.maxCharacters === null || length <= step.maxCharacters);
return steps[index < 0 ? last : Math.min(index, last)]?.name ?? floor;
}
/** Inline Markdown as runs: **bold**, *italic*, `code`, [links](…) as their text. */
export function markdownInline(text) {
const runs = [];
// Not _italic_: underscores inside names (snake_case) stay as written.
const pattern = /(\*\*|__)(.+?)\1|(\*)(\S(?:.*?\S)?)\3|`([^`]+)`|\[([^\]]+)]\([^\s)]+(?:\s+"[^"]*")?\)/g;
let at = 0;
for (const match of String(text).matchAll(pattern)) {
if (match.index > at) runs.push({text: text.slice(at, match.index)});
if (match[2] !== undefined) runs.push({text: match[2], strong: true});
else if (match[4] !== undefined) runs.push({text: match[4], em: true});
else if (match[5] !== undefined) runs.push({text: match[5], code: true});
else runs.push({text: match[6]});
at = match.index + match[0].length;
}
if (at < text.length) runs.push({text: text.slice(at)});
return runs;
}
/** Notes as blocks to build with DOM calls, never as HTML: headings, lists
* (with task boxes), quotes and paragraphs. */
export function markdownBlocks(md) {
const blocks = [];
let paragraph = [];
const flush = () => {
if (paragraph.length) blocks.push({type: 'p', runs: markdownInline(paragraph.join(' '))});
paragraph = [];
};
for (const raw of String(md || '').split(/\r?\n/)) {
const line = raw.trimEnd();
const heading = line.match(/^\s{0,3}(#{1,6})\s+(.*)$/);
const item = line.match(/^\s*([-*+•]|\d+[.)])\s+(?:\[( |x)\]\s+)?(.*)$/i);
const quote = line.match(/^\s{0,3}>\s?(.*)$/);
if (!line.trim()) flush();
else if (heading) {
flush();
blocks.push({type: 'h', level: Math.min(heading[1].length, 3), runs: markdownInline(heading[2])});
} else if (item) {
flush();
const type = /\d/.test(item[1]) ? 'ol' : 'ul';
const entry = {runs: markdownInline(item[3]), ...(item[2] !== undefined ? {checked: item[2].toLowerCase() === 'x'} : {})};
const last = blocks.at(-1);
if (last?.type === type) last.items.push(entry);
else blocks.push({type, items: [entry]});
} else if (quote) {
flush();
blocks.push({type: 'quote', runs: markdownInline(quote[1])});
} else paragraph.push(line.trim());
}
flush();
return blocks;
}
/** `text` split where the search's words appear, ignoring case and accents. */
export function highlightSegments(text, query) {
const fold = (value) => value.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
const words = [...new Set(fold(String(query || '')).split(/\s+/).filter((word) => word.length > 1))];
const source = String(text || '');
if (!words.length || !source) return [{text: source, match: false}];
// Fold one character at a time so positions in the folded text map back to the original.
let folded = '';
const origin = [];
for (let index = 0; index < source.length; index++) {
const piece = fold(source[index]);
for (let k = 0; k < piece.length; k++) origin.push(index);
folded += piece;
}
const marks = Array.from({length: source.length}, () => false);
for (const word of words) {
for (let at = folded.indexOf(word); at >= 0; at = folded.indexOf(word, at + 1)) {
for (let k = at; k < at + word.length; k++) marks[origin[k]] = true;
}
}
const segments = [];
for (let index = 0; index < source.length; index++) {
const last = segments.at(-1);
if (last && last.match === marks[index]) last.text += source[index];
else segments.push({text: source[index], match: marks[index]});
}
return segments;
}
SHA-256: a82b7d33b9daf3d3b6c400b858e24aa3234d233ca4bdb2dc260e597ced93333e