From b8ac3d43bafa37f0ca0455707fceaa34eb09591e Mon Sep 17 00:00:00 2001 From: Denis Skripchenko Date: Mon, 26 Oct 2026 18:41:05 +0300 Subject: [PATCH 1/2] =?UTF-8?q?fix:=201.1.2=20=E2=80=94=20PDF=20on=20iOS/i?= =?UTF-8?q?PadOS=20prints=20the=20operation,=20margins=20survive=20the=20p?= =?UTF-8?q?rint=20dialog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WebKit on iOS/iPadOS prints the top page instead of the print frame (dozens of sheets of the reference's interface). There the view is printed from the page: a shadow root plus a print-only stylesheet hiding the rest. Desktop keeps the frame. Margins are split between @page and the view's own padding (repeated on every sheet), so a dialog's "None"/"Minimum" margins no longer put the text on the paper's edge (8 mm instead of 0). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 ++ docs/de/reference.md | 9 +- docs/en/reference.md | 9 +- docs/internal/backlog.md | 10 ++- docs/ru/reference.md | 8 +- docs/zh/reference.md | 8 +- package.json | 2 +- scripts/browser-check.mjs | 50 ++++++++++- src/vue/index.ts | 2 +- src/vue/print.ts | 177 +++++++++++++++++++------------------- src/vue/printStyles.ts | 97 +++++++++++++++++++++ tests/print.spec.ts | 46 ++++++++++ 12 files changed, 328 insertions(+), 97 deletions(-) create mode 100644 src/vue/printStyles.ts create mode 100644 tests/print.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c8ec86..ed8b65e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # @dskripchenko/openapi +## 1.1.2 + +### Patch Changes + +- **PDF on iPhone and iPad: the operation, not the whole page.** WebKit on iOS and iPadOS ignores a frame's `print()` and prints the top page — the reference's header, a blank sheet and the whole interface over dozens of sheets. There the print view is now printed from the page itself: it sits in a shadow root (the host's styles stay out) and a print-only stylesheet hides the rest of the page while the dialog is open; the container and the stylesheet go away after printing. Desktop browsers keep the hidden frame. `printOperation` / `printDocument` take `mode: 'auto' | 'frame' | 'page'` (`auto` by default) and resolve with the frame or the page container (`HTMLElement`). +- **Margins that survive the print dialog.** With "None" or "Minimum" margins (common in print dialogs on Windows) the dialog drops `@page`, and the text ran to the paper's edge. The margins are now split between `@page` and the print view's own padding, repeated on every sheet: about 14 mm at the sides as before, and 8 mm when the dialog drops `@page` (was 0). + ## 1.1.1 ### Patch Changes diff --git a/docs/de/reference.md b/docs/de/reference.md index 272e740..5f26326 100644 --- a/docs/de/reference.md +++ b/docs/de/reference.md @@ -632,10 +632,17 @@ gedruckt: Der Security-Abschnitt nennt die Schemas, und das Beispiel wird ohne sie gebaut. Sie wird in einen versteckten Frame mit eigenem Stylesheet gerendert, sodass die Hostseite nicht umgestaltet wird, und ihr Titel — `{API} — {operation}` — ist das, was Browser als Dateinamen der PDF anbieten. +Unter iOS und iPadOS, wo WebKit statt eines Frames die ganze Seite druckt, +wird stattdessen von der Seite selbst gedruckt: Die Ansicht liegt in einem +Shadow Root (die Stile des Hosts bleiben draußen), und ein reines +Druck-Stylesheet blendet den Rest der Seite aus, solange der Dialog offen ist. +Die Ränder halten auch, wenn ein Druckdialog mit den Rändern „Keine“ oder +„Minimal“ die eigenen Ränder des Stylesheets verwirft: Der Text bleibt auf +jedem Blatt etwa 8 mm vom Papierrand entfernt. Den Dialog selbst kann man nicht überspringen: Ein Browser lässt eine Seite keine PDF ohne ihn speichern. -`printOperation(entry, ctx, { url? })` und `printDocument(ctx, { base? })` +`printOperation(entry, ctx, { url?, mode? })` und `printDocument(ctx, { base?, mode? })` aus `@dskripchenko/openapi/vue` tun dasselbe aus Code; sie nehmen den Kontext der Referenz entgegen (siehe [den Kontext](#der-kontext)). `url` ist die mit der Operation gedruckte Adresse, `base` die Seite, an die die Anker diff --git a/docs/en/reference.md b/docs/en/reference.md index aa2eaf9..7097d7c 100644 --- a/docs/en/reference.md +++ b/docs/en/reference.md @@ -593,10 +593,15 @@ interactive parts. Credentials are never printed: the security section names the schemes, and the sample is built without them. It is rendered into a hidden frame with its own stylesheet, so the host page is not restyled, and its title — `{API} — {operation}` — is what browsers offer as the PDF's file -name. The dialog itself cannot be skipped: a browser does not let a page +name. On iOS and iPadOS, where WebKit prints the whole page rather than a +frame, it is printed from the page itself instead: the view sits in a shadow +root (the host's styles stay out) and a print-only stylesheet hides the rest +of the page while the dialog is open. The margins hold up when a print +dialog's "None" or "Minimum" margins drop the stylesheet's own: the text keeps +about 8 mm from the paper's edge on every sheet. The dialog itself cannot be skipped: a browser does not let a page save a PDF without it. -`printOperation(entry, ctx, { url? })` and `printDocument(ctx, { base? })` +`printOperation(entry, ctx, { url?, mode? })` and `printDocument(ctx, { base?, mode? })` from `@dskripchenko/openapi/vue` do the same from code; they take the reference context (see [the context](#the-context)). `url` is the address printed with the operation, `base` the page the operation anchors are diff --git a/docs/internal/backlog.md b/docs/internal/backlog.md index 22f7cc3..11bd260 100644 --- a/docs/internal/backlog.md +++ b/docs/internal/backlog.md @@ -3,7 +3,15 @@ Найденное и отложенное — то, что не вошло в текущую работу. Каждый пункт: что видно, где воспроизводится, первичный разбор, что проверить. -## PDF операции на мобильном: много пустых листов +## ✅ PDF операции на мобильном: много пустых листов — исправлено в 1.1.2 + +Исправлено 2026-10-26: на iOS/iPadOS печать со страницы (shadow root + +`@media print`), на десктопе — по-прежнему фрейм. Проверки в +`scripts/browser-check.mjs` («print (iOS)»): iPhone в Chromium даёт PDF той же +длины, что и фрейм; в WebKit (iPhone 13) при печати видна только операция. +Заодно — поля, не зависящие от `@page` (печать на Windows с полями «Нет»). + +### Как было **Что видно (2026-10-25, iPhone, Safari).** Кнопка PDF у операции открывает системный диалог печати на 25 страниц. На первой — шапка документа («API» и diff --git a/docs/ru/reference.md b/docs/ru/reference.md index 630864a..9f62c6c 100644 --- a/docs/ru/reference.md +++ b/docs/ru/reference.md @@ -604,10 +604,16 @@ PDF» — один из принтеров: называет схемы, а пример строится без них. Вид отрисовывается в скрытом фрейме со своей таблицей стилей, поэтому страница-хост не меняет вид, а его заголовок — `{API} — {operation}` — браузеры предлагают как имя файла PDF. +На iOS и iPadOS, где WebKit печатает не фрейм, а всю страницу, вид печатается +с самой страницы: он лежит в теневом DOM (стили хоста не протекают), а +таблица стилей для печати скрывает остальную страницу, пока открыт диалог. +Поля держатся, даже если в диалоге печати выбраны поля «Нет» или +«Минимальные» и он отбрасывает поля из стилей: текст остаётся примерно в 8 мм +от края листа на каждой странице. Сам диалог пропустить нельзя: браузер не даёт странице сохранить PDF без него. -`printOperation(entry, ctx, { url? })` и `printDocument(ctx, { base? })` из +`printOperation(entry, ctx, { url?, mode? })` и `printDocument(ctx, { base?, mode? })` из `@dskripchenko/openapi/vue` делают то же из кода; они принимают контекст справочника (см. [контекст](#контекст)). `url` — адрес, печатаемый вместе с операцией, `base` — страница, к которой добавляются якоря операций. diff --git a/docs/zh/reference.md b/docs/zh/reference.md index 2d9bb3c..6dba9d2 100644 --- a/docs/zh/reference.md +++ b/docs/zh/reference.md @@ -504,10 +504,14 @@ OpenID Connect 访问令牌及其有效期(过期的不会恢复),以及 b 所选语言和 cURL 的请求示例,以及操作的地址——不含任何交互元素。凭据永远不会被打印: 安全部分只列出方案名称,示例也不带凭据生成。它渲染在一个带独立样式表的隐藏框架中, 因此宿主页面不会被改变样式;其标题——`{API} — {operation}`——就是浏览器建议的 PDF 文件名。 +在 iOS 和 iPadOS 上,WebKit 打印的是整个页面而不是框架,因此改为直接从页面本身打印: +视图位于 shadow root 中(宿主样式不会渗入),对话框打开期间,仅用于打印的样式表会隐藏页面其余部分。 +即使打印对话框选择“无”或“最小”边距而丢弃样式表自身的边距,页边距依然保持: +每一页上文字与纸张边缘约保持 8 mm。 对话框本身无法跳过:浏览器不允许页面在没有它的情况下保存 PDF。 -`@dskripchenko/openapi/vue` 中的 `printOperation(entry, ctx, { url? })` 和 -`printDocument(ctx, { base? })` 在代码中完成同样的事;它们接收参考页的上下文 +`@dskripchenko/openapi/vue` 中的 `printOperation(entry, ctx, { url?, mode? })` 和 +`printDocument(ctx, { base?, mode? })` 在代码中完成同样的事;它们接收参考页的上下文 (见 [上下文](#上下文))。`url` 是随操作一起打印的地址,`base` 是操作锚点所追加到的页面。 ## 请求示例 diff --git a/package.json b/package.json index 8a1e56c..306eb4e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@dskripchenko/openapi", - "version": "1.1.1", + "version": "1.1.2", "description": "OpenAPI 2.0/3.0/3.1 in YAML or JSON with zero runtime dependencies — parse, validate, render with try-it and code samples, and edit visually (Vue components on @dskripchenko/ui)", "keywords": [ "openapi", diff --git a/scripts/browser-check.mjs b/scripts/browser-check.mjs index 17e820e..dc0f64c 100644 --- a/scripts/browser-check.mjs +++ b/scripts/browser-check.mjs @@ -5,7 +5,7 @@ // is checked against the current sources; OA_CHECK_SKIP_BUILD=1 reuses the // existing bundle. import { Buffer } from 'node:buffer' -import { existsSync, mkdirSync } from 'node:fs' +import { existsSync, mkdirSync, writeFileSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { deflateRawSync } from 'node:zlib' import { resolve } from 'node:path' @@ -899,14 +899,62 @@ try { check('print: a sample and the operation URL', printed.text.includes('curl') && printed.text.includes('/standalone.html#kitchen/operation/createOrder')) check('print: the host page is untouched', (await em.locator('.oa-embed__card').first().isVisible()) && (await em.evaluate(() => document.querySelectorAll('iframe[data-oa-print]').length)) === 1) const pdfPage = await browser.newPage() + writeFileSync(`${out}/operation.html`, printed.html) await pdfPage.setContent(printed.html) await pdfPage.emulateMedia({ media: 'print' }) const pdf = await pdfPage.pdf({ path: `${out}/operation.pdf`, format: 'A4', preferCSSPageSize: true }) check('print: a PDF comes out', pdf.length > 1000, `${pdf.length} bytes`) + const pad = await pdfPage.evaluate(() => { + const cs = window.getComputedStyle(document.body) + return { left: parseFloat(cs.paddingLeft), top: parseFloat(cs.paddingTop), clone: cs.boxDecorationBreak || cs.webkitBoxDecorationBreak } + }) + // 8 mm ≈ 30 px: the text stays off the edge even when the dialog drops @page. + check('print: a margin of its own, on every sheet', pad.left >= 30 && pad.top >= 22 && pad.clone === 'clone', JSON.stringify(pad)) await pdfPage.close() check('embed: no page errors', emErrors.length === 0, emErrors.join('; ')) await em.close() + // iOS/iPadOS: WebKit there prints the top page, not a frame, so the view is + // printed on the page itself, the rest hidden on paper. Chromium as an iPhone + // takes that path; its PDF must be the operation alone, as from the frame. + const pageCount = (buf) => (buf.toString('latin1').match(/\/Type\s*\/Page[^s]/g) ?? []).length + const iphone = await browser.newContext({ viewport: { width: 390, height: 844 }, userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1', isMobile: true, hasTouch: true }) + const ip = await iphone.newPage() + await ip.addInitScript(() => (window.print = () => (window.__printed = (window.__printed ?? 0) + 1))) + const ipErrors = [] + ip.on('pageerror', (e) => ipErrors.push(String(e))) + await ip.route('https://auth.example.com/**', (route) => route.fulfill({ contentType: 'application/json', body: '{}' })) + await ip.goto(`${base}embed.html`) + await ip.waitForFunction(() => document.querySelectorAll('.oa-embed__card').length === 3) + await ip.locator('#create .oa-embed__pdf').click() + await ip.waitForFunction(() => window.__printed > 0) + const onPage = await ip.evaluate(() => { + const host = document.querySelector('[data-oa-print-page]:not(style)') + return { + frames: document.querySelectorAll('iframe[data-oa-print]').length, + ops: host?.shadowRoot?.querySelectorAll('.oap-op').length ?? 0, + controls: host?.shadowRoot?.querySelectorAll('button, input, .oa-tryit').length ?? -1, + shown: host ? window.getComputedStyle(host).display : 'missing', + title: document.title, + } + }) + check('print (iOS): on the page, not in a frame', onPage.frames === 0 && onPage.ops === 1 && onPage.controls === 0, JSON.stringify(onPage)) + check('print (iOS): the container is hidden on screen, the title names the operation', onPage.shown === 'none' && onPage.title === 'Kitchen Sink API — Create an order', JSON.stringify(onPage)) + await ip.emulateMedia({ media: 'print' }) + const onPaper = await ip.evaluate(() => ({ + host: window.getComputedStyle(document.querySelector('[data-oa-print-page]:not(style)')).display, + others: [...document.body.children].filter((el) => !el.hasAttribute('data-oa-print-page') && window.getComputedStyle(el).display !== 'none').map((el) => el.tagName + '.' + el.className), + })) + check('print (iOS): on paper only the operation shows', onPaper.host === 'block' && onPaper.others.length === 0, JSON.stringify(onPaper)) + const iosPdf = await ip.pdf({ path: `${out}/operation-ios.pdf`, format: 'A4', preferCSSPageSize: true }) + check('print (iOS): as many sheets as the operation from the frame', pageCount(iosPdf) <= pageCount(pdf) + 1 && pageCount(iosPdf) >= 1, `${pageCount(iosPdf)} vs ${pageCount(pdf)} pages`) + await ip.emulateMedia({ media: 'screen' }) + await ip.evaluate(() => window.dispatchEvent(new window.Event('afterprint'))) + const afterPrint = await ip.evaluate(() => ({ left: document.querySelectorAll('[data-oa-print-page]').length, title: document.title })) + check('print (iOS): afterprint removes the container and its stylesheet, restores the title', afterPrint.left === 0 && afterPrint.title !== 'Kitchen Sink API — Create an order', JSON.stringify(afterPrint)) + check('print (iOS): no page errors', ipErrors.length === 0, ipErrors.join('; ')) + await iphone.close() + // The Vue component on its own; an unknown operation is reported in place. const ev = await browser.newPage({ viewport: { width: 1280, height: 1200 } }) await ev.addInitScript(stubPrint) diff --git a/src/vue/index.ts b/src/vue/index.ts index 6053c17..252a473 100644 --- a/src/vue/index.ts +++ b/src/vue/index.ts @@ -11,7 +11,7 @@ export { OAUTH_MESSAGE, relayOAuthCallback } from './oauthPopup' export { referenceKey, useReference, type ReferenceContext, type ServerState, type SpecInput, type SpecSource } from './context' export { default as OpenApiPage } from './OpenApiPage.vue' export { PAGE_THEMES, resolveLocale, type PageTheme } from './page' -export { printDocument, printOperation, type PrintDocumentOptions, type PrintOptions } from './print' +export { printDocument, printOperation, type PrintDocumentOptions, type PrintMode, type PrintOptions } from './print' export { findOperation } from './embed' export { default as OpenApiBlock, type BlockTab } from './OpenApiBlock.vue' export { blockEn, blockRu, BLOCK_LOCALES, type BlockLabels } from './blocks/labels' diff --git a/src/vue/print.ts b/src/vue/print.ts index d38a17f..93683d7 100644 --- a/src/vue/print.ts +++ b/src/vue/print.ts @@ -2,19 +2,33 @@ * Printing an operation (or the whole spec) through the browser's own print * dialog, which also saves PDF files — no PDF library involved. * - * The print view is rendered once, as static HTML, and written into a hidden - * iframe that carries only its own stylesheet: the host page's styles do not - * leak in, and the host page itself is neither hidden nor restyled. The - * frame's title (`{API} — {operation}`) is what browsers offer as the PDF's - * file name; the host's title is set to it for the dialog's duration too, - * since some browsers take the top page's. The frame goes away after - * printing, or when the next print starts. + * The print view is rendered once, as static HTML, and printed one of two ways: + * + * - `frame` (desktop browsers): written into a hidden iframe that carries only + * its own stylesheet, and the frame is printed. The host page is neither + * hidden nor restyled. + * - `page` (iOS and iPadOS): WebKit there ignores a frame's `print()` and + * prints the whole top page — the reference's interface over dozens of + * sheets. The view goes into a shadow root on the page (the host's styles + * stay out), and a print-only stylesheet hides everything else for the + * dialog's duration. + * + * The title (`{API} — {operation}`) is what browsers offer as the PDF's file + * name: the frame's, and the host's for the dialog's duration too, since some + * browsers take the top page's. Everything goes away after printing, or when + * the next print starts. */ import { createApp, h, nextTick, type Component } from 'vue' import type { OperationEntry } from '../model' import { referenceKey, type ReferenceContext } from './context' import OaPrintDocument from './OaPrintDocument.vue' import OaPrintOperation from './OaPrintOperation.vue' +import { PAGE_PRINT_CSS, PRINT_CSS, printsWholePage, shadowPrintCss } from './printStyles' + +export { PAGE_PRINT_CSS, PRINT_CSS, printsWholePage, shadowPrintCss } + +/** How the print view reaches the dialog: see the module comment. `auto` picks `page` on iOS/iPadOS. */ +export type PrintMode = 'auto' | 'frame' | 'page' export interface PrintOptions { /** @@ -22,66 +36,18 @@ export interface PrintOptions { * hash, `#` and the operation's canonical anchor. */ url?: string + mode?: PrintMode } export interface PrintDocumentOptions { /** The page the operation anchors are appended to; the current page by default. */ base?: string + mode?: PrintMode } -/** The stylesheet of the print document: A4, light colors whatever the page's theme, nothing interactive. */ -export const PRINT_CSS = ` -@page { size: A4; margin: 16mm 14mm 18mm; } -:root { color-scheme: light; } -* { box-sizing: border-box; } -html, body { margin: 0; background: #fff; color: #1a1d23; } -body { font: 10.5pt/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; -webkit-print-color-adjust: exact; print-color-adjust: exact; } -@media screen { body { max-width: 210mm; margin: 0 auto; padding: 16mm 14mm; } } -h1, h2, h3, h4 { margin: 1.1em 0 0.4em; line-height: 1.25; break-after: avoid; page-break-after: avoid; } -h1 { font-size: 18pt; margin-top: 0; } -h2 { font-size: 12.5pt; padding-bottom: 3px; border-bottom: 1px solid #d5d9e0; } -h3 { font-size: 11pt; } -h4 { font-size: 10pt; color: #4a5160; } -p, ul, ol { margin: 0.4em 0; } -a { color: #1d4ed8; text-decoration: none; word-break: break-all; } -a[href^="http"]:not(.oap-url)::after { content: " (" attr(href) ")"; color: #4a5160; font-size: 0.9em; } -code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; font-size: 9pt; } -code { padding: 0 2px; border-radius: 3px; background: #f1f3f6; overflow-wrap: anywhere; } -pre code { padding: 0; background: none; } -pre, .oap-code { margin: 0.4em 0; padding: 8px 10px; border: 1px solid #d5d9e0; border-radius: 4px; background: #f7f8fa; white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; break-inside: avoid; page-break-inside: avoid; } -table { width: 100%; margin: 0.4em 0 0.8em; border-collapse: collapse; break-inside: auto; } -tr, .oap-security li { break-inside: avoid; page-break-inside: avoid; } -thead { display: table-header-group; } -th, td { padding: 4px 6px; border: 1px solid #d5d9e0; text-align: left; vertical-align: top; overflow-wrap: anywhere; font-size: 9pt; } -th { background: #f1f3f6; font-size: 9pt; font-weight: 600; } -th::first-letter { text-transform: uppercase; } -td > p:first-child, td .oap-md > :first-child { margin-top: 0; } -td .oap-md > :last-child { margin-bottom: 0; } -.oap-table--schema td:first-child { width: 32%; } -.oap-row--branch td { background: #fafbfc; } -.oap-page { break-before: page; page-break-before: always; } -.oap-op__head { margin-bottom: 8px; } -.oap-call { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px; margin: 6px 0; } -.oap-call__url { font-size: 10pt; background: none; } -.oap-method { display: inline-block; min-width: 46px; padding: 1px 6px; border: 1px solid currentColor; border-radius: 4px; font: 600 8.5pt/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; text-align: center; color: #4a5160; } -.oap-method--get { color: #1d4ed8; } .oap-method--post { color: #15803d; } .oap-method--put, .oap-method--patch { color: #b45309; } .oap-method--delete { color: #b91c1c; } -.oap-meta { display: grid; grid-template-columns: max-content 1fr; gap: 2px 12px; margin: 6px 0; font-size: 9.5pt; } -.oap-meta dt { color: #4a5160; } .oap-meta dd { margin: 0; } -.oap-flag, .oap-required { display: inline-block; margin-left: 6px; padding: 0 5px; border: 1px solid #d5d9e0; border-radius: 3px; font-size: 8pt; font-weight: 500; vertical-align: middle; color: #4a5160; } -.oap-required { border-color: #fca5a5; color: #b91c1c; } -.oap-flag--deprecated { border-color: #fcd34d; color: #92400e; } -.oap-note { color: #4a5160; font-size: 9pt; } -.oap-note code { margin-right: 4px; } -.oap-cycle { color: #4a5160; font-style: italic; font-size: 9pt; } -.oap-schema__root { margin: 0.3em 0; } -.oap-status { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; } -.oap-md img { max-width: 100%; } -.oap-md blockquote { margin: 0.4em 0; padding-left: 10px; border-left: 3px solid #d5d9e0; color: #4a5160; } -.oap-toc { padding-left: 1.4em; } -.oap-toc li { margin: 2px 0; } -.oap-toc .oap-method { min-width: 0; margin-right: 4px; } -.oap-footer { display: flex; flex-wrap: wrap; gap: 4px 16px; margin-top: 18px; padding-top: 6px; border-top: 1px solid #d5d9e0; color: #4a5160; font-size: 8.5pt; } -` +const escapeHtml = (s: string): string => s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!) + +const resolveMode = (mode: PrintMode = 'auto'): 'frame' | 'page' => (mode === 'auto' ? (printsWholePage() ? 'page' : 'frame') : mode) /** Renders a print view to static HTML with the given context. */ async function renderStatic(component: Component, props: Record, ctx: ReferenceContext): Promise { @@ -95,24 +61,45 @@ async function renderStatic(component: Component, props: Record return html } -let current: { frame: HTMLIFrameElement; restore: () => void } | null = null +let current: { node: HTMLElement; restore: () => void } | null = null -/** Removes the last print frame and gives the host page its title back. */ +/** Removes the last print frame (or page container) and gives the host page its title back. */ function cleanup(): void { if (!current) return current.restore() - current.frame.remove() + current.node.remove() current = null } -const escapeHtml = (s: string): string => s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!) +/** Resolves when the pictures among `images` have loaded or failed, or after a short wait. */ +async function imagesSettled(images: HTMLImageElement[]): Promise { + const pending = images.filter((img) => !img.complete) + if (!pending.length) return + await Promise.race([ + Promise.all( + pending.map( + (img) => + new Promise((done) => { + img.addEventListener('load', done, { once: true }) + img.addEventListener('error', done, { once: true }) + }), + ), + ), + new Promise((r) => setTimeout(r, 2000)), + ]) +} /** - * Writes `body` into a fresh hidden iframe and opens the print dialog for it. - * Resolves with the frame once the dialog is asked for. + * Opens the print dialog for `body` (static HTML styled by `PRINT_CSS`), in a + * hidden iframe or on the page itself (see `PrintMode`). Resolves with the + * frame or the page container once the dialog is asked for. */ -export async function printHtml(body: string, title: string, lang = document.documentElement.lang || 'en'): Promise { +export async function printHtml(body: string, title: string, lang = document.documentElement.lang || 'en', mode: PrintMode = 'auto'): Promise { cleanup() + return resolveMode(mode) === 'page' ? printOnPage(body, title, lang) : printInFrame(body, title, lang) +} + +async function printInFrame(body: string, title: string, lang: string): Promise { const frame = document.createElement('iframe') frame.setAttribute('data-oa-print', '') frame.setAttribute('aria-hidden', 'true') @@ -122,7 +109,7 @@ export async function printHtml(body: string, title: string, lang = document.doc frame.style.cssText = 'position:fixed;left:-10000px;top:0;width:210mm;height:297mm;border:0;opacity:0;pointer-events:none' document.body.appendChild(frame) const hostTitle = document.title - current = { frame, restore: () => void (document.title = hostTitle) } + current = { node: frame, restore: () => void (document.title = hostTitle) } const doc = frame.contentDocument! doc.open() @@ -132,21 +119,7 @@ export async function printHtml(body: string, title: string, lang = document.doc ) doc.close() // Pictures from the descriptions: printed once they arrive (or after a short wait). - const images = [...doc.images].filter((img) => !img.complete) - if (images.length) { - await Promise.race([ - Promise.all( - images.map( - (img) => - new Promise((done) => { - img.addEventListener('load', done, { once: true }) - img.addEventListener('error', done, { once: true }) - }), - ), - ), - new Promise((r) => setTimeout(r, 2000)), - ]) - } + await imagesSettled([...doc.images]) const win = frame.contentWindow if (!win) return frame const mine = current @@ -159,24 +132,54 @@ export async function printHtml(body: string, title: string, lang = document.doc return frame } +async function printOnPage(body: string, title: string, lang: string): Promise { + const host = document.createElement('div') + host.setAttribute('data-oa-print-page', '') + host.setAttribute('aria-hidden', 'true') + host.setAttribute('lang', lang) + const root = host.attachShadow({ mode: 'open' }) + root.innerHTML = `
${body}
` + const style = document.createElement('style') + style.setAttribute('data-oa-print-page', '') + style.textContent = PAGE_PRINT_CSS + document.head.appendChild(style) + document.body.appendChild(host) + const hostTitle = document.title + current = { + node: host, + restore: () => { + document.title = hostTitle + style.remove() + }, + } + await imagesSettled([...root.querySelectorAll('img')]) + const mine = current + window.addEventListener('afterprint', () => { + if (current === mine) cleanup() + }, { once: true }) + document.title = title + window.print() + return host +} + /** The address of an operation in the reference: the page without its hash, `#`, the anchor. */ export function operationUrl(entry: OperationEntry, ctx: ReferenceContext, base = window.location.href.split('#')[0]!): string { return `${base}#${ctx.anchorPrefix.value}operation/${entry.id}` } /** Opens the print dialog for one operation (paper, or "Save as PDF"). */ -export async function printOperation(entry: OperationEntry, ctx: ReferenceContext, options: PrintOptions = {}): Promise { +export async function printOperation(entry: OperationEntry, ctx: ReferenceContext, options: PrintOptions = {}): Promise { const url = options.url ?? operationUrl(entry, ctx) const html = await renderStatic(OaPrintOperation, { entry, url }, ctx) const api = ctx.spec.value.document.info.title const name = entry.operation.summary || `${entry.method.toUpperCase()} ${entry.path}` - return printHtml(html, api ? `${api} — ${name}` : name) + return printHtml(html, api ? `${api} — ${name}` : name, undefined, options.mode) } /** Opens the print dialog for the whole spec: the introduction, every operation, the schemas. */ -export async function printDocument(ctx: ReferenceContext, options: PrintDocumentOptions = {}): Promise { +export async function printDocument(ctx: ReferenceContext, options: PrintDocumentOptions = {}): Promise { const base = options.base ?? window.location.href.split('#')[0]! const html = await renderStatic(OaPrintDocument, { base }, ctx) const info = ctx.spec.value.document.info - return printHtml(html, [info.title, info.version].filter(Boolean).join(' — ') || 'OpenAPI') + return printHtml(html, [info.title, info.version].filter(Boolean).join(' — ') || 'OpenAPI', undefined, options.mode) } diff --git a/src/vue/printStyles.ts b/src/vue/printStyles.ts new file mode 100644 index 0000000..94fe85d --- /dev/null +++ b/src/vue/printStyles.ts @@ -0,0 +1,97 @@ +/** + * The print view's stylesheets and the choice of how to print: plain + * TypeScript, no Vue (see print.ts). + */ +/** iOS and iPadOS (which reports itself as a Mac, with touch): every browser there is WebKit. */ +export function printsWholePage(nav: Pick = navigator): boolean { + return /\b(iPhone|iPad|iPod)\b/.test(nav.userAgent) || (nav.platform === 'MacIntel' && nav.maxTouchPoints > 1) +} + +/** + * The stylesheet of the print document: A4, light colors whatever the page's + * theme, nothing interactive. The margins are split: `@page` gives most of + * them, the body's own padding (repeated on every sheet) the rest — a print + * dialog set to "None" / "Minimum" margins drops `@page`, and the text would + * touch the paper's edge. + */ +export const PRINT_CSS = ` +@page { size: A4; margin: 10mm 6mm 12mm; } +:root { color-scheme: light; } +* { box-sizing: border-box; } +html, body { margin: 0; background: #fff; color: #1a1d23; } +body { font: 10.5pt/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; -webkit-print-color-adjust: exact; print-color-adjust: exact; padding: 6mm 8mm; -webkit-box-decoration-break: clone; box-decoration-break: clone; } +@media screen { body { max-width: 210mm; margin: 0 auto; padding: 16mm 14mm; } } +h1, h2, h3, h4 { margin: 1.1em 0 0.4em; line-height: 1.25; break-after: avoid; page-break-after: avoid; } +h1 { font-size: 18pt; margin-top: 0; } +h2 { font-size: 12.5pt; padding-bottom: 3px; border-bottom: 1px solid #d5d9e0; } +h3 { font-size: 11pt; } +h4 { font-size: 10pt; color: #4a5160; } +p, ul, ol { margin: 0.4em 0; } +a { color: #1d4ed8; text-decoration: none; word-break: break-all; } +a[href^="http"]:not(.oap-url)::after { content: " (" attr(href) ")"; color: #4a5160; font-size: 0.9em; } +code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; font-size: 9pt; } +code { padding: 0 2px; border-radius: 3px; background: #f1f3f6; overflow-wrap: anywhere; } +pre code { padding: 0; background: none; } +pre, .oap-code { margin: 0.4em 0; padding: 8px 10px; border: 1px solid #d5d9e0; border-radius: 4px; background: #f7f8fa; white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; break-inside: avoid; page-break-inside: avoid; } +table { width: 100%; margin: 0.4em 0 0.8em; border-collapse: collapse; break-inside: auto; } +tr, .oap-security li { break-inside: avoid; page-break-inside: avoid; } +thead { display: table-header-group; } +th, td { padding: 4px 6px; border: 1px solid #d5d9e0; text-align: left; vertical-align: top; overflow-wrap: anywhere; font-size: 9pt; } +th { background: #f1f3f6; font-size: 9pt; font-weight: 600; } +th::first-letter { text-transform: uppercase; } +td > p:first-child, td .oap-md > :first-child { margin-top: 0; } +td .oap-md > :last-child { margin-bottom: 0; } +.oap-table--schema td:first-child { width: 32%; } +.oap-row--branch td { background: #fafbfc; } +.oap-page { break-before: page; page-break-before: always; } +.oap-op__head { margin-bottom: 8px; } +.oap-call { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px; margin: 6px 0; } +.oap-call__url { font-size: 10pt; background: none; } +.oap-method { display: inline-block; min-width: 46px; padding: 1px 6px; border: 1px solid currentColor; border-radius: 4px; font: 600 8.5pt/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; text-align: center; color: #4a5160; } +.oap-method--get { color: #1d4ed8; } .oap-method--post { color: #15803d; } .oap-method--put, .oap-method--patch { color: #b45309; } .oap-method--delete { color: #b91c1c; } +.oap-meta { display: grid; grid-template-columns: max-content 1fr; gap: 2px 12px; margin: 6px 0; font-size: 9.5pt; } +.oap-meta dt { color: #4a5160; } .oap-meta dd { margin: 0; } +.oap-flag, .oap-required { display: inline-block; margin-left: 6px; padding: 0 5px; border: 1px solid #d5d9e0; border-radius: 3px; font-size: 8pt; font-weight: 500; vertical-align: middle; color: #4a5160; } +.oap-required { border-color: #fca5a5; color: #b91c1c; } +.oap-flag--deprecated { border-color: #fcd34d; color: #92400e; } +.oap-note { color: #4a5160; font-size: 9pt; } +.oap-note code { margin-right: 4px; } +.oap-cycle { color: #4a5160; font-style: italic; font-size: 9pt; } +.oap-schema__root { margin: 0.3em 0; } +.oap-status { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; } +.oap-md img { max-width: 100%; } +.oap-md blockquote { margin: 0.4em 0; padding-left: 10px; border-left: 3px solid #d5d9e0; color: #4a5160; } +.oap-toc { padding-left: 1.4em; } +.oap-toc li { margin: 2px 0; } +.oap-toc .oap-method { min-width: 0; margin-right: 4px; } +.oap-footer { display: flex; flex-wrap: wrap; gap: 4px 16px; margin-top: 18px; padding-top: 6px; border-top: 1px solid #d5d9e0; color: #4a5160; font-size: 8.5pt; } +` + +/** + * The page stylesheet for `page` mode: on paper only the print container + * shows, and a host's full-height, scroll-clipped layout is let out so the + * container runs over as many sheets as it needs. + */ +export const PAGE_PRINT_CSS = ` +[data-oa-print-page] { display: none; } +@media print { + @page { size: A4; margin: 10mm 6mm 12mm; } + html, body { height: auto !important; min-height: 0 !important; max-height: none !important; overflow: visible !important; margin: 0 !important; padding: 0 !important; background: #fff !important; } + body > *:not([data-oa-print-page]) { display: none !important; } + [data-oa-print-page] { display: block !important; position: static !important; } +} +` + +/** + * PRINT_CSS for a shadow root: it speaks to a document (`:root`, `html, body`), + * here the container `.oap-body` plays the body; `@page` only works at the + * document level (PAGE_PRINT_CSS) and the screen-only page frame is dropped. + */ +export function shadowPrintCss(css = PRINT_CSS): string { + return css + .replace(/@page\s*\{[^}]*\}\n?/, '') + .replace(/@media screen \{[^{}]*\{[^}]*\}\s*\}\n?/, '') + .replace(/:root\s*\{/, ':host {') + .replace(/(^|\n)html, body \{/, '$1.oap-body {') + .replace(/(^|\n)body \{/, '$1.oap-body {') +} diff --git a/tests/print.spec.ts b/tests/print.spec.ts new file mode 100644 index 0000000..067fca5 --- /dev/null +++ b/tests/print.spec.ts @@ -0,0 +1,46 @@ +// @vitest-environment jsdom +import { describe, expect, it } from 'vitest' +import { PAGE_PRINT_CSS, PRINT_CSS, printsWholePage, shadowPrintCss } from '../src/vue/printStyles' + +const nav = (userAgent: string, platform = '', maxTouchPoints = 0) => ({ userAgent, platform, maxTouchPoints }) + +describe('print', () => { + it('prints on the page on iOS and iPadOS only', () => { + expect(printsWholePage(nav('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15', 'iPhone', 5))).toBe(true) + expect(printsWholePage(nav('Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) CriOS/130.0', 'iPad', 5))).toBe(true) + // iPadOS asks for the desktop site: a Mac with touch. + expect(printsWholePage(nav('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Version/18.0 Safari/605.1.15', 'MacIntel', 5))).toBe(true) + expect(printsWholePage(nav('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Version/18.0 Safari/605.1.15', 'MacIntel', 0))).toBe(false) + expect(printsWholePage(nav('Mozilla/5.0 (Linux; Android 14; Pixel 8) Chrome/130.0 Mobile Safari/537.36', 'Linux armv8l', 5))).toBe(false) + expect(printsWholePage(nav('Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/130.0', 'Win32', 0))).toBe(false) + }) + + it('turns the document stylesheet into one for the shadow container', () => { + const css = shadowPrintCss() + expect(css).not.toContain('@page') + expect(css).not.toContain('@media screen') + expect(css).not.toMatch(/(^|\n)(html, body|body) \{/) + expect(css).toContain(':host { color-scheme: light; }') + expect(css.match(/\.oap-body \{/g)).toHaveLength(2) + // Everything else is kept as is. + expect(css).toContain('.oap-page { break-before: page;') + expect(PRINT_CSS.length - css.length).toBeLessThan(200) + }) + + it('hides the page around the container on paper only', () => { + expect(PAGE_PRINT_CSS).toMatch(/\[data-oa-print-page\] \{ display: none; \}/) + expect(PAGE_PRINT_CSS).toContain('body > *:not([data-oa-print-page]) { display: none !important; }') + expect(PAGE_PRINT_CSS).toContain('overflow: visible !important') + expect(PAGE_PRINT_CSS).toContain('@page { size: A4;') + }) + + it('keeps a margin of its own when a print dialog drops @page', () => { + // "None" / "Minimum" margins in a print dialog ignore @page: the body's + // padding, repeated on every sheet, keeps the text off the paper's edge. + const body = PRINT_CSS.match(/(^|\n)body \{[^}]*\}/)![0] + expect(body).toContain('padding: 6mm 8mm') + expect(body).toContain('box-decoration-break: clone') + expect(shadowPrintCss()).toMatch(/\.oap-body \{[^}]*padding: 6mm 8mm/) + expect(PRINT_CSS).toContain('@page { size: A4; margin: 10mm 6mm 12mm; }') + }) +}) From cccc5f13400c942740039a137e1aa7c12f5c6b85 Mon Sep 17 00:00:00 2001 From: Denis Skripchenko Date: Mon, 26 Oct 2026 18:45:49 +0300 Subject: [PATCH 2/2] feat: bundle the lucide icons; fix a token expiry off by a minute The Vue components import their icons from lucide-vue-next directly and the build bundles them (ISC notice kept), so the package loads from an ESM CDN without lucide in the import map. store() read the clock twice, so a 60-minute token could show "61 min". Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ package.json | 1 + pnpm-lock.yaml | 3 +++ src/vue/OaAuth.vue | 6 ++++-- src/vue/OaOperation.vue | 2 +- src/vue/OpenApiOperation.vue | 2 +- src/vue/OpenApiReference.vue | 2 +- src/vue/blocks/OaBlockConstructor.vue | 2 +- vite.config.ts | 6 ++++++ 9 files changed, 20 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed8b65e..4997320 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ ### Patch Changes - **PDF on iPhone and iPad: the operation, not the whole page.** WebKit on iOS and iPadOS ignores a frame's `print()` and prints the top page — the reference's header, a blank sheet and the whole interface over dozens of sheets. There the print view is now printed from the page itself: it sits in a shadow root (the host's styles stay out) and a print-only stylesheet hides the rest of the page while the dialog is open; the container and the stylesheet go away after printing. Desktop browsers keep the hidden frame. `printOperation` / `printDocument` take `mode: 'auto' | 'frame' | 'page'` (`auto` by default) and resolve with the frame or the page container (`HTMLElement`). +- **The icons are bundled.** The operation, reference and block components import their ~13 lucide icons directly and the build bundles them (the ISC notice is kept, ~9 KB unminified), instead of importing `@dskripchenko/ui/icons` at runtime: the package loads from an ESM CDN without `lucide-vue-next` in the import map. +- A token's expiry read "61 min" for a 60-minute token now and then: the time and the expiry were two clock readings. - **Margins that survive the print dialog.** With "None" or "Minimum" margins (common in print dialogs on Windows) the dialog drops `@page`, and the text ran to the paper's edge. The margins are now split between `@page` and the print view's own padding, repeated on every sheet: about 14 mm at the sides as before, and 8 mm when the dialog drops `@page` (was 0). ## 1.1.1 diff --git a/package.json b/package.json index 306eb4e..0bdff52 100644 --- a/package.json +++ b/package.json @@ -95,6 +95,7 @@ "eslint": "^10.13.0", "eslint-plugin-vue": "^10.11.1", "jsdom": "^29.1.1", + "lucide-vue-next": "0.460.0", "playwright": "1.64.1", "prettier": "^3.9.10", "typescript": "^6.0.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c1ef710..691b73e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -38,6 +38,9 @@ importers: jsdom: specifier: ^29.1.1 version: 29.1.1 + lucide-vue-next: + specifier: 0.460.0 + version: 0.460.0(vue@3.5.44(typescript@6.0.3)) playwright: specifier: 1.64.1 version: 1.64.1 diff --git a/src/vue/OaAuth.vue b/src/vue/OaAuth.vue index 4e00ce2..2105ecc 100644 --- a/src/vue/OaAuth.vue +++ b/src/vue/OaAuth.vue @@ -170,8 +170,10 @@ function fetchVia(send: SendFn): typeof fetch { function store(name: string, token: OAuthToken): void { ctx.credentials[name] = token.accessToken - now.value = Date.now() - if (token.expiresIn !== undefined) ctx.tokenExpiry[name] = Date.now() + token.expiresIn * 1000 + // One clock reading: two could differ by a millisecond and round "60 min" up to 61. + const at = Date.now() + now.value = at + if (token.expiresIn !== undefined) ctx.tokenExpiry[name] = at + token.expiresIn * 1000 else delete ctx.tokenExpiry[name] } const messageOf = (e: unknown): string => { diff --git a/src/vue/OaOperation.vue b/src/vue/OaOperation.vue index 9e131c1..36f4ff6 100644 --- a/src/vue/OaOperation.vue +++ b/src/vue/OaOperation.vue @@ -5,7 +5,7 @@ */ import { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue' import { UidButton, UidMarkdown } from '@dskripchenko/ui' -import { Check, Link, Printer } from '@dskripchenko/ui/icons' +import { Check, Link, Printer } from 'lucide-vue-next' import type { Header, MediaType, Parameter, ParameterIn, RequestBody, Response } from '../core/types' import type { OperationEntry } from '../model' import { describe as describeSchema } from '../schema' diff --git a/src/vue/OpenApiOperation.vue b/src/vue/OpenApiOperation.vue index 668d243..0c95855 100644 --- a/src/vue/OpenApiOperation.vue +++ b/src/vue/OpenApiOperation.vue @@ -12,7 +12,7 @@ */ import { computed, ref } from 'vue' import { UidAlert, UidButton, UidDrawer, UidLocaleProvider, UidSpinner } from '@dskripchenko/ui' -import { ExternalLink, KeyRound, Printer, Settings2 } from '@dskripchenko/ui/icons' +import { ExternalLink, KeyRound, Printer, Settings2 } from 'lucide-vue-next' import type { LoadedSpec, ResolverOptions } from '../model' import type { SendFn } from '../request' import { SNIPPET_TARGETS, type SnippetTarget } from '../snippets' diff --git a/src/vue/OpenApiReference.vue b/src/vue/OpenApiReference.vue index 7855de4..3005f5f 100644 --- a/src/vue/OpenApiReference.vue +++ b/src/vue/OpenApiReference.vue @@ -17,7 +17,7 @@ */ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { UidAlert, UidButton, UidDrawer, UidInput, UidLocaleProvider, UidMarkdown, UidSelect, UidSpinner } from '@dskripchenko/ui' -import { Download, KeyRound, Menu, Printer, Settings2 } from '@dskripchenko/ui/icons' +import { Download, KeyRound, Menu, Printer, Settings2 } from 'lucide-vue-next' import { decodePrefill, pickSpec, resolveSection, splitLink } from '../links' import type { LoadedSpec } from '../model' import type { ResolverOptions } from '../model' diff --git a/src/vue/blocks/OaBlockConstructor.vue b/src/vue/blocks/OaBlockConstructor.vue index a0fd30f..1969f9d 100644 --- a/src/vue/blocks/OaBlockConstructor.vue +++ b/src/vue/blocks/OaBlockConstructor.vue @@ -7,7 +7,7 @@ */ import { computed, ref, watch } from 'vue' import { UidButton, UidCheckbox, UidFormField, UidInput, UidSelect, UidTextarea } from '@dskripchenko/ui' -import { Braces, Plus, X } from '@dskripchenko/ui/icons' +import { Braces, Plus, X } from 'lucide-vue-next' import { BLOCK_METHODS, BODY_TYPES, diff --git a/vite.config.ts b/vite.config.ts index 88c5fce..fdfd149 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,8 +1,13 @@ +import { readFileSync } from 'fs' import { resolve } from 'path' import { defineConfig } from 'vitest/config' import vue from '@vitejs/plugin-vue' import dts from 'vite-plugin-dts' +// The icons are bundled (no `lucide-vue-next` in a CDN import map); their license goes with them. +const lucideLicense = readFileSync(resolve(import.meta.dirname, 'node_modules/lucide-vue-next/LICENSE'), 'utf8').trim() +const lucideBanner = `/*! Includes icons from lucide-vue-next (https://lucide.dev)\n${lucideLicense.replace(/\*\//g, '* /')}\n*/` + export default defineConfig({ plugins: [ vue(), @@ -30,6 +35,7 @@ export default defineConfig({ // The core shared by both entries. output: { manualChunks: (id) => (id.includes('/src/') && !id.includes('/src/vue/') ? 'core' : undefined), + postBanner: (chunk) => (chunk.isEntry && chunk.name === 'vue' ? lucideBanner : ''), }, }, minify: false,