From e935abd0c3b35de4e95a00cc262bf5067acb439f Mon Sep 17 00:00:00 2001 From: yukkop Date: Thu, 29 Oct 2026 21:43:33 +0000 Subject: [PATCH] affine fix styles --- docs/README.md | 1 + docs/affine-typography.md | 61 ++++ nixos/system/hectic-lab/affine.nix | 37 ++ package/affine/default.nix | 22 +- .../affine/gitea-document-typography.patch | 142 ++++++++ package/default.nix | 7 +- test/nixos/affine-frontend.nix | 52 +++ test/nixos/default.nix | 3 +- test/package/affine/default.nix | 32 +- test/package/affine/test/runtime.sh | 4 + test/package/affine/test/typography.cjs | 320 ++++++++++++++++++ 11 files changed, 666 insertions(+), 15 deletions(-) create mode 100644 docs/affine-typography.md create mode 100644 package/affine/gitea-document-typography.patch create mode 100644 test/nixos/affine-frontend.nix create mode 100644 test/package/affine/test/typography.cjs diff --git a/docs/README.md b/docs/README.md index bd122906..9a6a97fe 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,6 +4,7 @@ - [Minecraft incident log](./minecraft-incidents.md) - [Project Zomboid backups](./project-zomboid-backups.md) - [Gitea Kanban CLI](./gitea-kanban-cli.md) +- [AFFiNE document typography](./affine-typography.md) ## Gitea runner labels diff --git a/docs/affine-typography.md b/docs/affine-typography.md new file mode 100644 index 00000000..8f3a9d51 --- /dev/null +++ b/docs/affine-typography.md @@ -0,0 +1,61 @@ +# AFFiNE document typography + +The frontend source patch in `package/affine/gitea-document-typography.patch` +adopts Gitea README typography without replacing BlockSuite's document model. +At the default 16px body size, H1-H6 use 32, 24, 20, 16, 14 and 13.6px. Headings +use 1.25 line height, 24px/16px section spacing, and H1/H2 dividers. Body text +uses 1.5 line height and 16px paragraph spacing; nested lists remain compact. +Quotes and inline code retain native AFFiNE colors and formatting. + +The scale and spacing are inspired by Gitea's MIT-licensed +[README markup stylesheet](https://github.com/go-gitea/gitea/blob/v1.27.3/web_src/css/markup/content.css). +This is an independently authored, scoped BlockSuite patch, not a wholesale +copy of that stylesheet; no vendored Gitea source files are changed. + +The patch is limited to page mode. Canvas notes, embedded canvas previews and +database block trees retain their existing typography. Below 640px, page text +reflows to its viewport instead of following the intrinsic width of a wide +table. Tables and databases retain their native horizontal scrollers. The +existing sidebar toggle can be used to give the document the full phone width. + +## Build and verify + +```sh +nix build .#affine-frontend-static --option post-build-hook '' +NIXPKGS_ALLOW_UNFREE=1 nix build --impure .#checks.x86_64-linux.affine-typography --option post-build-hook '' +``` + +The browser check uses the real source-built frontend with an isolated backend +and anonymous, browser-local example documents. It covers light/dark desktop +and phone layouts, heading metrics, colored text/highlights, inline code, +editing, rich blocks, native canvas sizing and nested selector boundaries. +Screenshots and computed-size results are retained in the check output. +Fixture writes are restricted to the isolated loopback test server; the harness +does not accept a remote URL override. +The backend used by that check still requires explicit unfree evaluation. + +## Current hectic-lab rollout + +`affine-frontend-static` contains regular, copied web assets, including admin +and mobile directories and upstream license notices. It does not contain +symlinks into store paths that would be unavailable inside a container. + +The existing Docker backend, database, Redis instance, image digests and data +paths remain unchanged. A companion `affine-frontend.service` applies a Compose +override mounting the source-built assets read-only at `/app/static`. It uses +`up --detach --no-deps --force-recreate affine`: only the application container +is reconciled. The main `affine.service` keeps its existing start/stop behavior. + +Changing the frontend reloads the companion unit. Stopping/removing that unit +recreates the application from the base Compose configuration, restoring the +stock frontend. A restart of the parent stack reapplies the frontend afterward. +Database credentials and keys remain generated runtime state; no secret values +are embedded in the Nix store or repository by this frontend change. +Frontend and backend release versions must match; the NixOS configuration +asserts this before deployment. + +Take a database/state backup before applying the first rollout, and verify that +PostgreSQL, Redis and migration container IDs remain unchanged. No database +upgrade or native-backend migration is part of this change. Application startup +may perform its usual background work; this is not a claim that the process +never writes to its database. diff --git a/nixos/system/hectic-lab/affine.nix b/nixos/system/hectic-lab/affine.nix index 15069aa7..d9a4da14 100644 --- a/nixos/system/hectic-lab/affine.nix +++ b/nixos/system/hectic-lab/affine.nix @@ -3,6 +3,7 @@ ... }: { pkgs, + lib, ... }: let affineDomain = "affine.${domain}"; @@ -129,7 +130,23 @@ }); compose = "${pkgs.docker-compose}/bin/docker-compose --project-name affine --env-file ${environmentFile} --file ${composeFile}"; + frontendStatic = pkgs.hectic.affine-frontend-static; + frontendOverride = (pkgs.formats.yaml {}).generate "affine-frontend-compose.yaml" { + services.affine.volumes = [ "${frontendStatic}:/app/static:ro" ]; + }; + frontendCompose = "${compose} --file ${frontendOverride}"; in { + assertions = [ + { + assertion = lib.hasPrefix "ghcr.io/toeverything/affine:${frontendStatic.version}@sha256:" affineImage; + message = "AFFiNE frontend assets and the deployed backend image must use the same release."; + } + { + assertion = frontendStatic.revision == "b4c8548c09da21b2898443559a5b846f0ccf5dd8"; + message = "AFFiNE frontend source revision must match the pinned 0.27.4 backend."; + } + ]; + systemd.tmpfiles.rules = [ "d ${stateDirectory} 0750 root root -" "d ${stateDirectory}/data 0750 root root -" @@ -185,6 +202,26 @@ in { }; }; + # Reconcile only the application container; leave the database and migration job alone. + systemd.services.affine-frontend = { + description = "Source-built AFFiNE frontend assets"; + wantedBy = [ "multi-user.target" ]; + requires = [ "affine.service" ]; + after = [ "affine.service" ]; + partOf = [ "affine.service" ]; + reloadIfChanged = true; + restartIfChanged = false; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + ExecStart = "${frontendCompose} up --detach --no-deps --force-recreate affine"; + ExecReload = "${frontendCompose} up --detach --no-deps --force-recreate affine"; + ExecStop = "${compose} up --detach --no-deps --force-recreate affine"; + TimeoutStartSec = "5min"; + TimeoutStopSec = "5min"; + }; + }; + systemd.services.affine-bootstrap = { description = "Prepare AFFiNE pilot basic authentication"; requiredBy = [ "nginx.service" ]; diff --git a/package/affine/default.nix b/package/affine/default.nix index 1d34d705..0c6c5314 100644 --- a/package/affine/default.nix +++ b/package/affine/default.nix @@ -3,6 +3,7 @@ stdenv, stdenvNoCC, fetchzip, + runCommand, config, makeWrapper, nodejs, @@ -13,6 +14,7 @@ openssl, inputs, system, + frontendPatches ? [ ./gitea-document-typography.patch ], }: let @@ -153,6 +155,7 @@ let pname = "affine-frontend"; inherit version src yarnOfflineCache; missingHashes = ./missing-hashes.json; + patches = frontendPatches; nativeBuildInputs = [ nodejs @@ -186,6 +189,23 @@ let runHook postInstall ''; }; + + frontendStatic = runCommand "affine-frontend-static-${version}" { + inherit version; + passthru = { inherit revision; }; + meta = { + description = "Source-built AFFiNE web assets with document typography patches"; + license = [ lib.licenses.mit lib.licenses.mpl20 ]; + platforms = [ "x86_64-linux" ]; + }; + } '' + mkdir -p "$out/admin" "$out/mobile" "$out/licenses" + cp -RL ${frontend}/web/. "$out/" + cp -RL ${frontend}/admin/. "$out/admin/" + cp -RL ${frontend}/mobile/. "$out/mobile/" + cp ${src}/LICENSE ${src}/LICENSE-MIT "$out/licenses/" + cp ${src}/packages/backend/server/LICENSE "$out/licenses/AFFINE-EE-and-MPL" + ''; in stdenv.mkDerivation (finalAttrs: { pname = "affine"; @@ -282,7 +302,7 @@ stdenv.mkDerivation (finalAttrs: { ''; passthru = { - inherit frontend native prismaEngines prismaQueryEngine prismaSchemaEngine yarnOfflineCache18; + inherit frontend frontendStatic native prismaEngines prismaQueryEngine prismaSchemaEngine yarnOfflineCache18; }; meta = { diff --git a/package/affine/gitea-document-typography.patch b/package/affine/gitea-document-typography.patch new file mode 100644 index 00000000..52ae517f --- /dev/null +++ b/package/affine/gitea-document-typography.patch @@ -0,0 +1,142 @@ +diff --git a/blocksuite/affine/blocks/root/src/page/page-root-block.ts b/blocksuite/affine/blocks/root/src/page/page-root-block.ts +--- a/blocksuite/affine/blocks/root/src/page/page-root-block.ts ++++ b/blocksuite/affine/blocks/root/src/page/page-root-block.ts +@@ -103,0 +104,138 @@ export class PageRootBlockComponent extends BlockComponent { ++ ++ /* Page document typography excludes canvas and database block trees. */ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ > .affine-block-component { ++ margin: 0 !important; ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-list:not(affine-edgeless-root *, affine-database *) ++ > .affine-block-component { ++ margin: 0 0 4px !important; ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper.text:not(affine-edgeless-root *, affine-database *), ++ affine-page-root ++ .affine-page-root-block-container ++ affine-list:not(affine-edgeless-root *, affine-database *) ++ .affine-list-rich-text-wrapper:not(affine-edgeless-root *, affine-database *) { ++ line-height: 1.5; ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper.text:not(affine-edgeless-root *, affine-database *) { ++ margin: 0 0 16px; ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper:not(affine-edgeless-root *, affine-database *):is(.h1, .h2, .h3, .h4, .h5, .h6) { ++ margin: 24px 0 16px; ++ font-weight: 600; ++ line-height: 1.25; ++ letter-spacing: normal; ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper.h1:not(affine-edgeless-root *, affine-database *) { ++ padding-bottom: 0.3em; ++ font-size: calc(var(--affine-font-base) * 2); ++ border-bottom: 1px solid var(--affine-divider-color); ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper.h2:not(affine-edgeless-root *, affine-database *) { ++ padding-bottom: 0.3em; ++ font-size: calc(var(--affine-font-base) * 1.5); ++ border-bottom: 1px solid var(--affine-divider-color); ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper.h3:not(affine-edgeless-root *, affine-database *) { ++ font-size: calc(var(--affine-font-base) * 1.25); ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper.h4:not(affine-edgeless-root *, affine-database *) { ++ font-size: var(--affine-font-base); ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper.h5:not(affine-edgeless-root *, affine-database *) { ++ font-size: calc(var(--affine-font-base) * 0.875); ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper.h6:not(affine-edgeless-root *, affine-database *) { ++ font-size: calc(var(--affine-font-base) * 0.85); ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper:not(affine-edgeless-root *, affine-database *):is(.h1, .h2, .h3, .h4, .h5, .h6) ++ code:not(affine-edgeless-root *, affine-database *) { ++ font-size: inherit; ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper.quote:not(affine-edgeless-root *, affine-database *) { ++ margin: 0 0 16px; ++ padding: 0 0 0 15px; ++ line-height: 1.5; ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ .affine-paragraph-rich-text-wrapper.quote:not(affine-edgeless-root *, affine-database *)::after { ++ width: 0.25em; ++ height: 100%; ++ margin: 0; ++ border-radius: 0; ++ } ++ ++ affine-page-root ++ .affine-page-root-block-container ++ affine-paragraph:not(affine-edgeless-root *, affine-database *) ++ code:not(affine-edgeless-root *, affine-database *), ++ affine-page-root ++ .affine-page-root-block-container ++ affine-list:not(affine-edgeless-root *, affine-database *) ++ code:not(affine-edgeless-root *, affine-database *) { ++ font-family: var(--affine-font-code-family); ++ font-size: 85%; ++ font-variant-ligatures: none; ++ } ++ ++ @container viewport (width <= 640px) { ++ .affine-page-viewport.affine-page-viewport ++ > div:first-child:has(> [data-affine-editor-container].page-mode):not(affine-edgeless-root *, affine-database *) { ++ display: block !important; ++ width: 100% !important; ++ min-width: 0 !important; ++ } ++ } diff --git a/package/default.nix b/package/default.nix index afeb1116..66a9f372 100644 --- a/package/default.nix +++ b/package/default.nix @@ -182,11 +182,14 @@ in { pg-15-ext-plsh = buildPlShExt pkgs "15"; stable-video-diffusion-api = pkgs.callPackage ./stable-video-diffusion-api {}; media-browser = pkgs.callPackage ./media-browser {}; -} // pkgs.lib.optionalAttrs (system == "x86_64-linux") { +} // pkgs.lib.optionalAttrs (system == "x86_64-linux") (let affine = pkgs.callPackage ./affine { inherit inputs system; nodejs = pkgs.nodejs_22; }; -} // pkgs.lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { +in { + inherit affine; + affine-frontend-static = affine.frontendStatic; +}) // pkgs.lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { with-attic-cache = pkgs.callPackage ./with-attic-cache {}; } diff --git a/test/nixos/affine-frontend.nix b/test/nixos/affine-frontend.nix new file mode 100644 index 00000000..8a001732 --- /dev/null +++ b/test/nixos/affine-frontend.nix @@ -0,0 +1,52 @@ +{ system, inputs, pkgs, ... }: +pkgs.lib.optionalAttrs (system == "x86_64-linux") (let + lib = inputs.nixpkgs.lib; + revision = "b4c8548c09da21b2898443559a5b846f0ccf5dd8"; + mkSystem = version: sourceRevision: lib.nixosSystem { + inherit system; + modules = [ + (import ../../nixos/system/hectic-lab/affine.nix { domain = "example.test"; }) + { + system.stateVersion = "26.05"; + nixpkgs.overlays = [ (_: _: { + hectic.affine-frontend-static = pkgs.runCommand "affine-static-test" { + inherit version; + passthru.revision = sourceRevision; + } ''mkdir -p "$out"''; + }) ]; + } + ]; + }; + cfg = (mkSystem "0.27.4" revision).config; + mismatchedCfg = (mkSystem "0.27.5" revision).config; + mismatchedRevisionCfg = (mkSystem "0.27.4" "different-source").config; + main = cfg.systemd.services.affine; + frontend = cfg.systemd.services.affine-frontend; +in { + affine-frontend-module = + assert frontend.requires == [ "affine.service" ]; + assert frontend.after == [ "affine.service" ]; + assert frontend.partOf == [ "affine.service" ]; + assert frontend.reloadIfChanged; + assert !frontend.restartIfChanged; + assert frontend.serviceConfig.Type == "oneshot"; + assert frontend.serviceConfig.RemainAfterExit; + assert frontend.serviceConfig.ExecStart == frontend.serviceConfig.ExecReload; + assert lib.hasInfix "affine-frontend-compose.yaml up --detach --no-deps --force-recreate affine" frontend.serviceConfig.ExecStart; + assert frontend.serviceConfig.ExecStop == lib.replaceStrings + [ " up --detach --wait" ] [ " up --detach --no-deps --force-recreate affine" ] main.serviceConfig.ExecStart; + assert lib.hasSuffix "affine-compose.yaml up --detach --wait" main.serviceConfig.ExecStart; + assert lib.hasSuffix "affine-compose.yaml down" main.serviceConfig.ExecStop; + assert !lib.hasInfix "affine-frontend-compose.yaml" main.serviceConfig.ExecStart; + assert cfg.services.nginx.virtualHosts."affine.example.test".locations."/".proxyPass == "http://127.0.0.1:3010"; + assert !(cfg.systemd.services ? affine-native); + assert lib.any (check: + check.message == "AFFiNE frontend assets and the deployed backend image must use the same release." && + !check.assertion + ) mismatchedCfg.assertions; + assert lib.any (check: + check.message == "AFFiNE frontend source revision must match the pinned 0.27.4 backend." && + !check.assertion + ) mismatchedRevisionCfg.assertions; + pkgs.runCommand "affine-frontend-module" {} ''touch "$out"''; +}) diff --git a/test/nixos/default.nix b/test/nixos/default.nix index 0fdec717..eb835fd8 100644 --- a/test/nixos/default.nix +++ b/test/nixos/default.nix @@ -33,7 +33,8 @@ let caseSensitive = false; }; }).config; -in (import ./affine.nix { inherit system inputs self pkgs; }) // { +in (import ./affine.nix { inherit system inputs self pkgs; }) // + (import ./affine-frontend.nix { inherit system inputs pkgs; }) // { p4d-module-basic = assert enabledCfg.users.users.p4d.isSystemUser; assert enabledCfg.users.users.p4d.group == "p4d"; diff --git a/test/package/affine/default.nix b/test/package/affine/default.nix index e0c0bf1e..666b3c10 100644 --- a/test/package/affine/default.nix +++ b/test/package/affine/default.nix @@ -1,18 +1,28 @@ { system, self, pkgs, ... }: -pkgs.lib.optionalAttrs (system == "x86_64-linux") { - affine-runtime = pkgs.runCommand "affine-runtime" { - nativeBuildInputs = [ - pkgs.dash - pkgs.curl - pkgs.jq - pkgs.nodejs_22 - (pkgs.postgresql_16.withPackages (ps: [ ps.pgvector ])) - pkgs.redis - ]; +let + runtimeInputs = [ + pkgs.dash + pkgs.curl + pkgs.jq + pkgs.nodejs_22 + (pkgs.postgresql_16.withPackages (ps: [ ps.pgvector ])) + pkgs.redis + ]; + check = name: extra: pkgs.runCommand name ({ + nativeBuildInputs = runtimeInputs; AFFINE_PACKAGE = self.packages.${system}.affine; AFFINE_CLIENT_TEST = ./test/client.cjs; - } '' + } // extra) '' dash ${./test/runtime.sh} touch "$out" ''; +in pkgs.lib.optionalAttrs (system == "x86_64-linux") { + affine-runtime = check "affine-runtime" {}; + affine-typography = check "affine-typography" { + nativeBuildInputs = runtimeInputs ++ [ pkgs.playwright-driver ]; + PLAYWRIGHT_CORE_PATH = "${pkgs.playwright-driver}"; + PLAYWRIGHT_BROWSERS_PATH = "${pkgs.playwright-driver.browsers}"; + AFFINE_TYPOGRAPHY_TEST = ./test/typography.cjs; + AFFINE_TYPOGRAPHY_PATCH = ../../../package/affine/gitea-document-typography.patch; + }; } diff --git a/test/package/affine/test/runtime.sh b/test/package/affine/test/runtime.sh index fae086a3..e14794eb 100644 --- a/test/package/affine/test/runtime.sh +++ b/test/package/affine/test/runtime.sh @@ -98,6 +98,10 @@ JS node "$AFFINE_CLIENT_TEST" +if [ -n "${AFFINE_TYPOGRAPHY_TEST:-}" ]; then + node "$AFFINE_TYPOGRAPHY_TEST" +fi + # Check idempotent predeploy against an already migrated, running installation. if ! "$AFFINE_PACKAGE/bin/affine-migrate" > "$TMPDIR/migrate-again.log" 2>&1; then cat "$TMPDIR/migrate-again.log" diff --git a/test/package/affine/test/typography.cjs b/test/package/affine/test/typography.cjs new file mode 100644 index 00000000..f4f26e1b --- /dev/null +++ b/test/package/affine/test/typography.cjs @@ -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(`
+
Page
+
Canvas
+
Preview
+
Database
+
Preview
+
+
Document
+
`); + 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 };