'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]'); 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/pages/' + slug + '/fixtures', { version: '0', title: '媒体和链接', lead: '', style: 'plain', body: '

示例图片

' + '

示例链接

' + '

待复制段落

待删除段落

' + '' + '', }); 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(), 26); 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(), 5); 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(), 3); 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 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); 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 sourcePage.goto('/services'); await sourcePage.locator('.catalog-card').first().waitFor(); await sourcePage.goto('/network'); assert.equal(await sourcePage.locator('.network-group').count(), 2); await sourcePage.close(); } 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 () => { const browser = await chromium.launch({executablePath: process.env.CHROMIUM_EXECUTABLE || undefined}); try { await run(browser); console.log('Passed Chromium dashboard, categorized library, canvas persistence, and scoped article archives.'); } finally { await browser.close(); } })().catch((error) => { console.error(error); process.exitCode = 1; });