This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-23 02:26:51 +04:00
1 parent 9b6241e541
commit cc2e033b04
9 files changed
+450 -66

No files matched your search

+3 -18
View File
@@ -1075,26 +1075,11 @@ CHUNK_MIN_SIZE_TARGET = int(os.getenv('CHUNK_MIN_SIZE_TARGET', '0'))
CHUNK_OVERLAP = int(os.getenv('CHUNK_OVERLAP', '100'))
DEFAULT_RAG_TEMPLATE = """### Task:
Respond to the user query using the provided context, incorporating inline citations in the format [id] **only when the <source> tag includes an explicit id attribute** (e.g., <source id="1">).
DEFAULT_RAG_TEMPLATE = """Answer the user's message using the sources inside <context> below. They were retrieved automatically for this conversation and may be incomplete or irrelevant.
### Guidelines:
- If you don't know the answer, clearly state that.
- If uncertain, ask the user for clarification.
- Respond in the same language as the user's query.
- If the context is unreadable or of poor quality, inform the user and provide the best possible answer.
- If the answer isn't present in the context but you possess the knowledge, explain this to the user and provide the answer using your own understanding.
- **Only include inline citations using [id] (e.g., [1], [2]) when the <source> tag includes an id attribute.**
- Do not cite if the <source> tag does not contain an id attribute.
- Do not use XML tags in your response.
- Ensure citations are concise and directly related to the information provided.
Cite a source directly after each statement it supports, using its id in square brackets: "The warranty covers parts for two years [1]." For several sources, write [1][2]. Use only ids that appear in the context. A <source> tag with nothing inside it labels the material just above it.
### Example of Citation:
If the user asks about a specific topic and the information is found in a source with a provided id attribute, the response should include the citation like in the following example:
* "According to the study, the proposed method increases efficiency by 20% [1]."
### Output:
Provide a clear and direct response to the user's query, including inline citations in the format [id] only when the <source> tag with id attribute is present in the context.
If the sources don't contain the answer, say so, then answer from your own knowledge if you can. If the context is unrelated to the message, ignore it. Reply in the user's language, and don't reproduce the <context> or <source> tags.
<context>
{{CONTEXT}}
@@ -42,6 +42,32 @@
if (citations[index]) {
console.log('Showing citation modal for:', citations[index]);
// A cited document whose layout the retrieved text loses opens beside the chat,
// at the cited page when one is known. Plain text files read the same in the popup.
const metadata = citations[index].metadata?.[0];
const fileName = String(metadata?.name ?? citations[index].source?.name ?? '');
if (!readOnly && metadata?.file_id && /\.(pdf|docx|pptx|xlsx|xls)$/i.test(fileName)) {
showTabs.set(true);
showEmbeds.set(true);
embed.set({
file: {
id: metadata.file_id,
page: Number.isInteger(metadata.page) ? metadata.page + 1 : null,
// The cited passages of this file, each with its page
passages: (citations[index].document ?? [])
.map((text, i) => ({ text, metadata: citations[index].metadata?.[i] }))
.filter((passage) => passage.metadata?.file_id === metadata.file_id)
.map(({ text, metadata }) => ({
text,
page: Number.isInteger(metadata?.page) ? metadata.page + 1 : null
}))
},
title: fileName,
chatId: chatId
});
return;
}
if (citations[index]?.source?.embed_url) {
const embedUrl = citations[index].source.embed_url;
// The embed panel renders anything it cannot read as a URL as raw HTML
@@ -10,7 +10,6 @@
import XMark from '$lib/components/icons/XMark.svelte';
import Textarea from '$lib/components/common/Textarea.svelte';
import ToolOutputFile from '$lib/components/chat/Messages/ToolOutputFile.svelte';
const i18n = getContext('i18n');
@@ -58,21 +57,6 @@
}
}
// The cited file as a display_file card, opened at the cited page.
const getFilePreviewItem = (doc: any) => {
const { file_id, name, page } = doc?.metadata ?? {};
const fileName = String(name ?? doc?.source?.name ?? '');
if (!file_id || !fileName.toLowerCase().endsWith('.pdf')) return null;
return {
type: 'file',
source: 'open_webui',
path: `/api/v1/files/${file_id}/content`,
name: fileName,
content_type: 'application/pdf',
...(Number.isInteger(page) ? { page: page + 1 } : {})
};
};
const decodeString = (str: string) => {
try {
return decodeURIComponent(str);
@@ -159,7 +143,7 @@
<div class="flex flex-col md:flex-row w-full px-5 pb-5 md:space-x-4">
<div
class="flex flex-col w-full dark:text-base-200 overflow-y-scroll max-h-[70vh] scrollbar-thin gap-1"
class="flex flex-col w-full dark:text-base-200 overflow-y-scroll max-h-[22rem] scrollbar-thin gap-1"
>
{#each mergedDocuments as document, documentIdx}
<div class="flex flex-col w-full gap-2">
@@ -229,11 +213,6 @@
{/if}
</div>
{#if getFilePreviewItem(document)}
<!-- Only the first source loads its file until another is opened -->
<ToolOutputFile item={getFilePreviewItem(document)} expanded={documentIdx === 0} />
{/if}
{#if document.metadata?.html}
<iframe
class="w-full border-0 h-auto rounded-none"
@@ -22,7 +22,7 @@
const i18n = getContext<Writable<i18nType>>('i18n');
export let expanded = true;
let expanded = true;
let loading = false;
let loadedKey = '';
let error = '';
+6 -3
View File
@@ -1470,6 +1470,8 @@
// A chat's artifacts or Overview tab names the chat it belongs to.
$: tabLabel = (tab: Tab) => {
if (tab.kind === 'terminal') return terminalTitles[tab.sessionId ?? ''] || tab.label;
// A cited file is named like any other file tab.
if (tab.kind === 'preview' && $embed?.file) return $embed.title || tab.label;
const source =
(tab.kind === 'artifacts' || tab.kind === 'overview') &&
tab.sourceTabId &&
@@ -1707,7 +1709,8 @@
openFeatureTab('comments');
}
$: if (viewReady && $showEmbeds && showPreviewTab) {
openFeatureTab('preview');
// A cited file opens beside the chat, so the answer stays readable.
openFeatureTab('preview', !!$embed?.file);
showEmbeds.set(false);
}
$: if (viewReady && $voiceCall) openFeatureTab('voice');
@@ -2472,8 +2475,8 @@
{:else}
<Icon name="folder" size={14} />
{/if}
{:else if tab.kind === 'file'}
<Icon name={fileIconName(tab.label)} size={14} strokeWidth={1.4} />
{:else if tab.kind === 'file' || (tab.kind === 'preview' && $embed?.file)}
<Icon name={fileIconName(tabLabel(tab))} size={14} strokeWidth={1.4} />
{:else if tab.kind === 'terminal'}
<Icon
name={terminalIconName(
+196 -18
View File
@@ -1,7 +1,106 @@
<script lang="ts">
import { getContext, onDestroy } from 'svelte';
import { embed } from '$lib/stores';
import { getFileContentById } from '$lib/apis/files';
import { quoteLines, quoteMarks } from '$lib/utils/comments/highlights';
import FullHeightIframe from '$lib/components/common/FullHeightIframe.svelte';
import PdfPagesPreview from '$lib/components/common/PdfPagesPreview.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import FilePreview from '$lib/components/chat/FileNav/FilePreview.svelte';
import Markdown from '$lib/components/chat/Messages/Markdown.svelte';
// A cited upload, shown at its cited page. PDFs also mark the cited text.
let fileId = '';
let fileLoading = false;
let fileData: ArrayBuffer | null = null;
let fileDocxData: ArrayBuffer | null = null;
let fileOfficeSlides: string[] | null = null;
let excelWorkbook: import('xlsx').WorkBook | null = null;
let selectedExcelSheet = '';
$: fileName = String($embed?.title ?? '');
$: fileExt = fileName.split('.').pop()?.toLowerCase() ?? '';
const loadFile = async (id: string, ext: string) => {
fileId = id;
fileData = fileDocxData = fileOfficeSlides = excelWorkbook = null;
selectedExcelSheet = '';
fileLoading = !!id;
if (!id) return;
try {
const data = await getFileContentById(id);
if (fileId !== id || !data) return;
if (ext === 'pdf') fileData = data;
else if (ext === 'docx') fileDocxData = data;
else if (ext === 'pptx') {
const { pptxToImages } = await import('$lib/utils/pptxToHtml');
const slides = (await pptxToImages(data)).images;
if (fileId === id) fileOfficeSlides = slides;
} else {
const { readExcelWorkbook } = await import('$lib/utils/excelToTable');
const workbook = await readExcelWorkbook(data);
if (fileId === id && workbook.SheetNames.length > 0) {
selectedExcelSheet = workbook.SheetNames[0];
excelWorkbook = workbook;
}
}
} catch (e) {
console.error(e);
} finally {
if (fileId === id) fileLoading = false;
}
};
$: if (($embed?.file?.id ?? '') !== fileId) loadFile($embed?.file?.id ?? '', fileExt);
let filePage: number | null = null;
let fileQuotes: string[] = [];
// Hovering a mark shows the retrieved passage it came from.
let fileQuoteTexts: { text: string; page: number | null }[] = [];
let hoveredText: {
text: string;
page: number | null;
left: number;
top: number;
above: boolean;
} | null = null;
const CARD_WIDTH = 352;
// The card stays while the pointer travels from the mark onto it, so it can be scrolled and selected.
let closeTimer: ReturnType<typeof setTimeout> | null = null;
const keepQuoteText = () => {
if (closeTimer) clearTimeout(closeTimer);
closeTimer = null;
};
const closeQuoteText = (delay = 300) => {
keepQuoteText();
closeTimer = setTimeout(() => (hoveredText = null), delay);
};
const showQuoteText = (index: number | null, rect: DOMRect | null) => {
const passage = index === null ? null : fileQuoteTexts[index];
if (!passage || !rect) return closeQuoteText();
keepQuoteText();
// Below the mark, or above it when there is more room there
const above = rect.bottom > window.innerHeight / 2;
hoveredText = {
...passage,
left: Math.max(12, Math.min(rect.left, window.innerWidth - CARD_WIDTH - 12)),
top: above ? rect.top - 6 : rect.bottom + 6,
above
};
};
onDestroy(keepQuoteText);
let fileSource: any = null;
$: if ($embed?.file !== fileSource) {
fileSource = $embed?.file ?? null;
filePage = fileSource?.page ?? null;
// The cited passages are marked on the pages they appear on
const quotes = (fileSource?.passages ?? []).flatMap((passage) =>
quoteLines(passage.text ?? '').map((quote) => ({ quote, passage }))
);
fileQuotes = quotes.map(({ quote }) => quote);
fileQuoteTexts = quotes.map(({ passage }) => passage);
hoveredText = null;
}
const i18n = getContext<any>('i18n');
export let overlay = false;
// Preserve the former embed close label for i18n extraction.
@@ -42,31 +141,110 @@
{#if $embed}
<div class="h-full w-full flex flex-col">
<div
class="pointer-events-auto z-20 flex justify-between items-center pb-3 px-2 font-primar text-base-900 dark:text-base-0 flex-shrink-0"
>
<div class="flex-1 flex items-center justify-between pl-2">
<a
class="flex items-center space-x-2 hover:underline"
href={$embed?.url}
target="_blank"
rel="noopener noreferrer"
>
{$embed?.title ?? 'Embedded Content'}
</a>
<!-- A cited file is named by its tab, like other file tabs -->
{#if !$embed?.file}
<div
class="pointer-events-auto z-20 flex justify-between items-center pb-3 px-2 font-primar text-base-900 dark:text-base-0 flex-shrink-0"
>
<div class="flex-1 flex items-center justify-between pl-2">
<a
class="flex items-center space-x-2 hover:underline"
href={$embed?.url}
target="_blank"
rel="noopener noreferrer"
>
{$embed?.title ?? 'Embedded Content'}
</a>
</div>
</div>
</div>
{/if}
<div class="w-full flex-1 min-h-0 relative">
{#if overlay}
<div class=" absolute top-0 left-0 right-0 bottom-0 z-10"></div>
{/if}
<FullHeightIframe
src={getSrcUrl($embed?.url ?? '', $embed?.chatId, $embed?.messageId, $embed?.sourceId)}
payload={$embed?.source ?? null}
iframeClassName="w-full h-full"
/>
{#if $embed?.file}
{#if fileData}
{#key `${fileId}:${filePage}`}
<PdfPagesPreview
data={fileData}
targetPage={filePage}
highlightQuotes={fileQuotes}
onQuoteHover={showQuoteText}
className="w-full h-full"
/>
{/key}
{:else if fileDocxData || fileOfficeSlides || excelWorkbook}
<!-- Previews drawn as real text get the cited passages marked too -->
<div
class="flex h-full min-h-0 flex-col"
use:quoteMarks={{ quotes: fileQuotes, onHover: showQuoteText }}
>
<FilePreview
selectedFile={fileName}
fileLoading={false}
{fileDocxData}
{fileOfficeSlides}
{excelWorkbook}
bind:selectedExcelSheet
currentSlide={Math.max(0, (filePage ?? 1) - 1)}
targetPage={filePage}
target={null}
readOnly={true}
/>
</div>
{:else}
<div
class="flex h-full items-center justify-center text-xs text-base-500 dark:text-base-400"
>
{#if fileLoading}
<Spinner className="size-3.5 text-base-400 dark:text-base-500" />
{:else}
{$i18n.t('Preview failed')}
{/if}
</div>
{/if}
{#if hoveredText}
<!-- Styled as the file and chat hover previews are -->
<div
role="tooltip"
class="fixed z-[9999] flex max-h-[min(17.5rem,calc(100vh-1.5rem))] w-[22rem] max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden rounded-2xl bg-base-0 font-normal text-base-900 shadow-[0_16px_40px_-28px_rgba(0,0,0,0.55)] ring-1 ring-base-1000/5 dark:bg-base-850 dark:text-base-100 dark:ring-base-0/10"
style:left={`${hoveredText.left}px`}
style:top={`${hoveredText.top}px`}
style:transform={hoveredText.above ? 'translateY(-100%)' : ''}
on:mouseenter={keepQuoteText}
on:mouseleave={() => closeQuoteText(150)}
>
<!-- Labelled as the comment popover on a file is: one quiet line above the text -->
{#if hoveredText.page}
<div
class="shrink-0 px-3 pt-2 text-[0.6875rem] leading-4 text-base-500 dark:text-base-400"
>
{$i18n.t('Page')}
{hoveredText.page}
</div>
{/if}
<!-- Everything at the small preview size, headings and tables included -->
<div
class="markdown-prose-xs min-h-0 min-w-full max-w-full flex-1 overflow-auto scrollbar-thin px-3 pb-2 {hoveredText.page
? 'pt-1'
: 'pt-2'} !leading-snug text-base-800 dark:text-base-200 [&_*]:!text-xs [&_*]:!leading-snug [&_:is(h1,h2,h3,h4,h5,h6)]:!my-1 [&_:is(h1,h2,h3,h4,h5,h6)]:!font-medium [&_:is(td,th)]:!px-1.5 [&_:is(td,th)]:!py-0.5 [&_:is(td,th)]:!text-[0.6875rem] [&_strong]:!font-medium"
>
<Markdown
content={hoveredText.text.trim().replace(/\n\n+/g, '\n\n')}
id="cited-passage"
/>
</div>
</div>
{/if}
{:else}
<FullHeightIframe
src={getSrcUrl($embed?.url ?? '', $embed?.chatId, $embed?.messageId, $embed?.sourceId)}
payload={$embed?.source ?? null}
iframeClassName="w-full h-full"
/>
{/if}
</div>
</div>
{/if}
+53 -1
View File
@@ -6,7 +6,15 @@
import Spinner from './Spinner.svelte';
import { readPdfComments } from '$lib/utils/comments/pdf';
import { mapWordComments, type PdfTextRun } from '$lib/utils/comments/pdfAnchors';
import { findTextRange, highlightRange, commentPin } from '$lib/utils/comments/highlights';
import {
findTextRange,
highlightRange,
markRange,
markAt,
rangeOf,
textIndex,
commentPin
} from '$lib/utils/comments/highlights';
import type { FileComment, CommentResult } from '$lib/utils/comments/types';
const i18n: any = getContext('i18n');
@@ -23,6 +31,10 @@
export let onCommentSelect: ((comment: FileComment) => void) | null = null;
export let selectedComment: FileComment | null = null;
export let sourceComments: FileComment[] | null = null;
/** Text to mark on whichever rendered pages contain it, such as a cited passage. */
export let highlightQuotes: string[] | null = null;
/** Called with the index of the quote under the pointer and where its mark sits, or null. */
export let onQuoteHover: ((index: number | null, rect: DOMRect | null) => void) | null = null;
export let onAnchors: ((ids: string[]) => void) | null = null;
let mappedSource: FileComment[] | null = null;
let mappedDoc: PdfDocument | null = null;
@@ -93,8 +105,45 @@
let lastWidth = 0;
let lastHeight = 0;
let resizeTimer: ReturnType<typeof setTimeout>;
const renderQuoteHighlights = () => {
for (const wrapper of Array.from(
sceneElement?.querySelectorAll<HTMLElement>('.pdf-page-wrapper') ?? []
)) {
wrapper.querySelector('.quote-highlight-layer')?.remove();
if (!highlightQuotes?.length || !wrapper.querySelector('.textLayer')?.hasChildNodes())
continue;
const layer = document.createElement('div');
layer.className = 'quote-highlight-layer';
Object.assign(layer.style, {
position: 'absolute',
inset: '0',
pointerEvents: 'none',
zIndex: '3'
});
const text = textIndex(wrapper);
highlightQuotes.forEach((quote, index) => {
// A quote found more than once on the page is left unmarked
const range = rangeOf(text, quote);
if (range) markRange(wrapper, layer, range, String(index));
});
if (layer.hasChildNodes()) wrapper.appendChild(layer);
}
};
// Marks let the text under them be selected, so the pointer is matched to them by position.
let hoveredQuote: number | null = null;
const handleQuoteHover = (event: MouseEvent | null) => {
if (!onQuoteHover) return;
const mark = event ? markAt(sceneElement, event.clientX, event.clientY) : undefined;
const index = mark ? Number(mark.dataset.quote) : null;
if (index === hoveredQuote) return;
hoveredQuote = index;
onQuoteHover(index, mark?.getBoundingClientRect() ?? null);
};
const renderCommentMarkers = async () => {
const token = ++markerToken;
renderQuoteHighlights();
if (!sceneElement || !pdfDoc || (!onComments && !sourceComments)) return;
const doc = pdfDoc;
for (const wrapper of Array.from(
@@ -725,6 +774,7 @@
$: if (sourceComments && pdfDoc) void mapSourceComments();
$: if (selectedComment && !loading) void renderCommentMarkers();
$: if (highlightQuotes && !loading) void renderCommentMarkers();
onDestroy(() => {
markerToken++;
@@ -767,6 +817,8 @@
on:wheel|nonpassive={handleWheel}
on:dblclick|capture|stopPropagation={() => {}}
on:pointerdown={focusViewer}
on:mousemove={handleQuoteHover}
on:mouseleave={() => handleQuoteHover(null)}
on:keydown={handleKeyDown}
>
<div
@@ -17,6 +17,8 @@
export let onCommentSelect: ((comment: FileComment) => void) | null = null;
export let selectedComment: FileComment | null = null;
export let sourceComments: FileComment[] | null = null;
export let highlightQuotes: string[] | null = null;
export let onQuoteHover: ((index: number | null, rect: DOMRect | null) => void) | null = null;
export let onAnchors: ((ids: string[]) => void) | null = null;
type PdfDocument = import('pdfjs-dist').PDFDocumentProxy;
@@ -209,6 +211,8 @@
{onCommentSelect}
{selectedComment}
{sourceComments}
{highlightQuotes}
{onQuoteHover}
{onAnchors}
className="w-full h-full"
/>
+160 -3
View File
@@ -57,14 +57,18 @@ export function commentPin(id: string, label: string): HTMLButtonElement {
return button;
}
export function findTextRange(container: HTMLElement, quote: string): Range | null {
const chars: Array<{ node: Text; offset: number; end: number }> = [];
type TextIndex = { text: string; chars: Array<{ node: Text; offset: number; end: number }> };
/** The text under a container with whitespace removed, mapped back to its nodes. */
export function textIndex(container: HTMLElement, within: string | null = '.textLayer'): TextIndex {
const chars: TextIndex['chars'] = [];
let text = '';
const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);
let next: Node | null;
while ((next = walker.nextNode())) {
const node = next as Text;
if (!node.parentElement?.closest('.textLayer')) continue;
const parent = node.parentElement;
if (within ? !parent?.closest(within) : parent?.closest('style, script')) continue;
let offset = 0;
for (const char of node.data) {
for (const normalized of char.normalize('NFKC'))
@@ -75,6 +79,11 @@ export function findTextRange(container: HTMLElement, quote: string): Range | nu
offset += char.length;
}
}
return { text, chars };
}
/** The range of a quote that appears exactly once in the indexed text. */
export function rangeOf({ text, chars }: TextIndex, quote: string): Range | null {
const needle = quote.normalize('NFKC').replace(/\s/g, '');
const index = needle ? text.indexOf(needle) : -1;
if (index < 0 || text.indexOf(needle, index + 1) !== -1) return null;
@@ -86,3 +95,151 @@ export function findTextRange(container: HTMLElement, quote: string): Range | nu
range.setEnd(end.node, end.end);
return range;
}
export function findTextRange(container: HTMLElement, quote: string): Range | null {
return rangeOf(textIndex(container), quote);
}
/** The lines of a retrieved Markdown passage, as they would read on the source page. */
export function quoteLines(passage: string, limit = 400): string[] {
const lines = passage
// Table cells and other HTML blocks become lines of their own
.replace(/<[^<>]+>/g, '\n')
.replace(/!?\[([^\[\]]*)\]\([^()]*\)/g, '$1')
.split(/\n|\|/)
// A sentence can still match where the rest of its paragraph reads differently
.flatMap((line) => line.split(/(?<=[.!?;:])\s+/))
.map((line) =>
line
.replace(/^\s*(#{1,6}|[-*+>]|\d+[.)])\s+/, '')
.replace(/[*_`$]/g, '')
.trim()
)
.filter((line) => line.replace(/\s/g, '').length >= 6);
return [...new Set(lines)].slice(0, limit);
}
/** Mark a text range without making it a comment target. */
export function markRange(
container: HTMLElement,
layer: HTMLElement,
range: Range,
quote = ''
): void {
const bounds = container.getBoundingClientRect();
const scale = bounds.width / container.offsetWidth || 1;
for (const rect of range.getClientRects()) {
if (rect.width <= 0 || rect.height <= 0) continue;
const mark = document.createElement('div');
mark.dataset.quote = quote;
Object.assign(mark.style, {
position: 'absolute',
left: `${(rect.left - bounds.left) / scale}px`,
top: `${(rect.top - bounds.top) / scale}px`,
width: `${rect.width / scale}px`,
height: `${rect.height / scale}px`,
borderRadius: '2px',
background: 'rgba(250,204,21,.25)'
});
layer.appendChild(mark);
}
}
/** The quote mark under a point. Marks ignore the pointer so the text under them stays selectable. */
export function markAt(root: ParentNode | null | undefined, x: number, y: number) {
return Array.from(root?.querySelectorAll<HTMLElement>('[data-quote]') ?? []).find((mark) => {
const rect = mark.getBoundingClientRect();
return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
});
}
type QuoteMarkOptions = {
quotes: string[];
onHover?: (index: number | null, rect: DOMRect | null) => void;
};
/**
* Mark quotes in any preview drawn as real text, such as a Word document or a sheet.
* The marks sit in the preview's own scrolling area and are redrawn when it changes.
*/
export function quoteMarks(node: HTMLElement, options: QuoteMarkOptions) {
let layer: HTMLElement | null = null;
let timer: ReturnType<typeof setTimeout> | null = null;
let hovered: number | null = null;
let revealed = false;
const observer = new MutationObserver(() => {
if (timer) clearTimeout(timer);
timer = setTimeout(draw, 200);
});
const observe = () =>
observer.observe(node, {
subtree: true,
childList: true,
attributes: true,
attributeFilter: ['style', 'class']
});
function draw() {
observer.disconnect();
layer?.remove();
layer = null;
const index = options.quotes.length ? textIndex(node, null) : null;
const ranges = options.quotes
.map((quote, i) => ({ i, range: index && rangeOf(index, quote) }))
.filter((found): found is { i: number; range: Range } => !!found.range);
if (ranges.length) {
// The marks scroll with the text, so they live inside whatever scrolls it
let scroller = ranges[0].range.startContainer.parentElement ?? node;
while (scroller !== node && !/auto|scroll/.test(getComputedStyle(scroller).overflowY))
scroller = scroller.parentElement ?? node;
if (getComputedStyle(scroller).position === 'static') scroller.style.position = 'relative';
layer = document.createElement('div');
Object.assign(layer.style, {
position: 'absolute',
left: '0',
top: '0',
width: '0',
height: '0',
pointerEvents: 'none',
zIndex: '3'
});
scroller.prepend(layer);
for (const { i, range } of ranges) markRange(layer, layer, range, String(i));
if (!revealed && layer.firstElementChild) {
revealed = true;
layer.firstElementChild.scrollIntoView({ block: 'center' });
}
}
observe();
}
const hover = (event: MouseEvent | null) => {
const mark = event ? markAt(layer, event.clientX, event.clientY) : undefined;
const index = mark ? Number(mark.dataset.quote) : null;
if (index === hovered) return;
hovered = index;
options.onHover?.(index, mark?.getBoundingClientRect() ?? null);
};
const leave = () => hover(null);
node.addEventListener('mousemove', hover);
node.addEventListener('mouseleave', leave);
draw();
return {
update(next: QuoteMarkOptions) {
const changed = next.quotes !== options.quotes;
options = next;
if (!changed) return;
revealed = false;
draw();
},
destroy() {
observer.disconnect();
if (timer) clearTimeout(timer);
node.removeEventListener('mousemove', hover);
node.removeEventListener('mouseleave', leave);
layer?.remove();
}
};
}