Fix homepage headings when reduced motion is enabled

This commit is contained in:
2026-11-12 17:19:27 +03:00
parent 3ae835e6ff
commit 3424556a21
5 changed files with 123 additions and 3 deletions
File diff suppressed because one or more lines are too long
@@ -0,0 +1,25 @@
# Заголовки при отключённых анимациях
Основа исправления — `mission-core-v2-promo`, commit `3ae835e`. При проверке 12 ноября 2026 года публичный `assets/custom/js/app.js` совпал с этой веткой побайтно: SHA-256 `ef3b74263de4482a576fa7940c7443e702d2eb6c6d92b17e74388688444be98f`. Контент CMS отличается от Git; ветку целиком поверх CMS не импортировать.
## Причина
Модуль `hg` в `assets/custom/js/app.js` сначала скрывал части заголовка (`opacity: 0`) и сдвигал их. При `prefers-reduced-motion: reduce` обработчик появления восстанавливал видимость контейнера и обычного текста, но не частей заголовка. Видимость родителя не отменяет прозрачность дочерних элементов. Ошибка зависит от настройки уменьшения движения, а не только от операционной системы.
## Исправление
В начале инициализации `hg` добавлен отдельный ранний выход для уже вычисленного флага уменьшения движения. Контейнер видим; исходные заголовки и абзацы остаются в документе без клонирования, разбиения, скрытия и подписки на появление/исчезновение при прокрутке.
Обычный сценарий ниже раннего выхода сохранён побайтно. Не менялись параметры GSAP, задержки, направление, размытие и повторное появление. Настройка считывается при загрузке страницы, как в исходной версии; после изменения системной настройки страницу нужно перезагрузить.
Новая версия скрипта — `17cdd0495032` (первые 12 знаков SHA-256). Ссылка обновлена в `templates/pages/home/shell.html` и `index.html`, чтобы обойти старый браузерный кеш и сохранить исправление при следующих сборках CMS.
## Проверка
`node --test test/*.test.mjs`: все 8 тестов проходят. Два новых теста режима уменьшения движения падают на исходном скрипте из-за прозрачных заголовков и проходят на исправленном. Проверяются заголовки со span и без него, исходный текст без копий, отсутствие сдвигов и повторного скрытия при прокрутке. Третий тест проверяет прежнюю анимацию, задержки, stagger, скрытие и повторное появление в обратном направлении. Тест использует настоящий модуль из поставляемого файла.
Дополнительно проверено в Chrome на локальной копии свежего экспорта CMS. Для сравнения двух сценариев только в preview-сервере флаг Zq задавался true/false; в поставляемом архиве настройка по-прежнему читается из prefers-reduced-motion. Исходная версия в reduced-режиме оставляет оба span главного h1 с opacity 0. Исправленная показывает их с opacity 1 и transform none, в том числе заголовки следующих секций. В обычном режиме подтвержден переход opacity от 0 к 1 и завершение transform в нулевой позиции; размытие снимается.
## Поставка
Взять свежий полный бэкап проекта CMS `mission-core`, сохранить оригинал для отката. В копии ZIP заменить только `assets/custom/js/app.js` и версии URL в двух HTML-файлах. Все прочие файлы, включая контент и медиа, должны совпасть с исходным бэкапом побайтно. Импортировать через админку Mission Core и опубликовать штатной кнопкой. Git push не является публикацией сайта.
+1 -1
View File
@@ -27,7 +27,7 @@
<script id="node-dc-static-config" type="application/json">{"assets":{"icon":"./assets/custom/icon.glb","logo":"./assets/uploads/images/Logo/2025-05-14-23.46.35-mqvznn10.jpg"}}</script>
<script>window.__API_ORIGIN__=window.location.origin;</script>
<script defer src="./assets/custom/js/app.js?v=ef3b74263de4" crossorigin="anonymous"></script>
<script defer src="./assets/custom/js/app.js?v=17cdd0495032" crossorigin="anonymous"></script>
<style>
.DEBUG_HIDE {
visibility: hidden !important;
+1 -1
View File
@@ -27,7 +27,7 @@
<script id="node-dc-static-config" type="application/json">{"assets":{"icon":"{{js:staticElements.content.assets.webglModelSrc}}","logo":"{{js:staticElements.content.assets.logoPng}}"}}</script>
<script>window.__API_ORIGIN__=window.location.origin;</script>
<script defer src="./assets/custom/js/app.js?v=ef3b74263de4" crossorigin="anonymous"></script>
<script defer src="./assets/custom/js/app.js?v=17cdd0495032" crossorigin="anonymous"></script>
<style>
.DEBUG_HIDE {
visibility: hidden !important;
+95
View File
@@ -0,0 +1,95 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const source = fs.readFileSync(process.env.HEADING_SCRIPT || new URL('../assets/custom/js/app.js', import.meta.url), 'utf8');
// Exercise the shipped heading module, not a rewritten copy of its logic.
const start = source.indexOf('var vK="h1, h2, h3, h4"');
const end = source.indexOf('var PH={}', start);
assert.ok(start >= 0 && end > start, 'heading module boundaries must exist');
const moduleSource = source.slice(start, end);
function fixture({ reduced = false, spans = true } = {}) {
const calls = [], observers = [], clones = [], words = [];
const node = (name) => ({ name, isConnected: true, style: {}, setAttribute() {}, closest() { return null; } });
const heading = node('heading');
const headingParts = spans ? [node('title'), node('subtitle')] : [heading];
heading.querySelectorAll = () => spans ? headingParts : [];
const paragraph = node('paragraph');
paragraph.cloneNode = () => { const clone = node('paragraph clone'); clones.push(clone); return clone; };
const group = node('group');
group.querySelector = () => heading;
group.querySelectorAll = () => [paragraph];
group.insertBefore = () => {};
paragraph.parentElement = group;
const record = (method, targets, props) => {
calls.push({ method, targets: targets.map(x => x.name), props });
for (const target of targets) {
for (const key of ['opacity', 'xPercent', 'yPercent', 'filter']) {
if (key in props) target.style[key] = props[key];
}
}
};
vm.runInNewContext(moduleSource + '\ndK(group,{group:"hero"});', {
group, Zq: reduced,
CSS: { escape: x => x },
document: {
querySelectorAll: () => [group],
createElement: () => ({ style: {}, appendChild() {} }),
},
L$: class {
constructor() { this.words = [node('word 1'), node('word 2')]; words.push(...this.words); }
},
n: {
set: (targets, props) => record('set', targets, props),
to: (targets, props) => record('to', targets, props),
fromTo: (targets, from, props) => { record('from', targets, from); record('to', targets, props); },
killTweensOf: targets => calls.push({ method: 'kill', targets: targets.map(x => x.name) }),
},
l1: (target, options) => observers.push(options),
});
return { group, headingParts, paragraph, words, clones, calls, observers,
enter(direction = 1) { observers.forEach(o => o.callback({ isIn: true, direction })); },
leave() { observers.forEach(o => o.callback({ isIn: false, direction: 1 })); },
};
}
for (const spans of [true, false]) {
test(`reduced motion keeps ${spans ? 'split' : 'plain'} headings and original copy visible`, () => {
const f = fixture({ reduced: true, spans });
f.enter(); f.leave(); f.enter(-1);
for (const element of [...f.headingParts, f.paragraph]) {
assert.notEqual(element.style.opacity, 0, `${element.name} must not be hidden`);
assert.notEqual(element.style.opacity, '0', `${element.name} must not be hidden`);
assert.ok(!element.style.xPercent && !element.style.yPercent, 'no animation offsets');
}
assert.equal(f.clones.length, 0, 'static copy must not be split or cloned');
assert.equal(f.observers.length, 0, 'scroll must not hide static headings again');
assert.equal(f.calls.filter(c => c.method === 'to' || c.method === 'from').length, 0);
});
}
test('normal motion retains heading reveal, paragraph stagger, and replay on scroll', () => {
const f = fixture();
assert.equal(f.observers.length, 1);
assert.equal(f.clones.length, 1);
assert.equal(f.headingParts[0].style.opacity, 0);
assert.equal(f.headingParts[0].style.xPercent, 20);
f.enter();
const headingTween = f.calls.find(c => c.method === 'to' && c.targets[0] === 'title');
assert.equal(headingTween.props.opacity, 1);
assert.equal(headingTween.props.filter, 'blur(0px)');
assert.equal(headingTween.props.stagger.each, 0.2);
assert.equal(headingTween.props.stagger.from, 'start');
assert.equal(headingTween.props.delay, 0.1);
const paragraphTween = f.calls.find(c => c.method === 'to' && c.targets[0] === 'word 1');
assert.equal(paragraphTween.props.stagger.each, 0.04);
assert.ok(Math.abs(paragraphTween.props.delay - 0.15) < 1e-9);
assert.equal(f.group._hgAnimated, true);
f.leave();
assert.equal(f.headingParts[0].style.opacity, 0);
f.enter(-1);
assert.equal(f.headingParts[0].style.opacity, 1);
assert.equal(f.calls.filter(c => c.method === 'to' && c.targets[0] === 'title').at(-1).props.stagger.from, 'end');
});