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
React-pdf-highloghter в первый раз. ⇐ Javascript
Форум по Javascript
1756983701
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>
Этот код работает правильно для загрузки документов, но основные моменты не появляются в начале. Когда я нажимаю на документ в любом месте, только тогда я могу увидеть их почему? Это то, что я не могу понять на самом деле.
Подробнее здесь: [url]https://stackoverflow.com/questions/79755629/react-pdf-highloghter-first-time-load-issue[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия