Files
laysense.cn/tests/studio-browser.cjs

604 lines
36 KiB
JavaScript

'use strict';
const assert = require('node:assert/strict');
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const baseURL = process.env.LAYSENSE_TEST_URL || 'http://127.0.0.1:8787';
const email = process.env.LAYSENSE_TEST_EMAIL;
const password = process.env.LAYSENSE_TEST_PASSWORD;
if (!email || !password) {
throw new Error('Set LAYSENSE_TEST_EMAIL and LAYSENSE_TEST_PASSWORD for a disposable test database.');
}
async function run(browser) {
const context = await browser.newContext({baseURL, viewport: {width: 1480, height: 960}, reducedMotion: 'reduce'});
const page = await context.newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.goto('/admin/login');
await page.locator('[name=email]').fill(email);
await page.locator('[name=password]').fill(password);
await page.locator('form button[type=submit]').click();
await page.waitForURL('**/admin');
const csrf = await page.locator('[name=csrf]').first().inputValue();
const slug = 'studio-browser-' + Date.now().toString(36);
async function post(path, values) {
const response = await context.request.post(path, {
form: {csrf, ...values},
headers: {'X-Requested-With': 'XMLHttpRequest'},
});
assert.equal(response.status(), 200, await response.text());
return response.json();
}
await post('/admin/new-page', {slug, name: '画布测试页'});
await page.goto('/admin');
const dashboard = page.locator('[data-page-list]');
const settingsLinks = page.getByRole('region', {name: '站点编辑'}).locator('.dashboard-setting-buttons .button');
assert.deepEqual(await settingsLinks.evaluateAll((links) => links.map((link) => link.getAttribute('href'))), [
'/admin/settings/header', '/admin/settings/footer', '/admin/settings/cdn', '/admin/media',
]);
await dashboard.locator('[data-page-search]').fill(slug);
assert.equal(await dashboard.locator('[data-page-item]:visible').count(), 1);
const draft = dashboard.locator('[data-page-item]:visible');
assert.equal(await draft.getAttribute('data-page-item'), 'draft');
assert.equal(await draft.getByRole('link', {name: '预览'}).getAttribute('href'), '/admin/pages/' + slug + '/preview');
await dashboard.locator('[data-page-status]').selectOption('published');
await dashboard.locator('[data-page-empty]').waitFor({state: 'visible'});
await dashboard.locator('[data-page-status]').selectOption('draft');
assert.equal(await dashboard.locator('[data-page-item]:visible').count(), 1);
assert.equal(await page.getByRole('navigation', {name: '后台导航'}).getByRole('link', {name: '页面'}).getAttribute('aria-current'), 'page');
await post('/admin/page-blocks/' + slug, {operation: 'create', key: 'fixtures', preset: 'text'});
await post('/admin/page-blocks/' + slug, {operation: 'create', key: 'fee-sample', preset: 'existing-sc-pricing'});
await post('/admin/pages/' + slug + '/fixtures', {
version: '0', title: '媒体和链接', lead: '', style: 'plain',
body: '<p><img src="/assets/favicon.png" alt="示例图片" width="96"></p>'
+ '<p><a href="/services">示例链接</a></p>'
+ '<p id="copy-fixture">待复制段落</p><p>待删除段落</p>'
+ '<video controls width="260" preload="none"><source src="/assets/original/drag-in-components.mp4"></video>'
+ '<audio controls src="/assets/original/drag-in-components.mp4" preload="none"></audio>',
});
const editorPath = '/admin/pages/' + slug;
await page.goto(editorPath);
const version = await page.locator('#studio-page-settings [name=version]').inputValue();
await post(editorPath, {
version, name: '画布测试页', status: 'draft', title: '画布测试页',
description: '', heading: '画布测试页', accent: '', lead: '待删除的首屏简介',
image: '/assets/original/home-hero.webp', alt: '首屏示例', image_scale: '0',
});
await page.reload();
const frame = page.frameLocator('iframe[title="可编辑页面画布"]');
const sizing = page.locator('[data-media-sizing]');
const properties = page.locator('[data-canvas-properties]');
const tools = page.getByRole('group', {name: '所选元素'});
const align = (label) => tools.getByRole('button', {name: label, exact: true}).click();
const closeProperties = () => properties.locator('[data-property-close]').click();
const image = frame.locator('#fixtures img');
await image.click();
await sizing.waitFor({state: 'visible'});
assert.equal(await image.getAttribute('data-studio-selected'), '');
const handle = page.getByRole('slider', {name: '媒体宽度'});
const initial = await image.boundingBox();
const grip = await handle.boundingBox();
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
await page.mouse.down();
await page.mouse.move(grip.x + grip.width / 2 + 145, grip.y + grip.height / 2, {steps: 8});
assert((await image.boundingBox()).width > initial.width + 100);
await page.mouse.up();
const imageSize = await image.getAttribute('class');
assert.match(imageSize, /studio-media-\d+/);
assert.notEqual(imageSize, 'studio-media-100');
await image.dblclick();
await properties.waitFor({state: 'visible'});
assert.equal(await properties.locator('h2').textContent(), '正文图片');
await properties.locator('[name=url]').fill('/assets/original/home-hero.webp');
await properties.locator('button[type=submit]').click();
assert.equal(await image.getAttribute('src'), '/assets/original/home-hero.webp');
await image.click();
await align('居右');
const rightEdge = await image.boundingBox();
const leftHandle = await handle.boundingBox();
assert(Math.abs(rightEdge.x - (leftHandle.x + leftHandle.width / 2)) < 2);
await align('居中');
const centeredImage = await image.evaluate((node) => {
const bounds = node.getBoundingClientRect();
const parent = node.parentElement.getBoundingClientRect();
return Math.abs((bounds.left + bounds.right) / 2 - (parent.left + parent.right) / 2) < 2;
});
assert(centeredImage);
const hero = frame.locator('[data-studio-hero-image]');
await page.locator('iframe[title="可编辑页面画布"]').evaluate((iframe) => iframe.contentWindow.scrollTo(0, 0));
await hero.click();
await sizing.waitFor({state: 'visible'});
assert.equal(await hero.getAttribute('data-studio-selected'), '');
await handle.press('ArrowLeft');
assert.equal(await page.locator('[name=image_scale]').inputValue(), '99');
await sizing.locator('[data-replace-media]').click();
assert.equal(await properties.locator('h2').textContent(), '首屏图片');
await closeProperties();
const heroTitle = frame.locator('[data-studio-field=heading]');
await heroTitle.click();
await align('居右');
assert.equal(await heroTitle.evaluate((node) => getComputedStyle(node.parentElement).textAlign), 'right');
await frame.locator('#fixtures a').click();
await tools.getByRole('button', {name: '属性'}).click();
await properties.waitFor({state: 'visible'});
assert.equal(await properties.locator('h2').textContent(), '正文链接');
await properties.locator('[name=url]').fill('/articles');
await properties.locator('button[type=submit]').click();
assert.equal(await frame.locator('#fixtures a').getAttribute('href'), '/articles');
for (const [tag, label] of [['video', '视频'], ['audio', '音频']]) {
const media = frame.locator('#fixtures ' + tag);
await media.dispatchEvent('dblclick');
await properties.waitFor({state: 'visible'});
assert.equal(await properties.locator('h2').textContent(), label);
await closeProperties();
}
const copyText = frame.locator('#fixtures').getByText('待复制段落', {exact: true});
await copyText.click();
await align('居中');
await align('居左');
assert.equal(await copyText.evaluate((node) => getComputedStyle(node).textAlign), 'left');
await align('居右');
assert.equal(await copyText.evaluate((node) => getComputedStyle(node).textAlign), 'right');
await tools.getByRole('button', {name: '复制'}).click();
assert.equal(await copyText.count(), 2);
assert.equal(await frame.locator('#copy-fixture').count(), 1);
const oldParagraph = frame.getByText('待删除段落', {exact: true});
await oldParagraph.click();
await tools.getByRole('button', {name: '删除'}).click();
assert.equal(await oldParagraph.count(), 0);
await frame.getByText('待删除的首屏简介', {exact: true}).click();
await tools.getByRole('button', {name: '删除'}).click();
assert.equal(await page.locator('[name=lead]').inputValue(), '');
const sectionTitle = frame.locator('#fixtures [data-studio-part=title]');
await sectionTitle.click();
await align('居中');
assert.equal(await sectionTitle.evaluate((node) => getComputedStyle(node).textAlign), 'center');
const gallery = page.locator('[data-canvas-presets]');
const modules = gallery.locator('[data-library-panel=modules]');
const elements = gallery.locator('[data-library-panel=elements]');
const moduleTab = gallery.getByRole('tab', {name: '组件'});
const elementTab = gallery.getByRole('tab', {name: '元素'});
const backToModules = () => modules.getByRole('button', {name: '返回分类'}).click();
const openModule = (key) => modules.locator('[data-library-category="' + key + '"]').click();
assert.equal(await modules.locator('[data-library-category]:visible').count(), 7);
assert.equal(await modules.locator('[data-template-card]:visible').count(), 0);
assert.equal(await modules.locator('[data-template-card]').count(), 59);
assert.equal(await modules.locator('[data-canvas-template^=existing-pagepan]').count(), 0);
assert.equal(await modules.locator('[data-canvas-template=existing-highspeaker-registration]').count(), 0);
assert.equal(await modules.locator('[data-canvas-template=existing-highspeaker-features]').getAttribute('data-template-title'), '特性组');
assert.equal(await modules.getByText('按锚点新建区块').count(), 1);
assert.equal(await gallery.locator('[data-library-panel=layers]').getByText(/首屏与目录|按锚点新建区块/).count(), 0);
assert.equal(await page.locator('#studio-page-settings').getByText('首屏与目录').count(), 1);
await copyText.first().click();
await moduleTab.press('ArrowRight');
assert.equal(await elementTab.getAttribute('aria-selected'), 'true');
assert.equal(await elements.locator('[data-library-category]:visible').count(), 4);
assert.equal(await elements.locator('[data-canvas-element]:visible').count(), 0);
const structural = elements.locator('[data-library-category=structure-elements]');
await structural.click();
assert.equal(await elements.locator('[data-library-category]:visible').count(), 0);
assert.equal(await elements.locator('[data-canvas-element]:visible').count(), 12);
await elements.getByRole('button', {name: '插入分割线'}).click();
await frame.locator('#fixtures .studio-divider').waitFor();
await elements.getByRole('button', {name: '插入留白'}).click();
await frame.locator('#fixtures .studio-spacer').waitFor();
await elements.getByRole('button', {name: '返回分类'}).click();
assert(await structural.evaluate((button) => button === document.activeElement));
await moduleTab.click();
const brokenPreviews = await modules.locator('[data-template-card] img').evaluateAll(async (images) => {
for (const image of images) image.loading = 'eager';
await Promise.all(images.map((image) => image.decode()));
return images.filter((image) => image.naturalWidth !== 768).length;
});
assert.equal(brokenPreviews, 0);
await openModule('cover');
assert.equal(await modules.locator('[data-template-card]:visible').count(), 7);
const cover = gallery.locator('[data-template-preview=cover]');
await cover.hover();
const peek = gallery.locator('[data-template-peek]');
await peek.waitFor({state: 'visible'});
assert((await peek.boundingBox()).width > (await cover.boundingBox()).width);
await cover.focus();
await page.keyboard.press('Enter');
const dialog = gallery.locator('[data-template-dialog]');
await dialog.waitFor({state: 'visible'});
assert.equal(await dialog.locator('h2').textContent(), '图文封面');
await dialog.locator('[data-template-use]').click();
await frame.locator('section[id^=block-] h2').filter({hasText: '图文封面'}).waitFor();
await backToModules();
await openModule('layout');
const search = modules.locator('[data-template-search]');
await search.fill('does-not-exist');
await modules.locator('[data-template-empty]').waitFor({state: 'visible'});
await search.fill('双栏');
assert.equal(await modules.locator('[data-template-card]:visible').count(), 1);
await search.fill('重点提示');
await modules.locator('[data-template-empty]').waitFor({state: 'visible'});
await backToModules();
await openModule('details');
await modules.locator('[data-canvas-template=pricing]').click();
await frame.locator('.studio-pricing').waitFor();
await modules.locator('[data-canvas-template=existing-sc-materials]').click();
await frame.locator('section[id^=block-]').filter({hasText: '申请软著需要哪些材料'}).waitFor();
await modules.locator('[data-canvas-template=existing-sc-pricing]').click();
const reused = frame.locator('section[id^=block-]').filter({hasText: '服务方案与价格'});
const reusedId = await reused.getAttribute('id');
assert.equal(await reused.locator('#' + reusedId + '-price1').count(), 1);
assert.equal(await frame.locator('#fee-sample-price1').count(), 1);
await backToModules();
await openModule('content');
await search.fill('重点提示');
await modules.locator('[data-canvas-template=notice]').click();
await frame.locator('.studio-notice').waitFor();
await search.fill('分类文章');
await modules.locator('[data-canvas-template=articles]').click();
await frame.locator('section[id^=block-] h2').filter({hasText: '分类文章'}).waitFor();
await Promise.all([
page.waitForResponse((response) => response.url().endsWith(editorPath) && response.request().method() === 'POST' && response.ok()),
page.getByRole('button', {name: '保存页面', exact: true}).first().click(),
]);
await page.locator('[data-save-confirmation]').waitFor({state: 'visible'});
await frame.locator('section[id^=block-] .studio-cover').waitFor();
assert.equal(await frame.locator('#fixtures a').getAttribute('href'), '/articles');
assert.equal(await frame.locator('#fixtures img').getAttribute('src'), '/assets/original/home-hero.webp');
assert.deepEqual((await image.getAttribute('class')).split(/\s+/).sort(), [imageSize, 'studio-align-center'].sort());
assert.equal(await heroTitle.evaluate((node) => getComputedStyle(node.parentElement).textAlign), 'right');
assert.equal(await sectionTitle.evaluate((node) => getComputedStyle(node).textAlign), 'center');
assert.deepEqual(await copyText.evaluateAll((nodes) => nodes.map((node) => getComputedStyle(node).textAlign)), ['right', 'right']);
await frame.locator('.studio-notice').waitFor();
await frame.locator('#fixtures .studio-divider').waitFor();
await frame.locator('#fixtures .studio-spacer').waitFor();
await frame.locator('.studio-pricing').waitFor();
assert.match(await frame.locator('[data-visual]').getAttribute('class'), /studio-media-99/);
assert.equal(await copyText.count(), 2);
assert.equal(await frame.locator('#copy-fixture').count(), 1);
assert.equal(await oldParagraph.count(), 0);
assert.equal(await page.locator('[name=lead]').inputValue(), '');
const feedSection = frame.locator('section[id^=block-]').filter({hasText: '分类文章'});
const feedId = await feedSection.getAttribute('id');
await feedSection.locator('.article-list').waitFor();
const phone = await browser.newContext({
baseURL, viewport: {width: 390, height: 844}, isMobile: true, hasTouch: true,
storageState: await context.storageState(),
});
const phonePage = await phone.newPage();
phonePage.on('pageerror', (error) => errors.push(error.message));
await phonePage.goto(editorPath);
const phoneGallery = phonePage.locator('[data-canvas-presets]');
await phoneGallery.locator('[data-library-category=cover]').tap();
await phoneGallery.locator('[data-template-preview=banner]').tap();
await phoneGallery.locator('[data-template-dialog]').waitFor({state: 'visible'});
assert.equal(await phoneGallery.locator('[data-template-dialog] h2').textContent(), '横幅');
await phonePage.goto(editorPath + '#blocks');
assert.equal(await phoneGallery.getByRole('tab', {name: '图层'}).getAttribute('aria-selected'), 'true');
assert(await phoneGallery.locator('#blocks').evaluate((details) => details.open));
await phone.close();
await verifyArticleLibrary(browser, context, page, post, slug, feedId);
await verifyHomeModules(context, page);
assert.deepEqual(errors, []);
await context.close();
}
async function verifyArticleLibrary(browser, context, page, post, slug, feedId) {
const category = String(Date.now());
await post('/admin/article-categories', {slug: category, name: '自定义测试分类'});
const articleSlug = slug + '-article';
await page.goto('/admin/articles/new');
const editor = page.locator('[data-editor-host]');
const markdown = editor.locator('.toastui-editor-md-container .ProseMirror');
const preview = editor.locator('.toastui-editor-md-preview');
await markdown.waitFor();
await preview.waitFor();
await page.locator('[name=title]').fill('测试 Markdown 和富文本');
await page.locator('[name=slug]').fill(articleSlug);
await page.locator('[name="categories[]"][value="' + category + '"]').check();
await page.locator('[name="categories[]"][value=product]').check();
await page.locator('[name=status]').selectOption('published');
await markdown.fill('**Markdown 分屏**');
await preview.locator('strong').getByText('Markdown 分屏').waitFor();
await page.getByRole('button', {name: '保存文章'}).click();
await page.waitForURL(/\/admin\/articles\/\d+/);
const articleAdmin = new URL(page.url()).pathname;
const publishedPath = '/articles/' + articleSlug;
const sourcePage = await context.newPage();
await sourcePage.goto(publishedPath);
assert.equal(await sourcePage.locator('[itemprop=articleSection]').count(), 3);
await sourcePage.locator('[itemprop=articleBody] strong').getByText('Markdown 分屏').waitFor();
await page.goto(articleAdmin);
await editor.locator('.toastui-editor-mode-switch').getByText('所见即所得', {exact: true}).click();
const rich = editor.locator('.toastui-editor-ww-container .ProseMirror');
await rich.waitFor();
await rich.press('End');
await page.keyboard.insertText(' 富文本');
await page.getByRole('button', {name: '从媒体库插入图片'}).click();
await page.locator('[data-media-query]').fill('favicon.png');
page.once('dialog', (dialog) => dialog.accept('媒体库图片'));
await page.locator('.picker-item', {hasText: 'favicon.png'}).click();
await rich.locator('img[alt="媒体库图片"]').waitFor();
await page.getByRole('button', {name: '保存文章'}).click();
await page.locator('[data-save-confirmation]').waitFor({state: 'visible'});
await page.reload();
await rich.waitFor();
assert.equal(await page.locator('[name=body_format]').inputValue(), 'html');
await sourcePage.reload();
assert.match(await sourcePage.locator('[itemprop=articleBody]').textContent(), /Markdown 分屏 富文本/);
await sourcePage.locator('[itemprop=articleBody] img[alt="媒体库图片"]').waitFor();
const sectionPath = '/admin/pages/' + slug + '/' + feedId;
await page.goto(sectionPath);
await page.locator('[name=feed_mode]').selectOption('merged');
await page.locator('[name="feed_categories[]"][value=announcement]').uncheck();
await page.locator('[name="feed_categories[]"][value=product]').uncheck();
await page.locator('[name="feed_categories[]"][value="' + category + '"]').check();
await page.getByRole('button', {name: '保存区块'}).click();
await page.locator('[data-save-confirmation]').waitFor({state: 'visible'});
assert(await page.locator('[name="feed_categories[]"][value="' + category + '"]').isChecked());
let contentVersion = await page.locator('[name=version]').inputValue();
assert.equal(contentVersion, '1');
const canvasPath = '/admin/pages/' + slug + '/preview';
await sourcePage.goto(canvasPath);
const feed = sourcePage.locator('#' + feedId + ' .article-feed');
assert.equal(await feed.locator('a[href="' + publishedPath + '"]').count(), 1);
assert.equal(await feed.getByRole('tab').count(), 0);
await page.locator('[name=feed_mode]').selectOption('tabs');
await page.getByRole('button', {name: '保存区块'}).click();
await page.locator('[data-save-confirmation]').waitFor({state: 'visible'});
contentVersion = await page.locator('[name=version]').inputValue();
assert.equal(contentVersion, '2');
await sourcePage.reload();
const customTab = feed.getByRole('tab', {name: '自定义测试分类'});
await customTab.waitFor();
await feed.getByRole('tab', {name: '新闻'}).press('ArrowRight');
assert.equal(await customTab.getAttribute('aria-selected'), 'true');
assert.equal(await feed.getByRole('tabpanel').count(), 1);
assert.equal(await feed.locator('a[href="' + publishedPath + '"]:visible').count(), 1);
const noJS = await browser.newContext({baseURL, javaScriptEnabled: false, storageState: await context.storageState()});
const noJSPage = await noJS.newPage();
await noJSPage.goto(canvasPath);
assert.equal(await noJSPage.locator('#' + feedId + ' a[href="' + publishedPath + '"]:visible').count(), 2);
await noJS.close();
assert((await context.request.get('/articles/category/' + category)).ok());
await verifyScopedArchive(context, page, sourcePage, post, slug, feedId, category, publishedPath);
await verifyEditableLandingPages(page, sourcePage, category, publishedPath, slug);
await sourcePage.goto('/network');
assert.equal(await sourcePage.locator('.network-group').count(), 2);
await sourcePage.close();
await page.goto(articleAdmin);
const deletePath = articleAdmin + '/delete';
const deleteForm = page.locator('form[action="' + deletePath + '"]');
const version = await deleteForm.locator('[name=version]').inputValue();
const csrf = await deleteForm.locator('[name=csrf]').inputValue();
const headers = {'X-Requested-With': 'XMLHttpRequest'};
assert.equal((await context.request.post(deletePath, {form: {version}, headers})).status(), 403);
assert.equal((await context.request.post(deletePath, {form: {csrf, version: String(Number(version) + 1)}, headers})).status(), 409);
assert.equal((await context.request.get(publishedPath)).status(), 200);
await page.getByText('删除文章', {exact: true}).click();
await deleteForm.getByRole('button', {name: '永久删除'}).click();
await page.waitForURL('**/admin/articles?deleted=1');
await page.getByText('文章已删除。', {exact: true}).waitFor();
assert.equal(await page.locator('a[href="' + articleAdmin + '"]').count(), 0);
assert.equal((await context.request.get(articleAdmin)).status(), 404);
assert.equal((await context.request.get(publishedPath)).status(), 404);
assert(!(await (await context.request.get('/sitemap.xml')).text()).includes(publishedPath + '</loc>'));
}
async function verifyEditableLandingPages(admin, publicPage, category, articlePath, slug) {
await publicPage.goto('/articles');
const defaultLinks = publicPage.locator('#updates .article-list a');
assert.equal(await defaultLinks.filter({hasText: 'LayFi'}).count(), 0);
assert.equal(await defaultLinks.filter({hasText: 'PAGEPAN 小飞页'}).count(), 0);
await admin.goto('/admin/pages/articles');
const frame = admin.frameLocator('iframe[title="可编辑页面画布"]');
await frame.locator('#updates h2').click();
const tools = admin.getByRole('group', {name: '所选元素'});
await tools.getByRole('button', {name: '模块设置'}).click();
const settings = admin.locator('[data-module-dialog]');
for (const option of await settings.locator('[name="feed_categories[]"]').all()) await option.uncheck();
await settings.locator('[name="feed_categories[]"][value="' + category + '"]').check();
await settings.locator('[name=feed_limit]').fill('30');
await settings.getByRole('button', {name: '应用'}).click();
await admin.getByRole('button', {name: '保存页面', exact: true}).first().click();
await admin.locator('[data-save-confirmation]').waitFor();
await publicPage.reload();
assert.equal(await publicPage.locator('#updates a[href="' + articlePath + '"]').count(), 1);
assert.equal(await publicPage.locator('#updates a[href="/articles/' + slug + '-excluded"]').count(), 0);
const allUpdates = publicPage.locator('#updates').getByRole('link', {name: '查看全部动态'});
assert.equal(await allUpdates.getAttribute('href'), '/articles/feed/articles/updates');
await allUpdates.click();
await publicPage.waitForURL('**/articles/feed/articles/updates');
const archiveLinks = publicPage.locator('.article-list a');
const excludedPath = '/articles/' + slug + '-excluded';
assert.equal(await archiveLinks.filter({hasText: '分类分页样例 20'}).count(), 1);
assert.equal(await publicPage.locator('.article-list a[href="' + excludedPath + '"]').count(), 0);
await publicPage.getByRole('link', {name: '下一页'}).click();
await publicPage.waitForURL('**/articles/feed/articles/updates?page=2');
assert.equal(await publicPage.locator('.article-list a[href="' + articlePath + '"]').count(), 1);
assert.equal(await publicPage.locator('.article-list a[href="' + excludedPath + '"]').count(), 0);
assert.equal((await publicPage.request.get('/articles/feed/articles/updates?category=announcement')).status(), 404);
await admin.goto('/admin/pages/services');
await frame.locator('#catalog h2').click();
await tools.getByRole('button', {name: '模块设置'}).click();
assert.equal(await settings.locator('[name=feed_mode]').inputValue(), 'catalog');
assert(await settings.locator('[name="feed_categories[]"][value=services]').isChecked());
await settings.locator('[name=module_title]').fill('产品目录验证');
await settings.getByRole('button', {name: '应用'}).click();
await admin.getByRole('button', {name: '保存页面', exact: true}).first().click();
await admin.locator('[data-save-confirmation]').waitFor();
await publicPage.goto('/services');
await publicPage.getByRole('heading', {name: '产品目录验证'}).waitFor();
const cards = publicPage.locator('#catalog .catalog-card');
assert(await cards.count() > 0);
assert.equal(await cards.getByRole('link', {name: '查看详情', exact: true}).count(), 0);
assert.equal(await cards.locator('a[href="/pagepan#download"]').count(), 1);
await admin.goto('/admin/pages/contact');
await frame.locator('#contact-information a[href="mailto:public@laysense.cn"]').waitFor();
await publicPage.goto('/contact');
await publicPage.getByRole('heading', {name: '联系来笙', exact: true}).waitFor();
assert.equal(await publicPage.locator('#contact-information a[href="mailto:public@laysense.cn"]').count(), 1);
}
async function verifyScopedArchive(context, admin, page, post, slug, feedId, category, articlePath) {
const scope = '/articles/feed/' + slug + '/' + feedId;
const scopedResponse = (query = '') => context.request.get(scope + query);
assert.equal((await scopedResponse()).status(), 404);
await admin.goto('/admin/pages/' + slug);
await admin.locator('[name=description]').fill('公开文章区块筛选测试。');
await admin.locator('[name=status]').selectOption('published');
await admin.getByRole('button', {name: '保存页面', exact: true}).first().click();
await admin.locator('[data-save-confirmation]').waitFor({state: 'visible'});
const excluded = await post('/admin/articles/new', {
title: '分类范围外测试文章', slug: slug + '-excluded', body_format: 'markdown',
body: '只属于公告分类。', status: 'published', 'categories[]': 'announcement',
});
assert(excluded.redirect);
await page.goto('/' + slug);
const archiveLink = page.locator('#' + feedId).getByRole('link', {name: '查看全部动态'});
assert.equal(await archiveLink.getAttribute('href'), scope);
await archiveLink.click();
await page.waitForURL('**' + scope);
const list = page.locator('main .article-list');
assert.equal(await list.locator('a[href="' + articlePath + '"]').count(), 1);
assert.equal(await list.locator('a[href="/articles/' + slug + '-excluded"]').count(), 0);
assert.doesNotMatch(await list.locator('a[href="' + articlePath + '"] .article-category').textContent(), /产品/);
const filters = page.getByRole('navigation', {name: '动态分类'});
assert.deepEqual(await filters.getByRole('link').allTextContents(), ['全部', '新闻', '自定义测试分类']);
assert.equal((await scopedResponse('?category=announcement')).status(), 404);
assert.equal((await scopedResponse('?category[]=news')).status(), 404);
assert.equal((await scopedResponse('?categories=announcement')).status(), 200);
assert.doesNotMatch(await (await scopedResponse('?categories=announcement')).text(), /分类范围外测试文章/);
for (let index = 0; index < 21; index++) {
await post('/admin/articles/new', {
title: '分类分页样例 ' + index, slug: slug + '-sample-' + index, body_format: 'markdown',
body: '所选分类中的分页样例。', status: 'published', 'categories[]': category,
});
}
const categoryPath = scope + '?category=' + category;
await filters.getByRole('link', {name: '自定义测试分类'}).click();
await page.waitForURL('**' + categoryPath);
const next = page.getByRole('link', {name: '下一页'});
assert.equal(await next.getAttribute('href'), categoryPath + '&page=2');
await next.click();
await page.waitForURL('**' + categoryPath + '&page=2');
assert.equal(await list.locator('a').count(), 2);
assert.equal(await page.getByRole('link', {name: '上一页'}).getAttribute('href'), categoryPath);
assert.equal(await filters.getByRole('link', {name: '全部'}).getAttribute('href'), scope);
assert.equal(await page.getByRole('link', {name: '返回原页面'}).getAttribute('href'), '/' + slug + '#' + feedId);
}
async function verifyHomeModules(context, page) {
await page.goto('/admin/pages/home');
const frame = page.frameLocator('iframe[title="可编辑页面画布"]');
const tools = page.getByRole('group', {name: '所选元素'});
const directory = frame.locator('#hero-directory .hero-directory');
const cards = directory.locator(':scope > a');
const card = cards.nth(1);
assert.equal(await cards.count(), 5);
await card.click();
const edit = tools.getByRole('button', {name: '属性'});
assert.equal((await edit.textContent()).trim(), '');
await edit.click();
const props = page.locator('[data-canvas-properties]');
await props.locator('[name=label]').fill('PAGEPAN 导航验证');
await props.locator('[name=note]').fill('编辑过的导航说明');
await props.locator('[name=url]').fill('/pagepan#download');
await props.getByRole('button', {name: '应用'}).click();
assert.equal(await card.locator('small').textContent(), '编辑过的导航说明');
await cards.last().click();
await tools.getByRole('button', {name: '删除'}).click();
assert.equal(await cards.count(), 4);
await verifyDirectoryWidth(directory);
await frame.locator('#network h2').click();
const moduleSettings = tools.getByRole('button', {name: '模块设置'});
await moduleSettings.waitFor();
assert.equal(await tools.getByRole('button').allTextContents().then((items) => items.map((text) => text.trim()).join('')), '');
assert.equal(await tools.getByRole('button').count(), 3);
assert.equal(await frame.locator('#network h2').getAttribute('contenteditable'), null);
const copyButton = tools.getByRole('button', {name: '复制'});
await copyButton.click();
const pending = frame.locator('[data-studio-dynamic][id^=block-]').filter({hasText: '模块副本将在保存页面后生效。'});
const id = await pending.getAttribute('id');
await moduleSettings.click();
const dialog = page.locator('[data-module-dialog]');
await dialog.locator('[name=module_title]').fill('复制的伙伴模块');
await dialog.locator('[name=feed_limit]').fill('1');
await dialog.locator('[name="feed_categories[]"][value=supported-projects]').uncheck();
assert(await dialog.locator('[name="feed_categories[]"][value=partners]').isChecked());
await dialog.getByRole('button', {name: '应用'}).click();
await page.getByRole('button', {name: '保存页面', exact: true}).first().click();
await page.locator('[data-save-confirmation]').waitFor();
await frame.locator('#' + id + ' h2').getByText('复制的伙伴模块').waitFor();
const publicPage = await context.newPage();
await publicPage.goto('/');
const module = publicPage.locator('#' + id);
assert.equal(await module.locator('.network-group').count(), 1);
assert.equal(await module.locator('.network-list li').count(), 1);
assert.equal(await module.getByRole('link', {name: '查看全部'}).getAttribute('href'), '/articles/feed/home/' + id);
assert.equal(await publicPage.locator('#hero-directory a').nth(1).getAttribute('href'), '/pagepan#download');
assert.equal(await publicPage.locator('#hero-directory a').nth(1).locator('small').textContent(), '编辑过的导航说明');
const publicDirectory = publicPage.locator('#hero-directory .hero-directory');
assert.equal(await publicDirectory.locator(':scope > a').count(), 4);
await verifyDirectoryWidth(publicDirectory);
await publicPage.setViewportSize({width: 390, height: 844});
await verifyDirectoryWidth(publicDirectory);
assert.equal(await publicPage.locator('#network #supported-projects').count(), 1);
await page.bringToFront();
await frame.locator('#' + id + ' h2').click();
page.once('dialog', (prompt) => prompt.accept());
await tools.getByRole('button', {name: '删除'}).click();
await frame.locator('#' + id).waitFor({state: 'detached'});
await page.getByRole('button', {name: '保存页面', exact: true}).first().click();
await page.locator('[data-save-confirmation]').waitFor();
await publicPage.reload();
assert.equal(await publicPage.locator('#' + id).count(), 0);
assert.equal(await publicPage.locator('#network').count(), 1);
assert.equal((await context.request.get('/articles/feed/home/' + id)).status(), 404);
await publicPage.close();
}
async function verifyDirectoryWidth(directory) {
assert(await directory.evaluate((node) => {
const rightEdge = node.getBoundingClientRect().right - node.clientLeft;
const lastLink = node.lastElementChild.getBoundingClientRect();
return Math.abs(rightEdge - lastLink.right) < 1;
}));
}
(async () => {
const browser = await chromium.launch({executablePath: process.env.CHROMIUM_EXECUTABLE || undefined});
try {
await run(browser);
console.log('Passed Chromium dashboard, template library, dynamic modules, homepage link reflow, scoped archives, and article deletion.');
} finally {
await browser.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});