Link citation numbers generated by Perplexity models in UI

This commit is contained in:
Phil Szalay 2025-03-25 16:03:25 +01:00
parent c56dbe19cf
commit 91f547ba9c
3 changed files with 28 additions and 1 deletions

View File

@ -64,6 +64,11 @@ math {
@apply underline;
}
/* Remove underline for citation links */
.markdown-prose a[title="citation"] {
@apply no-underline;
}
.font-primary {
font-family: 'Archivo', sans-serif;
}

View File

@ -115,6 +115,7 @@
{content}
{model}
{save}
{sources}
sourceIds={(sources ?? []).reduce((acc, s) => {
let ids = [];
s.document.forEach((document, index) => {

View File

@ -15,6 +15,7 @@
export let content;
export let model = null;
export let save = false;
export let sources = null;
export let sourceIds = [];
export let onSourceClick = () => {};
@ -25,13 +26,33 @@
throwOnError: false
};
// Function to handle citation linking
function linkifyCitations(content, sources) {
if (!content || !sources || sources.length === 0) return content;
// Regex to match citation markers like [1], [2], etc.
const citationRegex = /\[(\d+)]/g;
// Replace markers with special tokens that can be processed by the markdown renderer
return content.replace(citationRegex, (match, number) => {
const citationIndex = parseInt(number, 10) - 1; // Convert to 0-based index
if (sources[citationIndex]) {
// Create a special token with a data-citation attribute that will be recognized by the renderer
return ` [${match}](${sources[citationIndex].source.name} "citation")`;
}
return match; // If no citation exists, keep it as is
});
}
marked.use(markedKatexExtension(options));
marked.use(markedExtension(options));
$: (async () => {
if (content) {
// Process citations before passing to marked lexer
const processedContent = sources ? linkifyCitations(content, sources) : content;
tokens = marked.lexer(
replaceTokens(processResponseContent(content), sourceIds, model?.name, $user?.name)
replaceTokens(processResponseContent(processedContent), sourceIds, model?.name, $user?.name)
);
}
})();