fix(web-test): состояние группы по контролу сворачивания, а не по вёрстке содержимого

На боевой форме вскрылись случаи, которые прежнее правило не покрывало. Замеры показали,
что любая эвристика «по первому сиблингу за заголовком» нежизнеспособна:

- служебная обёртка .logicGroupContainer пишется двумя способами (у таблицы
  <дочерний>#group_div, у вложенной группы <дочерний>_div) — знали только первый;
- display самой обёртки плавает: block до первого тогла, none после;
- первые узлы группы могут быть скрыты своей логикой, а видимое содержимое идёт дальше
  по цепочке — раскрытая группа читалась как свёрнутая, и постусловие роняло успешный клик.

Теперь состояние берётся из контрола сворачивания: у варианта «картинка» — кадр gx спрайта
hideshow у каретки (полярность обратна дереву в dom/grid.mjs), у варианта «гиперссылка»
каретки нет, там принадлежность по отступу — дети группы смещены глубже её заголовка,
свободный сосед стоит на уровне заголовка. База отсчёта — левый край блока заголовка
(каретка сдвигает текст вправо), обход ограничен: у последней свёрнутой группы границы за
ней нет, и первый видимый узел нашёлся через 107 сиблингов в чужой ветке формы.

Клик по заголовку группы теперь сперва скроллит цель в вид: цель кликается по координатам,
и ниже вьюпорта клик молча не доходил.

Ответ на клик отдаёт clicked.group (техническое имя) и clicked.title (текущий заголовок):
заголовок ключом быть не может — он повторяется между блоками формы и меняется при
раскрытии (CollapsedRepresentationTitle), после чего клик по прежнему тексту не находит
элемент. При смене заголовка hint говорит, чем кликать дальше.

Фикстура: вложенная группа первым ребёнком, «скрыт первый узел» в двух вариантах контрола,
группа с меняющимся заголовком в конце формы (уезжает за вьюпорт). Каждый кейс проверен на
красноту без своей правки.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Nick Shirokov
2026-07-28 16:12:07 +03:00
co-authored by Claude Opus 5
parent 006e64405c
commit d0e81a1715
7 changed files with 257 additions and 45 deletions
+1
View File
@@ -14,6 +14,7 @@ export {
closeCrossScript,
readFormScript,
findClickTargetScript,
scrollGroupIntoViewScript,
findFieldButtonScript,
resolveFieldsScript,
detectNewFormScript,
+54 -32
View File
@@ -1,4 +1,4 @@
// web-test dom shared v1.9 — embedded JS function constants
// web-test dom shared v1.10 — embedded JS function constants
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
/**
* Shared function strings embedded into page.evaluate() generators.
@@ -69,24 +69,39 @@ export const TEXT_CLICK_POINT_FN = `function textClickPoint(el) {
* Collapsed state of a form group — single source of truth for getFormState().groups[]
* and the click-target resolver.
*
* PopUp groups: the panel `<base>#panel_div` carries the state directly.
* 1C lays the form out FLAT: a group's content is not nested inside it but follows as
* absolutely-positioned siblings of `<base>#title_div`. Anything derived from "the first
* sibling" is unreliable — measured on live forms:
* • before a container child comes an empty `.logicGroupContainer` (height 0), spelled
* `<child>#group_div` for a table but `<child>_div` for a nested group;
* • that wrapper's own display FLIPS between runs (block before the first toggle, none
* after) — this is the "readings synced after the first toggle" from the bug report;
* • a group's leading nodes can stay `display:none` by their own logic (a table whose
* command bar is hidden) while the visible content sits further down the chain.
* Neither the wrappers' geometry nor the group's own `<base>_div` can serve as the signal:
* all of them are always zero-height.
*
* Collapsible groups: 1C lays the form out FLAT (content is not nested in the group, it
* follows as siblings of `<base>#title_div`, absolutely positioned). Usually the first
* sibling is the group's own first child, and its `display` IS the state.
*
* But when that child is itself a container (a table, a nested group), 1C inserts a
* bookkeeping wrapper `<childName>#group_div.logicGroupContainer` FIRST — always
* `display:block`, always `height:0`, and EMPTY: the real nodes
* (`<childName>КоманднаяПанель_div`, `<childName>_div`, …) follow it as further siblings,
* they are not inside it. Reading that wrapper's display reported `collapsed:false` for a
* group that was genuinely collapsed, so `{expand:true}` became a silent no-op.
*
* So: on hitting the wrapper, walk the following siblings while they share its id prefix
* (the prefix stops the walk at foreign nodes such as `separatePanelArea`, keeping the
* "free element between groups" case safe) and report collapsed when none of them is
* visible. Neither the wrapper's own geometry nor the group's `<base>_div` can serve as
* the signal — both are always zero-height.
* Signals, in order:
* 1. PopUp — the panel `<base>#panel_div` carries the state directly.
* 2. Caret (`ControlRepresentation=Picture`) — `<base>#titleBtn img` is the `hideshow`
* sprite, frame `gx`: 0 collapsed, non-zero expanded. Note the polarity is OPPOSITE
* to tree nodes in dom/grid.mjs (gx=0 = expanded there) — different sprite.
* 3. Otherwise (`TitleHyperlink`, which has no caret, no aria-expanded and no state class
* on the title): ownership by INDENT. A group's children sit deeper than its title
* (`#title_div` at left:12px → children at 22px), while a free element between groups
* sits at the title's own level. So walk the siblings, skip hidden nodes and wrappers
* (they are not positioned — left comes back `auto`), and the first VISIBLE node
* decides: deeper than the title ⇒ own content ⇒ expanded; same level or shallower
* ⇒ that's already someone else, stop. Nothing own and visible ⇒ collapsed, which is
* sound because a group with every element hidden is not rendered by the platform at all.
* The baseline is the leftmost part of the title BLOCK, not `#title_div` alone: with a
* caret the text is pushed right by its width (measured live: caret box 12px, title
* 33px, own children 22px), so anchoring on the title alone would read the group's own
* child as foreign. Only matters if a caret is present but signal 2 did not fire.
* The walk is capped: a group's own nodes sit right after its title, whereas the LAST
* collapsed group on a form has no boundary behind it at all — measured live, the first
* node with height came 107 siblings later, deep inside an unrelated branch, and would
* have been mistaken for the group's content.
*
* @param base element id prefix without suffix, e.g. `form1_ГруппаТовары`
* @returns `true` collapsed, `false` expanded, `null` when the layout is unrecognised.
@@ -94,21 +109,28 @@ export const TEXT_CLICK_POINT_FN = `function textClickPoint(el) {
export const GROUP_STATE_FN = `function groupCollapsed(base) {
const panelDiv = document.getElementById(base + '#panel_div');
if (panelDiv) return getComputedStyle(panelDiv).display === 'none';
const titleDiv = document.getElementById(base + '#title_div');
const sib = titleDiv && titleDiv.nextElementSibling;
if (!sib) return null;
const WRAP = '#group_div';
if (sib.id && sib.id.endsWith(WRAP) && sib.classList.contains('logicGroupContainer')) {
const pfx = sib.id.slice(0, -WRAP.length);
let seen = false;
for (let n = sib.nextElementSibling; n; n = n.nextElementSibling) {
if (!n.id || !n.id.startsWith(pfx)) break;
seen = true;
if (n.offsetWidth > 0 && n.offsetHeight > 0) return false;
}
return seen ? true : null;
const caret = document.querySelector('[id="' + base + '#titleBtn"] img');
const src = caret ? (caret.getAttribute('src') || '') : '';
if (src.indexOf('hideshow') !== -1) {
const gx = src.match(/[?&]gx=(\\d+)/);
if (gx) return gx[1] === '0';
}
return getComputedStyle(sib).display === 'none';
const titleDiv = document.getElementById(base + '#title_div');
if (!titleDiv) return null;
let titleLeft = parseFloat(getComputedStyle(titleDiv).left);
const caretDiv = document.getElementById(base + '#titleBtn_div');
const caretLeft = caretDiv ? parseFloat(getComputedStyle(caretDiv).left) : NaN;
if (!isNaN(caretLeft) && (isNaN(titleLeft) || caretLeft < titleLeft)) titleLeft = caretLeft;
if (isNaN(titleLeft)) return null;
let candidates = false, scanned = 0;
for (let n = titleDiv.nextElementSibling; n && scanned < 20; n = n.nextElementSibling, scanned++) {
if (n.offsetWidth === 0 && n.offsetHeight === 0) { candidates = true; continue; }
const left = parseFloat(getComputedStyle(n).left);
if (isNaN(left)) { candidates = true; continue; }
if (left > titleLeft) return false;
break;
}
return candidates ? true : null;
}`;
/**
@@ -324,6 +324,39 @@ export function findClickTargetScript(formNum, text, { tableName, gridSelector }
})()`;
}
/**
* Scroll a collapsible group's title into view and return the FRESH click point for it.
*
* A group's title is clicked by coordinates (its click target is a nested label, not the
* element with the id), and `mouse.click` outside the viewport lands nowhere — the toggle
* silently did nothing. Seen live: the second «Показать детализацию» on a long form sat at
* y=848 with a viewport of 834. Playwright's own auto-scroll does not apply here because
* that path is selector-based, not coordinate-based.
*
* Same target choice as findClickTargetScript: the caret `#titleBtn` when visible (compact,
* aim at its centre), otherwise the title text via textClickPoint.
*
* @returns `{ x, y }` after scrolling, or `null` when the group is not on the form.
*/
export function scrollGroupIntoViewScript(formNum, groupName) {
const p = `form${formNum}_`;
return `(() => {
${TEXT_CLICK_POINT_FN}
const base = ${JSON.stringify(p)} + ${JSON.stringify(groupName)};
const tt = document.getElementById(base + '#title_text');
const btn = document.getElementById(base + '#titleBtn');
const btnVisible = btn && (btn.offsetWidth > 0 || btn.offsetHeight > 0);
const anchor = btnVisible ? btn : tt;
if (!anchor) return null;
anchor.scrollIntoView({ block: 'center' });
if (btnVisible) {
const r = btn.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) };
}
return textClickPoint(tt);
})()`;
}
/**
* Find a field's action button (DLB, OB, CLR, CB) by fuzzy field name.
* Returns { fieldName, buttonId, buttonType } or { error, available }.
@@ -1,24 +1,38 @@
// web-test forms/click-group v1.1 — click handler for collapsible/popup form-group titles.
// web-test forms/click-group v1.2 — click handler for collapsible/popup form-group titles.
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
//
// Reuses the tree/grid expand vocabulary so the model has ONE mental model:
// clickElement('<заголовок группы>', { expand: true }) — раскрыть (идемпотентно)
// clickElement('<заголовок группы>', { expand: false }) — свернуть (идемпотентно)
// clickElement('<заголовок группы>', { toggle: true }) — переключить
// clickElement('<заголовок группы>') — переключить (голый клик)
// clickElement('<group title>', { expand: true }) — reveal (idempotent)
// clickElement('<group title>', { expand: false }) — hide (idempotent)
// clickElement('<group title>', { toggle: true }) — flip
// clickElement('<group title>') — flip (bare click)
//
// target.collapsed приходит из findClickTargetScript (по display первого контент-сиблинга).
// target.collapsed comes from findClickTargetScript (groupCollapsed in dom/_shared.mjs).
import { page } from '../core/state.mjs';
import { scrollGroupIntoViewScript } from '../../dom.mjs';
import { waitForStable } from '../core/wait.mjs';
import { modifierClick, returnFormState } from '../core/helpers.mjs';
import { shouldClickToggle } from '../table/grid-toggle.mjs';
// Group captions repeat across a form's blocks («Показать детализацию» in every block), and a
// collapsible group swaps its own caption when expanded (CollapsedRepresentationTitle:
// «Показать детализацию» ↔ «Скрыть детализацию»). Compare normalised so a real caption swap
// is not confused with nbsp/ё spelling differences.
const norm = (s) => (s || '').replace(/ /g, ' ').replace(/ё/gi, 'е').trim().toLowerCase();
export async function clickFormGroupTarget(target, ctx) {
const { formNum, modifier, toggle, expand } = ctx;
// shouldClickToggle ждёт { isExpanded }; при неизвестном состоянии (undefined) кликаем всегда.
// shouldClickToggle expects { isExpanded }; with an unknown state (undefined) always click.
const state = target.collapsed == null ? null : { isExpanded: !target.collapsed };
const shouldClick = shouldClickToggle(state, expand, toggle);
if (shouldClick) await modifierClick(target.x, target.y, modifier);
if (shouldClick) {
// The target is clicked by coordinates, and on a long form those go stale or fall outside
// the viewport — the click then silently does nothing. Scroll the title into view and take
// a fresh point.
const pt = await page.evaluate(scrollGroupIntoViewScript(formNum, target.label));
await modifierClick(pt?.x ?? target.x, pt?.y ?? target.y, modifier);
}
await waitForStable(formNum);
const result = await returnFormState({
clicked: { kind: 'formGroup', name: target.name, toggled: shouldClick, ...(modifier ? { modifier } : {}) },
@@ -27,11 +41,22 @@ export async function clickFormGroupTarget(target, ctx) {
: 'Group already in desired state.',
});
// Постусловие: клик, который ничего не переключил, — молчаливая ложь (то же правило, что
// guard на disabled в core/click.mjs). Проверяем ТОЛЬКО когда клик реально был сделан и
// состояние читаемо: при collapsed == null (нераспознанная вёрстка) сверять не с чем.
// The technical name is the stable key: it finds the entry in groups[] and clicks the same
// group again. The caption cannot do that — it changes when the group expands.
const after = (result.groups || []).find(g => g.name === target.label);
if (target.label) result.clicked.group = target.label;
if (after) {
result.clicked.title = after.title;
if (norm(after.title) !== norm(target.name)) {
result.hint += ` The group is now titled "${after.title}"`
+ ` — click it by that caption or by its technical name "${target.label}".`;
}
}
// Postcondition: a click that toggled nothing is a silent lie (same rule as the disabled
// guard in core/click.mjs). Checked ONLY when a click actually happened and the state is
// readable: with collapsed == null (unrecognised layout) there is nothing to compare against.
if (shouldClick && target.collapsed != null) {
const after = (result.groups || []).find(g => g.name === target.label);
if (after && after.collapsed === target.collapsed) {
throw new Error(`clickElement: group "${target.name}" did not toggle `
+ `(collapsed stayed ${after.collapsed})`);