rtl-analyzer 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,106 +2,116 @@
2
2
 
3
3
  Find direction-dependent styles, inspect suggested fixes, and review changes for RTL and LTR interfaces.
4
4
 
5
- [View on npm](https://www.npmjs.com/package/rtl-analyzer) · [Quick start](#quick-start) · [Review modes](#review-modes) · [Example](#example) · [Developer testing guide](https://github.com/FoushWare/rtl-analyzer/blob/main/docs/guides/developer-testing.md)
5
+ [Quick start](#quick-start) · [Workflow](#how-a-review-works) · [Example projects](#example-projects) · [Limits](#what-is-and-is-not-covered) · [Advanced setup guide](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/docs/guides/developer-testing.md)
6
6
 
7
7
  ## Quick start
8
8
 
9
9
  Requires **Node.js 22.12 or later**. Run from your frontend project's root:
10
10
 
11
11
  ```sh
12
- npx rtl-analyzer
12
+ npx rtl-analyzer@0.4.0
13
13
  ```
14
14
 
15
- Or install as a development dependency:
15
+ The command scans the current directory, writes reports to an external temporary directory and opens the report in your default browser. It does not start the live review services. For a scan of one directory, or command help:
16
16
 
17
17
  ```sh
18
- npm install --save-dev rtl-analyzer
19
- npx --no-install rtl-analyzer
18
+ npx rtl-analyzer@0.4.0 scan ./src --format json
19
+ npx rtl-analyzer@0.4.0 --help
20
20
  ```
21
21
 
22
- The default command scans the current directory, writes reports to an external temporary directory and requests your default browser. It does not start the live review services. For a scan of a specific directory or command help:
22
+ A read-only scan needs no configuration. **Live Fix Studio review does need configuration**: explicit scan and copy scope, validation scripts, source-to-page bindings, your project's installed dependencies and Chromium. The [advanced setup guide](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/docs/guides/developer-testing.md) covers it. To try the whole flow first, use one of the [example projects](#example-projects).
23
23
 
24
- ```sh
25
- npx rtl-analyzer scan ./src --format json
26
- npx rtl-analyzer --help
27
- npx rtl-analyzer preview --help
28
- ```
24
+ ## How a review works
29
25
 
30
- Read-only recursive scans need no configuration. **Live Fix Studio review requires configuration**: explicit scan/copy scope and validation scripts in `rtl-project.config.json`, source/selector/route bindings in `rtl-preview.config.json`, your project's installed dependencies, and Chromium. The current runtime adapter supports Vite-compatible development scripts. Follow the [developer testing guide](https://github.com/FoushWare/rtl-analyzer/blob/main/docs/guides/developer-testing.md) to generate a source-enabled dashboard, serve it and start the companion with `npx --no-install rtl-analyzer preview`.
26
+ The screenshots below come from the released package running on the Workspace Integration example: a shared badge whose `margin-left: 8px` should follow the text direction.
31
27
 
32
- ## What you can review
28
+ ### 1. Run the scan and open Fix Studio
33
29
 
34
- | In Fix Studio | What it helps you understand |
35
- | --- | --- |
36
- | Findings list | Which direction-dependent patterns need attention |
37
- | Highlighted source | Where a finding appears in your code |
38
- | Details | Why the pattern may affect RTL behavior |
39
- | Before / After | What the suggested fix changes |
40
- | Component Review | How the change fits the component's intended behavior |
41
- | Decision | Whether to accept the proposed change |
30
+ Scan with a dashboard report and embedded source snippets, serve the report, and start the review companion. The dashboard reports the scan result and the number of findings.
42
31
 
43
- ## Review modes
32
+ ![RTL Analyzer dashboard header after a completed scan: "Scan complete, analyzed 15 files, 2 findings".](https://raw.githubusercontent.com/FoushWare/rtl-analyzer/v0.4.0/docs/images/readme/00-scan-complete.png)
44
33
 
45
- | Mode | Workflow | Choose it when… |
46
- | --- | --- | --- |
47
- | Prepare all, then review | Prepare supported suggestions in an isolated candidate, then inspect them together. | You want to review the proposals together. |
48
- | Review one by one | Prepare and inspect a selected suggestion in isolation. | You want to examine each proposal individually. |
34
+ ### 2. Choose a review mode
49
35
 
50
- Both modes start **Pending**. Preparation leaves your source unchanged. Explicitly accept the proposals you want, run **Validate changes** on that accepted set, then use the separate **Apply accepted changes to source** action. Receipt-backed rollback restores applied changes when the source still matches the receipt. The persisted batch-mode identifier remains `apply-first`.
36
+ **Prepare all, then review** prepares every eligible change in one isolated candidate so you can review them together. **Review one by one** prepares only the finding you are looking at. Both modes start with every decision **Pending**, and neither changes your source.
51
37
 
52
- ## Example
38
+ ![Fix Studio's review-mode chooser with the two options "Prepare all, then review" and "Review one by one".](https://raw.githubusercontent.com/FoushWare/rtl-analyzer/v0.4.0/docs/images/readme/01-choose-review-mode.png)
53
39
 
54
- A card uses physical left and right spacing:
40
+ ### 3. Find the finding in your code and on the page
55
41
 
56
- ```css
57
- .card {
58
- margin-left: 16px;
59
- padding-right: 24px;
60
- text-align: left;
61
- }
62
- ```
42
+ Each finding shows its highlighted source line and why it was flagged. For findings with a configured page binding, **Highlight targets** outlines the affected element in the running page.
63
43
 
64
- A suggested change uses logical properties:
44
+ ![A finding open in Fix Studio: the highlighted line "margin-left: 8px;" in the stylesheet, the rule explanation, and the highlighted element in the rendered page.](https://raw.githubusercontent.com/FoushWare/rtl-analyzer/v0.4.0/docs/images/readme/02-locate-finding.png)
65
45
 
66
- ```css
67
- .card {
68
- margin-inline-start: 16px;
69
- padding-inline-end: 24px;
70
- text-align: start;
71
- }
72
- ```
46
+ ### 4. Compare Before and After
73
47
 
74
- In horizontal writing mode (`horizontal-tb`), inline-start maps to the left in LTR and to the right in RTL. Use this change when the spacing should follow the text direction; keep physical positioning when the design requires a fixed side.
48
+ The code card shows the original declaration next to the suggested one. The live panes render the original application (Before) and an isolated copy with the change (After). Switch between **LTR** and **RTL**, and between apps when a finding is bound to more than one. In one-by-one mode, After shows only the finding you selected.
75
49
 
76
- ## A typical review
50
+ ![Before and After live panes side by side in RTL, with the badge outlined in both.](https://raw.githubusercontent.com/FoushWare/rtl-analyzer/v0.4.0/docs/images/readme/03-before-after.png)
77
51
 
78
- 1. Configure the project and scan it with source snippets enabled.
79
- 2. Start the dashboard server and companion, then choose a review mode.
80
- 3. Inspect a finding, its highlighted source and the mapped component.
81
- 4. Compare the original code with the suggestion in RTL and LTR.
82
- 5. Accept, reject or defer the proposal according to the component's intent.
83
- 6. Validate the accepted set, then separately apply it to source.
84
- 7. Verify the affected interface in both RTL and LTR.
52
+ ### 5. Make a decision
85
53
 
86
- If source or accepted decisions change during review, freshness checks can invalidate suggestions or validation. Failed or unavailable required evidence blocks source Apply.
54
+ Choose **Approve proposed change**, **Reject fix**, **Defer** or **Needs review**. Approving adds the change to your accepted set. Your project files still have not changed.
87
55
 
88
- ## What a scan does—and what still needs checking
56
+ ![Confirmation after approving a change: "Added to your accepted changes. Your project files have not changed."](https://raw.githubusercontent.com/FoushWare/rtl-analyzer/v0.4.0/docs/images/readme/04-decision.png)
89
57
 
90
- | The tool helps with | You still need to check |
91
- | --- | --- |
92
- | Finding direction-dependent code patterns | Whether the pattern is actually a bug |
93
- | Suggesting direction-aware alternatives | Whether the change matches the design |
94
- | Showing source context and proposed changes | The rendered component in RTL and LTR |
95
- | Identifying potentially stale suggestions | The latest source before applying a change |
58
+ ### 6. Validate the accepted changes
59
+
60
+ **Validate changes** runs your configured checks, and a scoped LTR/RTL runtime check, against a candidate that contains only the accepted changes.
61
+
62
+ ![Dialog "Validation passed: 1 changes validated. Your original source files have not changed."](https://raw.githubusercontent.com/FoushWare/rtl-analyzer/v0.4.0/docs/images/readme/05-validate.png)
63
+
64
+ ### 7. Apply to source, explicitly
65
+
66
+ Applying is a separate step. The confirmation names the destination project and every file that will be written. Rejected, deferred and unaccepted findings are excluded, and Apply creates receipt-backed backups.
67
+
68
+ ![The "Apply changes to source" confirmation listing the destination project and the affected file.](https://raw.githubusercontent.com/FoushWare/rtl-analyzer/v0.4.0/docs/images/readme/06-apply-confirmation.png)
69
+
70
+ Afterwards, check your diff and the interface in both directions.
71
+
72
+ ![Fix Studio after Apply, with the accepted change recorded as applied.](https://raw.githubusercontent.com/FoushWare/rtl-analyzer/v0.4.0/docs/images/readme/07-applied.png)
96
73
 
97
- Static HTML/CSS, CSS Modules, React inline styles, Emotion and MUI patterns are analyzed conservatively. Recognized utility classes and bounded SCSS declarations are detection-only; dynamic or ambiguous syntax may remain unsupported. A scan reports potential issues. It does not prove that a page renders correctly or replace browser testing.
74
+ ### 8. Roll back if needed
98
75
 
99
- Report publication and protected source operations use a trusted POSIX filesystem profile on macOS/Linux. Windows protected operations are unsupported. Safari, other package managers and an existing real-world project's acceptance remain unverified; no general framework compatibility is certified. Project scripts must be trusted. See the [setup and limitations](https://github.com/FoushWare/rtl-analyzer/blob/main/docs/guides/developer-testing.md) and [release evidence](https://github.com/FoushWare/rtl-analyzer/blob/main/docs/releases/rtl-analyzer-0.3.0.md).
76
+ **Review actions → Rollback applied changes** restores the files from the receipt. Rollback is refused if you edited the files after Apply, so it never overwrites your later work.
100
77
 
101
- ## Demo
78
+ ![The Review actions menu showing "Rollback applied changes".](https://raw.githubusercontent.com/FoushWare/rtl-analyzer/v0.4.0/docs/images/readme/08-rollback.png)
79
+
80
+ ### Batch mode: prepare eligible changes, then approve selected ones
81
+
82
+ In **Prepare all, then review**, the batch overview lists every change that could be prepared. Nothing is approved automatically. Select the rows you want, **Approve selected**, then **Validate** and apply as above. Preparing a batch never writes to your source; applying it requires the same explicit confirmation. Use **View diff** to inspect any row.
83
+
84
+ ![Batch review overview with two prepared fixes, a row checkbox for each, and the buttons Select all prepared, Approve selected and Validate.](https://raw.githubusercontent.com/FoushWare/rtl-analyzer/v0.4.0/docs/images/readme/09-batch-review.png)
85
+
86
+ If your source or your decisions change during a review, freshness checks can invalidate a suggestion or a validation. Failed or unavailable required evidence blocks Apply.
87
+
88
+ ## What is and is not covered
89
+
90
+ Verified in this release (macOS, Chromium, desktop width):
91
+
92
+ - **Suggested fixes and live Before/After** for literal physical `margin-*`, `padding-*` and `text-align` in simple class rules of stylesheets you declare as `custom-css`, and for other declarations (borders, offsets, transforms) you declare yourself in `cssProposals` ([CSS proposal setup](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/docs/guides/css-proposal-setup.md)).
93
+ - **Findings without a safe automatic fix** (for example fixed-edge positioning, ordering, transforms) are reported with an explanation and marked for manual review; you still get the Before view.
94
+ - **Detection only:** recognized utility classes and bounded SCSS declarations.
95
+ - **Live preview** supports Vite-compatible development scripts, including an Nx workspace that runs Vite. Next.js apps can be scanned statically, but live preview is not supported.
96
+ - **Not detected:** JavaScript key handling, focus order and other behavior that is not expressed in styles.
97
+
98
+ A scan reports potential issues; it does not prove a page renders correctly. Report publication and protected source operations use a trusted POSIX filesystem profile (macOS and Linux); Windows protected operations are unsupported. Safari, package managers other than npm and general framework compatibility are not certified. Project scripts must be trusted.
99
+
100
+ ## Example projects
101
+
102
+ Six runnable projects live in the repository under [`examples/`](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples). They are not part of the npm package. Copy one to a temporary folder before you apply anything.
103
+
104
+ | Project | What it shows |
105
+ | --- | --- |
106
+ | [Foundations Lab](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/foundations-lab) | Direction, spacing, edges, transforms in a Vite app |
107
+ | [Account Checkout](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/account-checkout) | Two supported fixes, one manual-review case, clean controls |
108
+ | [Admin Dashboard](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/admin-dashboard) | Tables, dialog and tabs; several manual-review findings |
109
+ | [Bilingual Storefront](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/bilingual-storefront) | Next.js and Tailwind; static scan only |
110
+ | [Interaction Playground](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/interaction-playground) | Drawer, rating and slider; scanner finds CSS risks, not key handling |
111
+ | [Workspace Integration](https://github.com/FoushWare/rtl-analyzer/tree/v0.4.0/examples/workspace-integration) | Nx workspace, two apps and a shared library |
102
112
 
103
- A video walkthrough and released-product screenshots have not been published yet.
113
+ Each project's README has its setup instructions and expected findings. The [hands-on testing guide](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/docs/guides/example-testing-guide.md) walks through all six.
104
114
 
105
115
  ## Development
106
116
 
107
- The public package bundles the pinned implementation at build time. Consumers install `rtl-analyzer`; the internal `@atlas/rtl-scanner` package is private. Clone with submodules and follow the [build, pack and verification commands](https://github.com/FoushWare/rtl-analyzer/blob/main/docs/guides/developer-testing.md#build-pack-and-verify). The package is licensed under [MIT](https://github.com/FoushWare/rtl-analyzer/blob/main/packages/rtl-analyzer/LICENSE).
117
+ The public package bundles a pinned implementation at build time. Consumers install `rtl-analyzer`; the internal `@atlas/rtl-scanner` package is private. Clone with submodules and follow the [build, pack and verification commands](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/docs/guides/developer-testing.md#build-pack-and-verify). Licensed under [MIT](https://github.com/FoushWare/rtl-analyzer/blob/v0.4.0/packages/rtl-analyzer/LICENSE).
@@ -41,24 +41,27 @@ function installContextPreview(config){
41
41
  await wait(60);document.querySelector('form button[type="submit"]')?.click();await until(()=>document.querySelector('.MuiDialogContent-root'));
42
42
  }
43
43
  }
44
- let cssEpoch=0,cssSignature='',cssCache=new WeakMap();
44
+ let cssEpoch=0,cssSignature='',cssCache=new WeakMap(),lastDirectionSignature='',directionRevision=0;
45
45
  const invalidateCss=()=>cssEpoch++;
46
- new MutationObserver(records=>{if(records.some(record=>{const node=record.target.nodeType===1?record.target:record.target.parentElement;return !node?.closest('[data-rtl-context-overlay]')}))invalidateCss()}).observe(document.documentElement,{subtree:true,childList:true,attributes:true,characterData:true});
46
+ const directionSnapshot=()=>{if(!active)return '';const nodes=select(active.mapping.selector);return JSON.stringify({root:getComputedStyle(document.documentElement).direction,targets:nodes.map(node=>getComputedStyle(node).direction),href:location.href});};
47
+ const notifyDirectionChange=()=>{if(!active)return;const signature=directionSnapshot();if(!signature||signature===lastDirectionSignature)return;lastDirectionSignature=signature;directionRevision++;parent.postMessage({type:'rtl-context-direction-changed',version:2,nonce:active.request.nonce,role:identity.role,application:identity.application,projectRoot:identity.projectRoot,sessionId:active.request.sessionId,runtimeSessionId:identity.sessionId,findingId:active.request.findingId,sourcePath:active.request.sourcePath,sourceSha256:config.sourceHashes[active.request.sourcePath],routeId:active.request.routeId,directionRevision,href:location.href,directions:JSON.parse(signature)},dashboardOrigin)};
48
+ new MutationObserver(records=>{if(records.some(record=>{const node=record.target.nodeType===1?record.target:record.target.parentElement;return !node?.closest('[data-rtl-context-overlay]')})){invalidateCss();notifyDirectionChange()}}).observe(document.documentElement,{subtree:true,childList:true,attributes:true,characterData:true});
47
49
  for(const type of ['pointerover','pointerout','focusin','focusout','input','change','click'])document.addEventListener(type,invalidateCss,true);
48
- window.addEventListener('hashchange',invalidateCss);window.addEventListener('resize',invalidateCss);
50
+ window.addEventListener('hashchange',()=>{invalidateCss();notifyDirectionChange()});window.addEventListener('resize',()=>{invalidateCss();notifyDirectionChange()});setInterval(notifyDirectionChange,250);
49
51
  function specificity(selector){const clean=selector.replace(/:where\([^)]*\)/g,'').replace(/::[\w-]+/g,'').replace(/:(is|not|has)\(/g,'(');return [(clean.match(/#[\w-]+/g)||[]).length,(clean.match(/\.[\w-]+|\[[^\]]+\]|:[\w-]+/g)||[]).length,(clean.replace(/#[\w-]+|\.[\w-]+|\[[^\]]+\]|:[\w-]+/g,'').match(/(?:^|[\s>+~(])([a-z][\w-]*)/gi)||[]).length]}
50
52
  function styleRules(){const out=[];let order=0;function walk(rules,owner,conditions,enabled){for(const rule of rules){if(rule.selectorText&&rule.style)out.push({rule,owner,conditions,enabled,order:order++});else if(rule.cssRules){let active=enabled;const condition=rule.conditionText||'';if(rule.constructor.name==='CSSMediaRule')active=active&&matchMedia(condition).matches;else if(rule.constructor.name==='CSSSupportsRule')active=active&&CSS.supports(condition);walk(rule.cssRules,owner,condition?[...conditions,condition]:conditions,active)}}}for(const sheet of document.styleSheets){try{walk(sheet.cssRules,sheet.ownerNode,[],!sheet.disabled&&(!sheet.media?.mediaText||matchMedia(sheet.media.mediaText).matches))}catch{}}return out}
53
+ function ownerMatches(owner,path){const vite=owner?.getAttribute('data-vite-dev-id')?.replaceAll('\\','/');if(vite?.endsWith('/'+path))return true;try{if(owner?.tagName!=='LINK')return false;const url=new URL(owner.href,location.href);return url.origin===location.origin&&decodeURIComponent(url.pathname)==='/'+path}catch{return false}}
51
54
  function cssResult(node,css,finding,rules){
52
- const key=[cssEpoch,finding.id,css.property,document.documentElement.dir,innerWidth,innerHeight].join('|'),cached=cssCache.get(node);
55
+ const key=[cssEpoch,finding.id,css.property,getComputedStyle(node).direction,innerWidth,innerHeight].join('|'),cached=cssCache.get(node);
53
56
  if(cached?.key===key&&getComputedStyle(node).getPropertyValue(cached.result.resolvedProperty)===cached.result.computedValue)return cached.result;
54
57
  let property=css.property;const opposite={'margin-left':'margin-right','margin-right':'margin-left','right':'left','left':'right'};
55
- if(css.inline&&!node.style.getPropertyValue(property)&&document.documentElement.dir==='rtl'&&opposite[property]&&rules.some(r=>r.enabled&&r.rule.style.getPropertyValue(opposite[property])===css.value&&safeMatches(node,r.rule.selectorText)))property=opposite[property];
58
+ if(css.inline&&!node.style.getPropertyValue(property)&&getComputedStyle(node).direction==='rtl'&&opposite[property]&&rules.some(r=>r.enabled&&r.rule.style.getPropertyValue(opposite[property])===css.value&&safeMatches(node,r.rule.selectorText)))property=opposite[property];
56
59
  const applicable=[],sources=[];
57
- for(const entry of rules){const {rule}=entry;if(!safeMatches(node,rule.selectorText))continue;const value=rule.style.getPropertyValue(property);if(!value)continue;const spec=rule.selectorText.split(',').filter(s=>safeMatches(node,s)).map(specificity).sort(compare).at(-1)||[0,0,0];const source=css.selector?entry.owner?.getAttribute('data-vite-dev-id')?.replaceAll('\\','/').includes('/'+finding.path)&&rule.selectorText.split(',').map(s=>s.trim()).includes(css.selector):value.replace(/\s/g,'')===css.value.replace(/\s/g,'');
60
+ for(const entry of rules){const {rule}=entry;if(!safeMatches(node,rule.selectorText))continue;const value=rule.style.getPropertyValue(property);if(!value)continue;const spec=rule.selectorText.split(',').filter(s=>safeMatches(node,s)).map(specificity).sort(compare).at(-1)||[0,0,0];const source=css.selector?ownerMatches(entry.owner,finding.path)&&rule.selectorText.split(',').map(s=>s.trim()).includes(css.selector):value.replace(/\s/g,'')===css.value.replace(/\s/g,'');
58
61
  const candidate={...entry,value,source,rank:[rule.style.getPropertyPriority(property)==='important'?1:0,0,...spec,entry.order]};if(source)sources.push(candidate);if(entry.enabled)applicable.push(candidate);
59
62
  }
60
63
  if(node.style.getPropertyValue(property)){const candidate={value:node.style.getPropertyValue(property),source:!!css.inline,conditions:[],enabled:true,rank:[node.style.getPropertyPriority(property)==='important'?1:0,1,0,0,0,1e9]};applicable.push(candidate);if(candidate.source)sources.push(candidate)}
61
- const winner=applicable.sort((a,b)=>compare(a.rank,b.rank)).at(-1),conditionActive=(!css.media||matchMedia(css.media).matches)&&(!css.rtlOnly||document.documentElement.dir==='rtl'&&!node.classList.contains('is-open'));
64
+ const winner=applicable.sort((a,b)=>compare(a.rank,b.rank)).at(-1),conditionActive=(!css.media||matchMedia(css.media).matches)&&(!css.rtlOnly||getComputedStyle(node).direction==='rtl'&&!node.classList.contains('is-open'));
62
65
  const result={sourceProperty:css.property,resolvedProperty:property,declaredValue:css.value,computedValue:getComputedStyle(node).getPropertyValue(property),selectorMatched:true,conditionActive,contribution:!conditionActive?'inactive':winner?.source?'contributing':sources.some(s=>s.enabled)?'overridden':'unresolved-cascade',winner:winner?{value:winner.value,selector:winner.rule?.selectorText||'style attribute',conditions:winner.conditions}:null,limitation:'CSSOM cascade attribution for these example rules (normal/important, specificity, order, media/supports, inline and generated sx); no universal layered/shadow stylesheet analysis. A contribution is not an RTL-defect verdict.'};cssCache.set(node,{key,result});return result;
63
66
  }
64
67
  function compare(a,b){for(let i=0;i<Math.max(a.length,b.length);i++){const delta=(a[i]||0)-(b[i]||0);if(delta)return delta}return 0}
@@ -75,18 +78,20 @@ function installContextPreview(config){
75
78
  if(!resolveData(request))return;
76
79
  const key=[request.nonce,request.findingId,request.routeId].join('|');
77
80
  if(!active||active.key!==key){active={key,mapping:binding.mapping,instance:request.instance,request};lastScroll='';preparing=true;try{await until(()=>document.querySelector(config.readySelector||'#root > *'));if(routeMatches(route,request))await prepare(route,binding.mapping)}finally{if(active?.key===key)preparing=false}}
81
+ else if(preparing)return;
78
82
  if(active?.key!==key)return;active.instance=request.instance;active.request=request;
79
83
  if(request.command==='reveal-navigation'){document.querySelector('.mobile-menu')?.click();await wait(80)}
80
84
  if(request.command==='reset-data'&&storageKey&&validSeed(request.seedData)){localStorage.setItem(storageKey,request.seedData);const next=new URL(route.path,location.origin);for(const key of ['demo','lang']){const value=new URLSearchParams(location.search).get(key);if(value)next.searchParams.set(key,value)}location.replace(next.href);return}
85
+ const probeRevision=directionRevision;
81
86
  const nodes=routeMatches(route,request)?select(binding.mapping.selector):[];
82
87
  if(request.command==='highlight')lastScroll='';
83
88
  const scrollKey=key+':'+request.instance+':'+nodes.length;if(request.instance!==-2&&nodes.length&&lastScroll!==scrollKey){const node=nodes[Math.max(0,request.instance)]||nodes[0];if(visible(node))node.scrollIntoView({block:'center',inline:'nearest',behavior:'instant'});lastScroll=scrollKey}
84
89
  boxes(nodes,request.instance);
85
90
  const rules=binding.mapping.css?styleRules():[];
86
91
  if(binding.mapping.css){const signature=rules.map(entry=>[entry.enabled,entry.conditions.join(' '),entry.rule.cssText].join('|')).join('\n');if(signature!==cssSignature){cssSignature=signature;cssEpoch++;cssCache=new WeakMap()}}
87
- const sourceRules=binding.mapping.configured&&binding.mapping.sourceSelector?styleRules().filter(entry=>entry.owner?.getAttribute('data-vite-dev-id')?.replaceAll('\\','/').endsWith('/'+binding.finding.path)&&entry.rule.selectorText.split(',').map(s=>s.trim()).includes(binding.mapping.sourceSelector)):[];
92
+ const sourceRules=binding.mapping.configured&&binding.mapping.sourceSelector?styleRules().filter(entry=>ownerMatches(entry.owner,binding.finding.path)&&entry.rule.selectorText.split(',').map(s=>s.trim()).includes(binding.mapping.sourceSelector)):[];
88
93
  const sourceStatus=!binding.mapping.configured||!binding.mapping.sourceSelector?'not-required':!sourceRules.length?'source-not-observed':!nodes.length?'target-not-found':nodes.some(node=>sourceRules.some(entry=>safeMatches(node,entry.rule.selectorText)))?'source-rule-matched':'target-source-mismatch';
89
- const targets=nodes.map((node,index)=>{const r=node.getBoundingClientRect();const explicitKey=node.getAttribute('id')||node.getAttribute('data-id')||node.getAttribute('data-key')||node.getAttribute('data-testid')||node.getAttribute('data-target-id');const nameSelector='h1,h2,h3,h4,h5,h6,strong,[data-name],.name,.contact-name';const h=(node.matches?.(nameSelector)?node:null)||node.querySelector?.(nameSelector);const nameText=(h?.textContent||node.getAttribute('aria-label')||node.getAttribute('title')||'').trim().replace(/\s+/g,' ');const emailSelector='.email,.contact-email,a[href^="mailto:"]';const emailEl=(node.matches?.(emailSelector)?node:null)||node.querySelector?.(emailSelector);const emailText=(emailEl?.textContent||emailEl?.getAttribute('href')?.replace(/^mailto:/,'')||'').trim();const cleanLabel=(binding.mapping.kind==='document'?'Whole document · '+document.title:(nameText||(emailText?emailText.split('@')[0]:'Target '+(index+1)))).slice(0,100);const rawCandidateKey=explicitKey||(nameText&&emailText?nameText+' · '+emailText:nameText||emailText||null);return {index,rawKey:rawCandidateKey,hasExplicitKey:!!explicitKey,label:cleanLabel,name:nameText||null,rendered:visible(node),inViewport:r.right>0&&r.bottom>0&&r.left<innerWidth&&r.top<innerHeight,rect:{x:r.x,y:r.y,width:r.width,height:r.height},...(binding.mapping.css?{css:cssResult(node,binding.mapping.css,binding.finding,rules)}:{})}});
94
+ const targets=nodes.map((node,index)=>{const r=node.getBoundingClientRect();const explicitKey=node.getAttribute('id')||node.getAttribute('data-id')||node.getAttribute('data-key')||node.getAttribute('data-testid')||node.getAttribute('data-target-id');const nameSelector='h1,h2,h3,h4,h5,h6,strong,[data-name],.name,.contact-name';const h=(node.matches?.(nameSelector)?node:null)||node.querySelector?.(nameSelector);const nameText=(h?.textContent||node.getAttribute('aria-label')||node.getAttribute('title')||'').trim().replace(/\s+/g,' ');const emailSelector='.email,.contact-email,a[href^="mailto:"]';const emailEl=(node.matches?.(emailSelector)?node:null)||node.querySelector?.(emailSelector);const emailText=(emailEl?.textContent||emailEl?.getAttribute('href')?.replace(/^mailto:/,'')||'').trim();const cleanLabel=(binding.mapping.kind==='document'?'Whole document · '+document.title:(nameText||(emailText?emailText.split('@')[0]:'Target '+(index+1)))).slice(0,100);const rawCandidateKey=explicitKey||(nameText&&emailText?nameText+' · '+emailText:nameText||emailText||null);return {index,effectiveDirection:getComputedStyle(node).direction,pageDirection:getComputedStyle(document.documentElement).direction,rawKey:rawCandidateKey,hasExplicitKey:!!explicitKey,label:cleanLabel,name:nameText||null,rendered:visible(node),inViewport:r.right>0&&r.bottom>0&&r.left<innerWidth&&r.top<innerHeight,rect:{x:r.x,y:r.y,width:r.width,height:r.height},...(binding.mapping.css?{css:cssResult(node,binding.mapping.css,binding.finding,rules)}:{})}});
90
95
  const keyCounts={};targets.forEach(t=>{if(t.rawKey)keyCounts[t.rawKey]=(keyCounts[t.rawKey]||0)+1});
91
96
  targets.forEach(t=>{
92
97
  if(t.rawKey&&keyCounts[t.rawKey]===1){t.key=t.rawKey;t.keyGuaranteed=true;t.ambiguous=false}
@@ -105,9 +110,9 @@ function installContextPreview(config){
105
110
  }
106
111
  });
107
112
  const seedData=storageKey?localStorage.getItem(storageKey):null,defaultSeedData=JSON.stringify(window.__rtlPreviewSeedInvoices||[]);
108
- const dataFingerprint=seedData?await fingerprint(seedData):null;if(active?.key!==key)return;lastFingerprint=dataFingerprint;
113
+ const dataFingerprint=seedData?await fingerprint(seedData):null;if(active?.key!==key||probeRevision!==directionRevision)return;lastFingerprint=dataFingerprint;
109
114
  const routeReady=!!document.querySelector(config.readySelector||'#root > *');
110
- parent.postMessage({type:'rtl-context-status',version:2,nonce:request.nonce,role:identity.role,application:identity.application,projectRoot:identity.projectRoot,sessionId:request.sessionId,runtimeSessionId:identity.sessionId,findingId:request.findingId,sourcePath:request.sourcePath,sourceSha256:config.sourceHashes[request.sourcePath],routeId:request.routeId,route:location.pathname,dir:document.documentElement.dir,routeReady,sourceStatus,targetStatus:preparing?'preparing':!routeReady?'route-not-ready':!routeMatches(route,request)?'navigated':sourceStatus==='source-not-observed'?'source-not-loaded':sourceStatus==='target-source-mismatch'?'target-mismatch':targets.some(t=>t.rendered)?binding.mapping.kind==='document'?'document':'verified':targets.length?'hidden':binding.mapping.configured?'missing-target':'unresolved',targets,dataFingerprint,seedData,defaultSeedData,dataScope:storageKey,fixtureData:config.dataAdapter==='none'?'application-data':'atlas-seed-v1'},dashboardOrigin);
115
+ parent.postMessage({type:'rtl-context-status',version:2,nonce:request.nonce,role:identity.role,application:identity.application,projectRoot:identity.projectRoot,sessionId:request.sessionId,runtimeSessionId:identity.sessionId,findingId:request.findingId,sourcePath:request.sourcePath,sourceSha256:config.sourceHashes[request.sourcePath],routeId:request.routeId,directionRevision:probeRevision,route:location.pathname,dir:getComputedStyle(document.documentElement).direction,routeReady,sourceStatus,targetStatus:preparing?'preparing':!routeReady?'route-not-ready':!routeMatches(route,request)?'navigated':sourceStatus==='source-not-observed'?'source-not-loaded':sourceStatus==='target-source-mismatch'?'target-mismatch':targets.some(t=>t.rendered)?binding.mapping.kind==='document'?'document':'verified':targets.length?'hidden':binding.mapping.configured?'missing-target':'unresolved',targets,dataFingerprint,seedData,defaultSeedData,dataScope:storageKey,fixtureData:config.dataAdapter==='none'?'application-data':'atlas-seed-v1'},dashboardOrigin);
111
116
  });
112
117
  }
113
118
  `;
@@ -3,7 +3,7 @@ import { readFile } from 'node:fs/promises';
3
3
  import { loadPreviewConfiguration, configuredMapping, routeUrl } from './preview-configuration.js';
4
4
  import { scan } from './scan.js';
5
5
  import { validateProjectSourcePath, candidateApplicationRuntime } from './review-session.js';
6
- import { composeWorkflowFile } from './review-workflow.js';
6
+ import { candidateEntries, composeWorkflowFile } from './review-workflow.js';
7
7
  import { verifiedSourceTransition } from './source-context.js';
8
8
  import { classifyEligibility } from './eligibility.js';
9
9
  export const ORIGINAL_PREVIEW_ORIGINS = { invoicing: 'http://127.0.0.1:4200', procurement: 'http://127.0.0.1:4201' };
@@ -56,12 +56,12 @@ export async function contextualPreview(root, query, workflow) {
56
56
  if (workflow?.session && entry && workflow.state === 'Reviewing') {
57
57
  // Verify the selected candidate file against its immutable baseline and actual patch membership.
58
58
  for (const [path, baseline] of Object.entries(workflow.baseline)) {
59
- const expected = composeWorkflowFile(baseline, workflow.entries.filter(e => e.patch?.path === path && e.applied && !['Rejected', 'Deferred', 'Flagged'].includes(e.decision)).map(e => e.patch));
59
+ const expected = composeWorkflowFile(baseline, candidateEntries(workflow).filter(e => e.patch?.path === path).map(e => e.patch));
60
60
  if (await readFile(await validateProjectSourcePath(workflow.session.candidateRoot, path), 'utf8') !== expected)
61
61
  throw Error('STALE_CANDIDATE_SOURCE');
62
62
  }
63
63
  const before = workflow.baseline[finding.path];
64
- const expected = composeWorkflowFile(before, workflow.entries.filter(e => e.patch?.path === finding.path && e.applied && !['Rejected', 'Deferred', 'Flagged'].includes(e.decision)).map(e => e.patch));
64
+ const expected = composeWorkflowFile(before, candidateEntries(workflow).filter(e => e.patch?.path === finding.path).map(e => e.patch));
65
65
  const candidateSource = await readFile(await validateProjectSourcePath(workflow.session.candidateRoot, finding.path), 'utf8');
66
66
  if (candidateSource !== expected)
67
67
  throw Error('STALE_CANDIDATE_SOURCE');
@@ -0,0 +1,98 @@
1
+ import postcss from 'postcss';
2
+ import { directionalProperty, propertyConflict } from './directional-properties.js';
3
+ import { hash } from './model.js';
4
+ export const CSS_CONFIGURED_TRANSFORMATION_ID = 'css-configured-intent';
5
+ const offsetVariable = (context, property) => '--rtl-offset-' + hash(context + '\0' + property).slice(0, 16);
6
+ function parseOffset(property, value) {
7
+ if (property === 'transform')
8
+ return /^translateX\((-?\d+(?:\.\d+)?)(%|px)\)$/.exec(value);
9
+ if (property === 'box-shadow')
10
+ return /^(-?\d+(?:\.\d+)?)(px)\s+0(?:px)?\s+\d+(?:\.\d+)?px\s+#[\da-f]{3,8}$/i.exec(value);
11
+ return null;
12
+ }
13
+ /** Suppress the physical-offset finding only when both literal directional branches are present. */
14
+ export function hasMirroredCssOffset(declaration, evidence) {
15
+ if (declaration.mechanism !== 'css' || !['transform', 'box-shadow'].includes(declaration.property))
16
+ return false;
17
+ const variable = offsetVariable(declaration.context, declaration.property);
18
+ const use = new RegExp(`var\\(${variable}, (-?\\d+(?:\\.\\d+)?(?:%|px))\\)`).exec(declaration.value);
19
+ if (!use)
20
+ return false;
21
+ const offset = parseOffset(declaration.property, declaration.value.replace(use[0], use[1]));
22
+ if (!offset || Number(offset[1]) === 0)
23
+ return false;
24
+ const definitions = evidence.filter(e => e.path === declaration.path && e.mechanism === 'css' && e.property === variable);
25
+ return definitions.length === 2 && definitions.some(e => e.context === declaration.context && e.value === use[1])
26
+ && definitions.some(e => e.context === declaration.context + '/&:dir(rtl)' && e.value === String(-Number(offset[1])) + offset[2]);
27
+ }
28
+ function replacementFor(declaration, finding) {
29
+ const rule = declaration.parent;
30
+ const intent = finding.cssProposal;
31
+ const { prop, value } = declaration;
32
+ if (rule?.type !== 'rule')
33
+ throw Error('CSS_INTENT_EXPECTED_RULE');
34
+ const peers = rule.nodes.filter((node) => node.type === 'decl' && node !== declaration);
35
+ const base = declaration.clone();
36
+ const serialize = (declarations) => declarations.map(d => d.toString()).join('; ') + (finding.original.endsWith(';') ? ';' : '');
37
+ if (peers.some(d => d.prop === prop || /^(all|direction|writing-mode)$/.test(d.prop)))
38
+ throw Error('CSS_INTENT_CONFLICTING_DECLARATIONS');
39
+ if (intent.kind === 'inline-edge') {
40
+ const spec = directionalProperty(prop, value);
41
+ if (!spec || !['borders', 'positioning'].includes(spec.family))
42
+ throw Error('CSS_INTENT_UNSUPPORTED_EDGE');
43
+ if (peers.some(d => propertyConflict(prop, d.prop, spec.family)))
44
+ throw Error('CSS_INTENT_CONFLICTING_EDGE');
45
+ if (spec.family === 'positioning' && !peers.some(d => d.prop === 'position' && /^(absolute|fixed)$/.test(d.value)))
46
+ throw Error('CSS_INTENT_EXPLICIT_POSITION_REQUIRED');
47
+ base.prop = spec.logical;
48
+ return serialize([base]);
49
+ }
50
+ if (intent.kind === 'dom-order') {
51
+ if (prop !== 'flex-direction' || value !== 'row-reverse' || !peers.some(d => d.prop === 'display' && /^(inline-)?flex$/.test(d.value)) || peers.some(d => d.prop === 'flex-flow'))
52
+ throw Error('CSS_INTENT_EXPLICIT_FLEX_ROW_REQUIRED');
53
+ base.value = 'row';
54
+ return serialize([base]);
55
+ }
56
+ if (intent.kind === 'logical-corners') {
57
+ const radii = value.split(/\s+/);
58
+ if (prop !== 'border-radius' || radii.length !== 4 || !radii.every(v => /^(0|\d+(?:\.\d+)?(?:px|rem|em|%))$/.test(v)) || peers.some(d => /^border-.*radius$/.test(d.prop)))
59
+ throw Error('CSS_INTENT_FOUR_LITERAL_CORNERS_REQUIRED');
60
+ return serialize(['start-start', 'start-end', 'end-end', 'end-start'].map((corner, i) => declaration.clone({ prop: `border-${corner}-radius`, value: radii[i] })));
61
+ }
62
+ if (intent.kind !== 'mirror-offset')
63
+ throw Error('CSS_INTENT_UNKNOWN');
64
+ const offset = parseOffset(prop, value);
65
+ if (!offset || Number(offset[1]) === 0)
66
+ throw Error('CSS_INTENT_LITERAL_HORIZONTAL_OFFSET_REQUIRED');
67
+ const variable = offsetVariable(finding.context, prop);
68
+ const literal = offset[1] + offset[2];
69
+ base.value = value.replace(literal, `var(${variable}, ${literal})`);
70
+ // Nest a direction-specific variable on the same target. Keep the original property and specificity.
71
+ return `${base.toString()}; ${variable}: ${literal}; &:dir(rtl) { ${variable}: ${-Number(offset[1])}${offset[2]}; }`;
72
+ }
73
+ export function proposeConfiguredCss(finding, source) {
74
+ const intent = finding.cssProposal;
75
+ if (!intent || intent.sourceDigest !== hash(source))
76
+ throw Error('CSS_INTENT_STALE_SOURCE');
77
+ if (finding.exceptionReason || finding.ownership !== 'custom-css' || finding.sourceMechanism !== 'css' || !finding.path.endsWith('.css'))
78
+ throw Error('CSS_INTENT_LOCAL_STYLESHEET_REQUIRED');
79
+ const { start, end } = finding.range;
80
+ const root = postcss.parse(source);
81
+ let declaration;
82
+ root.walkDecls(node => {
83
+ if (node.source?.start?.offset === start.offset && node.source?.end?.offset === end.offset)
84
+ declaration = node;
85
+ });
86
+ if (!declaration || source.slice(start.offset, end.offset) !== finding.original)
87
+ throw Error('CSS_INTENT_STALE_RANGE');
88
+ const d = declaration;
89
+ const rule = d.parent;
90
+ if (rule?.type !== 'rule' || rule.parent?.type !== 'root' || !/^\.[a-zA-Z_][\w-]*(?: \.[a-zA-Z_][\w-]*)*$/.test(rule.selector) || finding.context !== 'stylesheet/' + rule.selector)
91
+ throw Error('CSS_INTENT_UNSUPPORTED_SELECTOR');
92
+ if (rule.nodes.some(node => node.type !== 'decl' && node.type !== 'comment') || rule.nodes.some(node => node.type === 'comment' && /rtl-physical\s*:|rtl-icon\s*:/i.test(node.text)))
93
+ throw Error('CSS_INTENT_UNSUPPORTED_RULE_CONTENT');
94
+ const replacement = replacementFor(d, finding);
95
+ postcss.parse(source.slice(0, start.offset) + replacement + source.slice(end.offset));
96
+ return { transformationId: CSS_CONFIGURED_TRANSFORMATION_ID, reason: 'Project declares direction intent for this exact source. Verify the rendered result in each direction before approval.',
97
+ patch: { findingId: finding.id, path: finding.path, startOffset: start.offset, endOffset: end.offset, expectedSha256: hash(finding.original), replacement } };
98
+ }
@@ -37,19 +37,20 @@ export function proposeCssSpacing(finding, source) {
37
37
  reject('CSS_SPACING_UNSUPPORTED_RULE_CONTENT');
38
38
  if (rule.nodes.some(n => n.type === 'comment' && /rtl-physical\s*:/i.test(n.text)))
39
39
  reject('CSS_SPACING_INTENTIONAL_PHYSICAL');
40
- let writingMode = false, collision = false;
41
- root.walkDecls(n => { if (n.prop.toLowerCase() === 'writing-mode' && n.value !== 'horizontal-tb')
42
- writingMode = true; if (n.prop.toLowerCase() === 'direction')
43
- writingMode = true; });
44
- if (writingMode)
40
+ // A stylesheet selector alone cannot establish ancestry or co-matching classes.
41
+ // Proposal generation is syntactic; scoped browser evidence evaluates the actual
42
+ // cascade (including inheritance and active conditions) before validation/Apply.
43
+ // A directly declared non-horizontal mode is already conclusively unsupported.
44
+ if (rule.nodes.some(n => n.type === 'decl' && n.prop.toLowerCase() === 'writing-mode' && n.value.trim() !== 'horizontal-tb'))
45
45
  reject('CSS_SPACING_DIRECTION_OR_WRITING_MODE_REVIEW');
46
- root.walkRules(r => { if (r !== rule && (r.selector.includes(rule.selector) || r.selector.includes('*')))
46
+ const family = match[1];
47
+ const conflicts = (prop) => prop === 'all' || prop === family || prop.startsWith(family + '-inline') || prop.startsWith(family + '-block') || prop.startsWith(family + '-left') || prop.startsWith(family + '-right');
48
+ let collision = false;
49
+ root.walkRules(r => { if (r !== rule && (r.selector.includes(rule.selector) || r.selector.includes('*')) && r.nodes.some(n => n.type === 'decl' && conflicts(n.prop.toLowerCase())))
47
50
  collision = true; });
48
51
  if (collision)
49
52
  reject('CSS_SPACING_CASCADE_SELECTOR_CONFLICT');
50
- const family = match[1];
51
- if (rule.nodes.some(n => { if (n === d || n.type !== 'decl')
52
- return false; const prop = n.prop.toLowerCase(); return prop === 'all' || prop === 'position' || prop === 'writing-mode' || prop === 'direction' || prop === family || prop.startsWith(family + '-inline') || prop.startsWith(family + '-block') || prop === d.prop; }))
53
+ if (rule.nodes.some(n => n !== d && n.type === 'decl' && (conflicts(n.prop.toLowerCase()) || n.prop.toLowerCase() === 'position')))
53
54
  reject('CSS_SPACING_CASCADE_DECLARATION_CONFLICT');
54
55
  const tokens = valueParser(d.value).nodes.filter(n => n.type !== 'space' && n.type !== 'comment');
55
56
  if (tokens.length !== 1 || tokens[0].type !== 'word' || !/^(-?(?:\d*\.)?\d+(?:px|em|rem|%|vw|vh|ch|ex)?|auto)$/.test(tokens[0].value) || family === 'padding' && tokens[0].type === 'word' && (/^-/.test(tokens[0].value) || tokens[0].value === 'auto'))
@@ -0,0 +1,37 @@
1
+ /** Batch overview reuses persisted entries and existing detail/operation flows. */
2
+ export const batchReviewClientSource = String.raw `
3
+ let batchOpen=false,batchSelection=new Set(),batchScroll=0,batchOwner=null;
4
+ const batchStyle=el('style');batchStyle.textContent='.workspace[hidden]{display:none!important}.batch-review{margin:10px 12px;padding:18px;border-radius:12px;border:1px solid var(--theme-line);min-width:0}.batch-review p{margin:6px 0}.batch-review h2{margin:4px 0 8px;font-size:20px}.batch-review h1{font-size:32px;margin:0 0 6px;letter-spacing:-.02em}.batch-stage{color:var(--theme-muted);margin-bottom:14px!important;font-weight:650}.batch-stats{display:flex;flex-wrap:wrap;gap:10px;margin:12px 0}.batch-stat,.batch-panel{border:1px solid var(--theme-line);border-radius:8px;padding:11px;flex:1;min-width:150px}.batch-stat strong{display:block;font-size:23px}.batch-table-wrap{overflow:auto;max-height:320px}.batch-review table{border-collapse:collapse;width:100%;text-align:left}.batch-review th,.batch-review td{padding:9px 10px;border-bottom:1px solid color-mix(in srgb,var(--theme-line) 68%,transparent)}.batch-review th{font-size:12px;letter-spacing:.03em}.batch-review td code{overflow-wrap:anywhere;color:var(--theme-muted)}.batch-review tbody tr:hover{background:var(--theme-raised)}.batch-review button{padding:8px 12px;border:1px solid var(--theme-line);border-radius:7px;background:var(--theme-raised);color:var(--theme-text)}.batch-review button:disabled{opacity:.5}.batch-review input[type=checkbox]{width:19px;height:19px;accent-color:var(--theme-accent)}.batch-manual{margin:10px 0;border:1px solid var(--theme-warn);border-radius:8px;padding:12px}.batch-manual li{margin:7px 0}.batch-footer{position:sticky;bottom:0;display:flex;gap:10px;align-items:center;flex-wrap:wrap;padding:11px 0;background:var(--theme-surface);border-top:1px solid var(--theme-line);z-index:2}.batch-live{color:var(--theme-muted)}.batch-footer .batch-primary{margin-left:auto}.batch-back{margin-left:8px}@media(max-width:600px){.batch-review{margin:8px;padding:12px}.batch-review h1{font-size:28px}.batch-review th,.batch-review td{padding:8px 5px}.batch-footer .batch-primary{margin-left:0}}';document.head.append(batchStyle);
5
+ function batchFindingLabel(f){const prop=(f.original||'').split(':')[0];return f.ruleId==='RTL.CSS.PHYSICAL'?'Review physical '+(prop.startsWith('padding')?'padding':prop.startsWith('margin')?'margin':prop.startsWith('border')?'border':'alignment'):f.ruleId==='RTL.BIDI.ISOLATION'?'Review '+(f.original?.includes('email')?'email':'name')+' direction':by.get(f.id)?.title||f.message||f.ruleId;}
6
+ const reviewableBatchEntries=()=>workflow?.entries.filter(e=>all.some(f=>f.id===e.finding.id))||[];
7
+ const batchEligible=e=>e.batch?.state==='ready'&&!!e.patch&&e.decision==='Pending';
8
+ function openBatch(focus=true){if(!workflow||sourceContextError||workflow.mode!=='apply-first')return;batchOpen=true;renderBatch();const list=document.querySelector('.batch-table-wrap');if(list)list.scrollTop=batchListScroll;scrollTo(0,batchScroll);if(focus)requestAnimationFrame(()=>document.querySelector('.batch-review h1')?.focus({preventScroll:true}));requestAnimationFrame(()=>{scrollTo(0,batchScroll);const list=document.querySelector('.batch-table-wrap');if(list)list.scrollTop=batchListScroll});}
9
+ let batchListScroll=0;
10
+ function openBatchDetail(f){batchScroll=scrollY;batchListScroll=document.querySelector('.batch-table-wrap')?.scrollTop||0;batchOpen=false;document.querySelector('.batch-review')?.remove();document.querySelector('.workspace').hidden=false;selectReviewFinding(f);renderBatch();requestAnimationFrame(()=>scrollTo(0,Math.max(0,document.querySelector('.workspace').offsetTop-16)));}
11
+ async function prepareBatchOverview(){
12
+ if(!workflow||workflow.mode!=='apply-first'||workflow.state!=='Reviewing')return;
13
+ operationWindow('Preparing batch','Preparing supported fixes in an isolated candidate…',true);
14
+ const result=await api(endpoint+'/'+workflow.id+'/prepare-batch',{});workflow=result.workflow;dismissOperation();batchSelection.clear();batchOwner=workflow.id;batchScroll=0;batchListScroll=0;batchOpen=true;
15
+ return result;
16
+ }
17
+ function renderBatch(){
18
+ const workspace=document.querySelector('.workspace');if(!workspace)return;
19
+ let back=document.querySelector('.batch-back');if(workflow?.mode==='apply-first'&&workflow.state==='Reviewing'&&!batchOpen){if(!back){back=el('button','Back to batch','panel-toggle-btn batch-back');back.onclick=()=>openBatch();document.querySelector('.panel-controls')?.append(back)}}else back?.remove();
20
+ if(!batchOpen||!workflow||workflow.mode!=='apply-first'||workflow.state!=='Reviewing'||!workflow.batchPreparedAt||sourceContextError){document.querySelector('.batch-review')?.remove();workspace.hidden=false;return}
21
+ workspace.hidden=true;if(batchOwner!==workflow.id){batchOwner=workflow.id;batchSelection.clear();batchListScroll=0;batchScroll=0}
22
+ const entries=reviewableBatchEntries(),ready=entries.filter(e=>e.batch?.state==='ready'&&e.patch),pending=ready.filter(batchEligible),approved=entries.filter(e=>e.decision==='Accepted'),manual=entries.filter(e=>e.batch?.state!=='ready'||!e.patch||['Deferred','Flagged'].includes(e.decision));
23
+ const ids=new Set(pending.map(e=>e.finding.id));for(const id of batchSelection)if(!ids.has(id))batchSelection.delete(id);
24
+ const old=document.querySelector('.batch-review'),listTop=old?.querySelector('.batch-table-wrap')?.scrollTop||0,focusId=old?.contains(document.activeElement)?document.activeElement.dataset.batchId:null,focusLabel=old?.contains(document.activeElement)&&document.activeElement.tagName==='BUTTON'?document.activeElement.textContent:null;
25
+ const screen=el('section','','batch-review');screen.setAttribute('aria-label','Batch review');const title=el('h1','Batch review');title.tabIndex=-1;screen.append(title,el('p','Review the fixes prepared in an isolated candidate. Original source files are unchanged.'),el('p',workflow.applyEligibility?.eligible?'Prepare ✓ → Review → Validate ✓ → Apply (awaiting confirmation)':'Prepare ✓ → Review (current step) → Validate → Apply','batch-stage'));
26
+ const stats=el('div','','batch-stats');for(const [count,label] of [[ready.length,'fixes prepared'],[pending.length,'pending approval'],[manual.length,'need manual review'],[approved.length,'approved']]){const stat=el('div','','batch-stat');stat.append(el('strong',count),el('span',label));stats.append(stat)}screen.append(stats);
27
+ if(!ready.length)screen.append(el('p','No fixes are ready for batch approval. Review the reasons below, open a finding for code review, or use Defer / Needs review. Original source has not changed.','batch-empty'));
28
+ const panel=el('div','','batch-panel');panel.append(el('h2','Prepared fixes'),el('p','Showing all '+ready.length+' prepared fixes across the selected review scope. Select all prepared includes all eligible pending rows; Explorer and search do not limit this batch.'));
29
+ const wrap=el('div','','batch-table-wrap'),table=el('table'),head=el('thead'),header=el('tr');for(const name of ['Select','Finding','File','Status','Action'])header.append(el('th',name));head.append(header);table.append(head);const body=el('tbody');
30
+ for(const e of ready){const row=el('tr'),cell=el('td'),checkbox=document.createElement('input');checkbox.type='checkbox';checkbox.setAttribute('aria-label','Select '+e.finding.path+' '+e.finding.original);checkbox.dataset.batchId=e.finding.id;checkbox.checked=batchSelection.has(e.finding.id);checkbox.disabled=busy||!!uncertainOperation||!batchEligible(e);checkbox.onchange=()=>{checkbox.checked?batchSelection.add(e.finding.id):batchSelection.delete(e.finding.id);renderBatch()};cell.append(checkbox);const finding=el('td',batchFindingLabel(e.finding)),file=el('td');file.append(el('code',e.finding.path));const status=el('td',e.decision==='Accepted'?'Approved':e.decision==='Flagged'?'Needs review':e.decision),actionCell=el('td'),diff=el('button','View diff');diff.onclick=()=>openBatchDetail(e.finding);actionCell.append(diff);row.append(cell,finding,file,status,actionCell);body.append(row)}table.append(body);wrap.append(table);panel.append(wrap);screen.append(panel);
31
+ if(manual.length){const block=el('section','','batch-manual');block.append(el('h2','Needs manual review'));const list=el('ul');for(const e of manual){const item=el('li',e.finding.path+' · '+e.finding.original+' · '+(['Deferred','Flagged'].includes(e.decision)?(e.decision==='Flagged'?'Needs review':'Deferred')+' · Unresolved; excluded from approved Apply.':e.batch?.reason||e.reason||'No supported automatic fix.')),view=el('button','Review code');view.onclick=()=>openBatchDetail(e.finding);item.append(view);list.append(item)}block.append(list);screen.append(block)}
32
+ const footer=el('div','','batch-footer'),selectAll=el('button','Select all prepared');selectAll.disabled=busy||!!uncertainOperation||!pending.length;selectAll.onclick=()=>{for(const e of pending)batchSelection.add(e.finding.id);renderBatch()};const clear=el('button','Clear selection');clear.disabled=busy||!batchSelection.size;clear.onclick=()=>{batchSelection.clear();renderBatch()};const count=el('span',batchSelection.size+' selected','batch-selection-count');count.setAttribute('role','status');const approve=el('button','Approve selected','batch-primary');approve.disabled=busy||!!uncertainOperation||!batchSelection.size;approve.onclick=async()=>{const ids=[...batchSelection];const result=await operate(()=>api(endpoint+'/'+workflow.id+'/approve-batch',{findingIds:ids}),'Approving selected fixes');if(result?.workflow){batchSelection.clear();render();document.querySelector('.batch-selection-count')?.focus()}};footer.append(selectAll,clear,count,approve);screen.append(footer);
33
+ const stateCopy=workflow.applyEligibility?.eligible?'Validation passed for this exact approved set. The current validation candidate contains only '+approved.length+' approved changes; other prepared proposals are excluded. Apply requires explicit source confirmation.':workflow.validationInvalidation||(!approved.length?'Approve eligible prepared fixes to enable Validate.':workflow.validation?.state==='Failed'?'Validation failed: '+workflow.applyEligibility?.reason:'Validate '+approved.length+' approved changes. Original source has not changed.');const live=el('p',stateCopy,'batch-live');live.setAttribute('role','status');screen.append(live);
34
+ const validate=el('button',workflow.applyEligibility?.eligible?'Apply '+approved.length+' changes to source':'Validate '+approved.length+' approved changes','batch-primary');validate.disabled=busy||!!uncertainOperation||!approved.length;validate.onclick=()=>workflow.applyEligibility?.eligible?applyConfirmation():runDashboardOperation('validate');screen.append(validate);if(error)screen.append(el('p',error,'batch-error'));
35
+ if(old)old.replaceWith(screen);else workspace.before(screen);wrap.scrollTop=listTop;if(focusId)screen.querySelector('input[data-batch-id="'+CSS.escape(focusId)+'"]')?.focus({preventScroll:true});else if(focusLabel)[...screen.querySelectorAll('button')].find(b=>b.textContent===focusLabel&&!b.disabled)?.focus({preventScroll:true});
36
+ }
37
+ `;