diff --git a/CHANGELOG.md b/CHANGELOG.md
index aa672a9..452f7af 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,16 @@
All notable Doc2FAQ changes are recorded here. Version numbers follow semantic versioning; entries describe shipped source functionality and do not imply an external AI service.
+## [Unreleased]
+
+### Added
+- Export preview, copy, and downloads can include only approved FAQs, with a count of the selected entries.
+- The browser demo shows original PDF page numbers on FAQ sources and links to those pages while the PDF is loaded.
+
+### Changed
+- Browser drafting suggests more specific questions for common handbook, product guide, and policy sections. Generated suggestions retain their original section titles and keep explicit Q&A separate.
+- Similar-question flags preserve differences in word order and qualifying terms such as roles and negation.
+
## [0.5.0] — 2026-11-08
### Added
diff --git a/README.md b/README.md
index 683c4e0..750de24 100644
--- a/README.md
+++ b/README.md
@@ -8,6 +8,12 @@ Created by **Okan Tiktas** · [OKAN-SOFTWARE](https://github.com/OKAN-SOFTWARE).
> **Latest release: v0.5.0 — Source & Review.** Download the ready-to-run JAR, Windows ZIP, and checksum file from [GitHub Releases](https://github.com/OKAN-SOFTWARE/Doc2FAQ/releases/tag/v0.5.0).
+## In development for v0.6.0
+
+- **Approved-only exports:** choose **All FAQs** or **Approved only** for preview, copy, and downloads. The selection count updates as you review.
+- **Original PDF pages:** the development browser demo shows page numbers beside the extracted passage. Open the referenced page in a new tab while the original PDF is loaded.
+- **Draft quality:** browser suggestions use more specific phrasing for common sections and keep adjacent explicit Q&A separate. Similar-question flags compare normalized wording in order so differences in roles and qualifying terms stay visible.
+
## New in v0.5.0 — Source & Review
I redesigned Doc2FAQ with an illustrated homepage and a responsive FAQ workbench. Visit the [product homepage](https://okantiktas.com/projects/doc2faq/) for an overview, or try the [interactive browser demo](https://okantiktas.com/projects/doc2faq/demo/) to import documents, review FAQs, and export the results directly in your browser. The browser demo and downloadable Java application have different processing engines, so their FAQ suggestions may differ. See the [v0.5.0 changes](CHANGELOG.md#050--2026-11-08) and [design system](docs/DESIGN-SYSTEM.md) for details.
@@ -209,7 +215,7 @@ The preview heading and footer display the full project version from `pom.xml`.
6. Combine the question/answer search with the **All statuses**, **Needs review**, or **Approved** filter. Read the visible and review counts; use **Clear filters** to restore the list. Filters do not restrict saved projects, previews, or exports.
7. Reorder, remove, or add FAQs. Review similar questions, choose Keep both or merge, and use Undo immediately after a removal/merge if needed. Review status changes clear that undo history too.
8. Set the document title and use **Save work** to keep source, edits, order, references, duplicate decisions, and review status. **Open saved work** resumes a project. Optional autosave is off by default. New schema-2 project files require v0.5 or later; schema-1 files open with Needs review defaults.
-9. Choose **Markdown**, **JSON**, **HTML**, **PDF**, or **Word**, optionally include references, and inspect **Preview export**. Use **Copy** for text formats or **Download** for any format. All FAQs are included, even if filtered out. Any blank question or answer blocks export; approval is a review aid and is not required to export.
+9. Choose **Markdown**, **JSON**, **HTML**, **PDF**, or **Word**, optionally include references, and inspect **Preview export**. Use **Copy** for text formats or **Download** for any format. Choose **All FAQs** (default) or **Approved only**. Every selected FAQ needs a completed question and answer. Preview, copy, and download use the selected scope in draft order.
Example document for **Generate Mode**:
@@ -321,7 +327,7 @@ GitHub Actions automatically runs the Java and JavaScript checks on pushes and p
| `'mvn' is not recognized` | Run the temporary PATH command above, reopen CMD after permanent PATH setup, or use the full `mvn.cmd` path |
| Maven selects the wrong Java version | Check `mvn -version` and set `JAVA_HOME` to your JDK 21 installation |
| `No complete Q&A pairs found` | Switch from **Extract Mode** to **Generate Mode**, or format existing pairs as Markdown question headings |
-| No FAQs visible after filtering | Use **Clear filters**; the draft and its export still include every FAQ |
+| No FAQs visible after filtering | Use **Clear filters** to show the full draft. Check **Export scope** for the current export selection |
| Approval changes after editing | Expected: edited or merged content returns to Needs review |
| Saved project will not open in v0.4 | Schema-2 projects need v0.5 or later; keep the original schema-1 file when using older releases |
| Browser document tools fail to load | Allow the version-pinned jsDelivr libraries and retry; document content remains on your device |
diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md
index 9436c31..65a53e4 100644
--- a/docs/USER-GUIDE.md
+++ b/docs/USER-GUIDE.md
@@ -1,6 +1,6 @@
# Doc2FAQ — Source & Review guide
-This guide describes the `0.5.0` release-candidate source build, which has not yet been published. The latest published v0.4.0 download does not include the new source viewer or approval filters. See the [README](../README.md) for installation and [browser-demo comparison](WEB-DEMO.md) for the website's supported features.
+This guide describes the current development build. See the [README](../README.md) for installation and the [browser-demo comparison](WEB-DEMO.md) for differences between the website and Java app.
## Create a draft
@@ -13,7 +13,7 @@ Changing source text or mode clears the current draft. Save work before replacin
## Compare an answer with its source
-Select **View source beside answer** on an FAQ. The read-only viewer highlights every matching original passage, including multiple references retained after merging. On desktop it sits beside the editor; on narrow screens it stacks above it. References use extracted-text line numbers, not original PDF pages. **Show source** expands a specific excerpt within the FAQ card.
+Select **View source beside answer** on an FAQ. The read-only viewer highlights every matching original passage, including multiple references retained after merging. On desktop it sits beside the editor; on narrow screens it stacks above it. The Java app shows extracted-text line numbers. In the browser demo, select **Open PDF page** to jump to the original page in your browser’s PDF viewer. Saved projects keep the page numbers and extracted text. The page links are available while the original PDF is loaded. **Show source** expands a specific excerpt within the FAQ card.
Editing a question or answer preserves the source viewer's content and scroll position. Explicitly opening a source selection scrolls to its first highlight. Selecting another FAQ updates the highlighted passages. Manually added FAQs have no automatic source reference; the viewer says so. An edited badge means the current text differs from its original draft; approving does not remove that history.
@@ -28,7 +28,7 @@ Editing a question or answer preserves the source viewer's content and scroll po
| Undo a removal or merge | Restores the previous snapshot, including status |
| Open a schema-1 project | Needs review unless a recognized status was explicitly present |
-Approval is a manual review decision. It does not automatically verify accuracy or prevent export of other complete FAQs.
+Review the answer against its source before approving it. Choose **Approved only** when you want to share only the FAQs you approved.
## Search and organize
@@ -36,7 +36,7 @@ Search matches questions and answers without case sensitivity. Combine it with A
Editing a matching FAQ can make it disappear from the filtered list; the edit remains in the draft. Search and filters never remove data, restrict exports, or limit saved projects.
-Similar-question warnings use word overlap. Keep both retains distinct passages; Merge into this FAQ combines answers and source references. Review the merged result. Undo removal / merge restores the previous snapshot until another edit, addition, reorder, review choice, or approval-status change clears that history.
+Similar-question warnings compare normalized wording and word order, ignoring differences such as punctuation and common articles. Keep both retains distinct passages; Merge into this FAQ combines answers and source references. Review the merged result. Undo removal / merge restores the previous snapshot until another edit, addition, reorder, review choice, or approval-status change clears that history.
## Save and reopen
@@ -48,6 +48,6 @@ Optional browser autosave is off by default. Enabling it stores source and draft
## Export
-Set the document title and download filename, choose a format, optionally include source references, and preview the result. All FAQs are exported in draft order, regardless of search or status filters. Every entry must have a nonblank question and answer; approval is optional.
+Set the document title and download filename, choose a format, optionally include source references, and preview the result. Choose **All FAQs** (default) or **Approved only** under **Export scope**. The selected count updates as you review. Preview, copy, and download use that selection in draft order, independent of search and review filters. Each selected entry needs a complete question and answer. **Save work** always keeps the whole draft.
Markdown, JSON, and standalone HTML can be copied or downloaded. In the Java app, PDF and Word downloads use the local Java server. On the website demo, document import and PDF/Word generation run in the browser. Both apply their own pagination. The browser demo requires an initial download of version-pinned document libraries; your document content is not uploaded. Browser PDF fonts have Latin character coverage; Word preserves Unicode. Unsupported PDF glyphs produce an error suggesting Word. Finished FAQ JSON is an export, not a saved project: use Save work to preserve review state and resume editing later.
diff --git a/docs/WEB-DEMO.md b/docs/WEB-DEMO.md
index f7878fc..a48be1d 100644
--- a/docs/WEB-DEMO.md
+++ b/docs/WEB-DEMO.md
@@ -10,13 +10,15 @@ The public-facing homepage route is `https://okantiktas.com/projects/doc2faq/`.
| Extract explicit Q&A | Simplified JavaScript rules | Java extraction service |
| Suggest questions from sections | Simplified Markdown-heading rules | Java generation service, with broader heuristics |
| Source viewer, editing, reorder, duplicate review | Shared frontend | Yes |
+| Original PDF page references | Page numbers and links to the currently loaded PDF | Extracted-text lines |
+| Export scope | All FAQs or Approved only | All FAQs or Approved only |
| Approval status, search, filters | Shared frontend | Yes |
| Saved projects and optional browser autosave | Yes; schemas 1/2 read, schema 2 saved | Yes |
| Markdown/JSON/HTML export | Browser downloads | Browser downloads |
| PDF/DOCX import and export | Yes; browser PDF.js / Word XML extraction and PDF-LIB / docx exports | Yes; PDFBox / Apache POI |
| OCR, external AI, accounts/billing | No | Not implemented |
-PDF and Word files are processed on the visitor's device. PDF import is limited to 5 MB, 50 pages and 50,000 extracted characters; DOCX import is limited to 5 MB, 50,000 extracted characters, 1,000 archive entries and an 8 MB expanded main XML part. Legacy `.doc`, password-protected PDFs and image-only/scanned PDFs are not supported. Word extraction reads main-document paragraphs and tables, mapping standard Heading 1–6 styles to Markdown section headings (levels 2–6) so the generator treats Heading 1 as a section rather than a document title. Headers/footers, images and complex layouts may not be retained. Browser PDF export **embeds bundled DejaVu Sans regular/bold font subsets** for Turkish, extended Latin, IPA and many mathematical symbols. If a font still cannot display a character, the app recommends Word rather than silently dropping it. Word exports preserve Unicode. Both exports include every FAQ regardless of filters and optionally include source references.
+PDF and Word files are processed on the visitor's device. PDF import is limited to 5 MB, 50 pages and 50,000 extracted characters; DOCX import is limited to 5 MB, 50,000 extracted characters, 1,000 archive entries and an 8 MB expanded main XML part. Legacy `.doc`, password-protected PDFs and image-only/scanned PDFs are not supported. Word extraction reads main-document paragraphs and tables, mapping standard Heading 1–6 styles to Markdown section headings (levels 2–6) so the generator treats Heading 1 as a section rather than a document title. Headers/footers, images and complex layouts may not be retained. Browser PDF export **embeds bundled DejaVu Sans regular/bold font subsets** for Turkish, extended Latin, IPA and many mathematical symbols. If a font still cannot display a character, the app recommends Word rather than silently dropping it. Word exports preserve Unicode. Both exports follow **Export scope** and can include extracted-text source references. During review, **View source beside answer** shows links to the original PDF pages in a browser PDF viewer. Saved work keeps page numbers but stores only extracted text, so reopened projects display page numbers without clickable links.
The demo demonstrates the review workflow; it is not a hosted Java backend and does not claim identical generation results. Its development features may be newer than the latest published JAR. No pasted text is sent to an FAQ server. Optional autosave and downloaded project files contain source text; clear saved data on shared devices. Normal website hosting still serves the page and assets. The document adapter lazily loads version-pinned PDF.js, PDF-LIB, fontkit, JSZip and docx code from jsDelivr. DejaVu fonts are **served by the same website**, not downloaded from a third-party font service. An internet connection is needed on first use; load failures leave the workspace available for retry. See [third-party libraries](../web-demo/THIRD-PARTY.md).
@@ -43,8 +45,8 @@ The portfolio is hosted through its existing GitHub-main → Hostinger deploymen
- Examples and pasted TXT/Markdown work in both modes; text source references match exactly.
- Source highlights remain stable while typing, including on mobile.
- Approvals persist after save/open and optional autosave/reload; edits/merges reset approval.
-- Search and status filters combine; downloads and previews retain all FAQs.
-- Import real PDF and Word files, then export and open PDF and Word downloads. Check page breaks, references, long tokens, Unicode Word text, and PDF glyph errors.
+- Combine search and status filters, then switch export scope. Verify that previews and downloads use the selected scope and preserve draft order.
+- Import real PDF and Word files. Follow an original PDF page link, then export and open PDF and Word downloads. Check page breaks, references, long tokens, Unicode Word text, and PDF glyph errors.
- Invalid, oversized, protected, scanned and excessive-page files are rejected without replacing the current workspace. Clear or edit during processing to confirm late results/downloads are discarded.
- No document content becomes executable HTML; no FAQ requests go to a server.
- Check desktop, narrow-screen controls, keyboard navigation, and reduced-motion behavior.
diff --git a/scripts/build-web-demo.mjs b/scripts/build-web-demo.mjs
index 79bab07..d408ba6 100644
--- a/scripts/build-web-demo.mjs
+++ b/scripts/build-web-demo.mjs
@@ -22,11 +22,10 @@ html = html.replaceAll('@project.version@', version)
.replace('LOCAL JAVA WORKSPACE', 'THE INTERACTIVE PLAYGROUND')
.replace('WELCOME TO DOC2FAQ /', 'WELCOME TO THE DOC2FAQ PLAYGROUND /')
.replace('PDF/DOCX files are processed by this server in memory; no documents are permanently saved.', 'Demo text is processed in this browser. Load an example to get started.')
- .replace('Paste text or open .txt, .md, .pdf, or .docx (up to 5 MB for PDF/Word). Choose how to build your draft.', 'Paste text or open .txt, .md, .pdf, or .docx. PDF/Word files: up to 5 MB; PDFs: up to 50 pages. Documents are processed in your browser. Legacy .doc files and OCR are not supported.')
- .replace('Content preview. PDF and Word downloads apply their own page layout.', 'All FAQs are included, even when filtered. PDF and Word downloads apply their own pagination.');
+ .replace('Paste text or open .txt, .md, .pdf, or .docx (up to 5 MB for PDF/Word). Choose how to build your draft.', 'Paste text or open .txt, .md, .pdf, or .docx. PDF/Word files: up to 5 MB; PDFs: up to 50 pages. Documents are processed in your browser. Legacy .doc files and OCR are not supported.');
const noteStart = html.indexOf('
Good to know.'); const noteEnd = html.indexOf('
', noteStart) + 4; -html = html.slice(0, noteStart) + 'Browser demo. Text processing and text exports happen on your device. Nothing you paste is sent to an FAQ server. No AI is used. This simplified demo may produce different drafts from the full Java app. Source references use text lines, not PDF pages. Optional autosave stores source and drafts in this browser; use Clear saved data on shared devices. Saved projects contain the source. PDF and Word (.docx) import/export run in your browser. Scanned PDFs need OCR, which is not included. PDF export embeds bundled DejaVu Sans fonts for extended Unicode coverage; unsupported scripts may still require Word. Document libraries load from a CDN when needed; your document content is not uploaded.
' + html.slice(noteEnd); +html = html.slice(0, noteStart) + 'Browser demo. Text processing and text exports happen on your device. Nothing you paste is sent to an FAQ server. No AI is used. This simplified demo may produce different drafts from the full Java app. Source references use extracted-text lines. Imported PDFs also show original page numbers during review. Optional autosave stores source and drafts in this browser; use Clear saved data on shared devices. Saved projects contain the source. PDF and Word (.docx) import/export run in your browser. Scanned PDFs need OCR, which is not included. PDF export embeds bundled DejaVu Sans fonts for extended Unicode coverage; unsupported scripts may still require Word. Document libraries load from a CDN when needed; your document content is not uploaded.
' + html.slice(noteEnd); html = html.replace('Try the review workflow here. The latest downloadable release may have fewer features than this development demo. Compare demo and app ↗
\n" + escapeHtml(item.answer.trim()).replace(/\n/g, "
") + "
Search and filters change this view. Exports always include all FAQs.
+Search and review filters change the workspace view. Export scope controls what you share.
diff --git a/src/main/resources/static/project.js b/src/main/resources/static/project.js index 4267658..9be29a7 100644 --- a/src/main/resources/static/project.js +++ b/src/main/resources/static/project.js @@ -49,6 +49,22 @@ const downloadName = string(project.downloadName ?? defaultDownloadName(name), 180, "download filename"); if (!Array.isArray(project.items) || project.items.length > 30) fail("A project can contain at most 30 FAQs."); const sourceLines = lines(text); + const pdfPages = project.source.pdfPages ?? []; + if (!Array.isArray(pdfPages) || pdfPages.length > 50 || (pdfPages.length && !/\.pdf$/i.test(name))) { + fail("Invalid PDF page references."); + } + let previousPage = 0; + let previousEnd = 0; + const validatedPages = pdfPages.map((entry) => { + const {page, startLine, endLine} = entry ?? {}; + if (![page, startLine, endLine].every(Number.isInteger) || page <= previousPage || page > 50 || + startLine <= previousEnd || endLine < startLine || endLine > sourceLines.length) { + fail("Invalid PDF page references."); + } + previousPage = page; + previousEnd = endLine; + return {page, startLine, endLine}; + }); const ids = new Set(); let answerCharacters = 0; const items = project.items.map((raw) => { @@ -84,7 +100,7 @@ }); if (answerCharacters > 300000) fail("FAQ text must not exceed 300,000 characters."); for (const item of items) item.keptWith = item.keptWith.filter((key) => ids.has(key) && key !== item.id); - return {type: "doc2faq-project", schemaVersion: 2, title, downloadName, mode: project.mode, source: {text, name}, items}; + return {type: "doc2faq-project", schemaVersion: 2, title, downloadName, mode: project.mode, source: {text, name, ...(validatedPages.length ? {pdfPages: validatedPages} : {})}, items}; } function serialize(project) { const text = JSON.stringify(validateProject(project), null, 2) + "\n"; @@ -97,17 +113,13 @@ try { data = JSON.parse(text); } catch { fail("This file is not valid JSON."); } return validateProject(data); } - function words(question) { - return new Set(question.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}]+/gu) || []); + function questionKey(question) { + const words = question.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}]+/gu) || []; + return words.filter((word) => !["a", "an", "the", "please"].includes(word)).join(" "); } function similar(a, b) { - const first = words(a), second = words(b); - if (!first.size || !second.size) return false; - for (const party of ["client", "provider"]) { - if (first.has(party) !== second.has(party)) return false; - } - const shared = [...first].filter((word) => second.has(word)).length; - return shared / (first.size + second.size - shared) >= 0.7; + const first = questionKey(a); + return first.length > 0 && first === questionKey(b); } function related(items, item) { return items.filter((other) => other !== item && !item.keptWith.includes(other.id) && diff --git a/src/main/resources/static/styles.css b/src/main/resources/static/styles.css index 9d69805..21e7b80 100644 --- a/src/main/resources/static/styles.css +++ b/src/main/resources/static/styles.css @@ -94,6 +94,7 @@ body::before{content:"";position:fixed;inset:0;pointer-events:none;z-index:0;bac .review-status-select{margin:4px 10px 12px 0} .source-viewer{margin-top:18px;border:1px solid #426b78;border-radius:10px;padding:14px;position:sticky;top:16px;background:#101f30} .source-viewer-heading{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap} +.source-pdf-pages:not(:empty){display:flex;flex-wrap:wrap;gap:8px;margin-bottom:10px} .source-viewer-heading h4{margin:0;font-size:15px} .source-viewer-content{max-height:440px;overflow:auto;font:12px/1.7 ui-monospace,monospace;background:#0c1829;border-radius:6px;padding:10px 0} .source-line{display:flex;gap:12px;padding:2px 10px;white-space:pre-wrap;overflow-wrap:anywhere} diff --git a/src/test/js/app-state.test.cjs b/src/test/js/app-state.test.cjs index 512a9d9..5369fa3 100644 --- a/src/test/js/app-state.test.cjs +++ b/src/test/js/app-state.test.cjs @@ -8,11 +8,12 @@ const script = readFileSync(path.resolve(__dirname, "../../main/resources/static function harness(saved = new Map(), blocked = false, fetcher = null, confirmer = () => true) { const elements = new Map(); + const revoked = []; function node(tag = "") { return {tag, value: "", checked: false, disabled: false, children: [], handlers: {}, textContent: "", addEventListener(name, fn) { this.handlers[name] = fn; }, append(...values) { this.children.push(...values); }, replaceChildren(...values) { this.children = values; }, - focus() {}, querySelector() { return null; }}; + focus() {}, querySelector() { return null; }, showModal() {}, click() {}, remove() {}}; } function element(id) { if (!elements.has(id)) elements.set(id, node(id)); @@ -20,17 +21,19 @@ function harness(saved = new Map(), blocked = false, fetcher = null, confirmer = } element("draft-mode").value = "extract"; element("export-format").value = "markdown"; + element("export-scope").value = "all"; const storage = { getItem(key) { if (blocked) throw new Error("Storage blocked"); return saved.get(key) ?? null; }, setItem(key, value) { if (blocked) throw new Error("Storage blocked"); saved.set(key, value); }, removeItem(key) { if (blocked) throw new Error("Storage blocked"); saved.delete(key); } }; - const context = {Doc2FaqProject: tools, document: {getElementById: element, createElement: node}, + const context = {Doc2FaqProject: tools, document: {getElementById: element, createElement: node, body: node("body")}, + URL: {createObjectURL: () => "blob:doc2faq-test", revokeObjectURL: (url) => revoked.push(url)}, FormData: class { append() {} }, localStorage: storage, setTimeout(fn) { fn(); return 1; }, clearTimeout() {}, confirm: confirmer, fetch: fetcher || (async () => ({ok: true, json: async () => ({items: [{question: "Where is support?", answer: "Ask the team.", source: {section: "Support", startLine: 1, endLine: 2, excerpt: "Q: Where is support?\nA: Ask the team."}}]})}))}; vm.runInNewContext(script, context); - return {element, saved}; + return {element, saved, revoked}; } async function makeDraft(app) { @@ -340,3 +343,61 @@ test("editing FAQs preserves source viewer nodes and scroll; only explicit selec app.element("close-source-btn").handlers.click(); assert.equal(content.children.length, 0); }); + +test("approved-only export uses the same entries for preview and both binary formats", async () => { + const payloads = []; + const app = harness(new Map(), false, async (url, options) => { + if (url.includes("/export/")) { + payloads.push(JSON.parse(options.body)); + return {ok: true, blob: async () => ({})}; + } + return {ok: true, json: async () => ({items: [{question: "Approved question?", answer: "Complete answer."}]})}; + }); + await makeDraft(app); + const scope = app.element("export-scope"); + scope.value = "approved"; scope.handlers.change(); + assert.equal(app.element("preview-btn").disabled, true); + assert.match(app.element("export-count").textContent, /0 FAQs selected/); + const review = descendants(app.element("results")).find(node => node.className === "review-status-select"); + review.value = "approved"; review.handlers.change(); + app.element("add-item-btn").handlers.click(); + app.element("review-filter").value = "needs-review"; app.element("review-filter").handlers.change(); + assert.match(app.element("export-count").textContent, /1 FAQ selected/); + app.element("preview-btn").handlers.click(); + assert.deepEqual(app.element("preview-content").children.map(node => node.textContent), + ["FAQ draft", "Approved question?", "Complete answer."]); + for (const format of ["pdf", "docx"]) { + app.element("export-format").value = format; + await app.element("download-btn").handlers.click(); + } + assert.deepEqual(payloads.map(({items}) => items.map(({question}) => question)), [ + ["Approved question?"], ["Approved question?"] + ]); + scope.value = "all"; scope.handlers.change(); + assert.equal(app.element("download-btn").disabled, true); +}); + +test("browser PDF page links use original page numbers and release the file when source changes", async () => { + const pdfPages = [{page: 3, startLine: 1, endLine: 2}]; + const text = "Q: What?\nA: This."; + const app = harness(new Map(), false, async url => ({ok: true, json: async () => + url.includes("/documents/") ? {text, pdfPages} : {items: [{question: "What?", answer: "This.", + source: {section: "What?", startLine: 1, endLine: 2, excerpt: text}}]}})); + const input = app.element("file-input"); + input.files = [{name: "guide.pdf", size: 100, slice() { return {}; }}]; + await input.handlers.change({target: input}); + await app.element("generate-btn").handlers.click(); + const view = descendants(app.element("results")).find(node => node.textContent === "View source beside answer"); + view.handlers.click(); + const [link] = app.element("source-pdf-pages").children; + assert.equal(link.href, "blob:doc2faq-test#page=3"); + app.element("autosave-toggle").checked = true; + app.element("autosave-toggle").handlers.change(); + const restored = harness(app.saved); + descendants(restored.element("results")).find(node => node.textContent === "View source beside answer").handlers.click(); + assert.match(restored.element("source-viewer-note").textContent, /PDF page 3/); + assert.equal(restored.element("source-pdf-pages").children.length, 0); + app.element("source-text").handlers.input(); + assert.deepEqual(app.revoked, ["blob:doc2faq-test"]); + assert.equal(app.element("source-pdf-pages").children.length, 0); +}); diff --git a/src/test/js/app-ui.test.cjs b/src/test/js/app-ui.test.cjs index 066885f..6b35e4f 100644 --- a/src/test/js/app-ui.test.cjs +++ b/src/test/js/app-ui.test.cjs @@ -19,7 +19,8 @@ test("PDF and Word are the first two export choices, with PDF selected by defaul }); // This app has no frontend dependencies. Test the actual export functions with tiny DOM stubs. -const stub = () => ({value: "extract", addEventListener() {}}); +const scope = {value: "all", addEventListener() {}}; +const stub = (id) => id === "export-scope" ? scope : {value: "extract", addEventListener() {}}; const context = {Doc2FaqProject: require("../../main/resources/static/project.js"), document: {getElementById: stub}}; const withoutBoot = source.replace(/updateModeText\(\);\s*updateCount\(\);\s*render\(\);\s*$/, ""); vm.runInNewContext(withoutBoot + @@ -60,3 +61,21 @@ test("Selected export format controls output and extension", () => { assert.equal(item.ext, "md"); assert.match(item.text, /## What\?/); }); + +test("all text export formats omit unapproved entries in approved-only scope", () => { + app.setItems([ + {question: "Ready?", answer: "Yes.", reviewStatus: "approved"}, + {question: "Should this stay private?", answer: "", reviewStatus: "needs-review"} + ]); + scope.value = "approved"; + try { + assert.equal(app.validDraft(), true); + for (const exportText of [app.markdown(), app.html(), app.json()]) { + assert.match(exportText, /Ready\?/); + assert.doesNotMatch(exportText, /stay private/); + } + } finally { + scope.value = "all"; + } + assert.equal(app.validDraft(), false); +}); diff --git a/src/test/js/browser-documents.test.cjs b/src/test/js/browser-documents.test.cjs index 8878a9d..78d3d7c 100644 --- a/src/test/js/browser-documents.test.cjs +++ b/src/test/js/browser-documents.test.cjs @@ -107,3 +107,22 @@ test('contiguous PDF fragments keep words intact while positioned word gaps get const pdfjs={getDocument(){return {promise:Promise.resolve({numPages:1,getPage:async()=>({getTextContent:async()=>({items:fragments}),cleanup(){}})}),destroy:async()=>{}};}}; assert.equal(await tools.extractPdf(new TextEncoder().encode('%PDF-1.7'),pdfjs),'Doc2FAQ works well'); }); + +test('PDF page ranges preserve original numbering around blank pages', async () => { + const pages = [['Title', 'First answer'], [], ['Second answer']]; + const pdfjs = {getDocument: () => ({ + promise: Promise.resolve({ + numPages: pages.length, + getPage: async page => ({ + getTextContent: async () => ({items: pages[page - 1].map(str => ({str, hasEOL: true}))}), + cleanup() {} + }) + }), + destroy: async () => {} + })}; + const result = await tools.extractPdfWithPages(new TextEncoder().encode('%PDF-1.7'), pdfjs); + assert.deepEqual(result, { + text: 'Title\nFirst answer\n\nSecond answer', + pdfPages: [{page: 1, startLine: 1, endLine: 2}, {page: 3, startLine: 4, endLine: 4}] + }); +}); diff --git a/src/test/js/demo.test.cjs b/src/test/js/demo.test.cjs index 563a0b3..758aac0 100644 --- a/src/test/js/demo.test.cjs +++ b/src/test/js/demo.test.cjs @@ -53,3 +53,24 @@ test('unrecognized headings use string fallback even when named like Object prop assert.equal(result.items[2].question, 'What should I know about toString?'); assert.equal(result.items[3].question, 'What services are included?'); }); + +test('handbook, product guide and policy suggestions keep exact sections and distinct answers', () => { + const examples = [ + ['# Handbook\n## Paid Time Off\nSubmit PTO in the portal.\nQ: Who approves requests?\nA: Your manager.', + [{question: 'Who approves requests?', answer: 'Your manager.', section: 'Who approves requests?'}, + {question: 'How does paid time off work?', answer: 'Submit PTO in the portal.', section: 'Paid Time Off'}]], + ['# Product guide\n## System Requirements\nUse Java 21.\n## Installation\nOpen the installer.', + [{question: 'What are the system requirements?', answer: 'Use Java 21.', section: 'System Requirements'}, + {question: 'How do I install the product?', answer: 'Open the installer.', section: 'Installation'}]], + ['# Policy\n## Eligibility\nEmployees are eligible.\n## Eligibility\nContractors need approval.', + [{question: 'Who is eligible?', answer: 'Employees are eligible.', section: 'Eligibility'}, + {question: 'Who is eligible?', answer: 'Contractors need approval.', section: 'Eligibility'}]] + ]; + for (const [text, expected] of examples) { + const items = draft(text, 'generate').items; + assert.deepEqual(items.map(({question, answer, source}) => ({question, answer, section: source.section})), expected); + for (const {source} of items) { + assert.equal(source.excerpt, text.split('\n').slice(source.startLine - 1, source.endLine).join('\n')); + } + } +}); diff --git a/src/test/js/project.test.cjs b/src/test/js/project.test.cjs index 42e2e5f..44fa256 100644 --- a/src/test/js/project.test.cjs +++ b/src/test/js/project.test.cjs @@ -54,6 +54,10 @@ test("similarity flags repeated questions but distinguishes client and provider assert.equal(project.similar("What responsibilities does the client have?", "What responsibilities does the provider have?"), false); assert.equal(project.similar("What services are included?", "When does the agreement end?"), false); assert.equal(project.similar("", "?"), false); + assert.equal(project.similar("What is the eligibility rule?", "What is eligibility rule?"), true); + assert.equal(project.similar("Who can approve the reimbursement request?", "Who cannot approve the reimbursement request?"), false); + assert.equal(project.similar("Can managers approve contractors for the policy?", "Can contractors approve managers for the policy?"), false); + assert.equal(project.similar("What is the approval deadline for employees?", "What is the approval deadline for contractors?"), false); // Suggestions only: neither party's answer is automatically removed. const data = fixture(); data.items[1].question = data.items[0].question; assert.equal(project.related(data.items, data.items[0]).length, 1); diff --git a/web-demo/documents.js b/web-demo/documents.js index 4741564..b0fa4a8 100644 --- a/web-demo/documents.js +++ b/web-demo/documents.js @@ -44,7 +44,7 @@ if (!text.trim()) throw new Error('No readable text found. Scanned/image-only files need OCR, which is not included.'); return text; } - async function extractPdf(bytes, pdfjs) { + async function extractPdfWithPages(bytes, pdfjs) { if (new TextDecoder().decode(bytes.subarray(0, 5)) !== '%PDF-') throw new Error('This file is not a valid PDF.'); const task = pdfjs.getDocument({data: bytes, isEvalSupported: false, stopAtErrors: true}); let doc; @@ -52,6 +52,8 @@ doc = await task.promise; if (doc.numPages > 50) throw new Error('PDF files must not exceed 50 pages.'); let text = ''; + let nextLine = 1; + const pdfPages = []; for (let i = 1; i <= doc.numPages; i++) { const page = await doc.getPage(i), content = await page.getTextContent(); let line = '', pageText = '', lastY = null, previous = null; @@ -75,10 +77,16 @@ if (item.hasEOL) { pageText += line.trim() + '\n'; line = ''; lastY = null; previous = null; } if (text.length + pageText.length + line.length > MAX_TEXT) throw new Error('Extracted text exceeds 50,000 characters.'); } - text += pageText + line.trim() + (i < doc.numPages ? '\n\n' : ''); + pageText = (pageText + line).trim(); + if (pageText) { + const lineCount = pageText.split(/\r\n|[\n\r\v\f\u0085\u2028\u2029]/).length; + pdfPages.push({page: i, startLine: nextLine, endLine: nextLine + lineCount - 1}); + text += (text ? '\n\n' : '') + pageText; + nextLine += lineCount + 1; + } page.cleanup(); } - return checkedText(text.trim()); + return {text: checkedText(text), pdfPages}; } catch (error) { if (error.name === 'PasswordException') throw new Error('Password-protected PDFs are not supported. Use an unlocked copy.'); throw error; @@ -260,19 +268,22 @@ footers: {default: new Footer({children: [new Paragraph({alignment: AlignmentType.CENTER, children: [new TextRun({children: [PageNumber.CURRENT]})]})]})}, children}]}); return Packer.toBlob(doc); } + async function extractPdf(bytes, pdfjs) { + return (await extractPdfWithPages(bytes, pdfjs)).text; + } async function request(url, options) { try { if (url === '/api/documents/extract') { const file = options.body.get('file'); validateInput(file); const bytes = new Uint8Array(await file.arrayBuffer()); - let text; + let data; if (/\.pdf$/i.test(file.name)) { let pdfjs; try { pdfjs = await import(libraries.pdf); } catch { throw new Error('PDF tools could not load. Check your connection and try again.'); } pdfjs.GlobalWorkerOptions.workerSrc = libraries.worker; - text = await extractPdf(bytes, pdfjs); - } else text = await extractDocx(bytes, await loadScript(libraries.zip, 'JSZip')); - return {ok: true, json: async () => ({text})}; + data = await extractPdfWithPages(bytes, pdfjs); + } else data = {text: await extractDocx(bytes, await loadScript(libraries.zip, 'JSZip'))}; + return {ok: true, json: async () => data}; } if (url === '/api/faqs/export/pdf' || url === '/api/faqs/export/docx') { const data = JSON.parse(options.body); validateExport(data); @@ -288,7 +299,7 @@ throw new Error('Unsupported document operation.'); } catch (error) { return {ok: false, json: async () => ({message: error.message || 'Could not process this document.'})}; } } - const api = {request, validateInput, checkedText, validateZip, boundedEntry, headingPrefix, wordXmlText, extractDocx, extractPdf, validateExport, references, wrap, checkPdfGlyphs, exportPdf, exportDocx, libraries}; + const api = {request, validateInput, checkedText, validateZip, boundedEntry, headingPrefix, wordXmlText, extractDocx, extractPdf, extractPdfWithPages, validateExport, references, wrap, checkPdfGlyphs, exportPdf, exportDocx, libraries}; if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.Doc2FaqDocuments = api; })(globalThis); diff --git a/web-demo/engine.js b/web-demo/engine.js index 62648a4..3f7474c 100644 --- a/web-demo/engine.js +++ b/web-demo/engine.js @@ -2,26 +2,45 @@ (function (root) { 'use strict'; const splitLines = text => text.split(/\r\n|[\n\r\v\f\u0085\u2028\u2029]/); + const questionPrefix = /^(?:#{1,6}\s+|(?:Q|Question):\s*)/i; + const headingPrefix = /^#{1,6}\s+/; + const phrasing = new Map([ + ['services', 'What services are included?'], + ['support', 'Where can I get support?'], + ['team responsibilities', 'What are the team responsibilities?'], + ['knowledge sharing', 'How is knowledge shared?'], + ['technical skills', 'Which skills and technologies are listed?'], + ['paid time off', 'How does paid time off work?'], + ['system requirements', 'What are the system requirements?'], + ['installation', 'How do I install the product?'], + ['eligibility', 'Who is eligible?'], + ['exceptions', 'What exceptions apply?'] + ]); + function questionFrom(line) { + const prefix = questionPrefix.exec(line); + const question = prefix && line.endsWith('?') ? line.slice(prefix[0].length).trim() : ''; + return question.length > 1 ? question : ''; + } function draft(content, mode) { if (typeof content !== 'string' || !content.trim()) throw new Error('Add document text first.'); if (content.length > 50000) throw new Error('Document text exceeds 50,000 characters.'); const lines = splitLines(content), items = [], seen = new Set(); - function add(question, start, end, answerLines) { + function add(question, start, end, answerLines, section = question) { const answer = answerLines.join(' ').trim(); question = question.slice(0, 500); const key = question.toLowerCase() + '\n' + answer.toLowerCase(); if (!answer || !question || seen.has(key) || items.length >= 30) return; seen.add(key); - items.push({question, answer, source: {section: question, startLine: start + 1, endLine: end + 1, + items.push({question, answer, source: {section, startLine: start + 1, endLine: end + 1, excerpt: lines.slice(start, end + 1).join('\n')}}); } let question = null, start = 0, end = 0, answer = []; for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); - const prefix = /^(?:#{1,6}\s+|(?:Q|Question):\s*)/i.exec(line); - if (prefix && line.endsWith('?') && line.slice(prefix[0].length).trim().length > 1) { + const nextQuestion = questionFrom(line); + if (nextQuestion) { add(question || '', start, end, answer); - question = line.slice(prefix[0].length).trim(); start = end = i; answer = []; + question = nextQuestion; start = end = i; answer = []; } else if (line.startsWith('#')) { add(question || '', start, end, answer); question = null; answer = []; } else if (question && line) { @@ -31,24 +50,19 @@ } add(question || '', start, end, answer); if (mode === 'generate') { - const explicit = [...items]; - const headings = lines.map((line, i) => ({line: line.trim(), i})).filter(x => /^#{1,6}\s+/.test(x.line)); - for (let j = 0; j < headings.length; j++) { - const heading = headings[j], last = (headings[j + 1]?.i ?? lines.length) - 1; - const label = heading.line.replace(/^#{1,6}\s+/, '').trim(); - if (heading.line.startsWith('# ') || /\?$/.test(label) || /^faq\b/i.test(label) || - explicit.some(item => heading.i + 1 >= item.source.startLine && heading.i + 1 <= item.source.endLine)) continue; - let finish = last; + const sections = lines.map((line, i) => ({line: line.trim(), i})) + .filter(({line}) => headingPrefix.test(line) || questionFrom(line)); + for (const [j, heading] of sections.entries()) { + if (!headingPrefix.test(heading.line)) continue; + const label = heading.line.replace(headingPrefix, '').trim(); + if (heading.line.startsWith('# ') || questionFrom(heading.line) || /^faq\b/i.test(label)) continue; + let finish = (sections[j + 1]?.i ?? lines.length) - 1; while (finish > heading.i && !lines[finish].trim()) finish--; const body = lines.slice(heading.i + 1, finish + 1).map(line => line.trim()).filter(Boolean); - const phrasing = {services: 'What services are included?', support: 'Where can I get support?', - 'team responsibilities': 'What are the team responsibilities?', 'knowledge sharing': 'How is knowledge shared?', - 'technical skills': 'Which skills and technologies are listed?'}; - const suggestion = Object.hasOwn(phrasing, label.toLowerCase()) - ? phrasing[label.toLowerCase()] : 'What should I know about ' + label + '?'; - add(suggestion, heading.i, finish, body); + const suggestion = phrasing.get(label.toLowerCase()) ?? 'What should I know about ' + label + '?'; + add(suggestion, heading.i, finish, body, label); } - if (!headings.length && !items.length) { + if (!sections.some(({line}) => headingPrefix.test(line)) && !items.length) { let first = lines.findIndex(line => line.trim()), last = lines.length - 1; while (last > first && !lines[last].trim()) last--; add('What does this document explain?', first, last, lines.slice(first, last + 1).map(line => line.trim()).filter(Boolean));