React-pdf-highloghter в первый раз.Javascript

Форум по Javascript
Ответить
Anonymous
 React-pdf-highloghter в первый раз.

Сообщение Anonymous »

import { useCallback, useEffect, useRef, useState } from "react"
import { XIcon } from "lucide-react"

import { Button } from "../ui/button"
import {
RightDrawer,
RightDrawerTitle,
RightDrawerHeader,
RightDrawerContent,
RightDrawerClose,
RightDrawerDescription,
} from "@/components/right-drawer"

import {
PdfLoader,
PdfHighlighter,
Highlight,
Popup,
AreaHighlight,
type IHighlight,
Tip,
ScaledPosition,
NewHighlight,
Content,
} from "react-pdf-highlighter"

import { Spinner } from "../ui/spinner"

export interface SourceWithCitations {
title: string
document_url: string
citations: any[]
}

interface DocumentWithCitationsSidebarProps {
isOpen: boolean
onClose: () => void
sources: SourceWithCitations | null
}

const HighlightPopup = ({ comment }: { comment?: { text?: string; emoji?: string } }) =>
comment && comment.text ? (

{comment.emoji} {comment.text}

) : null

const resetHash = () => {
document.location.hash = ""
}

const getNextId = () => String(Math.random()).slice(2)

const parseIdFromHash = () =>
document.location.hash.slice("#highlight-".length)

export function DocumentWithCitationsSidebar({
isOpen,
onClose,
sources,
}: DocumentWithCitationsSidebarProps) {

const [highlights, setHighlights] = useState(sources?.citations ?? [])

// store scrollTo ref from PdfHighlighter
const scrollViewerTo = useRef void>(() => {})

// Reset highlights whenever sources change
useEffect(() => {
if (sources?.citations) {
const mapped = sources.citations.map((c, i) => ({
id: c.id ?? String(i + 1),
content: c.content ?? { text: "" },
comment: c.comment ?? {},
position: c.position,
}))
setHighlights(mapped)
} else {
setHighlights([])
}
}, [sources])

// After highlights are set, force re-render/scroll
useEffect(() => {
if (highlights.length > 0 && scrollViewerTo.current) {
// wait for PdfHighlighter to fully render pages
setTimeout(() => {
scrollViewerTo.current(highlights[0])
// trigger a resize to ensure highlights paint correctly
window.dispatchEvent(new Event("resize"))
}, 50)
}
}, [highlights])

const handleOpenChange = (open: boolean) => {
if (!open) {
onClose()
}
}

const getHighlightById = useCallback(
(id: string) => highlights.find((h) => h.id === id),
[highlights],
)

const scrollToHighlightFromHash = useCallback(() => {
const highlight = getHighlightById(parseIdFromHash())
if (highlight) {
scrollViewerTo.current(highlight)
}
}, [getHighlightById])

useEffect(() => {
window.addEventListener("hashchange", scrollToHighlightFromHash, false)
return () => {
window.removeEventListener("hashchange", scrollToHighlightFromHash, false)
}
}, [scrollToHighlightFromHash])

const addHighlight = (highlight: NewHighlight) => {
console.log("Saving highlight", highlight)
setHighlights((prev) => [
{ ...highlight, id: getNextId() } as IHighlight,
...prev,
])
}

const updateHighlight = (
highlightId: string,
position: Partial,
content: Partial,
) => {
console.log("Updating highlight", highlightId, position, content)
setHighlights((prev) =>
prev.map((h) =>
h.id === highlightId
? {
...h,
position: { ...h.position, ...position },
content: { ...h.content, ...content },
}
: h,
),
)
}

return (





{sources?.title}


{sources?.document_url}









{sources?.document_url && (
}>
{(pdfDocument) => (
event.altKey}
onScrollChange={resetHash}
scrollRef={(scrollTo) => {
scrollViewerTo.current = scrollTo
}}
onSelectionFinished={(
position,
content,
hideTipAndSelection,
transformSelection,
) => (
{
addHighlight({ content, position, comment })
hideTipAndSelection()
}}
/>
)}
highlightTransform={(
highlight,
index,
setTip,
hideTip,
viewportToScaled,
screenshot,
isScrolledTo,
) => {
const isTextHighlight = !highlight.content?.image

const component = isTextHighlight ? (

) : (
{
updateHighlight(
highlight.id,
{ boundingRect: viewportToScaled(boundingRect) },
{ image: screenshot(boundingRect) },
)
}}
/>
)

return (

setTip(highlight, () => popupContent)
}
onMouseOut={hideTip}
>
{component}

)
}}
highlights={highlights}
/>
)}

)}


)
}
< /code>
Этот код работает правильно для загрузки документов, но основные моменты не появляются в начале. Когда я нажимаю на документ в любом месте, только тогда я могу увидеть их почему? Это то, что я не могу понять на самом деле.


Подробнее здесь: https://stackoverflow.com/questions/797 ... load-issue
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»