Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# @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`).
- **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

### Patch Changes
Expand Down
9 changes: 8 additions & 1 deletion docs/de/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions docs/en/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion docs/internal/backlog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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» и
Expand Down
8 changes: 7 additions & 1 deletion docs/ru/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` — страница, к которой добавляются якоря операций.
Expand Down
8 changes: 6 additions & 2 deletions docs/zh/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 是操作锚点所追加到的页面。

## 请求示例
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down Expand Up @@ -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",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

50 changes: 49 additions & 1 deletion scripts/browser-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 4 additions & 2 deletions src/vue/OaAuth.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
2 changes: 1 addition & 1 deletion src/vue/OaOperation.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
2 changes: 1 addition & 1 deletion src/vue/OpenApiOperation.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
2 changes: 1 addition & 1 deletion src/vue/OpenApiReference.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
2 changes: 1 addition & 1 deletion src/vue/blocks/OaBlockConstructor.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/vue/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
Loading
Loading