@krizaka/ui 3.76.0 → 3.77.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blocks.css +14 -0
- package/dist/chunk-NM2DEHFZ.js +25 -0
- package/dist/chunk-NM2DEHFZ.js.map +1 -0
- package/dist/document-viewer.d.ts +23 -6
- package/dist/document-viewer.js +21 -5
- package/dist/document-viewer.js.map +1 -1
- package/dist/map/cards.d.ts +145 -0
- package/dist/map/cards.js +74 -0
- package/dist/map/cards.js.map +1 -0
- package/dist/map/pin.d.ts +57 -0
- package/dist/map/pin.js +53 -0
- package/dist/map/pin.js.map +1 -0
- package/dist/map/sheet.d.ts +80 -0
- package/dist/map/sheet.js +61 -0
- package/dist/map/sheet.js.map +1 -0
- package/dist/map.d.ts +41 -14
- package/dist/map.js +85 -112
- package/dist/map.js.map +1 -1
- package/dist/native/map.d.ts +29 -10
- package/dist/native/map.js +81 -107
- package/dist/native/map.js.map +1 -1
- package/dist/shop/services.js +1 -1
- package/dist/shop/services.js.map +1 -1
- package/dist/shop-composer.js +1 -1
- package/dist/shop-composer.js.map +1 -1
- package/dist/shop-gallery.js +2 -2
- package/dist/shop-gallery.js.map +1 -1
- package/dist/wall.d.ts +10 -5
- package/dist/wall.js +10 -4
- package/dist/wall.js.map +1 -1
- package/package.json +53 -8
- package/registry/app-frame.json +1 -1
- package/registry/document-viewer.json +9 -8
- package/registry/examples/document-viewer/highlights.js +2 -1
- package/registry/examples/document-viewer/highlights.tsx +3 -0
- package/registry/examples/map/pins.d.ts +4 -0
- package/registry/examples/map/pins.js +20 -0
- package/registry/examples/map/pins.tsx +27 -0
- package/registry/examples/map/place-sheet.d.ts +4 -0
- package/registry/examples/map/place-sheet.js +34 -0
- package/registry/examples/map/place-sheet.tsx +35 -0
- package/registry/examples/wall/tidy.d.ts +4 -0
- package/registry/examples/wall/tidy.js +27 -0
- package/registry/examples/wall/tidy.tsx +19 -0
- package/registry/index.json +9 -9
- package/registry/map.json +81 -13
- package/registry/nav-bar.json +1 -1
- package/registry/rail-nav.json +1 -1
- package/registry/shop-gallery.json +1 -1
- package/registry/shop.json +2 -2
- package/registry/site-footer.json +1 -1
- package/registry/wall.json +24 -2
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
],
|
|
43
43
|
"bestPractices": [
|
|
44
44
|
"Keep the list of passages in the page, next to the viewer: the viewer is not a keyboard route to each box, your list is (`activeId` / `onActiveChange`).",
|
|
45
|
+
"Light a region instead of a quote when the app already knows where the evidence sits (`region: { page, x, y, width, height }`, fractions of the page): no text layer needed, and a region outside the page is never drawn.",
|
|
45
46
|
"Pass the quote as the text layer reads it and, when you know it, the page: a quote the layout cut is still placed by its opening words, and a page alone still scrolls.",
|
|
46
47
|
"Use `onLocate` to tell the person what was placed and what was not (« page 3 », « not found in the text layer ») — a passage is never drawn at a guessed place.",
|
|
47
48
|
"Load pdf.js with `() => import(\"pdfjs-dist\")` and give it a same-origin worker (`workerSrc`): the engine only reaches pages that show a document."
|
|
@@ -67,7 +68,7 @@
|
|
|
67
68
|
],
|
|
68
69
|
"web": {
|
|
69
70
|
"entry": "@krizaka/ui/document-viewer",
|
|
70
|
-
"import": "import { DocumentViewer, locateQuote } from \"@krizaka/ui/document-viewer\";",
|
|
71
|
+
"import": "import { DocumentViewer, locateQuote, locateRegion } from \"@krizaka/ui/document-viewer\";",
|
|
71
72
|
"props": [
|
|
72
73
|
{
|
|
73
74
|
"component": "DocumentViewer",
|
|
@@ -136,10 +137,10 @@
|
|
|
136
137
|
{
|
|
137
138
|
"name": "highlights",
|
|
138
139
|
"title": "Findings in the file",
|
|
139
|
-
"description": "A one-page lease and
|
|
140
|
+
"description": "A one-page lease, two passages told by their quote and one by a region; pick one and the page scrolls to it and lights it.",
|
|
140
141
|
"path": "examples/document-viewer/highlights.tsx",
|
|
141
142
|
"module": "@krizaka/ui/registry/examples/document-viewer/highlights",
|
|
142
|
-
"code": "\"use client\";\n\nimport { DocumentViewer } from \"@krizaka/ui/document-viewer\";\nimport * as React from \"react\";\n\nconst PDF = \"JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUl0gL0NvdW50IDEgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA2MTIgNzkyXSAvQ29udGVudHMgNCAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNSAwIFIgPj4gPj4gPj4KZW5kb2JqCjQgMCBvYmoKPDwgL0xlbmd0aCAyMDkgPj4Kc3RyZWFtCkJUIC9GMSAxNCBUZiA3MiA3MDAgVGQgKEJBSUwgUkVTSURFTlRJRUwpIFRqIEVUCkJUIC9GMSAxMSBUZiA3MiA2NzAgVGQgKExlIGxvY2F0ZXVyIHBldXQgYXVnbWVudGVyIGxlIGxveWVyIGEgdG91dCBtb21lbnQuKSBUaiBFVApCVCAvRjEgMTEgVGYgNzIgNjUwIFRkIChMZSBkZXBvdCBkZSBnYXJhbnRpZSBlc3QgZGUgZGV1eCBtb2lzIGRlIGxveWVyLikgVGogRVQKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDExNSAwMDAwMCBuIAowMDAwMDAwMjQxIDAwMDAwIG4gCjAwMDAwMDA1MDAgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA2IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgo1NzAKJSVFT0YK\";\nconst quotes = [\n { id: \"r1\", quote: \"Le locateur peut augmenter le loyer à tout moment.\", label: \"Rent increase\" },\n { id: \"r2\", quote: \"Le dépôt de garantie est de deux mois de loyer.\", label: \"Deposit\" },\n];\n// pdf.js is the app's: `loadPdfjs={() => import(\"pdfjs-dist\")}` and a worker served from its own origin. Here, from a CDN.\nconst CDN = \"https://cdn.jsdelivr.net/npm/pdfjs-dist@5.4.149/build/\";\nconst loadPdfjs = () => import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${CDN}pdf.min.mjs`) as never;\n\n// Pick a passage in your own list: the viewer scrolls to it and lights it where it sits in the page.\nexport default function DocumentViewerHighlights() {\n const [active, setActive] = React.useState<string | null>(\"r1\");\n return (\n <div className=\"flex flex-col gap-3\">\n <div className=\"flex gap-2\">\n {quotes.map((q) => (\n <button key={q.id} type=\"button\" aria-pressed={active === q.id} className=\"rounded-md border border-border-default px-3 py-1 text-sm aria-pressed:bg-surface-3\" onClick={() => setActive(q.id)}>\n {q.label}\n </button>\n ))}\n </div>\n <DocumentViewer src={Uint8Array.from(atob(PDF), (c) => c.charCodeAt(0))} loadPdfjs={loadPdfjs} workerSrc={`${CDN}pdf.worker.min.mjs`} highlights={quotes} activeId={active} onActiveChange={setActive} />\n </div>\n );\n}\n"
|
|
143
|
+
"code": "\"use client\";\n\nimport { DocumentViewer } from \"@krizaka/ui/document-viewer\";\nimport * as React from \"react\";\n\nconst PDF = \"JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUl0gL0NvdW50IDEgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA2MTIgNzkyXSAvQ29udGVudHMgNCAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNSAwIFIgPj4gPj4gPj4KZW5kb2JqCjQgMCBvYmoKPDwgL0xlbmd0aCAyMDkgPj4Kc3RyZWFtCkJUIC9GMSAxNCBUZiA3MiA3MDAgVGQgKEJBSUwgUkVTSURFTlRJRUwpIFRqIEVUCkJUIC9GMSAxMSBUZiA3MiA2NzAgVGQgKExlIGxvY2F0ZXVyIHBldXQgYXVnbWVudGVyIGxlIGxveWVyIGEgdG91dCBtb21lbnQuKSBUaiBFVApCVCAvRjEgMTEgVGYgNzIgNjUwIFRkIChMZSBkZXBvdCBkZSBnYXJhbnRpZSBlc3QgZGUgZGV1eCBtb2lzIGRlIGxveWVyLikgVGogRVQKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDExNSAwMDAwMCBuIAowMDAwMDAwMjQxIDAwMDAwIG4gCjAwMDAwMDA1MDAgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA2IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgo1NzAKJSVFT0YK\";\n// Two passages told by their quote, and one told by a region of the page (fractions, origin top-left): an app that already\n// knows where a stamp or a mismatch sits lights it without any text to match.\nconst quotes = [\n { id: \"r1\", quote: \"Le locateur peut augmenter le loyer à tout moment.\", label: \"Rent increase\" },\n { id: \"r2\", quote: \"Le dépôt de garantie est de deux mois de loyer.\", label: \"Deposit\" },\n { id: \"r3\", region: { page: 1, x: 0.1, y: 0.1, width: 0.3, height: 0.05 }, label: \"Title block\" },\n];\n// pdf.js is the app's: `loadPdfjs={() => import(\"pdfjs-dist\")}` and a worker served from its own origin. Here, from a CDN.\nconst CDN = \"https://cdn.jsdelivr.net/npm/pdfjs-dist@5.4.149/build/\";\nconst loadPdfjs = () => import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${CDN}pdf.min.mjs`) as never;\n\n// Pick a passage in your own list: the viewer scrolls to it and lights it where it sits in the page.\nexport default function DocumentViewerHighlights() {\n const [active, setActive] = React.useState<string | null>(\"r1\");\n return (\n <div className=\"flex flex-col gap-3\">\n <div className=\"flex gap-2\">\n {quotes.map((q) => (\n <button key={q.id} type=\"button\" aria-pressed={active === q.id} className=\"rounded-md border border-border-default px-3 py-1 text-sm aria-pressed:bg-surface-3\" onClick={() => setActive(q.id)}>\n {q.label}\n </button>\n ))}\n </div>\n <DocumentViewer src={Uint8Array.from(atob(PDF), (c) => c.charCodeAt(0))} loadPdfjs={loadPdfjs} workerSrc={`${CDN}pdf.worker.min.mjs`} highlights={quotes} activeId={active} onActiveChange={setActive} />\n </div>\n );\n}\n"
|
|
143
144
|
}
|
|
144
145
|
]
|
|
145
146
|
},
|
|
@@ -147,19 +148,19 @@
|
|
|
147
148
|
"files": [
|
|
148
149
|
{
|
|
149
150
|
"path": "document-viewer/document-viewer.tsx",
|
|
150
|
-
"content": "// Client. A PDF drawn page by page (pdf.js), and passages of it lit where they sit. The app hands over the engine\n// (`loadPdfjs={() => import(\"pdfjs-dist\")}` — an optional peer, loaded only on a page that shows a document) and the\n// worker's address; it hands over the passages as quotes (`highlights`), and the viewer finds their place from the\n// PDF's own text positions (`locateQuote`): one box per line, in fractions of the page, so they follow any zoom.\n// `activeId` (controlled) scrolls to a passage and strengthens it; a click on a box calls `onActiveChange`. A passage\n// the text layer cannot place is never drawn at a guessed place: the viewer goes to its page when it is known and shows\n// the quote in a bar — and tells the app (`onLocate`) so its list can say \"page 3\" or \"not found\".\nimport * as React from \"react\";\nimport { tv } from \"tailwind-variants\";\n\nimport { useLatest, usePrefersReducedMotion } from \"../media\";\nimport { type Located, locateQuote, type PageText } from \"./locate\";\n\nexport const documentViewer = tv({\n slots: {\n root: \"relative flex min-w-0 flex-col gap-3\",\n pages: \"flex max-h-(--kz-document-viewer-height,70vh) flex-col gap-3 overflow-auto rounded-lg border border-border-default bg-surface-2 p-3 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent\",\n page: \"relative mx-auto w-full max-w-(--kz-document-viewer-page,56rem) shrink-0 overflow-hidden rounded-sm bg-white shadow-sm\",\n canvas: \"block h-auto w-full\",\n caption: \"absolute top-1 left-1 rounded-sm bg-surface-1/90 px-1.5 py-0.5 text-xs text-fg-secondary\",\n box: \"absolute cursor-pointer rounded-xs border border-warning/70 bg-warning/25 mix-blend-multiply transition-colors data-[active=true]:border-2 data-[active=true]:border-danger data-[active=true]:bg-danger/25 motion-reduce:transition-none\",\n bar: \"rounded-lg border border-border-default bg-surface-1 px-3 py-2 text-sm text-fg-secondary\",\n status: \"p-6 text-center text-sm text-fg-secondary\",\n },\n});\n\n/** The words of the viewer, passed translated. `{page}` and `{total}` are replaced. */\nexport type DocumentViewerLabels = {\n /** The accessible name of the pages' region. */\n region: string;\n loading: string;\n failed: string;\n /** A page's caption and accessible name: \"Page {page} of {total}\". */\n page: string;\n /** The bar above the pages when the active passage could only be placed on a page: \"Passage on page {page}:\". */\n onPage: string;\n /** The bar when the active passage is not in the text layer. */\n notFound: string;\n};\n\nexport const documentViewerLabels: DocumentViewerLabels = {\n region: \"Document pages\",\n loading: \"Loading the document…\",\n failed: \"The document could not be displayed.\",\n page: \"Page {page} of {total}\",\n onPage: \"Passage on page {page}:\",\n notFound: \"This passage is not in the document's text layer:\",\n};\n\n/** A passage to light: its quote (as the text layer reads it), the page if the app knows it, a name for screen readers. */\nexport type DocumentHighlight = { id: string; quote: string; page?: number; label?: string };\n\n/** What the viewer found for a passage. */\nexport type { Located };\n\n/** The members of pdf.js the viewer uses (`pdfjs-dist` ≥ 5), typed here so the package does not depend on it. */\nexport type PdfjsModule = {\n GlobalWorkerOptions: { workerSrc: string };\n getDocument(source: { url?: string; data?: Uint8Array }): { promise: Promise<PdfDocument>; destroy?: () => Promise<void> | void };\n};\nexport type PdfDocument = { numPages: number; getPage(n: number): Promise<PdfPage>; destroy?: () => Promise<void> | void };\nexport type PdfPage = {\n rotate: number;\n view: number[];\n getViewport(options: { scale: number }): { width: number; height: number };\n getTextContent(): Promise<{ items: readonly unknown[] }>;\n render(options: { canvas: HTMLCanvasElement; canvasContext: CanvasRenderingContext2D; viewport: { width: number; height: number } }): { promise: Promise<void>; cancel?: () => void };\n cleanup?: () => void;\n};\n\nexport type DocumentViewerProps = Omit<React.ComponentProps<\"div\">, \"children\" | \"onChange\"> & {\n /** The PDF: an address (same origin or CORS) or its bytes. */\n src: string | Uint8Array;\n /** Loads pdf.js: `() => import(\"pdfjs-dist\")`. An optional peer, never in a bundle without a document. */\n loadPdfjs: () => Promise<PdfjsModule>;\n /** The address of pdf.js's worker (`new URL(\"pdfjs-dist/build/pdf.worker.min.mjs\", import.meta.url).toString()`). */\n workerSrc: string;\n /** The passages to light. */\n highlights?: readonly DocumentHighlight[];\n /** The passage in focus: the viewer scrolls to it. */\n activeId?: string | null;\n /** A box was clicked (the id) or the focus was released (`null`). */\n onActiveChange?: (id: string | null) => void;\n /** Where each passage was found (`null`: nowhere) — once the text layer is read, and again if `highlights` change. */\n onLocate?: (found: Record<string, Located | null>) => void;\n /** Called when the document is open, with its page count. */\n onLoad?: (info: { pages: number }) => void;\n /** The words of the viewer, translated (English by default). */\n labels?: Partial<DocumentViewerLabels>;\n};\n\nconst fill = (template: string, vars: Record<string, string | number>) => template.replace(/\\{(\\w+)\\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m));\n\ntype Loaded = { doc: PdfDocument; texts: PageText[]; sizes: { width: number; height: number }[] };\ntype Phase = { state: \"loading\" } | { state: \"error\"; key: string } | ({ state: \"ready\"; key: string } & Loaded);\n\nconst isItem = (x: unknown): x is PageText[\"items\"][number] => typeof x === \"object\" && x !== null && typeof (x as { str?: unknown }).str === \"string\" && Array.isArray((x as { transform?: unknown }).transform);\n\nfunction PageCanvas({ page, doc, caption, onReady, className }: { page: number; doc: PdfDocument; caption: string; onReady?: () => void; className: string }) {\n const ref = React.useRef<HTMLCanvasElement>(null);\n const wrapper = React.useRef<HTMLDivElement>(null);\n const [visible, setVisible] = React.useState(() => typeof IntersectionObserver === \"undefined\");\n const ready = useLatest(onReady);\n React.useEffect(() => {\n const node = wrapper.current?.parentElement;\n if (!node) return;\n if (typeof IntersectionObserver === \"undefined\") return;\n const observer = new IntersectionObserver((entries) => entries.some((e) => e.isIntersecting) && setVisible(true), { rootMargin: \"600px 0px\" });\n observer.observe(node);\n return () => observer.disconnect();\n }, []);\n React.useEffect(() => {\n if (!visible) return;\n let task: { promise: Promise<void>; cancel?: () => void } | undefined;\n let cancelled = false;\n void (async () => {\n const p = await doc.getPage(page);\n const canvas = ref.current;\n const ctx = canvas?.getContext(\"2d\");\n if (cancelled || !canvas || !ctx) return;\n const base = p.getViewport({ scale: 1 });\n const dpr = typeof window === \"undefined\" ? 1 : Math.min(2, window.devicePixelRatio || 1);\n const scale = Math.min(2.5, Math.max(1, (canvas.parentElement?.clientWidth || base.width) / base.width)) * dpr;\n const viewport = p.getViewport({ scale });\n canvas.width = Math.floor(viewport.width);\n canvas.height = Math.floor(viewport.height);\n task = p.render({ canvas, canvasContext: ctx, viewport });\n await task.promise.catch(() => undefined);\n if (!cancelled) ready.current?.();\n })().catch(() => undefined);\n return () => {\n cancelled = true;\n task?.cancel?.();\n };\n }, [visible, doc, page, ready]);\n return (\n <div ref={wrapper} className=\"contents\">\n <canvas ref={ref} aria-hidden=\"true\" className={className} />\n <span className=\"sr-only\">{caption}</span>\n </div>\n );\n}\n\n/** A PDF with its passages lit — see the file's header. Client. */\nexport function DocumentViewer({ src, loadPdfjs, workerSrc, highlights = [], activeId = null, onActiveChange, onLocate, onLoad, labels, className, ...props }: DocumentViewerProps) {\n const words = { ...documentViewerLabels, ...labels };\n const s = documentViewer();\n const reduce = usePrefersReducedMotion();\n const [loaded, setPhase] = React.useState<Phase>({ state: \"loading\" });\n const callbacks = useLatest({ onLoad, onLocate });\n const containerRef = React.useRef<HTMLDivElement>(null);\n const bytes = typeof src === \"string\" ? src : src.byteLength + \":\" + src[0] + \":\" + src[src.length - 1];\n // A result belongs to the document it was read from: another `src` is loading again, with no reset inside the effect.\n const phase: Phase = loaded.state !== \"loading\" && loaded.key !== bytes ? { state: \"loading\" } : loaded;\n\n // Open the document and read every page's text layer (positions only; nothing is sent anywhere).\n React.useEffect(() => {\n let cancelled = false;\n let opened: { destroy?: () => Promise<void> | void } | undefined;\n void (async () => {\n const pdfjs = await loadPdfjs();\n pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;\n const loading = pdfjs.getDocument(typeof src === \"string\" ? { url: src } : { data: src.slice() });\n opened = loading;\n const doc = await loading.promise;\n const texts: PageText[] = [];\n const sizes: Loaded[\"sizes\"] = [];\n for (let n = 1; n <= doc.numPages; n++) {\n const page = await doc.getPage(n);\n const vp = page.getViewport({ scale: 1 });\n sizes.push({ width: vp.width, height: vp.height });\n const content = await page.getTextContent();\n // A rotated page has no reliable boxes: it keeps its size and an empty text layer (the app's page hint still works).\n texts.push({ page: n, width: vp.width, height: vp.height, items: page.rotate % 360 === 0 ? content.items.filter(isItem) : [] });\n page.cleanup?.();\n }\n if (cancelled) return;\n setPhase({ state: \"ready\", key: bytes, doc, texts, sizes });\n callbacks.current.onLoad?.({ pages: doc.numPages });\n })().catch(() => !cancelled && setPhase({ state: \"error\", key: bytes }));\n return () => {\n cancelled = true;\n void opened?.destroy?.();\n };\n // `src` is compared by content (`bytes`) so a re-render with the same bytes does not reopen the file.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [bytes, loadPdfjs, workerSrc, callbacks]);\n\n const key = highlights.map((h) => `${h.id}\\u0000${h.page ?? \"\"}\\u0000${h.quote}`).join(\"\\u0001\");\n const found = React.useMemo(() => {\n const out: Record<string, Located | null> = {};\n if (phase.state === \"ready\") for (const h of highlights) out[h.id] = locateQuote(phase.texts, h.quote, h.page);\n return out;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [phase, key]);\n React.useEffect(() => {\n if (phase.state === \"ready\") callbacks.current.onLocate?.(found);\n }, [found, phase.state, callbacks]);\n\n // Go to the active passage.\n const active = activeId ? highlights.find((h) => h.id === activeId) : undefined;\n const where = activeId ? found[activeId] : undefined;\n React.useEffect(() => {\n if (phase.state !== \"ready\" || !where) return;\n const root = containerRef.current;\n const target = root?.querySelector<HTMLElement>(where.boxes.length > 0 ? `[data-highlight=\"${CSS.escape(activeId!)}\"]` : `[data-page=\"${where.page}\"]`) ?? null;\n target?.scrollIntoView?.({ block: where.boxes.length > 0 ? \"center\" : \"start\", behavior: reduce ? \"auto\" : \"smooth\" });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [activeId, where, phase.state]);\n\n return (\n <div className={s.root({ className })} {...props}>\n {active && where !== undefined && where?.match !== \"exact\" && where?.match !== \"start\" ? (\n <p className={s.bar()} data-testid=\"document-viewer-bar\">\n {where?.match === \"page\" ? fill(words.onPage, { page: where.page }) : words.notFound} <q>{active.quote}</q>\n </p>\n ) : null}\n <div ref={containerRef} className={s.pages()} role=\"region\" aria-label={words.region} tabIndex={0}>\n {phase.state === \"loading\" ? <p className={s.status()}>{words.loading}</p> : null}\n {phase.state === \"error\" ? <p role=\"alert\" className={s.status()}>{words.failed}</p> : null}\n {phase.state === \"ready\"\n ? phase.texts.map((t, i) => {\n const size = phase.sizes[i]!;\n const caption = fill(words.page, { page: t.page, total: phase.doc.numPages });\n return (\n <div key={t.page} className={s.page()} data-page={t.page} style={{ aspectRatio: `${size.width} / ${size.height}` }}>\n <PageCanvas page={t.page} doc={phase.doc} caption={caption} className={s.canvas()} />\n <span className={s.caption()} aria-hidden=\"true\">{caption}</span>\n {highlights.flatMap((h) => {\n const f = found[h.id];\n if (!f || f.page !== t.page) return [];\n return f.boxes.map((b, k) => (\n <div\n key={`${h.id}:${k}`}\n aria-hidden=\"true\"\n data-highlight={h.id}\n data-active={h.id === activeId}\n className={s.box()}\n style={{ left: `${b.x * 100}%`, top: `${b.y * 100}%`, width: `${b.width * 100}%`, height: `${b.height * 100}%` }}\n onClick={() => onActiveChange?.(h.id === activeId ? null : h.id)}\n />\n ));\n })}\n </div>\n );\n })\n : null}\n </div>\n </div>\n );\n}\n"
|
|
151
|
+
"content": "// Client. A PDF drawn page by page (pdf.js), and passages of it lit where they sit. The app hands over the engine\n// (`loadPdfjs={() => import(\"pdfjs-dist\")}` — an optional peer, loaded only on a page that shows a document) and the\n// worker's address; it hands over the passages as quotes (`highlights`), and the viewer finds their place from the\n// PDF's own text positions (`locateQuote`): one box per line, in fractions of the page, so they follow any zoom.\n// `activeId` (controlled) scrolls to a passage and strengthens it; a click on a box calls `onActiveChange`. A passage\n// the text layer cannot place is never drawn at a guessed place: the viewer goes to its page when it is known and shows\n// the quote in a bar — and tells the app (`onLocate`) so its list can say \"page 3\" or \"not found\".\nimport * as React from \"react\";\nimport { tv } from \"tailwind-variants\";\n\nimport { useLatest, usePrefersReducedMotion } from \"../media\";\nimport { type Located, type PageText, type Region, resolveHighlight } from \"./locate\";\n\nexport const documentViewer = tv({\n slots: {\n root: \"relative flex min-w-0 flex-col gap-3\",\n pages: \"flex max-h-(--kz-document-viewer-height,70vh) flex-col gap-3 overflow-auto rounded-lg border border-border-default bg-surface-2 p-3 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent\",\n page: \"relative mx-auto w-full max-w-(--kz-document-viewer-page,56rem) shrink-0 overflow-hidden rounded-sm bg-white shadow-sm\",\n canvas: \"block h-auto w-full\",\n caption: \"absolute top-1 left-1 rounded-sm bg-surface-1/90 px-1.5 py-0.5 text-xs text-fg-secondary\",\n box: \"absolute cursor-pointer rounded-xs border border-warning/70 bg-warning/25 mix-blend-multiply transition-colors data-[active=true]:border-2 data-[active=true]:border-danger data-[active=true]:bg-danger/25 motion-reduce:transition-none\",\n bar: \"rounded-lg border border-border-default bg-surface-1 px-3 py-2 text-sm text-fg-secondary\",\n status: \"p-6 text-center text-sm text-fg-secondary\",\n },\n});\n\n/** The words of the viewer, passed translated. `{page}` and `{total}` are replaced. */\nexport type DocumentViewerLabels = {\n /** The accessible name of the pages' region. */\n region: string;\n loading: string;\n failed: string;\n /** A page's caption and accessible name: \"Page {page} of {total}\". */\n page: string;\n /** The bar above the pages when the active passage could only be placed on a page: \"Passage on page {page}:\". */\n onPage: string;\n /** The bar when the active passage is not in the text layer. */\n notFound: string;\n};\n\nexport const documentViewerLabels: DocumentViewerLabels = {\n region: \"Document pages\",\n loading: \"Loading the document…\",\n failed: \"The document could not be displayed.\",\n page: \"Page {page} of {total}\",\n onPage: \"Passage on page {page}:\",\n notFound: \"This passage is not in the document's text layer:\",\n};\n\n/** A passage to light: its quote (as the text layer reads it) and/or a `region` of a page the app already knows (a stamp, a\n mismatch — fractions of the page, origin top-left); the page if known, a name for screen readers. A valid region wins. */\nexport type DocumentHighlight = { id: string; quote?: string; region?: Region; page?: number; label?: string };\n\n/** What the viewer found for a passage. */\nexport type { Located };\n\n/** The members of pdf.js the viewer uses (`pdfjs-dist` ≥ 5), typed here so the package does not depend on it. */\nexport type PdfjsModule = {\n GlobalWorkerOptions: { workerSrc: string };\n getDocument(source: { url?: string; data?: Uint8Array }): { promise: Promise<PdfDocument>; destroy?: () => Promise<void> | void };\n};\nexport type PdfDocument = { numPages: number; getPage(n: number): Promise<PdfPage>; destroy?: () => Promise<void> | void };\nexport type PdfPage = {\n rotate: number;\n view: number[];\n getViewport(options: { scale: number }): { width: number; height: number };\n getTextContent(): Promise<{ items: readonly unknown[] }>;\n render(options: { canvas: HTMLCanvasElement; canvasContext: CanvasRenderingContext2D; viewport: { width: number; height: number } }): { promise: Promise<void>; cancel?: () => void };\n cleanup?: () => void;\n};\n\nexport type DocumentViewerProps = Omit<React.ComponentProps<\"div\">, \"children\" | \"onChange\"> & {\n /** The PDF: an address (same origin or CORS) or its bytes. */\n src: string | Uint8Array;\n /** Loads pdf.js: `() => import(\"pdfjs-dist\")`. An optional peer, never in a bundle without a document. */\n loadPdfjs: () => Promise<PdfjsModule>;\n /** The address of pdf.js's worker (`new URL(\"pdfjs-dist/build/pdf.worker.min.mjs\", import.meta.url).toString()`). */\n workerSrc: string;\n /** The passages to light. */\n highlights?: readonly DocumentHighlight[];\n /** The passage in focus: the viewer scrolls to it. */\n activeId?: string | null;\n /** A box was clicked (the id) or the focus was released (`null`). */\n onActiveChange?: (id: string | null) => void;\n /** Where each passage was found (`null`: nowhere) — once the text layer is read, and again if `highlights` change. */\n onLocate?: (found: Record<string, Located | null>) => void;\n /** Called when the document is open, with its page count. */\n onLoad?: (info: { pages: number }) => void;\n /** The words of the viewer, translated (English by default). */\n labels?: Partial<DocumentViewerLabels>;\n};\n\nconst regionKey = (r: Region | undefined) => (r ? [r.page, r.x, r.y, r.width, r.height].join(\",\") : \"\");\nconst fill = (template: string, vars: Record<string, string | number>) => template.replace(/\\{(\\w+)\\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m));\n\ntype Loaded = { doc: PdfDocument; texts: PageText[]; sizes: { width: number; height: number }[] };\ntype Phase = { state: \"loading\" } | { state: \"error\"; key: string } | ({ state: \"ready\"; key: string } & Loaded);\n\nconst isItem = (x: unknown): x is PageText[\"items\"][number] => typeof x === \"object\" && x !== null && typeof (x as { str?: unknown }).str === \"string\" && Array.isArray((x as { transform?: unknown }).transform);\n\nfunction PageCanvas({ page, doc, caption, onReady, className }: { page: number; doc: PdfDocument; caption: string; onReady?: () => void; className: string }) {\n const ref = React.useRef<HTMLCanvasElement>(null);\n const wrapper = React.useRef<HTMLDivElement>(null);\n const [visible, setVisible] = React.useState(() => typeof IntersectionObserver === \"undefined\");\n const ready = useLatest(onReady);\n React.useEffect(() => {\n const node = wrapper.current?.parentElement;\n if (!node) return;\n if (typeof IntersectionObserver === \"undefined\") return;\n const observer = new IntersectionObserver((entries) => entries.some((e) => e.isIntersecting) && setVisible(true), { rootMargin: \"600px 0px\" });\n observer.observe(node);\n return () => observer.disconnect();\n }, []);\n React.useEffect(() => {\n if (!visible) return;\n let task: { promise: Promise<void>; cancel?: () => void } | undefined;\n let cancelled = false;\n void (async () => {\n const p = await doc.getPage(page);\n const canvas = ref.current;\n const ctx = canvas?.getContext(\"2d\");\n if (cancelled || !canvas || !ctx) return;\n const base = p.getViewport({ scale: 1 });\n const dpr = typeof window === \"undefined\" ? 1 : Math.min(2, window.devicePixelRatio || 1);\n const scale = Math.min(2.5, Math.max(1, (canvas.parentElement?.clientWidth || base.width) / base.width)) * dpr;\n const viewport = p.getViewport({ scale });\n canvas.width = Math.floor(viewport.width);\n canvas.height = Math.floor(viewport.height);\n task = p.render({ canvas, canvasContext: ctx, viewport });\n await task.promise.catch(() => undefined);\n if (!cancelled) ready.current?.();\n })().catch(() => undefined);\n return () => {\n cancelled = true;\n task?.cancel?.();\n };\n }, [visible, doc, page, ready]);\n return (\n <div ref={wrapper} className=\"contents\">\n <canvas ref={ref} aria-hidden=\"true\" className={className} />\n <span className=\"sr-only\">{caption}</span>\n </div>\n );\n}\n\n/** A PDF with its passages lit — see the file's header. Client. */\nexport function DocumentViewer({ src, loadPdfjs, workerSrc, highlights = [], activeId = null, onActiveChange, onLocate, onLoad, labels, className, ...props }: DocumentViewerProps) {\n const words = { ...documentViewerLabels, ...labels };\n const s = documentViewer();\n const reduce = usePrefersReducedMotion();\n const [loaded, setPhase] = React.useState<Phase>({ state: \"loading\" });\n const callbacks = useLatest({ onLoad, onLocate });\n const containerRef = React.useRef<HTMLDivElement>(null);\n const bytes = typeof src === \"string\" ? src : src.byteLength + \":\" + src[0] + \":\" + src[src.length - 1];\n // A result belongs to the document it was read from: another `src` is loading again, with no reset inside the effect.\n const phase: Phase = loaded.state !== \"loading\" && loaded.key !== bytes ? { state: \"loading\" } : loaded;\n\n // Open the document and read every page's text layer (positions only; nothing is sent anywhere).\n React.useEffect(() => {\n let cancelled = false;\n let opened: { destroy?: () => Promise<void> | void } | undefined;\n void (async () => {\n const pdfjs = await loadPdfjs();\n pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;\n const loading = pdfjs.getDocument(typeof src === \"string\" ? { url: src } : { data: src.slice() });\n opened = loading;\n const doc = await loading.promise;\n const texts: PageText[] = [];\n const sizes: Loaded[\"sizes\"] = [];\n for (let n = 1; n <= doc.numPages; n++) {\n const page = await doc.getPage(n);\n const vp = page.getViewport({ scale: 1 });\n sizes.push({ width: vp.width, height: vp.height });\n const content = await page.getTextContent();\n // A rotated page has no reliable boxes: it keeps its size and an empty text layer (the app's page hint still works).\n texts.push({ page: n, width: vp.width, height: vp.height, items: page.rotate % 360 === 0 ? content.items.filter(isItem) : [] });\n page.cleanup?.();\n }\n if (cancelled) return;\n setPhase({ state: \"ready\", key: bytes, doc, texts, sizes });\n callbacks.current.onLoad?.({ pages: doc.numPages });\n })().catch(() => !cancelled && setPhase({ state: \"error\", key: bytes }));\n return () => {\n cancelled = true;\n void opened?.destroy?.();\n };\n // `src` is compared by content (`bytes`) so a re-render with the same bytes does not reopen the file.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [bytes, loadPdfjs, workerSrc, callbacks]);\n\n const key = highlights.map((h) => `${h.id}\\u0000${h.page ?? \"\"}\\u0000${h.quote ?? \"\"}\\u0000${regionKey(h.region)}`).join(\"\\u0001\");\n const found = React.useMemo(() => {\n const out: Record<string, Located | null> = {};\n if (phase.state === \"ready\") for (const h of highlights) out[h.id] = resolveHighlight(phase.texts, h);\n return out;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [phase, key]);\n React.useEffect(() => {\n if (phase.state === \"ready\") callbacks.current.onLocate?.(found);\n }, [found, phase.state, callbacks]);\n\n // Go to the active passage.\n const active = activeId ? highlights.find((h) => h.id === activeId) : undefined;\n const where = activeId ? found[activeId] : undefined;\n React.useEffect(() => {\n if (phase.state !== \"ready\" || !where) return;\n const root = containerRef.current;\n const target = root?.querySelector<HTMLElement>(where.boxes.length > 0 ? `[data-highlight=\"${CSS.escape(activeId!)}\"]` : `[data-page=\"${where.page}\"]`) ?? null;\n target?.scrollIntoView?.({ block: where.boxes.length > 0 ? \"center\" : \"start\", behavior: reduce ? \"auto\" : \"smooth\" });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [activeId, where, phase.state]);\n\n return (\n <div className={s.root({ className })} {...props}>\n {active && where !== undefined && where?.match !== \"exact\" && where?.match !== \"start\" && where?.match !== \"region\" ? (\n <p className={s.bar()} data-testid=\"document-viewer-bar\">\n {where?.match === \"page\" ? fill(words.onPage, { page: where.page }) : words.notFound} {active.quote ? <q>{active.quote}</q> : null}\n </p>\n ) : null}\n <div ref={containerRef} className={s.pages()} role=\"region\" aria-label={words.region} tabIndex={0}>\n {phase.state === \"loading\" ? <p className={s.status()}>{words.loading}</p> : null}\n {phase.state === \"error\" ? <p role=\"alert\" className={s.status()}>{words.failed}</p> : null}\n {phase.state === \"ready\"\n ? phase.texts.map((t, i) => {\n const size = phase.sizes[i]!;\n const caption = fill(words.page, { page: t.page, total: phase.doc.numPages });\n return (\n <div key={t.page} className={s.page()} data-page={t.page} style={{ aspectRatio: `${size.width} / ${size.height}` }}>\n <PageCanvas page={t.page} doc={phase.doc} caption={caption} className={s.canvas()} />\n <span className={s.caption()} aria-hidden=\"true\">{caption}</span>\n {highlights.flatMap((h) => {\n const f = found[h.id];\n if (!f || f.page !== t.page) return [];\n return f.boxes.map((b, k) => (\n <div\n key={`${h.id}:${k}`}\n aria-hidden=\"true\"\n data-highlight={h.id}\n data-active={h.id === activeId}\n className={s.box()}\n style={{ left: `${b.x * 100}%`, top: `${b.y * 100}%`, width: `${b.width * 100}%`, height: `${b.height * 100}%` }}\n onClick={() => onActiveChange?.(h.id === activeId ? null : h.id)}\n />\n ));\n })}\n </div>\n );\n })\n : null}\n </div>\n </div>\n );\n}\n"
|
|
151
152
|
},
|
|
152
153
|
{
|
|
153
154
|
"path": "document-viewer/index.ts",
|
|
154
|
-
"content": "/** @krizaka/ui/document-viewer — `DocumentViewer` (a PDF drawn by pdf.js, its passages lit where they sit), `locateQuote` (a quote → boxes, pure). Client (\"use client\"). */\nexport { type DocumentHighlight, DocumentViewer, documentViewer, type DocumentViewerLabels, documentViewerLabels, type DocumentViewerProps, type Located, type PdfDocument, type PdfjsModule, type PdfPage } from \"./document-viewer\";\nexport { type Box, fold, locateQuote, type PageText, type TextItem } from \"./locate\";\n"
|
|
155
|
+
"content": "/** @krizaka/ui/document-viewer — `DocumentViewer` (a PDF drawn by pdf.js, its passages lit where they sit), `locateQuote` (a quote → boxes, pure), `locateRegion` (a box of a page, checked). Client (\"use client\"). */\nexport { type DocumentHighlight, DocumentViewer, documentViewer, type DocumentViewerLabels, documentViewerLabels, type DocumentViewerProps, type Located, type PdfDocument, type PdfjsModule, type PdfPage } from \"./document-viewer\";\nexport { type Box, fold, locateQuote, locateRegion, type PageText, type Region, resolveHighlight, type TextItem } from \"./locate\";\n"
|
|
155
156
|
},
|
|
156
157
|
{
|
|
157
158
|
"path": "document-viewer/locate.ts",
|
|
158
|
-
"content": "// Pure: where a quoted passage sits on the pages of a PDF, from pdf.js's text positions. No DOM, no pdf.js import —\n// the viewer feeds it what `page.getTextContent()` returned, a test feeds it a fixture.\n\n/** A text item as pdf.js returns it (`TextItem`): the string, its matrix (`[a, b, c, d, x, baseline]`) and its size. */\nexport type TextItem = { str: string; transform: number[]; width: number; height: number };\n\n/** A rectangle in fractions of the page (0–1), origin top-left — independent of the zoom the page is drawn at. */\nexport type Box = { x: number; y: number; width: number; height: number };\n\n/** The text layer of one page: its size in PDF units (rotation 0) and its items in reading order. */\nexport type PageText = { page: number; width: number; height: number; items: readonly TextItem[] };\n\nexport type Located = {\n /** 1-based page where the passage starts. */\n page: number;\n /** One box per line of the passage (merged along a line); empty when only the page is known. */\n boxes: Box[];\n /** `exact`: the whole quote was found; `start`: only its opening words were (a quote cut by a different layout). */\n match: \"exact\" | \"start\" | \"page\";\n};\n\nconst FOLD: Record<string, string> = { \"’\": \"'\", \"‘\": \"'\", \"“\": '\"', \"”\": '\"', \"«\": '\"', \"»\": '\"', \"–\": \"-\", \"—\": \"-\", \" \": \" \", \" \": \" \", \"fi\": \"fi\", \"fl\": \"fl\" };\n\n/** The comparable form of a text: no whitespace, no soft hyphen, straight quotes, case and accents folded. */\nexport function fold(text: string): string {\n let out = \"\";\n for (const ch of text.normalize(\"NFKD\")) {\n if (/\\p{M}/u.test(ch) || /\\s/u.test(ch) || ch === \"\" || ch === \"\") continue;\n out += (FOLD[ch] ?? ch).toLowerCase();\n }\n return out;\n}\n\ntype Index = { text: string; at: { item: number; char: number }[] };\n\nfunction indexPage(items: readonly TextItem[]): Index {\n let text = \"\";\n const at: Index[\"at\"] = [];\n items.forEach((item, i) => {\n for (let c = 0; c < item.str.length; c++) {\n const piece = fold(item.str[c]!);\n for (let k = 0; k < piece.length; k++) {\n text += piece[k];\n at.push({ item: i, char: c });\n }\n }\n });\n return { text, at };\n}\n\n// Proportional faces: \"locataire\" is not as wide as nine capitals. pdf.js gives one width per item, so a position inside an\n// item is shared out by the Helvetica advance widths (per 1000 em) — close for any sans text, far better than a flat share.\nconst ADVANCE =\n \"278 278 355 556 556 889 667 191 333 333 389 584 278 333 278 278 556 556 556 556 556 556 556 556 556 556 278 278 584 584 584 556 1015 \" +\n \"667 667 722 722 667 611 778 722 278 500 667 556 833 722 778 667 778 722 667 611 722 667 944 667 667 611 278 278 278 469 556 333 \" +\n \"556 556 500 556 556 278 556 556 222 222 500 222 833 556 556 556 556 333 500 278 556 500 722 500 500 500\";\nconst ADVANCES = ADVANCE.split(\" \").map(Number);\nfunction advance(ch: string): number {\n const base = ch.normalize(\"NFD\")[0] ?? ch;\n const code = base.charCodeAt(0);\n return code >= 32 && code <= 126 ? (ADVANCES[code - 32] ?? 556) : 556;\n}\n/** The share (0–1) of an item's width that lies before character `n` of `text`. */\nfunction shareBefore(text: string, n: number): number {\n let before = 0;\n let total = 0;\n for (let i = 0; i < text.length; i++) {\n const a = advance(text[i]!);\n if (i < n) before += a;\n total += a;\n }\n return total > 0 ? before / total : n / Math.max(1, text.length);\n}\n\nfunction boxesOf(page: PageText, index: Index, from: number, to: number): Box[] {\n const spans = new Map<number, [number, number]>();\n for (let k = from; k < to; k++) {\n const { item, char } = index.at[k]!;\n const s = spans.get(item);\n spans.set(item, s ? [Math.min(s[0], char), Math.max(s[1], char + 1)] : [char, char + 1]);\n }\n const raw: Box[] = [];\n for (const [i, [c0, c1]] of [...spans].sort((a, b) => a[0] - b[0])) {\n const item = page.items[i]!;\n const size = item.height || Math.abs(item.transform[3] ?? 0) || 10;\n const x = (item.transform[4] ?? 0) + item.width * shareBefore(item.str, c0);\n const w = item.width * (shareBefore(item.str, c1) - shareBefore(item.str, c0));\n const top = page.height - ((item.transform[5] ?? 0) + size * 0.9);\n raw.push({ x: x / page.width, y: top / page.height, width: w / page.width, height: (size * 1.15) / page.height });\n }\n // Merge the pieces that sit on one line and touch (several items of one sentence) into one rectangle.\n const merged: Box[] = [];\n for (const b of raw) {\n const last = merged[merged.length - 1];\n const sameLine = last && Math.abs(last.y - b.y) < last.height * 0.5 && b.x - (last.x + last.width) < last.height * 1.5 && b.x >= last.x - 1e-9;\n if (last && sameLine) {\n const right = Math.max(last.x + last.width, b.x + b.width);\n last.y = Math.min(last.y, b.y);\n last.height = Math.max(last.height, b.height);\n last.width = right - last.x;\n } else merged.push({ ...b });\n }\n return merged.map((b) => ({ x: clamp01(b.x), y: clamp01(b.y), width: Math.min(b.width, 1 - clamp01(b.x)), height: Math.min(b.height, 1 - clamp01(b.y)) }));\n}\n\nconst clamp01 = (n: number) => Math.min(1, Math.max(0, n));\n\n/** The shortest opening worth highlighting alone: a few words, not a stray letter. */\nconst MIN_START = 24;\n\n/**\n * Where `quote` sits in the pages: the first page (starting with `hintPage`, if any) whose text contains it, and the\n * boxes of its lines. A quote that a different layout cut (a column break, a hyphen) is looked for by its opening\n * words (`match: \"start\"`); one that is nowhere gives `null`, or the hinted page alone (`match: \"page\"`). Never a guess:\n * a rotated page has no boxes, only its page.\n */\nexport function locateQuote(pages: readonly PageText[], quote: string, hintPage?: number): Located | null {\n const needle = fold(quote);\n const ordered = hintPage ? [...pages].sort((a, b) => Number(b.page === hintPage) - Number(a.page === hintPage)) : pages;\n if (needle.length > 0) {\n for (const mode of [\"exact\", \"start\"] as const) {\n const wanted = mode === \"exact\" ? needle : needle.slice(0, Math.max(MIN_START, Math.min(40, Math.floor(needle.length * 0.6))));\n if (mode === \"start\" && (needle.length <= wanted.length || wanted.length < MIN_START)) break;\n for (const page of ordered) {\n const index = indexPage(page.items);\n const found = index.text.indexOf(wanted);\n if (found < 0) continue;\n return { page: page.page, boxes: boxesOf(page, index, found, found + wanted.length), match: mode };\n }\n }\n }\n return hintPage && pages.some((p) => p.page === hintPage) ? { page: hintPage, boxes: [], match: \"page\" } : null;\n}\n"
|
|
159
|
+
"content": "// Pure: where a quoted passage sits on the pages of a PDF, from pdf.js's text positions. No DOM, no pdf.js import —\n// the viewer feeds it what `page.getTextContent()` returned, a test feeds it a fixture.\n\n/** A text item as pdf.js returns it (`TextItem`): the string, its matrix (`[a, b, c, d, x, baseline]`) and its size. */\nexport type TextItem = { str: string; transform: number[]; width: number; height: number };\n\n/** A rectangle in fractions of the page (0–1), origin top-left — independent of the zoom the page is drawn at. */\nexport type Box = { x: number; y: number; width: number; height: number };\n\n/** The text layer of one page: its size in PDF units (rotation 0) and its items in reading order. */\nexport type PageText = { page: number; width: number; height: number; items: readonly TextItem[] };\n\nexport type Located = {\n /** 1-based page where the passage starts. */\n page: number;\n /** One box per line of the passage (merged along a line); empty when only the page is known. */\n boxes: Box[];\n /** `region`: the box the app gave, as it is; `exact`: the whole quote was found; `start`: only its opening words were (a quote cut by a different layout). */\n match: \"exact\" | \"start\" | \"page\" | \"region\";\n};\n\n/** A region of a page the app already knows (a stamp, a font mismatch, a metadata area): its page and a box in fractions. */\nexport type Region = Box & { page: number };\n\nconst FOLD: Record<string, string> = { \"’\": \"'\", \"‘\": \"'\", \"“\": '\"', \"”\": '\"', \"«\": '\"', \"»\": '\"', \"–\": \"-\", \"—\": \"-\", \" \": \" \", \" \": \" \", \"fi\": \"fi\", \"fl\": \"fl\" };\n\n/** The comparable form of a text: no whitespace, no soft hyphen, straight quotes, case and accents folded. */\nexport function fold(text: string): string {\n let out = \"\";\n for (const ch of text.normalize(\"NFKD\")) {\n if (/\\p{M}/u.test(ch) || /\\s/u.test(ch) || ch === \"\" || ch === \"\") continue;\n out += (FOLD[ch] ?? ch).toLowerCase();\n }\n return out;\n}\n\ntype Index = { text: string; at: { item: number; char: number }[] };\n\nfunction indexPage(items: readonly TextItem[]): Index {\n let text = \"\";\n const at: Index[\"at\"] = [];\n items.forEach((item, i) => {\n for (let c = 0; c < item.str.length; c++) {\n const piece = fold(item.str[c]!);\n for (let k = 0; k < piece.length; k++) {\n text += piece[k];\n at.push({ item: i, char: c });\n }\n }\n });\n return { text, at };\n}\n\n// Proportional faces: \"locataire\" is not as wide as nine capitals. pdf.js gives one width per item, so a position inside an\n// item is shared out by the Helvetica advance widths (per 1000 em) — close for any sans text, far better than a flat share.\nconst ADVANCE =\n \"278 278 355 556 556 889 667 191 333 333 389 584 278 333 278 278 556 556 556 556 556 556 556 556 556 556 278 278 584 584 584 556 1015 \" +\n \"667 667 722 722 667 611 778 722 278 500 667 556 833 722 778 667 778 722 667 611 722 667 944 667 667 611 278 278 278 469 556 333 \" +\n \"556 556 500 556 556 278 556 556 222 222 500 222 833 556 556 556 556 333 500 278 556 500 722 500 500 500\";\nconst ADVANCES = ADVANCE.split(\" \").map(Number);\nfunction advance(ch: string): number {\n const base = ch.normalize(\"NFD\")[0] ?? ch;\n const code = base.charCodeAt(0);\n return code >= 32 && code <= 126 ? (ADVANCES[code - 32] ?? 556) : 556;\n}\n/** The share (0–1) of an item's width that lies before character `n` of `text`. */\nfunction shareBefore(text: string, n: number): number {\n let before = 0;\n let total = 0;\n for (let i = 0; i < text.length; i++) {\n const a = advance(text[i]!);\n if (i < n) before += a;\n total += a;\n }\n return total > 0 ? before / total : n / Math.max(1, text.length);\n}\n\nfunction boxesOf(page: PageText, index: Index, from: number, to: number): Box[] {\n const spans = new Map<number, [number, number]>();\n for (let k = from; k < to; k++) {\n const { item, char } = index.at[k]!;\n const s = spans.get(item);\n spans.set(item, s ? [Math.min(s[0], char), Math.max(s[1], char + 1)] : [char, char + 1]);\n }\n const raw: Box[] = [];\n for (const [i, [c0, c1]] of [...spans].sort((a, b) => a[0] - b[0])) {\n const item = page.items[i]!;\n const size = item.height || Math.abs(item.transform[3] ?? 0) || 10;\n const x = (item.transform[4] ?? 0) + item.width * shareBefore(item.str, c0);\n const w = item.width * (shareBefore(item.str, c1) - shareBefore(item.str, c0));\n const top = page.height - ((item.transform[5] ?? 0) + size * 0.9);\n raw.push({ x: x / page.width, y: top / page.height, width: w / page.width, height: (size * 1.15) / page.height });\n }\n // Merge the pieces that sit on one line and touch (several items of one sentence) into one rectangle.\n const merged: Box[] = [];\n for (const b of raw) {\n const last = merged[merged.length - 1];\n const sameLine = last && Math.abs(last.y - b.y) < last.height * 0.5 && b.x - (last.x + last.width) < last.height * 1.5 && b.x >= last.x - 1e-9;\n if (last && sameLine) {\n const right = Math.max(last.x + last.width, b.x + b.width);\n last.y = Math.min(last.y, b.y);\n last.height = Math.max(last.height, b.height);\n last.width = right - last.x;\n } else merged.push({ ...b });\n }\n return merged.map((b) => ({ x: clamp01(b.x), y: clamp01(b.y), width: Math.min(b.width, 1 - clamp01(b.x)), height: Math.min(b.height, 1 - clamp01(b.y)) }));\n}\n\nconst clamp01 = (n: number) => Math.min(1, Math.max(0, n));\n\n/** The shortest opening worth highlighting alone: a few words, not a stray letter. */\nconst MIN_START = 24;\n\n/**\n * Where `quote` sits in the pages: the first page (starting with `hintPage`, if any) whose text contains it, and the\n * boxes of its lines. A quote that a different layout cut (a column break, a hyphen) is looked for by its opening\n * words (`match: \"start\"`); one that is nowhere gives `null`, or the hinted page alone (`match: \"page\"`). Never a guess:\n * a rotated page has no boxes, only its page.\n */\nexport function locateQuote(pages: readonly PageText[], quote: string, hintPage?: number): Located | null {\n const needle = fold(quote);\n const ordered = hintPage ? [...pages].sort((a, b) => Number(b.page === hintPage) - Number(a.page === hintPage)) : pages;\n if (needle.length > 0) {\n for (const mode of [\"exact\", \"start\"] as const) {\n const wanted = mode === \"exact\" ? needle : needle.slice(0, Math.max(MIN_START, Math.min(40, Math.floor(needle.length * 0.6))));\n if (mode === \"start\" && (needle.length <= wanted.length || wanted.length < MIN_START)) break;\n for (const page of ordered) {\n const index = indexPage(page.items);\n const found = index.text.indexOf(wanted);\n if (found < 0) continue;\n return { page: page.page, boxes: boxesOf(page, index, found, found + wanted.length), match: mode };\n }\n }\n }\n return hintPage && pages.some((p) => p.page === hintPage) ? { page: hintPage, boxes: [], match: \"page\" } : null;\n}\n\nconst inUnit = (n: number) => Number.isFinite(n) && n >= 0 && n <= 1;\n\n/**\n * A region of a page, as it is: one box, no text needed. Never drawn when it is not on the pages — an unknown page, a box\n * outside 0–1 or empty, a value that is not a number — so a wrong box is `null`, not a guess.\n */\nexport function locateRegion(pages: readonly PageText[], region: Region): Located | null {\n const { page, x, y, width, height } = region;\n const valid = pages.some((p) => p.page === page) && inUnit(x) && inUnit(y) && width > 0 && height > 0 && inUnit(x + width) && inUnit(y + height);\n return valid ? { page, boxes: [{ x, y, width, height }], match: \"region\" } : null;\n}\n\n/** What to light for a highlight: its region when it has a valid one, otherwise its quote (if any). */\nexport function resolveHighlight(pages: readonly PageText[], h: { quote?: string; page?: number; region?: Region }): Located | null {\n const byRegion = h.region ? locateRegion(pages, h.region) : null;\n if (byRegion) return byRegion;\n if (h.quote) return locateQuote(pages, h.quote, h.page ?? h.region?.page);\n const hinted = h.page !== undefined && pages.some((p) => p.page === h.page);\n return hinted ? { page: h.page!, boxes: [], match: \"page\" } : null;\n}\n"
|
|
159
160
|
},
|
|
160
161
|
{
|
|
161
162
|
"path": "document-viewer/meta.ts",
|
|
162
|
-
"content": "import type { ComponentMeta } from \"../meta\";\n\nexport const meta = {\n title: \"Document viewer\",\n summary: \"A PDF drawn page by page with pdf.js, and the passages of a report lit where they sit — found from the PDF's own text positions, one box per line; the page and the quote when the text layer cannot place them.\",\n status: \"beta\",\n category: \"media\",\n domain: \"media\",\n platforms: \"web\",\n parity: { native: { status: \"gap\", issue: \"krizaka/krizaka-ui#278\", reason: \"Needs a PDF module; Yomizaka has no phone app yet.\" }, desktop: \"web\" },\n whenToUse: [\n \"To read a document beside what was said about it: findings, comments, extracted fields.\",\n \"To make a quoted passage visible in the original file instead of in a copy of its text.\",\n ],\n whenNotToUse: [\n { when: \"To play a video or a recording.\", use: \"video-player\" },\n { when: \"To show an image to crop.\" },\n { when: \"To let the browser open the file as it is: a link to the file is enough.\", use: \"button\" },\n ],\n bestPractices: [\n \"Keep the list of passages in the page, next to the viewer: the viewer is not a keyboard route to each box, your list is (`activeId` / `onActiveChange`).\",\n \"Pass the quote as the text layer reads it and, when you know it, the page: a quote the layout cut is still placed by its opening words, and a page alone still scrolls.\",\n \"Use `onLocate` to tell the person what was placed and what was not (« page 3 », « not found in the text layer ») — a passage is never drawn at a guessed place.\",\n \"Load pdf.js with `() => import(\\\"pdfjs-dist\\\")` and give it a same-origin worker (`workerSrc`): the engine only reaches pages that show a document.\",\n ],\n accessibility: {\n keyboard: [{ keys: \"Tab, arrows, Page Up / Down\", action: \"The pages' region is focusable and scrolls like any scrollable area.\" }],\n notes: [\n \"The region is named by `labels.region`; each page is announced by its caption (« Page 2 of 5 »).\",\n \"The highlight boxes are decorative (`aria-hidden`): the passages are reached through your list, whose entries scroll to them.\",\n \"A scanned PDF has no text layer: nothing is lit, and the pages stay readable as images — offer the text alternative yourself.\",\n \"A passage that cannot be placed is announced in a bar with its quote.\",\n ],\n },\n related: [\"tabs\", \"split-view\", \"video-player\"],\n web: {\n imports: [\"DocumentViewer\", \"locateQuote\"],\n examples: [\n { name: \"highlights\", title: \"Findings in the file\", description: \"A one-page lease and
|
|
163
|
+
"content": "import type { ComponentMeta } from \"../meta\";\n\nexport const meta = {\n title: \"Document viewer\",\n summary: \"A PDF drawn page by page with pdf.js, and the passages of a report lit where they sit — found from the PDF's own text positions, one box per line; the page and the quote when the text layer cannot place them.\",\n status: \"beta\",\n category: \"media\",\n domain: \"media\",\n platforms: \"web\",\n parity: { native: { status: \"gap\", issue: \"krizaka/krizaka-ui#278\", reason: \"Needs a PDF module; Yomizaka has no phone app yet.\" }, desktop: \"web\" },\n whenToUse: [\n \"To read a document beside what was said about it: findings, comments, extracted fields.\",\n \"To make a quoted passage visible in the original file instead of in a copy of its text.\",\n ],\n whenNotToUse: [\n { when: \"To play a video or a recording.\", use: \"video-player\" },\n { when: \"To show an image to crop.\" },\n { when: \"To let the browser open the file as it is: a link to the file is enough.\", use: \"button\" },\n ],\n bestPractices: [\n \"Keep the list of passages in the page, next to the viewer: the viewer is not a keyboard route to each box, your list is (`activeId` / `onActiveChange`).\",\n \"Light a region instead of a quote when the app already knows where the evidence sits (`region: { page, x, y, width, height }`, fractions of the page): no text layer needed, and a region outside the page is never drawn.\",\n \"Pass the quote as the text layer reads it and, when you know it, the page: a quote the layout cut is still placed by its opening words, and a page alone still scrolls.\",\n \"Use `onLocate` to tell the person what was placed and what was not (« page 3 », « not found in the text layer ») — a passage is never drawn at a guessed place.\",\n \"Load pdf.js with `() => import(\\\"pdfjs-dist\\\")` and give it a same-origin worker (`workerSrc`): the engine only reaches pages that show a document.\",\n ],\n accessibility: {\n keyboard: [{ keys: \"Tab, arrows, Page Up / Down\", action: \"The pages' region is focusable and scrolls like any scrollable area.\" }],\n notes: [\n \"The region is named by `labels.region`; each page is announced by its caption (« Page 2 of 5 »).\",\n \"The highlight boxes are decorative (`aria-hidden`): the passages are reached through your list, whose entries scroll to them.\",\n \"A scanned PDF has no text layer: nothing is lit, and the pages stay readable as images — offer the text alternative yourself.\",\n \"A passage that cannot be placed is announced in a bar with its quote.\",\n ],\n },\n related: [\"tabs\", \"split-view\", \"video-player\"],\n web: {\n imports: [\"DocumentViewer\", \"locateQuote\", \"locateRegion\"],\n examples: [\n { name: \"highlights\", title: \"Findings in the file\", description: \"A one-page lease, two passages told by their quote and one by a region; pick one and the page scrolls to it and lights it.\" },\n ],\n },\n} satisfies ComponentMeta;\n"
|
|
163
164
|
},
|
|
164
165
|
{
|
|
165
166
|
"path": "media.ts",
|
|
@@ -176,7 +177,7 @@
|
|
|
176
177
|
"registryDependencies": [],
|
|
177
178
|
"demo": {
|
|
178
179
|
"path": "examples/document-viewer/highlights.tsx",
|
|
179
|
-
"content": "\"use client\";\n\nimport { DocumentViewer } from \"@krizaka/ui/document-viewer\";\nimport * as React from \"react\";\n\nconst PDF = \"JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUl0gL0NvdW50IDEgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA2MTIgNzkyXSAvQ29udGVudHMgNCAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNSAwIFIgPj4gPj4gPj4KZW5kb2JqCjQgMCBvYmoKPDwgL0xlbmd0aCAyMDkgPj4Kc3RyZWFtCkJUIC9GMSAxNCBUZiA3MiA3MDAgVGQgKEJBSUwgUkVTSURFTlRJRUwpIFRqIEVUCkJUIC9GMSAxMSBUZiA3MiA2NzAgVGQgKExlIGxvY2F0ZXVyIHBldXQgYXVnbWVudGVyIGxlIGxveWVyIGEgdG91dCBtb21lbnQuKSBUaiBFVApCVCAvRjEgMTEgVGYgNzIgNjUwIFRkIChMZSBkZXBvdCBkZSBnYXJhbnRpZSBlc3QgZGUgZGV1eCBtb2lzIGRlIGxveWVyLikgVGogRVQKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDExNSAwMDAwMCBuIAowMDAwMDAwMjQxIDAwMDAwIG4gCjAwMDAwMDA1MDAgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA2IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgo1NzAKJSVFT0YK\";\nconst quotes = [\n { id: \"r1\", quote: \"Le locateur peut augmenter le loyer à tout moment.\", label: \"Rent increase\" },\n { id: \"r2\", quote: \"Le dépôt de garantie est de deux mois de loyer.\", label: \"Deposit\" },\n];\n// pdf.js is the app's: `loadPdfjs={() => import(\"pdfjs-dist\")}` and a worker served from its own origin. Here, from a CDN.\nconst CDN = \"https://cdn.jsdelivr.net/npm/pdfjs-dist@5.4.149/build/\";\nconst loadPdfjs = () => import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${CDN}pdf.min.mjs`) as never;\n\n// Pick a passage in your own list: the viewer scrolls to it and lights it where it sits in the page.\nexport default function DocumentViewerHighlights() {\n const [active, setActive] = React.useState<string | null>(\"r1\");\n return (\n <div className=\"flex flex-col gap-3\">\n <div className=\"flex gap-2\">\n {quotes.map((q) => (\n <button key={q.id} type=\"button\" aria-pressed={active === q.id} className=\"rounded-md border border-border-default px-3 py-1 text-sm aria-pressed:bg-surface-3\" onClick={() => setActive(q.id)}>\n {q.label}\n </button>\n ))}\n </div>\n <DocumentViewer src={Uint8Array.from(atob(PDF), (c) => c.charCodeAt(0))} loadPdfjs={loadPdfjs} workerSrc={`${CDN}pdf.worker.min.mjs`} highlights={quotes} activeId={active} onActiveChange={setActive} />\n </div>\n );\n}\n"
|
|
180
|
+
"content": "\"use client\";\n\nimport { DocumentViewer } from \"@krizaka/ui/document-viewer\";\nimport * as React from \"react\";\n\nconst PDF = \"JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUl0gL0NvdW50IDEgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA2MTIgNzkyXSAvQ29udGVudHMgNCAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNSAwIFIgPj4gPj4gPj4KZW5kb2JqCjQgMCBvYmoKPDwgL0xlbmd0aCAyMDkgPj4Kc3RyZWFtCkJUIC9GMSAxNCBUZiA3MiA3MDAgVGQgKEJBSUwgUkVTSURFTlRJRUwpIFRqIEVUCkJUIC9GMSAxMSBUZiA3MiA2NzAgVGQgKExlIGxvY2F0ZXVyIHBldXQgYXVnbWVudGVyIGxlIGxveWVyIGEgdG91dCBtb21lbnQuKSBUaiBFVApCVCAvRjEgMTEgVGYgNzIgNjUwIFRkIChMZSBkZXBvdCBkZSBnYXJhbnRpZSBlc3QgZGUgZGV1eCBtb2lzIGRlIGxveWVyLikgVGogRVQKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDExNSAwMDAwMCBuIAowMDAwMDAwMjQxIDAwMDAwIG4gCjAwMDAwMDA1MDAgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA2IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgo1NzAKJSVFT0YK\";\n// Two passages told by their quote, and one told by a region of the page (fractions, origin top-left): an app that already\n// knows where a stamp or a mismatch sits lights it without any text to match.\nconst quotes = [\n { id: \"r1\", quote: \"Le locateur peut augmenter le loyer à tout moment.\", label: \"Rent increase\" },\n { id: \"r2\", quote: \"Le dépôt de garantie est de deux mois de loyer.\", label: \"Deposit\" },\n { id: \"r3\", region: { page: 1, x: 0.1, y: 0.1, width: 0.3, height: 0.05 }, label: \"Title block\" },\n];\n// pdf.js is the app's: `loadPdfjs={() => import(\"pdfjs-dist\")}` and a worker served from its own origin. Here, from a CDN.\nconst CDN = \"https://cdn.jsdelivr.net/npm/pdfjs-dist@5.4.149/build/\";\nconst loadPdfjs = () => import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${CDN}pdf.min.mjs`) as never;\n\n// Pick a passage in your own list: the viewer scrolls to it and lights it where it sits in the page.\nexport default function DocumentViewerHighlights() {\n const [active, setActive] = React.useState<string | null>(\"r1\");\n return (\n <div className=\"flex flex-col gap-3\">\n <div className=\"flex gap-2\">\n {quotes.map((q) => (\n <button key={q.id} type=\"button\" aria-pressed={active === q.id} className=\"rounded-md border border-border-default px-3 py-1 text-sm aria-pressed:bg-surface-3\" onClick={() => setActive(q.id)}>\n {q.label}\n </button>\n ))}\n </div>\n <DocumentViewer src={Uint8Array.from(atob(PDF), (c) => c.charCodeAt(0))} loadPdfjs={loadPdfjs} workerSrc={`${CDN}pdf.worker.min.mjs`} highlights={quotes} activeId={active} onActiveChange={setActive} />\n </div>\n );\n}\n"
|
|
180
181
|
},
|
|
181
182
|
"props": [
|
|
182
183
|
{
|
|
@@ -7,7 +7,8 @@ import { jsx, jsxs } from "react/jsx-runtime";
|
|
|
7
7
|
var PDF = "JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUl0gL0NvdW50IDEgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA2MTIgNzkyXSAvQ29udGVudHMgNCAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNSAwIFIgPj4gPj4gPj4KZW5kb2JqCjQgMCBvYmoKPDwgL0xlbmd0aCAyMDkgPj4Kc3RyZWFtCkJUIC9GMSAxNCBUZiA3MiA3MDAgVGQgKEJBSUwgUkVTSURFTlRJRUwpIFRqIEVUCkJUIC9GMSAxMSBUZiA3MiA2NzAgVGQgKExlIGxvY2F0ZXVyIHBldXQgYXVnbWVudGVyIGxlIGxveWVyIGEgdG91dCBtb21lbnQuKSBUaiBFVApCVCAvRjEgMTEgVGYgNzIgNjUwIFRkIChMZSBkZXBvdCBkZSBnYXJhbnRpZSBlc3QgZGUgZGV1eCBtb2lzIGRlIGxveWVyLikgVGogRVQKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDExNSAwMDAwMCBuIAowMDAwMDAwMjQxIDAwMDAwIG4gCjAwMDAwMDA1MDAgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA2IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgo1NzAKJSVFT0YK";
|
|
8
8
|
var quotes = [
|
|
9
9
|
{ id: "r1", quote: "Le locateur peut augmenter le loyer \xE0 tout moment.", label: "Rent increase" },
|
|
10
|
-
{ id: "r2", quote: "Le d\xE9p\xF4t de garantie est de deux mois de loyer.", label: "Deposit" }
|
|
10
|
+
{ id: "r2", quote: "Le d\xE9p\xF4t de garantie est de deux mois de loyer.", label: "Deposit" },
|
|
11
|
+
{ id: "r3", region: { page: 1, x: 0.1, y: 0.1, width: 0.3, height: 0.05 }, label: "Title block" }
|
|
11
12
|
];
|
|
12
13
|
var CDN = "https://cdn.jsdelivr.net/npm/pdfjs-dist@5.4.149/build/";
|
|
13
14
|
var loadPdfjs = () => import(
|
|
@@ -4,9 +4,12 @@ import { DocumentViewer } from "@krizaka/ui/document-viewer";
|
|
|
4
4
|
import * as React from "react";
|
|
5
5
|
|
|
6
6
|
const PDF = "JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUl0gL0NvdW50IDEgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA2MTIgNzkyXSAvQ29udGVudHMgNCAwIFIgL1Jlc291cmNlcyA8PCAvRm9udCA8PCAvRjEgNSAwIFIgPj4gPj4gPj4KZW5kb2JqCjQgMCBvYmoKPDwgL0xlbmd0aCAyMDkgPj4Kc3RyZWFtCkJUIC9GMSAxNCBUZiA3MiA3MDAgVGQgKEJBSUwgUkVTSURFTlRJRUwpIFRqIEVUCkJUIC9GMSAxMSBUZiA3MiA2NzAgVGQgKExlIGxvY2F0ZXVyIHBldXQgYXVnbWVudGVyIGxlIGxveWVyIGEgdG91dCBtb21lbnQuKSBUaiBFVApCVCAvRjEgMTEgVGYgNzIgNjUwIFRkIChMZSBkZXBvdCBkZSBnYXJhbnRpZSBlc3QgZGUgZGV1eCBtb2lzIGRlIGxveWVyLikgVGogRVQKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDA5IDAwMDAwIG4gCjAwMDAwMDAwNTggMDAwMDAgbiAKMDAwMDAwMDExNSAwMDAwMCBuIAowMDAwMDAwMjQxIDAwMDAwIG4gCjAwMDAwMDA1MDAgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA2IC9Sb290IDEgMCBSID4+CnN0YXJ0eHJlZgo1NzAKJSVFT0YK";
|
|
7
|
+
// Two passages told by their quote, and one told by a region of the page (fractions, origin top-left): an app that already
|
|
8
|
+
// knows where a stamp or a mismatch sits lights it without any text to match.
|
|
7
9
|
const quotes = [
|
|
8
10
|
{ id: "r1", quote: "Le locateur peut augmenter le loyer à tout moment.", label: "Rent increase" },
|
|
9
11
|
{ id: "r2", quote: "Le dépôt de garantie est de deux mois de loyer.", label: "Deposit" },
|
|
12
|
+
{ id: "r3", region: { page: 1, x: 0.1, y: 0.1, width: 0.3, height: 0.05 }, label: "Title block" },
|
|
10
13
|
];
|
|
11
14
|
// pdf.js is the app's: `loadPdfjs={() => import("pdfjs-dist")}` and a worker served from its own origin. Here, from a CDN.
|
|
12
15
|
const CDN = "https://cdn.jsdelivr.net/npm/pdfjs-dist@5.4.149/build/";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
// registry/examples/map/pins.tsx
|
|
4
|
+
import { MapPin } from "@krizaka/ui/map/pin";
|
|
5
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
6
|
+
var SHAPES = ["drop", "disc", "tag"];
|
|
7
|
+
var STATES = ["default", "selected", "visited", "closed"];
|
|
8
|
+
function MapPins() {
|
|
9
|
+
return /* @__PURE__ */ jsxs("div", { className: "grid w-full max-w-xl grid-cols-[auto_repeat(4,1fr)] items-end gap-x-6 gap-y-5 rounded-xl border border-border-subtle bg-surface-1 p-5 text-xs text-fg-secondary", children: [
|
|
10
|
+
/* @__PURE__ */ jsx("span", {}),
|
|
11
|
+
STATES.map((state) => /* @__PURE__ */ jsx("span", { children: state }, state)),
|
|
12
|
+
SHAPES.map((shape) => /* @__PURE__ */ jsxs("div", { className: "contents", children: [
|
|
13
|
+
/* @__PURE__ */ jsx("span", { children: shape }),
|
|
14
|
+
STATES.map((state) => /* @__PURE__ */ jsx("span", { className: "flex h-12 items-end", children: /* @__PURE__ */ jsx(MapPin, { shape, state, size: 26 }) }, state))
|
|
15
|
+
] }, shape))
|
|
16
|
+
] });
|
|
17
|
+
}
|
|
18
|
+
export {
|
|
19
|
+
MapPins as default
|
|
20
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { MapPin, type MapPinShape, type MapPinState } from "@krizaka/ui/map/pin";
|
|
2
|
+
|
|
3
|
+
const SHAPES: MapPinShape[] = ["drop", "disc", "tag"];
|
|
4
|
+
const STATES: MapPinState[] = ["default", "selected", "visited", "closed"];
|
|
5
|
+
|
|
6
|
+
// The pins of a map, in their three shapes and four states: the state is said by shape too (hollow = visited,
|
|
7
|
+
// dashed = closed, larger = selected), so it never rests on colour alone.
|
|
8
|
+
export default function MapPins() {
|
|
9
|
+
return (
|
|
10
|
+
<div className="grid w-full max-w-xl grid-cols-[auto_repeat(4,1fr)] items-end gap-x-6 gap-y-5 rounded-xl border border-border-subtle bg-surface-1 p-5 text-xs text-fg-secondary">
|
|
11
|
+
<span />
|
|
12
|
+
{STATES.map((state) => (
|
|
13
|
+
<span key={state}>{state}</span>
|
|
14
|
+
))}
|
|
15
|
+
{SHAPES.map((shape) => (
|
|
16
|
+
<div key={shape} className="contents">
|
|
17
|
+
<span>{shape}</span>
|
|
18
|
+
{STATES.map((state) => (
|
|
19
|
+
<span key={state} className="flex h-12 items-end">
|
|
20
|
+
<MapPin shape={shape} state={state} size={26} />
|
|
21
|
+
</span>
|
|
22
|
+
))}
|
|
23
|
+
</div>
|
|
24
|
+
))}
|
|
25
|
+
</div>
|
|
26
|
+
);
|
|
27
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
// registry/examples/map/place-sheet.tsx
|
|
4
|
+
import { Button } from "@krizaka/ui/button";
|
|
5
|
+
import { StaticMap } from "@krizaka/ui/map";
|
|
6
|
+
import { MapInfoCard, RouteCard } from "@krizaka/ui/map/cards";
|
|
7
|
+
import { MapSheet } from "@krizaka/ui/map/sheet";
|
|
8
|
+
import * as React from "react";
|
|
9
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
10
|
+
var SHOP = [-73.5673, 45.5017];
|
|
11
|
+
var ME = [-73.58, 45.51];
|
|
12
|
+
function MapPlaceSheet() {
|
|
13
|
+
const [snap, setSnap] = React.useState("half");
|
|
14
|
+
return /* @__PURE__ */ jsxs("div", { className: "relative h-[34rem] w-full max-w-3xl overflow-hidden rounded-xl border border-border-subtle", children: [
|
|
15
|
+
/* @__PURE__ */ jsx(StaticMap, { label: "Atelier Rose, Montr\xE9al", center: [-73.575, 45.505], zoom: 13, places: [{ position: SHOP, label: "Atelier Rose" }] }),
|
|
16
|
+
/* @__PURE__ */ jsx(MapSheet, { label: "Atelier Rose", handleLabel: "Resize the panel", snap, onSnapChange: setSnap, children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-5", children: [
|
|
17
|
+
/* @__PURE__ */ jsx(MapInfoCard, { title: "Atelier Rose", meta: "Hair salon \xB7 1.4 km", status: "Open until 18:00", action: /* @__PURE__ */ jsx(Button, { size: "sm", children: "See the shop" }) }),
|
|
18
|
+
/* @__PURE__ */ jsx(
|
|
19
|
+
RouteCard,
|
|
20
|
+
{
|
|
21
|
+
destination: "Directions to Atelier Rose",
|
|
22
|
+
position: SHOP,
|
|
23
|
+
origin: ME,
|
|
24
|
+
directionsLabel: "Open in",
|
|
25
|
+
appLabels: { apple: "Apple Maps", google: "Google Maps", osm: "OpenStreetMap", waze: "Waze", transit: "Transit" },
|
|
26
|
+
times: [{ label: "On foot", value: "18 min" }, { label: "By bike", value: "7 min" }]
|
|
27
|
+
}
|
|
28
|
+
)
|
|
29
|
+
] }) })
|
|
30
|
+
] });
|
|
31
|
+
}
|
|
32
|
+
export {
|
|
33
|
+
MapPlaceSheet as default
|
|
34
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import { Button } from "@krizaka/ui/button";
|
|
4
|
+
import { StaticMap } from "@krizaka/ui/map";
|
|
5
|
+
import { MapInfoCard, RouteCard } from "@krizaka/ui/map/cards";
|
|
6
|
+
import { MapSheet, type MapSheetSnap } from "@krizaka/ui/map/sheet";
|
|
7
|
+
import * as React from "react";
|
|
8
|
+
|
|
9
|
+
const SHOP = [-73.5673, 45.5017] as const;
|
|
10
|
+
const ME = [-73.58, 45.51] as const;
|
|
11
|
+
|
|
12
|
+
// A place on the map: the sheet rises over it WITHOUT blocking it (no scrim, no trap) — three snap points on a phone, a
|
|
13
|
+
// card at the side from md. The info card says what the place is (one action); the route card opens the person's own
|
|
14
|
+
// navigation app. The times are given by the host from a real source — here, demo values.
|
|
15
|
+
export default function MapPlaceSheet() {
|
|
16
|
+
const [snap, setSnap] = React.useState<MapSheetSnap>("half");
|
|
17
|
+
return (
|
|
18
|
+
<div className="relative h-[34rem] w-full max-w-3xl overflow-hidden rounded-xl border border-border-subtle">
|
|
19
|
+
<StaticMap label="Atelier Rose, Montréal" center={[-73.575, 45.505]} zoom={13} places={[{ position: SHOP, label: "Atelier Rose" }]} />
|
|
20
|
+
<MapSheet label="Atelier Rose" handleLabel="Resize the panel" snap={snap} onSnapChange={setSnap}>
|
|
21
|
+
<div className="flex flex-col gap-5">
|
|
22
|
+
<MapInfoCard title="Atelier Rose" meta="Hair salon · 1.4 km" status="Open until 18:00" action={<Button size="sm">See the shop</Button>} />
|
|
23
|
+
<RouteCard
|
|
24
|
+
destination="Directions to Atelier Rose"
|
|
25
|
+
position={SHOP}
|
|
26
|
+
origin={ME}
|
|
27
|
+
directionsLabel="Open in"
|
|
28
|
+
appLabels={{ apple: "Apple Maps", google: "Google Maps", osm: "OpenStreetMap", waze: "Waze", transit: "Transit" }}
|
|
29
|
+
times={[{ label: "On foot", value: "18 min" }, { label: "By bike", value: "7 min" }]}
|
|
30
|
+
/>
|
|
31
|
+
</div>
|
|
32
|
+
</MapSheet>
|
|
33
|
+
</div>
|
|
34
|
+
);
|
|
35
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
// registry/examples/wall/tidy.tsx
|
|
4
|
+
import { Wall } from "@krizaka/ui/wall";
|
|
5
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
6
|
+
var m = {
|
|
7
|
+
wallLabel: "From the shop",
|
|
8
|
+
photo: (alt, hue) => /* @__PURE__ */ jsxs("svg", { role: "img", "aria-label": alt, viewBox: "0 0 240 240", children: [
|
|
9
|
+
/* @__PURE__ */ jsx("rect", { width: "240", height: "240", fill: hue }),
|
|
10
|
+
/* @__PURE__ */ jsx("path", { d: "m0 240 100-190 55 110 35-45 50 125Z", fill: "var(--kz-accent)", opacity: ".8" })
|
|
11
|
+
] })
|
|
12
|
+
};
|
|
13
|
+
var items = [
|
|
14
|
+
{ id: "front", kind: "polaroid", z: 1, img: m.photo("The shop front", "var(--kz-accent-soft)"), caption: "Rue Saint-Denis, since 2019" },
|
|
15
|
+
{ id: "note", kind: "note", z: 2, text: "Open late on Fridays. Walk-ins welcome.", signature: "Rose", attachment: "pin" },
|
|
16
|
+
{ id: "chair", kind: "polaroid", z: 3, img: m.photo("The first chair", "var(--kz-surface-3)"), caption: "The first chair", attachment: "pin" },
|
|
17
|
+
{ id: "window", kind: "polaroid", z: 4, img: m.photo("The window", "var(--kz-surface-2)"), caption: "The window in May" },
|
|
18
|
+
{ id: "sign", kind: "sign", z: 5, logo: "Atelier Rose", variant: "enamel" },
|
|
19
|
+
{ id: "wash", kind: "polaroid", z: 6, img: m.photo("The wash basin", "var(--kz-accent-soft)"), caption: "The wash basin" },
|
|
20
|
+
{ id: "note2", kind: "note", z: 7, text: "Bring a photo of the cut you like.", signature: "Rose" }
|
|
21
|
+
];
|
|
22
|
+
function WallTidy() {
|
|
23
|
+
return /* @__PURE__ */ jsx(Wall, { "aria-label": m.wallLabel, layout: "tidy", texture: "plaster", items });
|
|
24
|
+
}
|
|
25
|
+
export {
|
|
26
|
+
WallTidy as default
|
|
27
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Wall, type WallItem } from "@krizaka/ui/wall";
|
|
2
|
+
|
|
3
|
+
const m = {
|
|
4
|
+
wallLabel: "From the shop",
|
|
5
|
+
photo: (alt: string, hue: string) => <svg role="img" aria-label={alt} viewBox="0 0 240 240"><rect width="240" height="240" fill={hue} /><path d="m0 240 100-190 55 110 35-45 50 125Z" fill="var(--kz-accent)" opacity=".8" /></svg>,
|
|
6
|
+
};
|
|
7
|
+
const items: WallItem[] = [
|
|
8
|
+
{ id: "front", kind: "polaroid", z: 1, img: m.photo("The shop front", "var(--kz-accent-soft)"), caption: "Rue Saint-Denis, since 2019" },
|
|
9
|
+
{ id: "note", kind: "note", z: 2, text: "Open late on Fridays. Walk-ins welcome.", signature: "Rose", attachment: "pin" },
|
|
10
|
+
{ id: "chair", kind: "polaroid", z: 3, img: m.photo("The first chair", "var(--kz-surface-3)"), caption: "The first chair", attachment: "pin" },
|
|
11
|
+
{ id: "window", kind: "polaroid", z: 4, img: m.photo("The window", "var(--kz-surface-2)"), caption: "The window in May" },
|
|
12
|
+
{ id: "sign", kind: "sign", z: 5, logo: "Atelier Rose", variant: "enamel" },
|
|
13
|
+
{ id: "wash", kind: "polaroid", z: 6, img: m.photo("The wash basin", "var(--kz-accent-soft)"), caption: "The wash basin" },
|
|
14
|
+
{ id: "note2", kind: "note", z: 7, text: "Bring a photo of the cut you like.", signature: "Rose" },
|
|
15
|
+
];
|
|
16
|
+
|
|
17
|
+
export default function WallTidy() {
|
|
18
|
+
return <Wall aria-label={m.wallLabel} layout="tidy" texture="plaster" items={items} />;
|
|
19
|
+
}
|
package/registry/index.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@krizaka/ui",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.77.0",
|
|
4
4
|
"templatePurposes": {
|
|
5
5
|
"convince": {
|
|
6
6
|
"title": "Convince",
|
|
@@ -1004,7 +1004,7 @@
|
|
|
1004
1004
|
"native": 0
|
|
1005
1005
|
},
|
|
1006
1006
|
"dependencies": [
|
|
1007
|
-
"@krizaka/tokens@^3.
|
|
1007
|
+
"@krizaka/tokens@^3.77.0"
|
|
1008
1008
|
],
|
|
1009
1009
|
"registryDependencies": [
|
|
1010
1010
|
"account-menu",
|
|
@@ -3973,11 +3973,11 @@
|
|
|
3973
3973
|
}
|
|
3974
3974
|
},
|
|
3975
3975
|
"examples": {
|
|
3976
|
-
"web":
|
|
3976
|
+
"web": 7,
|
|
3977
3977
|
"native": 2
|
|
3978
3978
|
},
|
|
3979
3979
|
"dependencies": [
|
|
3980
|
-
"@krizaka/tokens@^3.
|
|
3980
|
+
"@krizaka/tokens@^3.77.0",
|
|
3981
3981
|
"@protomaps/basemaps@5.7.2",
|
|
3982
3982
|
"tailwind-variants@^3.3.1"
|
|
3983
3983
|
],
|
|
@@ -4385,7 +4385,7 @@
|
|
|
4385
4385
|
"native": 0
|
|
4386
4386
|
},
|
|
4387
4387
|
"dependencies": [
|
|
4388
|
-
"@krizaka/tokens@^3.
|
|
4388
|
+
"@krizaka/tokens@^3.77.0",
|
|
4389
4389
|
"radix-ui@^1.8.1",
|
|
4390
4390
|
"tailwind-variants@^3.3.1"
|
|
4391
4391
|
],
|
|
@@ -5253,7 +5253,7 @@
|
|
|
5253
5253
|
"native": 0
|
|
5254
5254
|
},
|
|
5255
5255
|
"dependencies": [
|
|
5256
|
-
"@krizaka/tokens@^3.
|
|
5256
|
+
"@krizaka/tokens@^3.77.0",
|
|
5257
5257
|
"radix-ui@^1.8.1",
|
|
5258
5258
|
"tailwind-variants@^3.3.1"
|
|
5259
5259
|
],
|
|
@@ -5700,7 +5700,7 @@
|
|
|
5700
5700
|
"native": 0
|
|
5701
5701
|
},
|
|
5702
5702
|
"dependencies": [
|
|
5703
|
-
"@krizaka/tokens@^3.
|
|
5703
|
+
"@krizaka/tokens@^3.77.0",
|
|
5704
5704
|
"zod@^4.6.7"
|
|
5705
5705
|
],
|
|
5706
5706
|
"registryDependencies": [
|
|
@@ -5920,7 +5920,7 @@
|
|
|
5920
5920
|
"native": 0
|
|
5921
5921
|
},
|
|
5922
5922
|
"dependencies": [
|
|
5923
|
-
"@krizaka/tokens@^3.
|
|
5923
|
+
"@krizaka/tokens@^3.77.0",
|
|
5924
5924
|
"radix-ui@^1.8.1",
|
|
5925
5925
|
"tailwind-variants@^3.3.1"
|
|
5926
5926
|
],
|
|
@@ -7374,7 +7374,7 @@
|
|
|
7374
7374
|
}
|
|
7375
7375
|
},
|
|
7376
7376
|
"examples": {
|
|
7377
|
-
"web":
|
|
7377
|
+
"web": 10,
|
|
7378
7378
|
"native": 0
|
|
7379
7379
|
},
|
|
7380
7380
|
"dependencies": [],
|