@@ -0,0 +1,320 @@
const assert = require ( 'node:assert/strict' ) ;
const fs = require ( 'node:fs/promises' ) ;
const path = require ( 'node:path' ) ;
const { chromium , devices } = require ( process . env . PLAYWRIGHT _CORE _PATH || 'playwright-core' ) ;
const base = 'http://127.0.0.1:13011' ;
const output = process . env . AFFINE _TYPOGRAPHY _OUTPUT || path . join ( process . env . out , 'typography' ) ;
const expectedSizes = [ 32 , 24 , 20 , 16 , 14 , 13.6 ] ;
async function executable ( ) {
if ( process . env . PLAYWRIGHT _CHROMIUM _EXECUTABLE ) return process . env . PLAYWRIGHT _CHROMIUM _EXECUTABLE ;
if ( ! process . env . PLAYWRIGHT _BROWSERS _PATH ) return undefined ;
const names = await fs . readdir ( process . env . PLAYWRIGHT _BROWSERS _PATH ) ;
for ( const name of names . filter ( name => / ^ chromium - \ d + $ / . test ( name ) ) ) {
for ( const dir of [ 'chrome-linux64' , 'chrome-linux' ] ) {
const candidate = path . join ( process . env . PLAYWRIGHT _BROWSERS _PATH , name , dir , 'chrome' ) ;
if ( await fs . access ( candidate ) . then ( ( ) => true , ( ) => false ) ) return candidate ;
}
}
return undefined ;
}
async function fixture ( page ) {
assert . equal ( new URL ( page . url ( ) ) . origin , base , 'Fixture writes are restricted to the isolated loopback test server' ) ;
return page . locator ( 'editor-host' ) . evaluate ( host => {
const store = host . store ;
if ( /^[0-9a-f]{8}-[0-9a-f-]{27}$/i . test ( store . workspace . id ) ) {
throw new Error ( 'Refusing to change a server-backed workspace' ) ;
}
const Text = store . root . props . title . constructor ;
const ids = { headings : [ ] , records : [ ] } ;
store . transact ( ( ) => {
store . root . props . title . clear ( ) ;
store . root . props . title . insert ( 'Читаемые документы' , 0 ) ;
const note = store . addBlock ( 'affine:note' , { xywh : '[0,0,800,1600]' } , store . root . id , 0 ) ;
const paragraph = ( type , text ) => store . addBlock ( 'affine:paragraph' , {
type , text : new Text ( text ) ,
} , note ) ;
ids . headings . push ( paragraph ( 'h1' , [
{ insert : 'H1 Архитектура проекта ' } ,
{ insert : 'код' , attributes : { code : true } } ,
] ) ) ;
for ( const [ index , title ] of [ 'H2 Цели и ограничения' , 'H3 Детали реализации' , 'H4 Проверки' , 'H5 Примечания' , 'H6 Ссылки' ] . entries ( ) ) {
ids . headings . push ( paragraph ( ` h ${ index + 2 } ` , title ) ) ;
}
ids . body = paragraph ( 'text' , 'Понятная иерархия заголовков и свободные интервалы помогают читать проектные идеи. Этот текст остаётся обычным редактируемым блоком AFFiNE.' ) ;
ids . color = paragraph ( 'text' , [
{ insert : 'Сохраняются ' } ,
{ insert : 'красный' , attributes : { color : 'var(--affine-text-highlight-foreground-red)' } } ,
{ insert : ' цвет и ' } ,
{ insert : 'маркер' , attributes : {
color : 'var(--affine-text-highlight-foreground-orange)' ,
background : 'var(--affine-text-highlight-orange)' ,
} } ,
] ) ;
ids . code = paragraph ( 'text' , [
{ insert : 'Команда ' } ,
{ insert : 'nix build' , attributes : {
code : true , color : 'var(--affine-text-highlight-foreground-red)' ,
} } ,
{ insert : ' использует отдельное моноширинное оформление.' } ,
] ) ;
ids . quote = paragraph ( 'quote' , 'Цитата выделена вертикальной чертой, но сохраняет обычное редактирование и форматирование текста.' ) ;
ids . link = paragraph ( 'text' , [ { insert : 'Ссылка на описание' , attributes : { link : 'https://example.invalid/project' } } ] ) ;
ids . list = store . addBlock ( 'affine:list' , { type : 'bulleted' , text : new Text ( 'Первая идея' ) } , note ) ;
ids . nestedList = store . addBlock ( 'affine:list' , { type : 'bulleted' , text : new Text ( 'Уточнение идеи' ) } , ids . list ) ;
ids . todo = store . addBlock ( 'affine:list' , { type : 'todo' , checked : false , text : new Text ( 'Проверить реализацию' ) } , note ) ;
ids . formula = store . addBlock ( 'affine:latex' , { latex : 'x^2 + y^2 = z^2' } , note ) ;
const columns = Object . fromEntries ( Array . from ( { length : 5 } , ( _ , index ) => [
` typography-c ${ index } ` , { columnId : ` typography-c ${ index } ` , order : ` a ${ index } ` } ,
] ) ) ;
const rows = { 'typography-r0' : { rowId : 'typography-r0' , order : 'a0' } } ;
const cells = Object . fromEntries ( Object . keys ( columns ) . map ( ( column , index ) => [
` typography-r0: ${ column } ` , { text : new Text ( ` Столбец ${ index + 1 } ` ) } ,
] ) ) ;
ids . table = store . addBlock ( 'affine:table' , { columns , rows , cells } , note ) ;
const options = [ 'Идеи' , 'Обсуждаем' , 'В работе' , 'Готово' ] . map ( ( value , index ) => ( {
id : ` typography-status- ${ index } ` , value , color : 'var(--affine-v2-chip-label-blue)' ,
} ) ) ;
ids . database = store . addBlock ( 'affine:database' , {
title : new Text ( 'Проектные идеи' ) ,
columns : [ { id : 'typography-status' , type : 'select' , name : 'Статус' , data : { options } } ] ,
views : [ {
id : 'typography-kanban' , name : 'Kanban' , mode : 'kanban' ,
columns : [ { id : 'title' , hide : false } , { id : 'typography-status' } ] ,
groupBy : { type : 'groupBy' , columnId : 'typography-status' , name : 'select' } ,
filter : { type : 'group' , op : 'and' , conditions : [ ] } ,
header : { titleColumn : 'title' , iconColumn : 'type' } ,
groupProperties : [ ] ,
} ] ,
} , note ) ;
} ) ;
store . transact ( ( ) => {
const cells = { } ;
for ( let index = 0 ; index < 4 ; index ++ ) {
const row = store . addBlock ( 'affine:paragraph' , { type : 'text' , text : new Text ( ` Предложение ${ index + 1 } ` ) } , ids . database ) ;
ids . records . push ( row ) ;
cells [ row ] = { 'typography-status' : { columnId : 'typography-status' , value : ` typography-status- ${ index } ` } } ;
}
store . updateBlock ( store . getModelById ( ids . database ) , { cells } ) ;
} ) ;
return ids ;
} ) ;
}
async function metrics ( page , ids ) {
return page . evaluate ( ids => {
const block = id => document . querySelector ( ` affine-paragraph[data-block-id=" ${ id } "] ` ) ;
const wrapper = id => block ( id ) . querySelector ( '.affine-paragraph-rich-text-wrapper' ) ;
const style = element => {
const css = getComputedStyle ( element ) ;
return {
size : parseFloat ( css . fontSize ) , line : parseFloat ( css . lineHeight ) ,
top : parseFloat ( css . marginTop ) , bottom : parseFloat ( css . marginBottom ) ,
border : parseFloat ( css . borderBottomWidth ) , color : css . color ,
} ;
} ;
const colorBlock = block ( ids . color ) ;
const deepest = ( element , text ) => [ ... element . querySelectorAll ( '*' ) ]
. filter ( child => child . textContent === text ) . at ( - 1 ) ;
const red = deepest ( colorBlock , 'красный' ) ;
let marker = deepest ( colorBlock , 'маркер' ) ;
while ( marker && marker !== colorBlock && getComputedStyle ( marker ) . backgroundColor === 'rgba(0, 0, 0, 0)' ) marker = marker . parentElement ;
const probe = document . createElement ( 'span' ) ;
probe . style . color = 'var(--affine-text-highlight-foreground-red)' ;
probe . style . backgroundColor = 'var(--affine-text-highlight-orange)' ;
colorBlock . append ( probe ) ;
const expectedColor = getComputedStyle ( probe ) . color ;
const expectedHighlight = getComputedStyle ( probe ) . backgroundColor ;
probe . remove ( ) ;
const code = block ( ids . code ) . querySelector ( 'code' ) ;
const headerCode = block ( ids . headings [ 0 ] ) . querySelector ( 'code' ) ;
const body = wrapper ( ids . body ) ;
const wideBlock = ( tag , id ) => {
const root = document . querySelector ( ` ${ tag } [data-block-id=" ${ id } "] ` ) ;
return [ root , ... root . querySelectorAll ( '*' ) ] . map ( element => ( {
overflow : getComputedStyle ( element ) . overflowX ,
width : element . clientWidth ,
scrollWidth : element . scrollWidth ,
} ) ) . filter ( value => [ 'auto' , 'scroll' ] . includes ( value . overflow ) && value . width > 0 )
. sort ( ( a , b ) => ( b . scrollWidth - b . width ) - ( a . scrollWidth - a . width ) ) [ 0 ] ;
} ;
return {
headings : ids . headings . map ( id => style ( wrapper ( id ) ) ) ,
headingBounds : ids . headings . map ( id => {
const rect = wrapper ( id ) . getBoundingClientRect ( ) ;
return { left : rect . left , right : rect . right } ;
} ) ,
viewportWidth : innerWidth ,
body : style ( body ) ,
red : getComputedStyle ( red ) . color ,
marker : getComputedStyle ( marker ) . backgroundColor ,
expectedColor , expectedHighlight ,
code : {
... style ( code ) ,
family : getComputedStyle ( code ) . fontFamily ,
colorMarkRetained : document . querySelector ( 'editor-host' ) . store . getModelById ( ids . code ) . props . text . toDelta ( )
. some ( op => op . attributes ? . code && op . attributes ? . color === 'var(--affine-text-highlight-foreground-red)' ) ,
} ,
headerCode : style ( headerCode ) ,
quoteWidth : parseFloat ( getComputedStyle ( wrapper ( ids . quote ) , '::after' ) . width ) ,
link : block ( ids . link ) . querySelector ( 'a' ) . href ,
tableCount : Number ( ! ! document . querySelector ( ` affine-table[data-block-id=" ${ ids . table } "] ` ) ) ,
databaseCount : Number ( ! ! document . querySelector ( ` affine-database[data-block-id=" ${ ids . database } "] ` ) ) ,
databaseMode : document . querySelector ( 'editor-host' ) . store . getModelById ( ids . database ) . props . views [ 0 ] . mode ,
databaseRecords : ids . records . map ( id => document . querySelector ( 'editor-host' ) . store . getModelById ( id ) . props . text . toString ( ) ) ,
databaseRenderedText : document . querySelector ( ` affine-database[data-block-id=" ${ ids . database } "] ` ) . textContent ,
formulaCount : Number ( ! ! document . querySelector ( ` [data-block-id=" ${ ids . formula } "] ` ) ) ,
tableScroll : wideBlock ( 'affine-table' , ids . table ) ,
databaseScroll : wideBlock ( 'affine-database' , ids . database ) ,
canvasSizes : ids . headings . map ( ( _ , index ) => parseFloat ( getComputedStyle ( body ) . getPropertyValue ( ` --affine-font-h- ${ index + 1 } ` ) ) ) ,
rootOverflow : document . documentElement . scrollWidth - document . documentElement . clientWidth ,
} ;
} , ids ) ;
}
function verify ( result , name ) {
result . headings . forEach ( ( heading , index ) => {
assert ( Math . abs ( heading . size - expectedSizes [ index ] ) < 0.05 , ` ${ name } : H ${ index + 1 } size ` ) ;
assert ( Math . abs ( heading . line / heading . size - 1.25 ) < 0.01 , ` ${ name } : heading line height ` ) ;
assert . equal ( heading . top , 24 , ` ${ name } : heading top margin ` ) ;
assert . equal ( heading . bottom , 16 , ` ${ name } : heading bottom margin ` ) ;
} ) ;
assert . equal ( result . headings [ 0 ] . border , 1 , ` ${ name } : H1 divider ` ) ;
assert . equal ( result . headings [ 1 ] . border , 1 , ` ${ name } : H2 divider ` ) ;
assert . equal ( result . body . line / result . body . size , 1.5 , ` ${ name } : body line height ` ) ;
assert . equal ( result . body . bottom , 16 , ` ${ name } : paragraph spacing ` ) ;
assert . equal ( result . red , result . expectedColor , ` ${ name } : custom foreground color ` ) ;
assert . notEqual ( result . red , result . body . color , ` ${ name } : color is not flattened ` ) ;
assert . equal ( result . marker , result . expectedHighlight , ` ${ name } : highlight color ` ) ;
// AFFiNE's code renderer deliberately uses the theme foreground, even with a stored color mark.
assert . equal ( result . code . color , result . body . color , ` ${ name } : native inline-code foreground ` ) ;
assert ( result . code . colorMarkRetained , ` ${ name } : inline-code formatting data retained ` ) ;
assert ( Math . abs ( result . code . size / result . body . size - 0.85 ) < 0.01 , ` ${ name } : inline code scale ` ) ;
assert . match ( result . code . family , /mono/i , ` ${ name } : inline code family ` ) ;
assert . equal ( result . headerCode . size , result . headings [ 0 ] . size , ` ${ name } : heading inline code ` ) ;
assert . equal ( result . quoteWidth , 4 , ` ${ name } : quote rail ` ) ;
assert . equal ( result . link , 'https://example.invalid/project' , ` ${ name } : rich link ` ) ;
assert ( result . tableCount > 0 && result . databaseCount > 0 && result . formulaCount > 0 , ` ${ name } : rich blocks retained ` ) ;
assert . equal ( result . databaseMode , 'kanban' , ` ${ name } : native Kanban view ` ) ;
assert . deepEqual ( result . databaseRecords , [ 'Предложение 1' , 'Предложение 2' , 'Предложение 3' , 'Предложение 4' ] , ` ${ name } : Kanban records retained ` ) ;
assert ( result . databaseRenderedText . includes ( 'Предложение 1' ) , ` ${ name } : Kanban card is rendered ` ) ;
assert ( result . rootOverflow <= 1 , ` ${ name } : no new window-level horizontal overflow ` ) ;
assert ( result . headingBounds . every ( rect => rect . left >= - 1 && rect . right <= result . viewportWidth + 1 ) , ` ${ name } : document headings fit the reading viewport ` ) ;
}
async function selectorBoundaries ( page , css ) {
const frameElement = await page . locator ( 'body' ) . evaluateHandle ( ( ) => {
const frame = document . createElement ( 'iframe' ) ;
frame . style . cssText = 'position:fixed;width:10px;height:10px;left:-1000px;' ;
document . body . append ( frame ) ;
return frame ;
} ) ;
const frame = await frameElement . asElement ( ) . contentFrame ( ) ;
await frame . setContent ( ` <!doctype html><style>
:root { --affine-font-base:16px; --affine-font-h-1:28px; --affine-divider-color:#ddd; }
.h1 {font-size:28px;line-height:36px;margin:18px 0 10px;}
${ css }
</style><affine-page-root><div class="affine-page-root-block-container">
<affine-paragraph><div class="affine-block-component" style="margin:10px 0"><div id="page" class="affine-paragraph-rich-text-wrapper h1">Page</div>
<affine-edgeless-root><affine-paragraph><div class="affine-block-component" style="margin:10px 0"><div id="nested" class="affine-paragraph-rich-text-wrapper h1">Canvas</div></div></affine-paragraph></affine-edgeless-root>
<affine-edgeless-root><div class="affine-page-viewport" style="container-name:viewport;container-type:inline-size;width:400px"><div id="nested-layout" style="display:table;min-width:100%"><div data-affine-editor-container class="page-mode">Preview</div></div></div></affine-edgeless-root>
<affine-database><affine-paragraph><div class="affine-block-component" style="margin:10px 0"><div id="database" class="affine-paragraph-rich-text-wrapper h1">Database</div></div></affine-paragraph></affine-database>
<affine-database><div class="affine-page-viewport" style="container-name:viewport;container-type:inline-size;width:400px"><div id="database-layout" style="display:table;min-width:100%"><div data-affine-editor-container class="page-mode">Preview</div></div></div></affine-database>
</div></affine-paragraph>
<div class="affine-page-viewport" style="container-name:viewport;container-type:inline-size;width:400px"><div id="page-layout" style="display:table;min-width:100%"><div data-affine-editor-container class="page-mode">Document</div></div></div>
</div></affine-page-root> ` ) ;
const values = await frame . evaluate ( ( ) => Object . fromEntries ( [ 'page' , 'nested' , 'database' ] . map ( id => {
const node = document . getElementById ( id ) ;
return [ id , { size : parseFloat ( getComputedStyle ( node ) . fontSize ) , margin : parseFloat ( getComputedStyle ( node . parentElement ) . marginTop ) } ] ;
} ) ) ) ;
assert . equal ( values . page . size , 32 , 'Page selector probe' ) ;
assert . equal ( values . page . margin , 0 , 'Page inline block margin override' ) ;
for ( const id of [ 'nested' , 'database' ] ) {
assert . equal ( values [ id ] . size , 28 , ` ${ id } : outer paragraph must not leak typography ` ) ;
assert . equal ( values [ id ] . margin , 10 , ` ${ id } : outer page must not leak spacing ` ) ;
}
assert . equal ( await frame . locator ( '#page-layout' ) . evaluate ( element => getComputedStyle ( element ) . display ) , 'block' , 'Narrow document layout must reflow' ) ;
assert . equal ( await frame . locator ( '#nested-layout' ) . evaluate ( element => getComputedStyle ( element ) . display ) , 'table' , 'Narrow embedded canvas preview layout must remain native' ) ;
assert . equal ( await frame . locator ( '#database-layout' ) . evaluate ( element => getComputedStyle ( element ) . display ) , 'table' , 'Narrow embedded database preview layout must remain native' ) ;
await frameElement . asElement ( ) . evaluate ( element => element . remove ( ) ) ;
}
async function main ( ) {
await fs . mkdir ( output , { recursive : true } ) ;
const patch = await fs . readFile ( process . env . AFFINE _TYPOGRAPHY _PATCH || path . join ( _ _dirname , '../../../../package/affine/gitea-document-typography.patch' ) , 'utf8' ) ;
const css = patch . split ( '\n' ) . filter ( line => line . startsWith ( '+' ) && ! line . startsWith ( '+++' ) ) . map ( line => line . slice ( 1 ) ) . join ( '\n' ) ;
const browser = await chromium . launch ( { executablePath : await executable ( ) , headless : true , args : [ '--no-sandbox' , '--disable-dev-shm-usage' ] } ) ;
const results = [ ] ;
try {
for ( const scenario of [
{ name : 'light-desktop' , colorScheme : 'light' , viewport : { width : 1440 , height : 1100 } } ,
{ name : 'dark-desktop' , colorScheme : 'dark' , viewport : { width : 1440 , height : 1100 } } ,
{ ... devices [ 'Pixel 7' ] , name : 'light-mobile' , colorScheme : 'light' , viewport : { width : 412 , height : 915 } } ,
{ ... devices [ 'Pixel 7' ] , name : 'dark-mobile' , colorScheme : 'dark' , viewport : { width : 412 , height : 915 } } ,
] ) {
const { name , ... options } = scenario ;
const context = await browser . newContext ( options ) ;
try {
const auth = await ( await context . request . get ( ` ${ base } /api/auth/session ` ) ) . json ( ) ;
assert ( ! auth . user , 'Typography tests must never use an authenticated production session' ) ;
const page = await context . newPage ( ) ;
page . setDefaultTimeout ( 30000 ) ;
await page . goto ( base , { waitUntil : 'domcontentloaded' , timeout : 45000 } ) ;
await page . waitForSelector ( 'editor-host' , { timeout : 45000 } ) ;
const dismiss = page . getByRole ( 'button' , { name : 'Dismiss' , exact : true } ) ;
if ( await dismiss . count ( ) ) await dismiss . dispatchEvent ( 'click' ) ;
if ( options . isMobile ) {
await page . locator ( '[data-testid="app-sidebar-arrow-button-collapse"][data-show="true"] button' ) . first ( ) . click ( ) ;
await page . waitForTimeout ( 400 ) ;
}
const ids = await fixture ( page ) ;
await page . waitForSelector ( ` affine-paragraph[data-block-id=" ${ ids . headings [ 5 ] } "] ` ) ;
await page . waitForTimeout ( 500 ) ;
const result = await metrics ( page , ids ) ;
verify ( result , name ) ;
if ( options . isMobile ) {
for ( const [ kind , scroll ] of [ [ 'table' , result . tableScroll ] , [ 'database' , result . databaseScroll ] ] ) {
assert ( scroll && scroll . scrollWidth > scroll . width , ` ${ name } : wide ${ kind } retains its own horizontal scrolling ` ) ;
}
}
console . log ( ` ${ name } : heading scale, spacing and rich-text colors verified ` ) ;
await selectorBoundaries ( page , css ) ;
await page . evaluate ( ( ) => document . fonts . ready ) ;
await page . locator ( 'editor-host' ) . evaluate ( host => {
const viewport = host . closest ( '.affine-page-viewport' ) ;
if ( viewport ) viewport . scrollTop = 0 ;
} ) ;
await page . waitForTimeout ( 100 ) ;
await page . screenshot ( { path : path . join ( output , ` ${ name } .png ` ) , fullPage : true } ) ;
await page . locator ( ` affine-database[data-block-id=" ${ ids . database } "] ` ) . screenshot ( { path : path . join ( output , ` ${ name } -kanban.png ` ) } ) ;
await page . locator ( ` affine-table[data-block-id=" ${ ids . table } "] ` ) . screenshot ( { path : path . join ( output , ` ${ name } -table.png ` ) } ) ;
const editable = page . locator ( ` affine-paragraph[data-block-id=" ${ ids . body } "] [contenteditable="true"] ` ) . first ( ) ;
await editable . click ( ) ;
await page . keyboard . type ( ' typography edit' ) ;
await page . waitForFunction ( id => document . querySelector ( 'editor-host' ) . store . getModelById ( id ) . props . text . toString ( ) . includes ( 'typography edit' ) , ids . body ) ;
await page . locator ( '.affine-page-root-block-container' ) . evaluate ( element => element . style . setProperty ( '--affine-font-base' , '20px' ) ) ;
assert . equal ( ( await metrics ( page , ids ) ) . headings [ 0 ] . size , 40 , 'User font-size preference must scale headings' ) ;
await page . locator ( '.affine-page-root-block-container' ) . evaluate ( element => element . style . removeProperty ( '--affine-font-base' ) ) ;
let canvas = null ;
if ( ! options . isMobile ) {
await page . getByTestId ( 'switch-edgeless-mode-button' ) . click ( ) ;
await page . waitForSelector ( 'affine-edgeless-root' ) ;
await page . locator ( 'affine-edgeless-root' ) . evaluate ( element => element . gfx . fitToScreen ( ) ) ;
await page . waitForSelector ( ` affine-paragraph[data-block-id=" ${ ids . headings [ 0 ] } "] .h1 ` ) ;
canvas = await page . evaluate ( ids => ids . headings . map ( id => parseFloat ( getComputedStyle ( document . querySelector ( ` affine-paragraph[data-block-id=" ${ id } "] .affine-paragraph-rich-text-wrapper ` ) ) . fontSize ) ) , ids ) ;
assert . deepEqual ( canvas , result . canvasSizes , ` ${ name } : canvas note typography must remain native ` ) ;
}
results . push ( { name , sizes : result . headings . map ( h => h . size ) , canvas , colorsPreserved : true ,
databaseMode : result . databaseMode , databaseRecords : result . databaseRecords . length ,
tableScroll : result . tableScroll , databaseScroll : result . databaseScroll } ) ;
console . log ( ` ${ name } : document hierarchy, colors, editing and rich blocks verified ${ canvas ? '; native canvas unchanged' : '' } ` ) ;
} finally { await context . close ( ) ; }
}
await fs . writeFile ( path . join ( output , 'results.json' ) , JSON . stringify ( results , null , 2 ) ) ;
} finally { await browser . close ( ) ; }
}
if ( require . main === module ) main ( ) . catch ( error => { console . error ( error . message ) ; process . exitCode = 1 ; } ) ;
module . exports = { fixture , metrics , verify } ;