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: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,8 @@ make deploy APP=http_example HOST=timeweb SKIP=caddy,cron
* **Перетаскивание собрано на `mousedown` и `mouseup`.** `Actions.dragAndDrop` в Selenium эмулирует мышь, а события HTML5 `dragstart` и `drop` браузер на неё не шлёт, поэтому `draggable` пример молча не срабатывал бы.
* **Сессия это подписанная кука с путём курса, и курс записан в её значении.** Урок про куки сохраняет их после входа, открывает страницу в новом браузере, подкладывает куки руками и идёт в закрытый раздел. Кука одного курса не открывает раздел другого, неподписанное значение не открывает ничего.
* **Учётки напечатаны на страницах входа и в уроках.** Их смена это правка курсов.
* **Дополнительные учётки и тексты обязательных полей задаются конфигом.** `extraAccounts` даёт вторую роль со своим разделом и заблокированную учётку, `usernameRequired` и `passwordRequired` включают отдельные сообщения о пустых полях. У приложения без этих ключей вход ведёт себя как раньше.
* **API и раздел сотрудника `/python-playwright` написаны руками** в `custom-server/src/python-playwright.ts`, спецификации на TypeSpec у них нет. Урок про API читает только эти поля и коды, и правило «Набор данных не меняется» на них тоже действует.

## Набор данных не меняется

Expand Down
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,16 @@

| Путь | Сценарий |
| --- | --- |
| `/python-playwright` | табло `#departures`, время вылета печатается в часовом поясе браузера, на узком экране строки складываются в карточки |
| `/python-playwright/login` → `/trips` | вход пассажира `passenger` / `flight123`, «My trips» |
| `/python-playwright` | табло `#departures` грузит рейсы запросом `api/departures`, время вылета печатается в часовом поясе браузера, часы `current-time`, на узком экране строки складываются в карточки, ссылки шапки уходят за кнопку «Navigation», блок «Travel alerts» прячется |
| `/python-playwright/login` → `/trips` | вход пассажира `passenger` / `flight123`, «My trips», «Flight updates», токен `auth_token` в localStorage, выход по бездействию через пять минут на `/session-expired` |
| `/python-playwright/login` → `/staff` | вход сотрудника `agent` / `staff123`, «Passenger list», пассажиру отвечает 403 «Access denied» |
| `/python-playwright/login` | `blocked` / `flight123` заблокирован, пустые поля дают «Username is required.» и «Password is required.» |
| `/python-playwright/packing` | список вещей вместо todomvc: поле «What do you need to pack?», `item`, `item-title`, счётчик `items-left` |
| `/python-playwright/check-in` | форма регистрации: подписи, `select` и множественный `select`, кастомный список «Meal», radio, чекбоксы, загрузка файлов, теневой DOM; «Checked in» появляется через секунду |
| `/python-playwright/boarding-pass` | `confirm` и `prompt`, «Airport map» в новой вкладке, оплата во фрейме `#payment`, скачивания `boarding-pass.pdf` и `trips.csv`, диалог выбора файла по «Attach visa» |
| `/python-playwright/extras` | доп. услуги `.extra` со счётчиком `extras-count`, промокод `WINTER26` действует до 1 января 2027 года по часам браузера |

API курса лежит под тем же префиксом и набор данных не меняет. `GET api/departures` фильтруется параметром `status`. `POST api/login` отдаёт токен `<учётка>-token` и открывает сессию браузера. `api/bookings` закрыт заголовком `Authorization: Bearer <токен>`: GET списка и записи, POST отвечает 201 (без `flight` или `passenger` 422), PUT и PATCH отвечают изменённой записью, DELETE отвечает 204.

У всех трёх одинаковое устройство входа. Форма `#login` с полями `#username` и `#password` и кнопкой `button.primary[data-test=login-button]`, флеш-сообщение `#flash`, выход по `/<курс>/logout`. Приложения описаны конфигом `apps` в `custom-server/src/ui-pages.ts`, страницы лежат фрагментами в `custom-server/assets/ui-pages/<курс>/`, префикс в них записан как `{{prefix}}`.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<main class="example">
<h1>Airport map</h1>
<p>Terminal 1: gates A1 to A12. Terminal 2: gates B1 to C9.</p>
<button type="button" id="close">Close</button>
</main>
<script>
document.title = 'Airport map';
document.getElementById('close').addEventListener('click', () => window.close());
</script>
33 changes: 33 additions & 0 deletions custom-server/assets/ui-pages/python-playwright/boarding-pass.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<main class="example">
<h1>Boarding pass</h1>
<p>Anna Berg, flight SK 204 to Lisbon, seat 14A.</p>
<p><a href="{{prefix}}/boarding-pass.pdf">Download boarding pass</a></p>
<p><a href="{{prefix}}/trips.csv">Export trips (CSV)</a></p>
<p><a href="{{prefix}}/airport-map" target="_blank">Airport map</a></p>
<button type="button" id="add-companion">Add companion</button>
<p id="companion"></p>
<button type="button" id="attach-visa">Attach visa</button>
<input type="file" id="visa" hidden />
<p id="visa-name"></p>
<h2>Seat upgrade</h2>
<iframe id="payment" title="Payment" src="{{prefix}}/payment"></iframe>
<button type="button" id="cancel">Cancel check-in</button>
<p id="status"></p>
</main>
<script>
document.getElementById('cancel').addEventListener('click', () => {
const status = document.getElementById('status');
status.textContent = confirm('Cancel your check-in?') ? 'Check-in cancelled' : 'Check-in kept';
});
document.getElementById('add-companion').addEventListener('click', () => {
const name = prompt('Companion name');
if (name) document.getElementById('companion').textContent = `Companion: ${name}`;
});
// Поле файла скрыто, диалог выбора открывает кнопка: это сценарий для
// expect_file_chooser, set_input_files здесь искать нечего.
const visa = document.getElementById('visa');
document.getElementById('attach-visa').addEventListener('click', () => visa.click());
visa.addEventListener('change', () => {
document.getElementById('visa-name').textContent = `Attached: ${visa.files[0].name}`;
});
</script>
95 changes: 95 additions & 0 deletions custom-server/assets/ui-pages/python-playwright/check-in.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<main class="example">
<h1>Online check-in</h1>
<baggage-allowance></baggage-allowance>
<form id="check-in-form">
<label for="first-name">First name</label>
<input id="first-name" />
<label for="last-name">Last name</label>
<input id="last-name" />
<label for="email">Email</label>
<input id="email" type="email" placeholder="name@example.com" />
<label for="birth-date">Date of birth</label>
<input id="birth-date" type="date" />
<label for="seat">Seat preference</label>
<select id="seat">
<option value="window">Window</option>
<option value="aisle">Aisle</option>
<option value="middle">Middle</option>
</select>
<label for="assistance">Special assistance</label>
<select id="assistance" multiple>
<option value="wheelchair">Wheelchair</option>
<option value="hearing">Hearing</option>
<option value="visual">Visual</option>
</select>
<span id="meal-label" class="label">Meal</span>
<div class="dropdown">
<button type="button" id="meal" aria-haspopup="listbox" aria-expanded="false" aria-labelledby="meal-label meal">Standard</button>
<ul id="meal-options" role="listbox" aria-labelledby="meal-label" hidden>
<li role="option" aria-selected="true">Standard</li>
<li role="option" aria-selected="false">Vegetarian</li>
<li role="option" aria-selected="false">Vegan</li>
</ul>
</div>
<fieldset>
<legend>Cabin class</legend>
<label class="choice"><input type="radio" name="cabin" value="economy" checked /> Economy</label>
<label class="choice"><input type="radio" name="cabin" value="business" /> Business</label>
</fieldset>
<label class="choice"><input type="checkbox" id="terms" /> I accept the terms</label>
<label class="choice"><input type="checkbox" id="offers" checked /> Send me travel offers</label>
<label class="choice"><input type="checkbox" id="sms" /> Text me flight updates</label>
<label for="passport">Passport scan</label>
<input id="passport" type="file" />
<label for="documents">Travel documents</label>
<input id="documents" type="file" multiple />
<button type="submit" data-testid="check-in">Check in</button>
</form>
<p class="error" hidden>Accept the terms to check in.</p>
<p class="result" hidden></p>
</main>
<script>
// Содержимое в теневом DOM: локаторы Playwright проходят его границу сами.
customElements.define(
'baggage-allowance',
class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' }).innerHTML = '<p>Baggage allowance: 23 kg</p>';
}
},
);

// Список питания собран не на <select>: select_option с ним не работает,
// выбирают двумя кликами, по кнопке и по варианту.
const meal = document.getElementById('meal');
const options = document.getElementById('meal-options');
meal.addEventListener('click', () => {
options.hidden = !options.hidden;
meal.setAttribute('aria-expanded', String(!options.hidden));
});
for (const option of options.querySelectorAll('[role="option"]')) {
option.addEventListener('click', () => {
for (const other of options.children) other.setAttribute('aria-selected', 'false');
option.setAttribute('aria-selected', 'true');
meal.textContent = option.textContent;
options.hidden = true;
meal.setAttribute('aria-expanded', 'false');
});
}

// Подтверждение приходит через секунду, как от настоящего сервера:
// assert сразу после клика его не застаёт, expect дожидается.
document.getElementById('check-in-form').addEventListener('submit', (event) => {
event.preventDefault();
const error = document.querySelector('.error');
const result = document.querySelector('.result');
result.hidden = true;
error.hidden = document.getElementById('terms').checked;
if (!error.hidden) return;
setTimeout(() => {
result.textContent = 'Checked in';
result.hidden = false;
}, 1000);
});
</script>
40 changes: 40 additions & 0 deletions custom-server/assets/ui-pages/python-playwright/extras.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<main class="example">
<h1>Extras</h1>
<p>Selected extras: <span data-testid="extras-count">0</span></p>
<ul id="extras">
<li class="extra"><h3>Priority boarding</h3><p class="price">15 EUR</p><button type="button">Add to trip</button></li>
<li class="extra"><h3>Extra legroom</h3><p class="price">30 EUR</p><button type="button">Add to trip</button></li>
<li class="extra"><h3>Lounge access</h3><p class="price">40 EUR</p><button type="button">Add to trip</button></li>
<li class="extra"><h3>Checked bag</h3><p class="price">25 EUR</p><button type="button">Add to trip</button></li>
</ul>
<form id="promo">
<label for="promo-code">Promo code</label>
<input id="promo-code" />
<button type="submit">Apply</button>
</form>
<p id="promo-result" role="status"></p>
</main>
<script>
const count = document.querySelector('[data-testid="extras-count"]');
for (const button of document.querySelectorAll('.extra button')) {
button.addEventListener('click', () => {
button.textContent = 'Added';
button.disabled = true;
count.textContent = String(Number(count.textContent) + 1);
});
}

// Промокод действует до конца 2026 года по часам браузера, поэтому
// page.clock.set_fixed_time переключает ответ без ожидания реальной даты.
document.getElementById('promo').addEventListener('submit', (event) => {
event.preventDefault();
const result = document.getElementById('promo-result');
if (document.getElementById('promo-code').value.trim() !== 'WINTER26') {
result.textContent = 'Unknown promo code';
} else if (new Date() < new Date(2027, 0, 1)) {
result.textContent = '20% off';
} else {
result.textContent = 'Promo code expired';
}
});
</script>
57 changes: 47 additions & 10 deletions custom-server/assets/ui-pages/python-playwright/index.html
Original file line number Diff line number Diff line change
@@ -1,23 +1,60 @@
<main>
<a href="{{prefix}}/login">My trips</a>
<h1 class="heading">Departures</h1>
<p id="timezone">Times are shown in your time zone.</p>
<p>Airport time: <span data-testid="current-time"></span></p>
<p><span id="flights-count" title="Flights today"></span></p>
<table id="departures">
<thead>
<tr><th>Flight</th><th>Destination</th><th>Time</th><th>Status</th></tr>
<tr><th>Flight</th><th>Destination</th><th>Time</th><th>Status</th><th>Gate</th></tr>
</thead>
<tbody>
<tr data-departure="2026-01-15T08:30:00Z"><td>SK 204</td><td>Lisbon</td><td class="time"></td><td>On time</td></tr>
<tr data-departure="2026-01-15T09:10:00Z"><td>SK 318</td><td>Oslo</td><td class="time"></td><td>Boarding</td></tr>
<tr data-departure="2026-01-15T11:45:00Z"><td>SK 527</td><td>Istanbul</td><td class="time"></td><td>Delayed</td></tr>
</tbody>
<tbody></tbody>
</table>
<p id="empty" hidden>No departures right now.</p>
<p id="error" hidden>Departures are unavailable. Try again later.</p>
</main>
<aside aria-label="Travel alerts">
<h2>Travel alerts</h2>
<p>Expect longer security lines on Friday morning.</p>
</aside>
<script>
// Время вылета хранится в UTC и печатается в часовом поясе браузера, поэтому
// timezone_id контекста Playwright меняет то, что видно на табло.
const format = new Intl.DateTimeFormat(undefined, { hour: '2-digit', minute: '2-digit', timeZoneName: 'short' });
for (const row of document.querySelectorAll('#departures tbody tr')) {
row.querySelector('.time').textContent = format.format(new Date(row.dataset.departure));
}
const clock = document.querySelector('[data-testid="current-time"]');
const tick = () => {
clock.textContent = new Date().toLocaleTimeString('en-GB', { hour12: false });
};
tick();
setInterval(tick, 1000);

// Рейсы приходят отдельным запросом: урок про моки подменяет его ответ
// через page.route и видит пустое табло или ошибку загрузки.
const render = (flights) => {
const body = document.querySelector('#departures tbody');
for (const item of flights) {
const row = document.createElement('tr');
row.dataset.departure = item.departure;
const slug = item.status.toLowerCase().replaceAll(' ', '-');
row.innerHTML = `<td data-testid="flight-number"></td><td></td><td class="time"></td><td class="status status-${slug}"></td><td></td>`;
const cells = row.querySelectorAll('td');
cells[0].textContent = item.flight;
cells[1].textContent = item.destination;
cells[2].textContent = format.format(new Date(item.departure));
cells[3].textContent = item.status;
cells[4].textContent = item.gate;
body.append(row);
}
document.getElementById('flights-count').textContent = `${flights.length} flights`;
document.getElementById('empty').hidden = flights.length > 0;
};

fetch('{{prefix}}/api/departures')
.then((response) => {
if (!response.ok) throw new Error(String(response.status));
return response.json();
})
.then(render)
.catch(() => {
document.getElementById('error').hidden = false;
});
</script>
1 change: 1 addition & 0 deletions custom-server/assets/ui-pages/python-playwright/logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
37 changes: 37 additions & 0 deletions custom-server/assets/ui-pages/python-playwright/packing.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<main class="example">
<h1>Packing list</h1>
<input id="new-item" aria-label="New item" placeholder="What do you need to pack?" autofocus />
<ul id="items"></ul>
<p data-testid="items-left">Nothing to pack yet</p>
</main>
<script>
const input = document.getElementById('new-item');
const list = document.getElementById('items');
const counter = document.querySelector('[data-testid="items-left"]');

const update = () => {
const left = list.querySelectorAll('input:not(:checked)').length;
const total = list.children.length;
counter.textContent = total === 0 ? 'Nothing to pack yet' : `${left} of ${total} left to pack`;
};

input.addEventListener('keydown', (event) => {
const title = input.value.trim();
if (event.key !== 'Enter' || !title) return;
const item = document.createElement('li');
item.dataset.testid = 'item';
item.innerHTML = '<input type="checkbox" aria-label="Packed" /><label data-testid="item-title"></label><button type="button">Delete</button>';
item.querySelector('label').textContent = title;
item.querySelector('input').addEventListener('change', (change) => {
item.classList.toggle('packed', change.target.checked);
update();
});
item.querySelector('button').addEventListener('click', () => {
item.remove();
update();
});
list.append(item);
input.value = '';
update();
});
</script>
Loading
Loading