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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ Vue CLI остаётся на последнем опубликованном в

## iframe и профиль Твой ФФ

Параметры `token`, `user_id`, `scopes` читаются из URL по примеру [rental-ui](https://github.com/profcomff/rental-ui/blob/main/src/store/profileStore.ts). Они сохраняются при внутренних переходах. Собственная шапка отсутствует, чтобы не дублировать шапку Твой ФФ. Область мини-приложения ограничена высотой iframe: содержимое прокручивается отдельно, а переключение печати и истории занимает постоянную нижнюю строку вне прокрутки. Это сохраняет доступ к меню в мобильных WebView; панель выбора файлов остаётся над ним, учитывается безопасная зона экрана.
Параметры `token`, `user_id`, `scopes` читаются из URL по примеру [rental-ui](https://github.com/profcomff/rental-ui/blob/main/src/store/profileStore.ts). Они сохраняются при внутренних переходах. Собственная шапка отсутствует, чтобы не дублировать шапку Твой ФФ. Область мини-приложения ограничена высотой iframe: содержимое прокручивается отдельно, а переключение печати и истории занимает постоянную нижнюю строку вне прокрутки. Если установленная оболочка обрезает iframe, высота и положение приложения подстраиваются под его видимую область через `IntersectionObserver`, без доступа к DOM родительского сайта. Это сохраняет доступ к меню в мобильных WebView; панель выбора файлов остаётся над ним, учитывается безопасная зона экрана.

Если передан токен, числовой `user_id` и хотя бы одно право `userdata.category.personal.read` / `userdata.category.credentials.read`, приложение автоматически запрашивает `GET /userdata/user/{id}` на том же API-хосте, что и сервис печати. Полученные поля `Личная информация / Полное имя` и `Учетные данные / Номер профсоюзного билета` заполняются по отдельности. Фамилия предлагается как первое слово ФИО и остаётся редактируемой. Уже начатый ввод не перезаписывается. При отсутствии данных или ошибке профиля остаётся ручной ввод. При доступной сессии профиля сохранённые реквизиты другого пользователя не подставляются.

Expand Down
55 changes: 53 additions & 2 deletions src/App.vue
Original file line number Diff line number Diff line change
@@ -1,9 +1,60 @@
<script setup lang="ts">
import { ref, watch } from "vue";
import {
ref,
watch,
onMounted,
onBeforeUnmount,
type CSSProperties,
} from "vue";
import { useRoute } from "vue-router";
import AppIcon from "@/components/AppIcon.vue";
const route = useRoute();
const content = ref<HTMLElement | null>(null);
const visibleViewport = ref<CSSProperties>({});
let viewportObserver: IntersectionObserver | undefined;
let viewportRefresh: number | undefined;
function stopViewportRefresh() {
window.clearInterval(viewportRefresh);
viewportRefresh = undefined;
}
onMounted(() => {
if (window.self === window.top) return;
// The host may clip a cross-origin iframe. Its innerHeight still includes
// the clipped area; intersectionRect describes the part actually on screen.
viewportObserver = new IntersectionObserver(
([entry]) => {
if (!entry?.isIntersecting || entry.intersectionRect.height < 1) {
stopViewportRefresh();
return;
}
const visible = entry.intersectionRect;
const full = entry.boundingClientRect;
const clipped = visible.height < full.height - 1;
visibleViewport.value = !clipped
? {}
: {
height: `${Math.floor(visible.height)}px`,
marginTop: `${Math.max(0, Math.ceil(visible.top - full.top))}px`,
};
if (!clipped) stopViewportRefresh();
else if (viewportRefresh === undefined) {
// ponytail: recheck clipped cross-origin viewports at 5 Hz; replace
// with host viewport messages if the embedding app supplies them.
viewportRefresh = window.setInterval(() => {
viewportObserver?.unobserve(document.documentElement);
viewportObserver?.observe(document.documentElement);
}, 200);
}
},
{ threshold: [0, 1] },
);
// Observe the full document, whose size is independent of the adjusted shell.
viewportObserver.observe(document.documentElement);
});
onBeforeUnmount(() => {
viewportObserver?.disconnect();
stopViewportRefresh();
});
watch(
() => route.path,
() => {
Expand All @@ -22,7 +73,7 @@ watch(
);
</script>
<template>
<main class="app-shell">
<main class="app-shell" :style="visibleViewport">
<div ref="content" class="app-content">
<router-view />
<footer>
Expand Down
71 changes: 71 additions & 0 deletions tests/browser/navigation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,74 @@ test("iframe scrolls its content without moving or covering navigation", async (
await page.setViewportSize({ width: 390, height: 420 });
await assertMenu();
});

test("cross-origin clipped iframe keeps navigation inside the visible host area", async ({
page,
}) => {
// Real mini-apps and their host have different origins. Fulfill locally to avoid
// Chromium's loopback-network permission prompt in the synthetic host page.
await page.route("http://127.0.0.1:9004/**", async (route) => {
await route.fulfill({ response: await route.fetch() });
});
await page.route("http://localhost:9004/clipped-fixture", (route) =>
route.fulfill({
contentType: "text/html",
body: `<meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0;height:100%;overflow:hidden}header{height:64px}main{height:calc(100% - 120px);overflow:hidden}iframe{height:100vh;width:100%;border:0}footer{height:56px}</style><header>Твой ФФ</header><main><iframe title="Принтер" src="http://127.0.0.1:9004/"></iframe></main><footer>Меню Твой ФФ</footer>`,
}),
);
await page.goto("http://localhost:9004/clipped-fixture");
const child = page.frameLocator("iframe");
const nav = child.getByRole("navigation", { name: "Разделы печати" });
await expect(nav).toBeVisible();
const assertVisibleMenu = async () => {
await expect
.poll(async () => {
const navBox = await nav.boundingBox();
const area = await page.locator("main").boundingBox();
return (
!!navBox &&
!!area &&
navBox.y >= area.y &&
navBox.y + navBox.height <= area.y + area.height + 1
);
})
.toBe(true);
};
await assertVisibleMenu();
await child.locator(".app-content").evaluate((el) => {
el.scrollTop = el.scrollHeight;
});
await assertVisibleMenu();
await nav.getByRole("link", { name: "История", exact: true }).click();
await expect(
child.getByRole("heading", { name: "Ваши документы" }),
).toBeVisible();
await page.locator("main").evaluate((el) => {
el.style.height = "300px";
});
await assertVisibleMenu();
await page.setViewportSize({ width: 412, height: 700 });
await assertVisibleMenu();
// Rotation can preserve the visible ratio while changing the pixel height.
await page.locator("main").evaluate((el) => {
el.style.height = "60vh";
});
await assertVisibleMenu();
await page.setViewportSize({ width: 412, height: 500 });
await assertVisibleMenu();
await page.setViewportSize({ width: 390, height: 844 });
await page.locator("main").evaluate((el) => {
el.style.height = "300px";
el.style.overflow = "auto";
});
await assertVisibleMenu();
// Host scrolling can move the visible slice without changing its area ratio.
await page.locator("main").evaluate((el) => {
el.scrollTop = 350;
});
await assertVisibleMenu();
await page.locator("main").evaluate((el) => {
el.scrollTop = 0;
});
await assertVisibleMenu();
});
Loading