dsh-reading-focus 0.0.0-stage → 0.8.4

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/lib/client.js ADDED
@@ -0,0 +1,1462 @@
1
+ window.__ModuleLoader__.load({id:'dsh-reading-focus',factory:(require)=>{
2
+ const React=require('react');
3
+ const RF_CSS = `
4
+ :host{all:initial}
5
+ .layer{position:fixed;inset:0;z-index:4;pointer-events:none}
6
+ .layer.pointer-layer{z-index:10}
7
+ .shape{position:fixed;pointer-events:none;box-sizing:border-box}
8
+ .panel{position:fixed;z-index:1000;width:min(320px,calc(100vw - 16px));max-height:calc(100vh - 16px);overflow:auto;box-sizing:border-box;border:1px solid var(--dsw-alias-border-l2,#d5dbe4);border-radius:var(--dsw-radius-lg,12px);background:var(--dsw-alias-bg-layer-2,#fff);color:var(--dsw-alias-label-primary,#27354a);box-shadow:var(--dsw-elevation-prominent,0 8px 30px #0003);font:13px/1.5 system-ui,sans-serif}
9
+ .panel[hidden],.rf-control-root [hidden]{display:none!important}
10
+ .top{display:flex;align-items:center;justify-content:space-between;padding:11px 14px;cursor:move;touch-action:none;border-bottom:1px solid var(--dsw-alias-border-l2,#dce1e8)}
11
+ .top .close{border:0;background:transparent;color:inherit;font-size:21px;line-height:1;cursor:pointer}
12
+ .panel-controls{padding:12px 14px}
13
+ .rf-control-root{font:14px/1.5 system-ui,sans-serif;color:var(--dsw-alias-label-primary,#27354a);max-width:720px;box-sizing:border-box}
14
+ .rf-control-root *{box-sizing:border-box}
15
+ .rf-control-root button{font:inherit;color:inherit;cursor:pointer}
16
+ .rf-control-root button:focus-visible,.rf-control-root input:focus-visible,.top button:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4f70d9);outline-offset:2px}
17
+ .heading{display:flex;justify-content:space-between;align-items:flex-start;gap:20px;margin-bottom:24px}
18
+ .heading h2{font-size:21px;line-height:1.3;margin:0 0 5px}
19
+ .heading p,.footnote{margin:0;color:var(--dsw-alias-label-secondary,#68778a);font-size:13px}
20
+ .switch{position:relative;display:inline-flex;flex:none;margin-top:3px}
21
+ .switch input{position:absolute;opacity:0;width:100%;height:100%;margin:0;cursor:pointer}
22
+ .switch span{display:block;width:38px;height:22px;border-radius:20px;background:var(--dsw-alias-border-l2,#abb6c5)}
23
+ .switch span:after{content:'';display:block;width:16px;height:16px;margin:3px;background:white;border-radius:50%;transition:transform .12s}
24
+ .switch input:checked+span{background:var(--dsw-alias-state-business-primary,#4f70d9)}
25
+ .switch input:checked+span:after{transform:translateX(16px)}
26
+ .switch input:focus-visible+span{outline:2px solid #4f70d9;outline-offset:3px}
27
+ .section-label{font-size:13px;font-weight:650;margin-bottom:9px}
28
+ .mode-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
29
+ /* An odd number of modes would leave one card alone in the last row; let it span instead. */
30
+ .mode-card{position:relative;text-align:left;display:flex;align-items:center;gap:12px;min-width:0;border:1px solid var(--dsw-alias-border-l2,#d8dee8);border-radius:var(--dsw-radius-md,9px);padding:12px;background:transparent}
31
+ .mode-card[aria-pressed=true]{border-color:var(--dsw-alias-state-business-primary,#4f70d9);background:var(--dsw-alias-state-business-tertiary,rgba(78,112,217,.08))}
32
+ .mode-card[aria-pressed=true]::after{content:'✓';position:absolute;right:5px;top:2px;font-size:12px;font-weight:700;color:var(--dsw-alias-label-primary,#27354a)}
33
+ .mode-card:disabled,.segments button:disabled{opacity:.7;cursor:default}
34
+ .mode-card strong,.mode-card small,.parameter strong,.parameter small,.segment-row strong,.segment-row small,.block-style-row strong,.block-style-row small,.gutter-row strong,.gutter-row small{display:block}
35
+ .mode-card strong{font-size:13px}
36
+ .mode-card small,.parameter small,.segment-row small,.block-style-row small,.gutter-row small,.steps small{font-size:11px;font-weight:400;color:var(--dsw-alias-label-secondary,#78879a)}
37
+ .mode-icon{width:40px;height:34px;border:1px solid var(--dsw-alias-border-l2,#c8d1dd);border-radius:5px;display:flex;flex-direction:column;justify-content:center;gap:4px;padding:5px;flex:none}
38
+ .mode-icon i{height:2px;background:var(--dsw-alias-label-tertiary,#a2afbf);border-radius:3px}
39
+ .mode-icon i:nth-child(2){height:5px;background:var(--dsw-alias-state-business-primary,#718be0);opacity:.7}
40
+ .icon-bands i{height:5px;opacity:.65;background:#88a5e4}
41
+ .icon-bands i:nth-child(1){background:#e4bf78}
42
+ .icon-bands i:nth-child(3){background:#bca1d9}
43
+ .icon-gradient i,.icon-gradient i:nth-child(2){height:2px;opacity:1;background:linear-gradient(90deg,#333,#2855c4,#a82a42)}
44
+ .gradient-palette select{max-width:150px;color:inherit;background:var(--dsw-alias-bg-layer-2,#fff);border:1px solid var(--dsw-alias-border-l2,#d8dee8);border-radius:6px;padding:4px}
45
+ .gradient-status{font-size:12px;color:var(--dsw-alias-label-secondary,#68778a);margin:8px 0}
46
+ .mode-options{margin-top:14px}
47
+ .mode-options:empty{display:none}
48
+ .parameter{display:grid;grid-template-columns:1fr auto;gap:8px;padding:14px 0;border-bottom:1px solid var(--dsw-alias-border-l2,#dce1e8)}
49
+ .parameter strong,.segment-row strong,.block-style-row strong,.gutter-row strong{font-size:13px}
50
+ .parameter output{align-self:start;border-radius:12px;background:var(--dsw-alias-interactive-bg-hover,#eef1f6);padding:2px 8px;font-size:12px}
51
+ .parameter input{grid-column:1/-1;width:100%;accent-color:var(--dsw-alias-state-business-primary,#4f70d9)}
52
+ .color-row,.font-row{margin-top:18px;padding-top:16px;border-top:1px solid var(--dsw-alias-border-l2,#dce1e8)}
53
+ .section-head{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
54
+ .section-head .section-label{margin:0}
55
+ .color-hint,.font-hint{margin:6px 0 0;font-size:11px;line-height:1.6;color:var(--dsw-alias-label-secondary,#78879a)}
56
+ .color-fields{display:grid;gap:16px;margin-top:12px}
57
+ .color-field{display:grid;gap:9px}
58
+ .color-field-head strong{display:block;font-size:12px}
59
+ .color-field-head small{display:block;font-size:11px;color:var(--dsw-alias-label-secondary,#78879a)}
60
+ .alpha-row{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:10px;font-size:11px;color:var(--dsw-alias-label-secondary,#78879a)}
61
+ .alpha-row input{width:100%;accent-color:var(--dsw-alias-state-business-primary,#4f70d9)}
62
+ .alpha-row output{font-variant-numeric:tabular-nums;min-width:38px;text-align:right}
63
+ .color-field-input{display:flex;align-items:center;gap:10px}
64
+ .color-field-input input[type=range]{flex:1;accent-color:var(--dsw-alias-state-business-primary,#4f70d9)}
65
+ .color-field-input output{font-size:12px;color:var(--dsw-alias-label-secondary,#78879a);font-variant-numeric:tabular-nums;min-width:44px;text-align:right}
66
+ .color-swatches{display:flex;flex-wrap:wrap;align-items:center;gap:7px}
67
+ .swatch{width:26px;height:26px;box-sizing:border-box;border-radius:50%;border:2px solid transparent;background:none;padding:0;cursor:pointer;display:inline-flex;align-items:center;justify-content:center}
68
+ .swatch[aria-pressed=true]{border-color:var(--dsw-alias-label-primary,#1b2330)}
69
+ .swatch>i{display:block;width:100%;height:100%;border-radius:50%;box-shadow:inset 0 0 0 1px rgba(0,0,0,.15)}
70
+ .swatch.custom>i{background:conic-gradient(from 90deg,#e05c6e,#f0b633,#39b98a,#4e9ee0,#9e70da,#e05c6e);box-shadow:inset 0 0 0 1px rgba(0,0,0,.12)}
71
+ /* In-panel colour picker: hue / saturation / lightness, no native dialog. */
72
+ .rf-control-root{position:relative}
73
+ .rf-picker{display:grid;gap:12px;margin-top:10px;padding:12px;border-radius:10px;background:var(--dsw-alias-interactive-bg-hover,#f4f6fa);border:1px solid var(--dsw-alias-border-l2,#e3e8f0)}
74
+ .rf-picker-head{display:flex;align-items:center;gap:10px}
75
+ .rf-picker-chip{width:34px;height:24px;border-radius:6px;box-shadow:inset 0 0 0 1px rgba(0,0,0,.14)}
76
+ .rf-picker-head{display:flex;align-items:center;gap:10px}
77
+ .rf-picker-chip{width:30px;height:24px;border-radius:6px;box-shadow:inset 0 0 0 1px rgba(0,0,0,.14)}
78
+ .rf-picker-hex{flex:1;min-width:0;padding:4px 8px;border:1px solid var(--dsw-alias-border-l2,#d8dee8);border-radius:6px;background:var(--dsw-alias-bg-layer-2,#fff);color:inherit;font:inherit;font-size:12px;letter-spacing:.5px;text-align:center}
79
+ .rf-disc{position:relative;width:132px;height:132px;margin:0 auto;border-radius:50%;cursor:crosshair;background:radial-gradient(circle at 50% 50%,#fff 0%,rgba(255,255,255,0) 72%),conic-gradient(from 0deg,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00);box-shadow:inset 0 0 0 1px rgba(0,0,0,.12)}
80
+ .rf-disc-dot{position:absolute;width:12px;height:12px;margin:-6px 0 0 -6px;border-radius:50%;border:2px solid #fff;box-shadow:0 0 0 1px rgba(15,23,42,.5);pointer-events:none}
81
+ .rf-picker-field{display:grid;grid-template-columns:42px 1fr 40px;align-items:center;gap:8px;font-size:11px;color:var(--dsw-alias-label-secondary,#78879a)}
82
+ .rf-picker-field input{width:100%}
83
+ .rf-picker-field output{text-align:right;font-variant-numeric:tabular-nums}
84
+ /* Gradient palette chips: the ramp itself is the icon. */
85
+ .palette-row{display:flex;gap:8px;grid-column:1/-1;margin-top:4px}
86
+ .palette-pill{width:58px;height:24px;border-radius:999px;border:2px solid transparent;box-shadow:inset 0 0 0 1px rgba(0,0,0,.14);cursor:pointer;padding:0}
87
+ .palette-pill[aria-pressed=true]{border-color:var(--dsw-alias-label-primary,#1b2330)}
88
+ .palette-pill:disabled{opacity:.6;cursor:default}
89
+ /* Numeric steppers: type the value or use the arrows, like the host's own font-size field. */
90
+ .stepper{display:inline-flex;align-items:center;gap:5px}
91
+ .stepper input[type=number]{width:58px;padding:4px 4px 4px 8px;border:1px solid var(--dsw-alias-border-l2,#d8dee8);border-radius:6px;background:var(--dsw-alias-bg-layer-2,#fff);color:inherit;font:inherit;font-size:13px;text-align:center;appearance:textfield}
92
+ .stepper input[type=number]::-webkit-outer-spin-button,.stepper input[type=number]::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}
93
+ .stepper-btns{display:inline-flex;flex-direction:column;gap:1px}
94
+ .stepper-btns button{width:18px;height:13px;padding:0;line-height:1;font-size:7px;border:1px solid var(--dsw-alias-border-l2,#d8dee8);background:var(--dsw-alias-bg-layer-2,#fff);color:var(--dsw-alias-label-secondary,#68778a);border-radius:3px;cursor:pointer}
95
+ .stepper-btns button:hover{color:var(--dsw-alias-label-primary,#1b2330);border-color:var(--dsw-alias-label-secondary,#9aa4b2)}
96
+ .stepper input[type=number]:focus{outline:2px solid var(--dsw-alias-state-business-primary,#4f70d9);outline-offset:1px}
97
+ .stepper em{font-style:normal;font-size:11px;color:var(--dsw-alias-label-secondary,#78879a)}
98
+ .number-parameter{grid-template-columns:1fr auto}
99
+ .number-parameter .stepper{grid-column:2;grid-row:1;align-self:center}
100
+ /* Band schemes: a colour set is easier to judge than three separate pickers. */
101
+ .scheme-row{display:flex;flex-wrap:wrap;gap:6px}
102
+ .scheme-row button{display:inline-flex;align-items:center;gap:5px;border:1px solid var(--dsw-alias-border-l2,#d8dee8);background:transparent;border-radius:999px;padding:4px 9px;font-size:12px;cursor:pointer}
103
+ .scheme-row button[aria-pressed=true]{border-color:var(--dsw-alias-state-business-primary,#4f70d9);box-shadow:0 0 0 1px var(--dsw-alias-state-business-primary,#4f70d9) inset}
104
+ .scheme-dots{display:inline-flex;align-items:center}
105
+ .scheme-dots i{width:11px;height:11px;border-radius:50%;margin-left:-3px;box-shadow:inset 0 0 0 1px rgba(0,0,0,.12)}
106
+ .scheme-dots i:first-child{margin-left:0}
107
+ .color-value{margin-left:auto;font-size:11px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary,#78879a)}
108
+ .reset-color,.reset-font{border:1px solid var(--dsw-alias-border-l2,#d8dee8);background:transparent;color:var(--dsw-alias-label-secondary,#68778a);border-radius:6px;padding:3px 9px;font-size:11px;cursor:pointer;white-space:nowrap}
109
+ .reset-color:hover,.reset-font:hover{color:var(--dsw-alias-label-primary,#1b2330)}
110
+ .font-fields{display:grid;gap:8px;margin-top:10px}
111
+ .font-fields label{display:grid;grid-template-columns:44px 1fr;align-items:center;gap:10px;font-size:12px;color:var(--dsw-alias-label-secondary,#78879a)}
112
+ .font-fields .stepper{justify-self:start}
113
+ .font-fields input{width:100%;accent-color:var(--dsw-alias-state-business-primary,#4f70d9)}
114
+ .segment-row,.block-style-row,.gutter-row{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:14px 0;border-bottom:1px solid var(--dsw-alias-border-l2,#dce1e8)}
115
+ .segments{display:flex;border:1px solid var(--dsw-alias-border-l2,#d8dee8);border-radius:7px;padding:2px;white-space:nowrap}
116
+ .segments button{border:0;background:transparent;border-radius:5px;padding:5px 8px;font-size:12px}
117
+ .segments button[aria-pressed=true]{background:var(--dsw-alias-interactive-bg-hover,#e9edf5);font-weight:650}
118
+ .steps{display:flex;align-items:center;gap:8px;padding:12px 0}
119
+ .steps button{border:1px solid var(--dsw-alias-border-l2,#d8dee8);background:transparent;border-radius:6px;padding:5px 9px}
120
+ .open-window{width:100%;margin-top:20px;padding:10px;border:0;border-radius:var(--dsw-radius-md,8px);background:var(--dsw-alias-state-business-primary,#4f70d9);color:#fff!important;font-weight:600!important}
121
+ :host-context(body[data-ds-dark-theme]) .open-window,body[data-ds-dark-theme] .open-window{color:#18233a!important}
122
+ .footnote{margin-top:8px;text-align:center}
123
+ .floating .heading{margin-bottom:12px}
124
+ .floating .heading h2{font-size:14px;margin:0}
125
+ .floating .heading p,.floating .mode-card small{display:none}
126
+ .floating .section-label{margin-bottom:6px}
127
+ .floating .mode-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}
128
+ .floating .mode-card{display:block;text-align:center;padding:7px 2px}
129
+ .floating .mode-card strong{font-size:11px}
130
+ .floating .mode-icon{display:none}
131
+ .floating .mode-options{margin-top:10px}
132
+ .floating .parameter,.floating .segment-row,.floating .block-style-row,.floating .gutter-row{padding:9px 0}
133
+ .floating .parameter small{display:none}
134
+ .floating .segment-row,.floating .block-style-row,.floating .gutter-row{display:block}
135
+ .floating .segments{margin-top:6px;justify-content:space-between}
136
+ .floating .segments button{flex:1}
137
+ @media(max-width:480px){.rf-control-root:not(.floating) .mode-grid{grid-template-columns:1fr}
138
+ .segment-row,.block-style-row,.gutter-row{align-items:flex-start;flex-direction:column}
139
+ }
140
+
141
+ `;
142
+
143
+ // Colour palettes for the gradient mode. Each palette pairs a base tone with two accents.
144
+ const RF_GRADIENT_PALETTES = {
145
+ Bright:{base:[0,0,0],a:[0,0,255],b:[196,30,30]},
146
+ Blues:{base:[0,0,0],a:[0,0,255],b:[144,19,254]},
147
+ Night:{base:[255,255,255],a:[158,141,252],b:[86,170,255]}
148
+ };
149
+ const rfMix=(a,b,t)=>a.map((v,i)=>v+(b[i]-v)*t);
150
+ // Each visual line sweeps one full arm of the palette, alternating direction:
151
+ // line 0 base -> A line 1 A -> base
152
+ // line 2 base -> B line 3 B -> base (then repeat)
153
+ // Consecutive lines therefore meet at an extreme - either fully saturated or fully base -
154
+ // and never in the middle of a ramp, which is what keeps a wrapped junction readable.
155
+ function rfPhase(line,t){switch(((line%4)+4)%4){case 0:return ['a',t];case 1:return ['a',1-t];case 2:return ['b',t];default:return ['b',1-t];}}
156
+ function rfPosition(x,first,last){return last>first?Math.max(0,Math.min(1,(x-first)/(last-first))):0;}
157
+ // A line with a single glyph can only show one colour, so it shows the colour it is entered
158
+ // with and leaves the pattern untouched. Advancing it instead would place that lone glyph on
159
+ // the arm's terminal colour and break the junction on both sides of the line.
160
+ function rfLineAdvance(line){return line.items.length>1?1:0;}
161
+ function rfNextOffset(offset,advance){return (offset+advance)%4;}
162
+ function rfFlowOffsets(counts){let n=0;return counts.map(count=>{const offset=n;n=rfNextOffset(n,count);return offset;});}
163
+ function rfPlanFlow(entries,owner){let offset=0;for(const entry of entries){if(entry.dirty||!entry.item||entry.item.offset!==offset||entry.item.owner!==owner)return {block:entry.block,offset,measure:entry.dirty||!entry.item};offset=rfNextOffset(offset,entry.item.advance);}return null;}
164
+ function rfLineColor(colors,line,t){const [side,phase]=rfPhase(line,t);return rfMix(colors.base,colors[side],Math.round(phase*31)/31).map(Math.round);}
165
+ function* rfGraphemeIterator(text){
166
+ if(typeof Intl.Segmenter==='function'){for(const x of new Intl.Segmenter(undefined,{granularity:'grapheme'}).segment(text))yield {start:x.index,end:x.index+x.segment.length};return;}
167
+ let index=0,join=false,current=null;for(const ch of text){const start=index;index+=ch.length;if(current&&(/\p{Mark}/u.test(ch)||/[\uFE00-\uFE0F]/u.test(ch)||ch==='\u200d'||join))current.end=index;else {if(current)yield current;current={start,end:index};}join=ch==='\u200d';}if(current)yield current;
168
+ }
169
+ function rfGraphemes(text){return [...rfGraphemeIterator(text)];}
170
+ // Accepts rgb()/rgba() as well as #rgb/#rrggbb, because the colour picker produces hex.
171
+ function rfParseColor(s){
172
+ if(typeof s!=='string')return null;
173
+ const trimmed=s.trim();
174
+ const hex=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(trimmed);
175
+ if(hex){
176
+ const h=hex[1].length===3?hex[1].split('').map(c=>c+c).join(''):hex[1];
177
+ return [Number.parseInt(h.slice(0,2),16),Number.parseInt(h.slice(2,4),16),Number.parseInt(h.slice(4,6),16),1];
178
+ }
179
+ const m=/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(trimmed);
180
+ if(!m)return null;
181
+ const a=m[4]===undefined?1:m[4].endsWith('%')?parseFloat(m[4])/100:+m[4];
182
+ return [+m[1],+m[2],+m[3],a];
183
+ }
184
+ function rfGradientColors(palette,dark,original,strength){
185
+ const target=RF_GRADIENT_PALETTES[palette],base=dark?[255,255,255]:[0,0,0];
186
+ const adapt=c=>dark?(palette==='Night'?c:rfMix(c,[255,255,255],.52)):(palette==='Night'?rfMix(c,[0,0,0],.48):c);
187
+ return {base:rfMix(original,base,strength),a:rfMix(original,adapt(target.a),strength),b:rfMix(original,adapt(target.b),strength)};
188
+ }
189
+ // Blocks that are never coloured: headings, code and tabular surfaces keep their own colour.
190
+ const RF_NO_GRADIENT='h1,h2,h3,h4,h5,h6,pre,table,figure,[data-code-block-content],[data-markdown-variant="compact"]';
191
+ // Versioned queue helper; a changed version can never publish stale work.
192
+ function rfGradientQueue(){
193
+ const versions=new Map(),queued=new Map();
194
+ return {touch(block,priority=false){const v=(versions.get(block)||0)+1;versions.set(block,v);queued.delete(block);queued.set(block,{version:v,priority});return v;},ensure(block,priority=false){if(!versions.has(block))this.touch(block,priority);},version:block=>versions.get(block),valid:(block,version)=>versions.get(block)===version,drop(block){versions.delete(block);queued.delete(block);},take(){let key;for(const [k,v] of queued){if(key===undefined)key=k;if(v.priority){key=k;break;}}if(key===undefined)return null;const entry=queued.get(key);queued.delete(key);return {block:key,...entry};},get size(){return queued.size;},clear(){versions.clear();queued.clear();}};
195
+ }
196
+ function createGradientController({state,roots,blocks,viewport,notify,flowOf}){
197
+ const prefix='rf-gradient-'+Math.random().toString(36).slice(2),registry=new Map(),cache=new Map(),dirty=new Set();
198
+ const media=window.matchMedia('(forced-colors: active)');let style=null,frame=0,status='',job=null,scanFrame=0,generation=0,flows=[],rerun=false,statusDirty=false;
199
+ // Only running body text is coloured. Headings and code keep the original text colour: a
200
+ // large heading glyph would otherwise carry a whole colour sweep by itself, which reads as
201
+ // an artefact rather than a reading aid. Inline emphasis inside a paragraph stays coloured.
202
+ const excluded='a,h1,h2,h3,h4,h5,h6,code,pre,kbd,samp,var,tt,table,thead,tbody,tfoot,tr,th,td,caption,figure,figcaption,math,svg,canvas,img,picture,video,button,input,textarea,select,label,summary,details,sup,sub,bdi,bdo,[dir="rtl"],[contenteditable]:not([contenteditable="false"]),[role="button"],[role="toolbar"],[role="menu"],[data-text-interaction-surface],[data-turn-process-inline],[data-code-block-banner],[data-code-block-content],[data-markdown-variant="compact"]';
203
+ const active=()=>state.enabled&&state.mode==='gradient';
204
+ const supported=()=>!!window.CSS?.highlights&&typeof Highlight==='function'&&!media.matches;
205
+ function setStatus(s){if(s!==status){status=s;notify();}}
206
+ // Cheap "is there still work" check: only the first non-clean block per flow needs looking at.
207
+ function statusPending(){if(job)return true;for(const flow of flows)for(const block of flow.blocks)if(dirty.has(block)||!cache.has(block))return true;return false;}
208
+ // No progress readout in the UI: internal state only, and only when it truly changes.
209
+ function updateStatus(){if(!statusDirty)return;statusDirty=false;setStatus(media.matches?'forced-colors':!window.CSS?.highlights||typeof Highlight!=='function'?'unsupported':job||statusPending()?'busy':'');}
210
+ function clearRegistry(){for(const {name,highlight} of registry.values())if(CSS.highlights.get(name)===highlight)CSS.highlights.delete(name);registry.clear();style?.remove();style=null;}
211
+ function discard(j){if(!j)return;for(const [color,range] of j.added)registry.get(color)?.highlight.delete(range);for(const [color,range] of j.removed)registry.get(color)?.highlight.add(range);}
212
+ function cancel(){generation++;if(frame)cancelAnimationFrame(frame);frame=0;discard(job);job=null;rerun=false;}
213
+ function clear(){cancel();if(scanFrame)cancelAnimationFrame(scanFrame);scanFrame=0;clearRegistry();cache.clear();dirty.clear();flows=[];}
214
+ function bucket(color){let b=registry.get(color);if(b)return b;if(!style){style=document.createElement('style');style.dataset.readingFocusGradient='';document.head.append(style);}const name=prefix+'-'+registry.size,highlight=new Highlight();style.append(document.createTextNode(`::highlight(${name}){color:${color}}\n`));CSS.highlights.set(name,highlight);b={name,highlight};registry.set(color,b);return b;}
215
+ function removeItem(item){if(!item)return;for(const [color,ranges] of item.colors){const b=registry.get(color);if(b)for(const range of ranges)b.highlight.delete(range);}}
216
+ function visible(el){const r=el.getBoundingClientRect(),v=viewport(el);return !!v&&r.bottom>=v.top-150&&r.top<=v.bottom+150&&r.right>=v.left&&r.left<=v.right;}
217
+ function scan(){
218
+ if(!active()){clear();setStatus('');return;}if(!supported()){clear();statusDirty=true;updateStatus();return;}
219
+ const grouped=new Map(),ordered=[...roots].filter(r=>r.isConnected).sort((a,b)=>a===b?0:a.compareDocumentPosition(b)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1);
220
+ for(const root of ordered){const key=flowOf(root);if(!grouped.has(key))grouped.set(key,{root:key,roots:[],blocks:[]});const f=grouped.get(key);f.roots.push(root);f.blocks.push(...blocks(root).filter(b=>!b.matches(RF_NO_GRADIENT)));}
221
+ const next=[...grouped.values()],live=new Set(next.flatMap(f=>f.blocks));
222
+ const changed=next.length!==flows.length||next.some((f,i)=>f.root!==flows[i]?.root||f.blocks.length!==flows[i]?.blocks.length||f.blocks.some((b,k)=>b!==flows[i].blocks[k]));
223
+ if(changed)cancel();flows=next;
224
+ for(const block of cache.keys())if(!live.has(block)){removeItem(cache.get(block));cache.delete(block);dirty.delete(block);}
225
+ for(const block of live)if(!cache.has(block)||cache.get(block).parent!==block.parentElement)dirty.add(block);
226
+ for(const block of dirty)if(!live.has(block))dirty.delete(block);
227
+ statusDirty=true;updateStatus();schedule();
228
+ }
229
+ // Only the first unresolved block in each flow can run; its prefix is known.
230
+ function nextWork(){const candidates=[];for(const flow of flows){const next=rfPlanFlow(flow.blocks.map(block=>({block,item:cache.get(block),dirty:dirty.has(block)})),flow.root);if(next)candidates.push({...next,flow});}return candidates.find(c=>c.flow.roots.some(visible))||candidates[0]||null;}
231
+ function schedule(){if(!frame&&(job||nextWork()))frame=requestAnimationFrame(work);}
232
+ function begin(entry){const {block,flow,offset,measure}=entry,old=cache.get(block),walker=measure?document.createTreeWalker(block,NodeFilter.SHOW_TEXT,{acceptNode(node){if(!node.parentElement||!node.data)return NodeFilter.FILTER_REJECT;for(let p=node.parentElement;p&&block.contains(p);p=p.parentElement)if(p.matches(excluded))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT;}}):null;const dark=document.body.hasAttribute('data-ds-dark-theme'),raw=rfParseColor(getComputedStyle(flow.root).color),colors=rfGradientColors(state.gradientPalette,dark,raw?.slice(0,3)||(dark?[255,255,255]:[0,0,0]),state.gradientStrength);return {block,blockRect:measure?block.getBoundingClientRect():null,offset,owner:flow.root,walker,node:null,segments:null,lines:measure?[]:old.lines,lineIndex:0,itemIndex:0,phase:offset,colors:new Map(),palette:colors,stage:measure?'measure':'color',added:[],removed:[],epoch:generation};}
233
+ function retry(j){discard(j);job=null;rerun=false;dirty.add(j.block);}
234
+ function work(){frame=0;const start=performance.now(),epoch=generation;let steps=0;
235
+ while(active()&&epoch===generation&&steps<400&&performance.now()-start<4){
236
+ if(!job){const entry=nextWork();if(!entry)break;if(!entry.block.isConnected){scan();break;}job=begin(entry);}
237
+ const j=job;if(j.epoch!==generation||!j.block.isConnected){discard(j);job=null;continue;}
238
+ if(j.stage==='measure'){
239
+ if(!j.node){j.node=j.walker.nextNode();if(!j.node){j.stage='color';continue;}const el=j.node.parentElement,st=getComputedStyle(el);if(st.display==='none'||st.visibility==='hidden'||st.direction==='rtl'||st.writingMode!=='horizontal-tb'){j.node=null;continue;}j.snapshot=j.node.data;j.segments=rfGraphemeIterator(j.snapshot);}
240
+ if(!j.node.isConnected||!j.block.contains(j.node)||!j.node.data.startsWith(j.snapshot)){retry(j);continue;}
241
+ const next=j.segments.next();if(next.done){j.node=null;j.segments=null;continue;}steps++;const seg=next.value,text=j.snapshot.slice(seg.start,seg.end);if(/^\s+$/u.test(text)||/[\u0590-\u08ff\u202a-\u202e\u2066-\u2069]/u.test(text))continue;
242
+ const range=document.createRange();range.setStart(j.node,seg.start);range.setEnd(j.node,seg.end);const origin=j.blockRect;const rects=range.getClientRects();
243
+ for(const r of rects){if(r.width<=0||r.height<=0)continue;const top=r.top-origin.top,bottom=r.bottom-origin.top,left=r.left-origin.left,right=r.right-origin.left;let line=j.lines.at(-1);const overlap=line?Math.min(line.bottom,bottom)-Math.max(line.top,top):0;if(!line||overlap<Math.min(line.bottom-line.top,bottom-top)*.5){line={top,bottom,first:(left+right)/2,last:(left+right)/2,items:[]};j.lines.push(line);}line.top=Math.min(line.top,top);line.bottom=Math.max(line.bottom,bottom);line.first=Math.min(line.first,(left+right)/2);line.last=Math.max(line.last,(left+right)/2);line.items.push({node:j.node,start:seg.start,end:seg.end,left,right});}
244
+ }else if(j.stage==='color'){
245
+ const line=j.lines[j.lineIndex];if(!line){j.stage='publish';j.iterator=j.colors.entries();j.current=null;continue;}const item=line.items[j.itemIndex++];if(!item){j.phase+=rfLineAdvance(line);j.lineIndex++;j.itemIndex=0;continue;}steps++;
246
+ if(!item.node.isConnected||!j.block.contains(item.node)||item.end>item.node.length){retry(j);continue;}
247
+ const rgb=rfLineColor(j.palette,j.phase,rfPosition((item.left+item.right)/2,line.first,line.last)),color=`rgb(${rgb.join(',')})`;if(!j.colors.has(color))j.colors.set(color,[]);const ranges=j.colors.get(color),last=ranges.at(-1);if(last&&last.endContainer===item.node&&last.endOffset===item.start)last.setEnd(item.node,item.end);else {const r=document.createRange();r.setStart(item.node,item.start);r.setEnd(item.node,item.end);ranges.push(r);}
248
+ }else if(j.stage==='publish'){
249
+ if(!j.current){const next=j.iterator.next();if(next.done){j.stage='remove';j.old=cache.get(j.block);j.oldIterator=j.old?.colors.entries();continue;}j.current={color:next.value[0],ranges:next.value[1],index:0};}
250
+ const c=j.current,range=c.ranges[c.index++];if(!range){j.current=null;continue;}bucket(c.color).highlight.add(range);j.added.push([c.color,range]);steps++;
251
+ }else {
252
+ if(!j.oldCurrent&&j.oldIterator){const next=j.oldIterator.next();if(!next.done)j.oldCurrent={color:next.value[0],ranges:next.value[1],index:0};}
253
+ if(j.oldCurrent){const c=j.oldCurrent,range=c.ranges[c.index++];if(range){registry.get(c.color)?.highlight.delete(range);j.removed.push([c.color,range]);steps++;continue;}j.oldCurrent=null;continue;}
254
+ cache.set(j.block,{offset:j.offset,owner:j.owner,parent:j.block.parentElement,lines:j.lines,advance:j.lines.reduce((n,line)=>n+rfLineAdvance(line),0),colors:j.colors});if(!rerun)dirty.delete(j.block);rerun=false;j.added=[];j.removed=[];job=null;
255
+ }
256
+ }
257
+ if(epoch!==generation)return;statusDirty=true;updateStatus();schedule();
258
+ }
259
+ function invalidate(block){if(!active())return;if(!block){cancel();for(const flow of flows)for(const item of flow.blocks)dirty.add(item);}else {dirty.add(block);if(job?.block===block)rerun=true;}if(!scanFrame)scanFrame=requestAnimationFrame(()=>{scanFrame=0;scan();});}
260
+ function onForced(){if(media.matches){clear();statusDirty=true;updateStatus();}else scan();}media.addEventListener('change',onForced);
261
+ const fonts=document.fonts;function onFonts(){invalidate();}fonts?.addEventListener('loadingdone',onFonts);
262
+ return {scan,invalidate,clear,status:()=>status,dispose(){clear();media.removeEventListener('change',onForced);fonts?.removeEventListener('loadingdone',onFonts);}};
263
+ }
264
+
265
+ // Shown in the settings panel so a loaded build can be identified at a glance.
266
+ const RF_VERSION = '0.8.4';
267
+ // One source of truth for the typography controls. The size range mirrors the host's own text
268
+ // stepper (10-22, default 14). Line height is not a ratio here: the host computes it as
269
+ // `24px + (size - 14)` (the `--dsh-content-font-delta` ladder), so this plugin only adds an
270
+ // optional extra on top of that instead of re-deriving a competing line height.
271
+ const RF_FONT = {sizeMin:10,sizeMax:22,sizeDefault:14,extraMin:0,extraMax:12,lineBase:24,baseSize:14};
272
+ // Candidate selector only: all consumers must validate the complete class token.
273
+ const RF_ROOT = '.xMeOpW_body > [class*="_markdown_"], [data-reading-focus-preview]';
274
+ function rfMarkdownClassToken(token) { return /^_markdown_[A-Za-z0-9]+_\d+$/.test(token); }
275
+ function rfRootIdentity({preview, bodyParent, classTokens}) {
276
+ return !!preview || !!bodyParent && classTokens.some(rfMarkdownClassToken);
277
+ }
278
+ function matchesRoot(node) {
279
+ return !!node && node.nodeType===1 && rfRootIdentity({preview:node.hasAttribute('data-reading-focus-preview'),bodyParent:!!node.parentElement?.classList.contains('xMeOpW_body'),classTokens:[...node.classList]});
280
+ }
281
+ function queryRoots(node) { return [...node.querySelectorAll(RF_ROOT)].filter(matchesRoot); }
282
+ function closestRoot(node) {
283
+ for(let el=node;el;el=el.parentElement)if(matchesRoot(el))return el;
284
+ return null;
285
+ }
286
+ const RF_BLOCK = 'p,li,h1,h2,h3,h4,h5,h6,blockquote,pre,table';
287
+ const RF_OCCLUDERS = '[data-composer-seat], [data-composer-card], [data-composer-overlay], [data-composer-dock], [data-composer-input], [data-code-block-banner], [data-conversation-region="composer"], [data-slot="conversation.input.dock"], [role="toolbar"], [role="menu"], [role="dialog"], dialog[open], [aria-modal="true"], footer';
288
+
289
+ function rfIntersect(a, b) {
290
+ const r = {left:Math.max(a.left,b.left), top:Math.max(a.top,b.top), right:Math.min(a.right,b.right), bottom:Math.min(a.bottom,b.bottom)};
291
+ return r.right > r.left && r.bottom > r.top ? r : null;
292
+ }
293
+ function rfSubtract(rect, cut) {
294
+ const i = rfIntersect(rect, cut);
295
+ if (!i) return [rect];
296
+ return [
297
+ {left:rect.left, top:rect.top, right:rect.right, bottom:i.top},
298
+ {left:rect.left, top:i.bottom, right:rect.right, bottom:rect.bottom},
299
+ {left:rect.left, top:i.top, right:i.left, bottom:i.bottom},
300
+ {left:i.right, top:i.top, right:rect.right, bottom:i.bottom}
301
+ ].filter(r => r.right-r.left > .1 && r.bottom-r.top > .1);
302
+ }
303
+ // Each mode is a different visual device, so each exposes its own set of controls rather than
304
+ // sharing one generic "colour + opacity" pair:
305
+ // ruler - tinted band with two solid edge lines; controls: line colour
306
+ // lines - clear window over dimmed surroundings; controls: veil colour, veil opacity
307
+ // blocks - the current block stays at full contrast, everything else recedes. Two ways to
308
+ // make it recede: fade the other text, or dim the page behind a veil.
309
+ // bands - cycling colour blocks; controls: three colours, block opacity
310
+ const RF_DEFAULT_COLORS={
311
+ ruler:{lineColor:'#f0b633',lineOpacity:.9},
312
+ lines:{veilColor:'#000000',veilOpacity:.45},
313
+ blocks:{dimOpacity:.48,veilColor:'#000000',veilOpacity:.30,tintColor:'#4e9ee0',tintOpacity:.08},
314
+ bands:{color:'#f0b633',color2:'#4e9ee0',color3:'#9e70da',opacity:.45}
315
+ };
316
+ // Suggested colours differ per slot, because the slots do different jobs: a marker line wants
317
+ // attention, a dimming veil wants dark neutrals, a band fill wants muted backgrounds. The lists are
318
+ // deliberately short - six near-identical dark circles is a decision the user cannot make.
319
+ const RF_PRESETS={
320
+ marker:['#f0b633','#e0703f','#e05c6e','#4e9ee0','#39b98a','#9e70da'],
321
+ veil:['#000000','#141a24','#3d4657','#697585'],
322
+ tint:['#4e9ee0','#39b98a','#f0b633','#9e70da'],
323
+ band:['#f0b633','#4e9ee0','#9e70da','#8a94a6']
324
+ };
325
+ // Band colours come in ready-made sets. Picking three colours by hand was the most confusing part
326
+ // of the panel, so the common case is a scheme plus one density slider; hand-picked colours stay
327
+ // available behind the "自定义" scheme.
328
+ const RF_BAND_SCHEMES=[
329
+ ['vivid','缤纷',['#f0b633','#4e9ee0','#9e70da']],
330
+ ['warm','暖色',['#f0b633','#e0703f','#e05c6e']],
331
+ ['cool','冷色',['#4e9ee0','#39b98a','#7a6de8']],
332
+ ['soft','柔和',['#e7d7a6','#b9d4ec','#d9c8ee']],
333
+ ['custom','自定义',null]
334
+ ];
335
+ const rfBandSchemeColors=name=>{const found=RF_BAND_SCHEMES.find(s=>s[0]===name);return found&&found[2]?(found[2]):null;};
336
+ // Per-mode descriptor: which controls to render and what they mean.
337
+ const RF_COLOR_SPECS={
338
+ ruler:[
339
+ {key:'lineColor',kind:'color',label:'线条颜色',alphaKey:'lineOpacity',alphaMin:30,alphaMax:100,hint:'上下两条实线和中间的淡色',palette:RF_PRESETS.marker}
340
+ ],
341
+ lines:[
342
+ {key:'veilColor',kind:'color',label:'遮罩颜色',alphaKey:'veilOpacity',alphaMin:15,alphaMax:85,hint:'颜色越深、越不透明,周围压得越暗',palette:RF_PRESETS.veil}
343
+ ],
344
+ // Block focus offers two presentations, each with its own controls.
345
+ blocksFade:[
346
+ {key:'dimOpacity',kind:'opacity',label:'其余文字透明度',hint:'越高,其余文字越淡;当前段落的文字不受影响',min:25,max:85}
347
+ ],
348
+ blocksVeil:[
349
+ {key:'veilColor',kind:'color',label:'遮罩颜色',alphaKey:'veilOpacity',alphaMin:15,alphaMax:70,hint:'颜色越深、越不透明,周围压得越暗',palette:RF_PRESETS.veil},
350
+ {key:'tintColor',kind:'color',label:'当前段落底色',alphaKey:'tintOpacity',alphaMin:5,alphaMax:40,hint:'给正在读的段落加一层淡色',palette:RF_PRESETS.tint}
351
+ ],
352
+ bands:[
353
+ {key:'scheme',kind:'scheme',label:'配色',hint:'三个颜色依次轮换'},
354
+ {key:'opacity',kind:'opacity',label:'色块浓度',hint:'越高,色块越明显;上限保证文字仍然清楚',min:10,max:45},
355
+ {key:'color',kind:'color',label:'色块一',onlyCustom:true,palette:RF_PRESETS.band},
356
+ {key:'color2',kind:'color',label:'色块二',onlyCustom:true,palette:RF_PRESETS.band},
357
+ {key:'color3',kind:'color',label:'色块三',onlyCustom:true,palette:RF_PRESETS.band}
358
+ ]
359
+ };
360
+ const rfColorSpecs = (mode,blockStyle) => mode==='blocks' ? RF_COLOR_SPECS[blockStyle==='veil'?'blocksVeil':'blocksFade'] : (RF_COLOR_SPECS[mode]||[]);
361
+ const rfHasColor = mode => mode==='blocks'||mode==='ruler'||mode==='lines'||mode==='bands';
362
+ function rfRgba(hex,opacity){const rgb=typeof hex==='string'?rfParseColor(hex):null;if(!rgb)return null;return `rgba(${rgb.slice(0,3).join(',')},${Number.isFinite(opacity)?opacity:1})`;}
363
+ // HSL round-trip so the in-panel picker can offer hue / saturation / lightness sliders instead of
364
+ // opening the browser's own colour dialog, which looks nothing like the rest of the panel.
365
+ function rfHexToHsl(hex){
366
+ const rgb=rfParseColor(hex);if(!rgb)return {h:40,s:70,l:57};
367
+ const r=rgb[0]/255,g=rgb[1]/255,b=rgb[2]/255;
368
+ const max=Math.max(r,g,b),min=Math.min(r,g,b),d=max-min;
369
+ let h=0;
370
+ if(d){if(max===r)h=((g-b)/d)%6;else if(max===g)h=(b-r)/d+2;else h=(r-g)/d+4;h*=60;if(h<0)h+=360;}
371
+ const l=(max+min)/2;
372
+ const s=d?d/(1-Math.abs(2*l-1)):0;
373
+ return {h:Math.round(h),s:Math.round(s*100),l:Math.round(l*100)};
374
+ }
375
+ function rfHslToHex(h,s,l){
376
+ const S=s/100,L=l/100, C=(1-Math.abs(2*L-1))*S, X=C*(1-Math.abs(((h/60)%2)-1)), m=L-C/2;
377
+ let r=0,g=0,b=0;
378
+ if(h<60)[r,g,b]=[C,X,0];else if(h<120)[r,g,b]=[X,C,0];else if(h<180)[r,g,b]=[0,C,X];
379
+ else if(h<240)[r,g,b]=[0,X,C];else if(h<300)[r,g,b]=[X,0,C];else [r,g,b]=[C,0,X];
380
+ const to=v=>Math.max(0,Math.min(255,Math.round((v+m)*255))).toString(16).padStart(2,'0');
381
+ return '#'+to(r)+to(g)+to(b);
382
+ }
383
+ // Resolve one slot's value, falling back to the mode defaults.
384
+ function rfColorValue(state,key,field,fallback){const entry=state.colors?.[key]||{};return entry[field]??RF_DEFAULT_COLORS[key]?.[field]??fallback;}
385
+ // Ruler colour at two strengths: a faint fill for the band, a solid line for its two edges.
386
+ function rfRulerColor(state,alpha){
387
+ const hex=rfColorValue(state,'ruler','lineColor','#f0b633');
388
+ const base=Number.isFinite(alpha)?alpha:rfColorValue(state,'ruler','lineOpacity',.9);
389
+ const rgb=rfParseColor(hex);if(!rgb)return null;
390
+ return `rgba(${rgb.slice(0,3).join(',')},${base})`;
391
+ }
392
+ function rfVeilColor(state){const key=state.mode==='blocks'?'blocks':'lines';return rfRgba(rfColorValue(state,key,'veilColor','#000000'),rfColorValue(state,key,'veilOpacity',.4));}
393
+ function rfTintColor(state){return rfRgba(rfColorValue(state,'blocks','tintColor','#4e9ee0'),rfColorValue(state,'blocks','tintOpacity',.1));}
394
+ // Block focus fades the text itself: the live text colour at reduced alpha blends with whatever
395
+ // background the theme uses, so no overlay is needed and the result inherits the real colours.
396
+ function rfDimColor(state){
397
+ const sample=document.querySelector('.xMeOpW_body p, .xMeOpW_body li, .xMeOpW_body');
398
+ const rgb=sample?rfParseColor(getComputedStyle(sample).color):null;
399
+ const base=rgb?rgb.slice(0,3):[230,232,238];
400
+ const alpha=rfColorValue(state,'blocks','dimOpacity',.45);
401
+ return `rgba(${base.join(',')},${alpha})`;
402
+ }
403
+ // Band hues. A named scheme supplies all three; only the custom scheme reads the saved colours.
404
+ function rfBandColors(state,dark){
405
+ const scheme=state.bandScheme||'vivid',preset=rfBandSchemeColors(scheme);
406
+ // The dark theme uses the same hues; the default alpha already suits both backgrounds.
407
+ if(preset)return preset.map(hex=>{const rgb=rfParseColor(hex)||[240,182,51];return rgb.slice(0,3).join(',');});
408
+ const fallback=['#f0b633','#4e9ee0','#9e70da'];
409
+ return ['color','color2','color3'].map((field,i)=>{
410
+ const rgb=rfParseColor(rfColorValue(state,'bands',field,fallback[i]))||rfParseColor(fallback[i]);
411
+ return rgb.slice(0,3).join(',');
412
+ });
413
+ }
414
+ // Gradient palette chips: a pill showing the actual ramp says more than a list of colour names.
415
+ const RF_GRADIENT_LABELS={Bright:'红蓝',Blues:'蓝紫',Night:'夜间'};
416
+ function rfGradientPill(name){
417
+ const p=RF_GRADIENT_PALETTES[name];if(!p)return 'transparent';
418
+ const rgb=c=>`rgb(${c.slice(0,3).join(',')})`;
419
+ // Only the two accent hues: including the base tone made the chip read as a black bar.
420
+ return `linear-gradient(90deg, ${rgb(p.a)} 0%, ${rgb(p.b)} 100%)`;
421
+ }
422
+ // Read back the size the reading body actually renders, in the same px units the host's own
423
+ // stepper uses, so the panel opens on the host's real value instead of assuming 14px.
424
+ function rfHostFontSize(){
425
+ const body=document.querySelector('.xMeOpW_body p, .xMeOpW_body li, .xMeOpW_body');
426
+ if(!body)return RF_FONT.sizeDefault;
427
+ const size=Number.parseFloat(getComputedStyle(body).fontSize);
428
+ return Number.isFinite(size)&&size>0?size:RF_FONT.sizeDefault;
429
+ }
430
+ // The host owns the line height: 24px plus the `--dsh-content-font-delta` ladder, i.e.
431
+ // `size + 10` px. The plugin never restates that number in CSS; it only adds `extra` on top.
432
+ function rfHostLineHeight(size){return RF_FONT.lineBase + (size - RF_FONT.baseSize);}
433
+ // The host publishes font size on <body>'s inline style, so writing documentElement would lose.
434
+ // rfTypographyWritten remembers what this plugin last wrote, so a host-side change can be told
435
+ // apart from our own write when the observer fires.
436
+ let rfTypographyWritten='';
437
+ function rfApplyTypography(font,{writeVar=true}={}){
438
+ const target=document.body;
439
+ const px=Number.isFinite(font?.size)?font.size:null;
440
+ const extra=Number.isFinite(font?.extra)?Math.max(0,font.extra):0;
441
+ let probe=document.getElementById('rf-typography');
442
+ if(!probe){probe=document.createElement('style');probe.id='rf-typography';document.head.append(probe);}
443
+ const rules=[];
444
+ if(px!==null&&writeVar){target.style.setProperty('--dsh-content-font-size',px.toFixed(2)+'px');rfTypographyWritten=px.toFixed(2)+'px';}
445
+ // Only an explicit extra spacing overrides the host ladder, and even then it rides the host's own
446
+ // variable: the size delta still applies, so a later font-size change keeps the added room.
447
+ if(px!==null&&extra>0)rules.push(`.xMeOpW_root .xMeOpW_body,.xMeOpW_root .xMeOpW_body p,.xMeOpW_root .xMeOpW_body li,:is(.xMeOpW_body>*){line-height:calc(${RF_FONT.lineBase}px + var(--dsh-content-font-delta, 0px) + ${extra}px)}`);
448
+ probe.textContent=rules.join('\n');
449
+ }
450
+ // The plugin owns that style element and any value it wrote itself: unloading it must not leave
451
+ // the host document permanently re-typeset, and it must not remove a size the host set later.
452
+ function rfClearTypography(){
453
+ document.getElementById('rf-typography')?.remove();
454
+ if(rfTypographyWritten&&document.body.style.getPropertyValue('--dsh-content-font-size')===rfTypographyWritten)document.body.style.removeProperty('--dsh-content-font-size');
455
+ rfTypographyWritten='';
456
+ }
457
+ // Only adjacent reconciled bands in the same visual lane may be joined.
458
+ function rfBandGroups(bands) {
459
+ const groups=[], last=new Map();
460
+ for(const band of bands){
461
+ const g=last.get(band.key),r=g?.rects.at(-1),b=band.rect;
462
+ if(g&&g.hue===band.hue&&g.clipKey===band.clipKey&&Math.min(r.right,b.right)>Math.max(r.left,b.left)&&Math.min(r.bottom,b.bottom)>=Math.max(r.top,b.top))g.rects.push(b);
463
+ else {const next={...band,rects:[b]};groups.push(next);last.set(band.key,next);}
464
+ }
465
+ return groups;
466
+ }
467
+ function rfBandMask(rects) {
468
+ const box={left:Math.min(...rects.map(r=>r.left)),top:Math.min(...rects.map(r=>r.top)),right:Math.max(...rects.map(r=>r.right)),bottom:Math.max(...rects.map(r=>r.bottom))};
469
+ const width=box.right-box.left,height=box.bottom-box.top;
470
+ // A continuous equal-width stack is one true rounded region, not rounded slices.
471
+ if(rects.every(r=>Math.abs(r.left-box.left)<.01&&Math.abs(r.right-box.right)<.01)){
472
+ const svg=`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><rect width="${width}" height="${height}" rx="4" fill="white"/></svg>`;
473
+ return {box,width,height,url:'data:image/svg+xml,'+encodeURIComponent(svg)};
474
+ }
475
+ const svgRect=(r,round='')=>`<rect x="${r.left-box.left}" y="${r.top-box.top}" width="${r.right-r.left}" height="${r.bottom-r.top}" ${round}/>`;
476
+ let content=rects.map(r=>svgRect(r,'rx="4"')).join('');
477
+ for(let i=0;i<rects.length;i++)for(let j=0;j<i;j++){
478
+ const a=rects[i],b=rects[j],left=Math.max(a.left,b.left),right=Math.min(a.right,b.right),top=Math.max(a.top,b.top),bottom=Math.min(a.bottom,b.bottom);
479
+ if(right>left&&bottom>=top)content+=svgRect({left,right,top:Math.max(Math.min(a.top,b.top),top-4),bottom:Math.min(Math.max(a.bottom,b.bottom),bottom+4)});
480
+ }
481
+ const svg=`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><g fill="white">${content}</g></svg>`;
482
+ return {box,width,height,url:'data:image/svg+xml,'+encodeURIComponent(svg)};
483
+ }
484
+ // Radius values preserve the original box; clipping happens after rounding.
485
+ function rfCornerRadii(values,w,h) {
486
+ const parse=(value)=>{const parts=value.trim().split(/\s+/);const n=(v,size)=>Math.max(0,parseFloat(v)||0)*(v?.endsWith('%')?size/100:1);return [n(parts[0],w),n(parts[1]||parts[0],h)];};
487
+ const r=values.map(parse), scale=Math.min(1,w/Math.max(1,r[0][0]+r[1][0]),w/Math.max(1,r[3][0]+r[2][0]),h/Math.max(1,r[0][1]+r[3][1]),h/Math.max(1,r[1][1]+r[2][1]));
488
+ return r.map(([x,y])=>[x*scale,y*scale]);
489
+ }
490
+ function rfRoundedPath(box,r) {
491
+ const {left:l,top:t,right:x,bottom:y}=box, [a,b,c,d]=r;
492
+ return `M ${l+a[0]} ${t} H ${x-b[0]} A ${b[0]} ${b[1]} 0 0 1 ${x} ${t+b[1]} V ${y-c[1]} A ${c[0]} ${c[1]} 0 0 1 ${x-c[0]} ${y} H ${l+d[0]} A ${d[0]} ${d[1]} 0 0 1 ${l} ${y-d[1]} V ${t+a[1]} A ${a[0]} ${a[1]} 0 0 1 ${l+a[0]} ${t} Z`;
493
+ }
494
+ function rfPaneMask(region,holes) {
495
+ const w=region.right-region.left,h=region.bottom-region.top,local=r=>({left:r.left-region.left,top:r.top-region.top,right:r.right-region.left,bottom:r.bottom-region.top});
496
+ const clips=[],paths=[];holes.forEach((hole,i)=>{const r=local(hole.rect),clip=local(hole.clip);clips.push(`<clipPath id="c${i}"><rect x="${clip.left}" y="${clip.top}" width="${clip.right-clip.left}" height="${clip.bottom-clip.top}"/></clipPath>`);paths.push(`<path d="${rfRoundedPath(r,hole.radii)}" clip-path="url(#c${i})"/>`);});
497
+ const svg=`<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}"><defs>${clips.join('')}<mask id="m" maskUnits="userSpaceOnUse" x="0" y="0" width="${w}" height="${h}" style="mask-type:luminance"><rect width="${w}" height="${h}" fill="white"/><g fill="black">${paths.join('')}</g></mask></defs><rect width="${w}" height="${h}" fill="white" mask="url(#m)"/></svg>`;
498
+ return 'data:image/svg+xml,'+encodeURIComponent(svg);
499
+ }
500
+ // Pure geometry/policy helpers are shared by the runtime and node unit tests.
501
+ function rfLineHeight(fontSize, lineHeight, measured) {
502
+ const font=Number.parseFloat(fontSize), size=Number.isFinite(font)&&font>0?font:16;
503
+ const css=Number.parseFloat(lineHeight), fallback=Number.isFinite(css)&&css>0?css:size*1.5;
504
+ return Number.isFinite(measured)&&measured>=size*.8&&measured<=fallback*2?measured:fallback;
505
+ }
506
+ function rfLineHole(y,count,lineHeight,box) {
507
+ const pad=Math.max(2,Math.min(5,lineHeight*.12)), half=(count*lineHeight)/2+pad;
508
+ return {left:box.left,right:box.right,top:y-half,bottom:y+half};
509
+ }
510
+ function rfLineCandidate(visible,view,x,y) {
511
+ return !!(visible&&view&&x>=view.left&&x<=view.right&&y>=view.top&&y<=view.bottom);
512
+ }
513
+ // Handle focus is frozen at the last reading Y; native capture owns the drag.
514
+ function rfHandlePolicy(state,event) {
515
+ if(event.type==='clear')return null;
516
+ if(event.type==='start')return event.scope&&event.scroll?{scope:event.scope,scroll:event.scroll,id:event.id}:null;
517
+ if(!state||event.id!==state.id)return state;
518
+ if(event.type==='end')return null;
519
+ return state;
520
+ }
521
+ function rfPanePolicy({sameScope, inScroll, structural, protectedControl, excluded}) {
522
+ if(!sameScope||excluded)return 'clear';
523
+ return !inScroll||structural||protectedControl?'freeze':'follow';
524
+ }
525
+ // The active host composer is rank 9; our own floating panel is rank 1000.
526
+ function rfPointerMode(mode) { return mode==='lines'||mode==='ruler'; }
527
+ function rfPointerLayer(enabled,mode) { return !!enabled&&rfPointerMode(mode); }
528
+ function rfLineRegion(content,outer) { return content&&outer?rfIntersect(content,outer):null; }
529
+ function rfRulerEdges(box) {
530
+ const thickness=Math.min(1,(box.bottom-box.top)/2);
531
+ return [{...box,bottom:box.top+thickness},{...box,top:box.bottom-thickness}];
532
+ }
533
+ function rfBarrierPolicy({known, image, visible, contents, overlay, overlapsText}) {
534
+ return !!(visible&&!contents&&!overlay&&(image||(known&&!overlapsText)));
535
+ }
536
+ // Five modes, each a distinct visual device. Block focus used to exist twice (paragraph and block
537
+ // modes drew the same rectangle with different strengths); it is now one mode with a presentation
538
+ // switch, so nothing is offered twice under two names.
539
+ const RF_MODES = [['ruler','阅读尺','定位当前行'],['lines','多行聚焦','聚焦附近几行'],['blocks','段落聚焦','当前段落突出'],['bands','色块分段','区分相邻内容'],['gradient','渐变阅读','为正文文字着色']];
540
+ // Earlier releases stored the removed `paragraph` mode; it maps onto the merged block mode.
541
+ function rfValidMode(mode) { if(mode==='paragraph')return 'blocks'; return RF_MODES.some(m=>m[0]===mode)?mode:'ruler'; }
542
+ // Every preference that survives a restart. Loading reads these fields and save() writes exactly
543
+ // this list, so a new preference is registered once and cannot be restored on load while never
544
+ // being saved - which is how the on/off switch used to lose its state.
545
+ const RF_PERSISTED=['enabled','mode','blockStyle','bandScheme','gutterHide','rulerLines','lineCount','segmentStyle','gradientPalette','gradientStrength','colors','font','position'];
546
+ function startReadingFocus() {
547
+ const KEY = 'dsh-reading-focus.v1';
548
+ const modes = RF_MODES;
549
+ const clamp = (v,a,b) => Math.max(a,Math.min(b,v));
550
+ let saved = {};
551
+ try { saved = JSON.parse(localStorage.getItem(KEY) || '{}') || {}; } catch {}
552
+ const validNumber = (v,d,a,b) => Number.isFinite(v) ? clamp(v,a,b) : d;
553
+ // Per-mode colours and typography stay optional: an absent entry means "use the built-in
554
+ // default", so upgrading from an older profile keeps working without migration.
555
+ // Every colour slot is a hex value or a 0..1 opacity. Unknown keys are ignored, so a saved
556
+ // profile from any earlier version keeps loading.
557
+ const RF_COLOR_KEYS=['ruler','lines','blocks','bands'];
558
+ const COLOR_FIELDS=/^[a-z]+Color\d?$/i;
559
+ const OPACITY_FIELDS=/^(opacity|[a-z]+Opacity)$/i;
560
+ const hex = v => typeof v==='string'&&/^#[0-9a-f]{6}$/i.test(v) ? v : null;
561
+ const readColorFields = entry => { const next={};
562
+ if(!entry||typeof entry!=='object')return next;
563
+ for(const [field,value] of Object.entries(entry)){
564
+ if(COLOR_FIELDS.test(field)){const c=hex(value);if(c)next[field]=c;}
565
+ else if(OPACITY_FIELDS.test(field)&&Number.isFinite(value))next[field]=clamp(value,0,1);
566
+ }
567
+ return next; };
568
+ const savedColors = stored => { const out={}; if(!stored||typeof stored!=='object')return out;
569
+ for(const key of RF_COLOR_KEYS){const next=readColorFields(stored[key]);if(Object.keys(next).length)out[key]=next;}
570
+ // Profiles written before the merge stored block-focus veil colours under `paragraph`.
571
+ const legacy=readColorFields(stored.paragraph);
572
+ if(Object.keys(legacy).length)out.blocks={...legacy,...(out.blocks||{})};
573
+ return out; };
574
+ // Profiles up to 0.8.3 stored a line-height ratio (briefly a px value); both are converted to the
575
+ // extra spacing above the host ladder so an upgrade cannot change the rendered line height.
576
+ const savedFont = stored => { const out={}; if(!stored||typeof stored!=='object')return out;
577
+ if(Number.isFinite(stored.size))out.size=clamp(stored.size,RF_FONT.sizeMin,RF_FONT.sizeMax);
578
+ if(Number.isFinite(stored.extra))out.extra=clamp(stored.extra,RF_FONT.extraMin,RF_FONT.extraMax);
579
+ else if(Number.isFinite(stored.lineHeight)){
580
+ const base=Number.isFinite(out.size)?out.size:RF_FONT.sizeDefault;
581
+ const px=stored.lineHeight<=5?stored.lineHeight*base:stored.lineHeight;
582
+ out.extra=clamp(Math.round(px-rfHostLineHeight(base)),RF_FONT.extraMin,RF_FONT.extraMax);
583
+ }
584
+ if(out.extra!==undefined&&out.size===undefined)out.size=RF_FONT.sizeDefault;
585
+ return out; };
586
+ const oldLineCount=Number.isInteger(saved.size)&&saved.size>=1&&saved.size<=6?saved.size:3;
587
+ const savedScheme=RF_BAND_SCHEMES.some(s=>s[0]===saved.bandScheme)?saved.bandScheme:'vivid';
588
+ const state = {enabled:saved.enabled===true, mode:rfValidMode(saved.mode), blockStyle:['fade','veil'].includes(saved.blockStyle)?saved.blockStyle:(saved.mode==='paragraph'?'veil':'fade'), bandScheme:savedScheme, gutterHide:saved.gutterHide!==false, rulerLines:Number.isInteger(saved.rulerLines)?clamp(saved.rulerLines,1,6):validNumber(saved.size,2,1,6), lineCount:Number.isInteger(saved.lineCount)&&saved.lineCount>=1&&saved.lineCount<=8?saved.lineCount:oldLineCount, segmentStyle:['paragraph','compact'].includes(saved.segmentStyle)?saved.segmentStyle:'paragraph', gradientPalette:Object.hasOwn(RF_GRADIENT_PALETTES,saved.gradientPalette)?saved.gradientPalette:'Bright', gradientStrength:validNumber(saved.gradientStrength,1,.1,1), colors:savedColors(saved.colors), font:savedFont(saved.font), position:saved.position && Number.isFinite(saved.position.x) && Number.isFinite(saved.position.y)?saved.position:null};
589
+ const host = document.createElement('div');
590
+ host.dataset.readingFocusUi = '';
591
+ document.body.append(host);
592
+ const shadow = host.attachShadow({mode:'open'});
593
+ shadow.innerHTML = `<style>${RF_CSS}</style><div class="layer" aria-hidden="true"></div>`;
594
+ const layer = shadow.querySelector('.layer');
595
+ const subscribers = new Set(), roots = new Set(), blockCache = new WeakMap();
596
+ let activeBody=null, activeBlock=null, hovering=false, lastX=0, lastY=0, hasPointer=false, panelHover=false, needsHit=false, frame=0, disposed=false, panel=null, panelControls=null, panelFrame=0, panelObserver=null, drag=null, returnFocus=null;
597
+ let occluderCandidates=null, widthDrag=null, pointerX=0, pointerY=0, pointerScope=null, pointerScroll=null, pointerSession=null;
598
+ // Reading ruler and line focus follow the pointer over the text column. The blank gutters on both
599
+ // sides are not reading space, so the effect steps aside there and the whole page becomes visible.
600
+ // A short delay plus a few pixels of slack keeps moving across the edge from flickering.
601
+ let gutterSince=0, gutterHidden=false, gutterTimer=0;
602
+ const RF_GUTTER_SLACK=10, RF_GUTTER_DELAY=110;
603
+ // Horizontal extent of the actual text column, which is narrower than the pane: the space between
604
+ // the column and the width handles is blank margin, not reading space.
605
+ // A brand-new session has a composer but no message body; the effects have nothing to focus on
606
+ // and must stay off until the first answer exists.
607
+ function hasConversation(scope){return !!scope?.querySelector?.(RF_ROOT);}
608
+ function textColumn(scope){
609
+ const body=scope?.querySelector?.('.xMeOpW_body');
610
+ if(body){const r=rect(body);if(r.right-r.left>8)return r;}
611
+ const root=scope?.querySelector?.(RF_ROOT);
612
+ if(root){const r=rect(root);if(r.right-r.left>8)return r;}
613
+ return bandsWidth(scope);
614
+ }
615
+ function gutterState(){
616
+ if(!pointerScope?.isConnected)return false;
617
+ const col=textColumn(pointerScope);
618
+ if(!(col.right>col.left))return false;
619
+ const inGutter=pointerX<col.left-RF_GUTTER_SLACK||pointerX>col.right+RF_GUTTER_SLACK;
620
+ if(!inGutter){
621
+ if(gutterTimer){clearTimeout(gutterTimer);gutterTimer=0;}
622
+ gutterSince=0;gutterHidden=false;return false;
623
+ }
624
+ if(!gutterSince)gutterSince=performance.now();
625
+ if(!gutterHidden&&performance.now()-gutterSince>=RF_GUTTER_DELAY)gutterHidden=true;
626
+ // The pointer may come to rest in the gutter with no further events: schedule one redraw.
627
+ else if(!gutterHidden&&!gutterTimer)gutterTimer=setTimeout(()=>{gutterTimer=0;queue();},RF_GUTTER_DELAY+20);
628
+ return gutterHidden;
629
+ }
630
+ function resetGutter(){if(gutterTimer){clearTimeout(gutterTimer);gutterTimer=0;}gutterSince=0;gutterHidden=false;}
631
+ function clearPointer(){pointerScope=null;pointerScroll=null;pointerSession=null;widthDrag=null;hovering=false;resetGutter();}
632
+ function pointerValid(){return !!(pointerScope?.isConnected&&pointerScroll?.isConnected&&pointerScope.getAttribute('data-conversation-session')===pointerSession&&pointerScroll.closest('[data-conversation-content][data-conversation-session]')===pointerScope);}
633
+ function anchorPointer(scope,scroll){pointerScope=scope;pointerScroll=scroll;pointerSession=scope.getAttribute('data-conversation-session');hovering=true;}
634
+ function save() { const out={}; for(const key of RF_PERSISTED)out[key]=state[key]; try { localStorage.setItem(KEY,JSON.stringify(out)); } catch {} }
635
+ // The host may change the same variable from its own settings; adopting it keeps the panel -
636
+ // and the next nudge - from re-applying a size the user has already replaced. Line height needs
637
+ // no adoption: the extra-spacing rule is written against the host's own delta variable.
638
+ function adoptHostTypography(){
639
+ if(!Number.isFinite(state.font?.size))return;
640
+ const raw=document.body.style.getPropertyValue('--dsh-content-font-size');
641
+ if(!raw||raw===rfTypographyWritten)return;
642
+ const px=Number.parseFloat(raw);
643
+ if(!Number.isFinite(px)||Math.abs(px-state.font.size)<.05)return;
644
+ state.font={size:clamp(px,RF_FONT.sizeMin,RF_FONT.sizeMax),extra:state.font.extra};
645
+ save();sync();
646
+ }
647
+ function sync() { for (const fn of [...subscribers]) fn(); }
648
+ function modalOpen() { return !!document.querySelector('dialog[open], [aria-modal="true"]'); }
649
+ function mountControls(container, floating=false, onOpenWindow=openWindow) {
650
+ container.innerHTML = `<style>${RF_CSS}</style><div class="rf-control-root ${floating?'floating':''}">
651
+ <div class="heading"><div><h2>阅读辅助</h2><p>选择适合自己的阅读方式,不改变正文。<small class="rf-version">v${RF_VERSION}</small></p></div><label class="switch"><input type="checkbox" aria-label="开启阅读辅助"><span></span></label></div>
652
+ <div class="section-label">选择效果</div>
653
+ <div class="mode-grid">${modes.map(([id,label,desc])=>`<button type="button" class="mode-card" data-mode="${id}" aria-pressed="false"><span class="mode-icon icon-${id}" aria-hidden="true"><i></i><i></i><i></i></span><span><strong>${label}</strong><small>${desc}</small></span></button>`).join('')}</div>
654
+ <div class="mode-options">
655
+ <div class="parameter gradient-palette"><span><strong>配色</strong><small>文字渐变使用哪一组颜色</small></span><div class="palette-row" role="group" aria-label="配色">${Object.keys(RF_GRADIENT_PALETTES).map(name=>`<button type="button" class="palette-pill" data-palette="${name}" aria-pressed="false" aria-label="${RF_GRADIENT_LABELS[name]||name}" title="${RF_GRADIENT_LABELS[name]||name}" style="background:${rfGradientPill(name)}"></button>`).join('')}</div></div>
656
+ <label class="parameter strength-parameter"><span><strong>颜色强度</strong><small>渐变颜色的明显程度</small></span><output class="strength-value"></output><input type="range" min="10" max="100" step="5" aria-label="效果强度"></label>
657
+ <label class="parameter range-size"><span><strong>覆盖行数</strong><small>跟随当前行高</small></span><output class="size-value"></output><input type="range" min="1" max="6" step="1" aria-label="覆盖行数"></label>
658
+ <div class="segment-row"><span><strong>分段样式</strong><small>整个列表合为一块,包含序号和多行内容</small></span><div class="segments" role="group" aria-label="分段样式"><button type="button" data-segment="paragraph" aria-pressed="false">整段色块</button><button type="button" data-segment="compact" aria-pressed="false">紧凑色带</button></div></div>
659
+ <div class="block-style-row"><span><strong>其余内容</strong><small>当前段落以外怎么变弱</small></span><div class="segments" role="group" aria-label="其余内容呈现方式"><button type="button" data-block-style="fade" aria-pressed="false">文字变淡</button><button type="button" data-block-style="veil" aria-pressed="false">遮罩压暗</button></div></div>
660
+ <div class="gutter-row"><span><strong>鼠标移到两侧空白</strong><small>左右留白不算正文,可以让效果让开</small></span><div class="segments" role="group" aria-label="两侧留白时的行为"><button type="button" data-gutter="hide" aria-pressed="false">隐藏效果</button><button type="button" data-gutter="keep" aria-pressed="false">保持显示</button></div></div>
661
+ </div>
662
+ <div class="color-row">
663
+ <div class="section-head"><span class="section-label">颜色</span><button type="button" class="reset-color">恢复默认</button></div>
664
+ <p class="color-hint"></p>
665
+ <div class="color-fields"></div>
666
+ </div>
667
+ <div class="font-row">
668
+ <div class="section-head"><span class="section-label">正文字体</span><button type="button" class="reset-font">恢复默认</button></div>
669
+ <p class="font-hint">与 DSH 共用字号;行高 = DSH 自动值 + 额外行距。「恢复默认」清除本插件的覆盖,回到 DSH 当前设置。</p>
670
+ <div class="font-fields"><label><span>字号</span><span class="stepper"><input type="number" min="${RF_FONT.sizeMin}" max="${RF_FONT.sizeMax}" step="1" inputmode="numeric" aria-label="正文字号"><span class="stepper-btns"><button type="button" data-nudge="1" aria-label="增加">&#9650;</button><button type="button" data-nudge="-1" aria-label="减少">&#9660;</button></span><em>px</em></span></label><label><span>额外行距</span><span class="stepper"><input type="number" min="${RF_FONT.extraMin}" max="${RF_FONT.extraMax}" step="1" inputmode="numeric" aria-label="额外行距"><span class="stepper-btns"><button type="button" data-nudge="1" aria-label="增加">&#9650;</button><button type="button" data-nudge="-1" aria-label="减少">&#9660;</button></span><em>px</em></span></label></div>
671
+ </div>
672
+ ${floating?'':'<button type="button" class="open-window">在正文中实时调节</button><p class="footnote">关闭调节窗不会关闭阅读效果。</p>'}</div>`;
673
+ const check=container.querySelector('input[type=checkbox]'), strength=container.querySelector('[aria-label="效果强度"]'), size=container.querySelector('[aria-label="覆盖行数"]');
674
+ const palettePills=[...container.querySelectorAll('[data-palette]')];
675
+ const fontSize=container.querySelector('[aria-label="正文字号"]'),fontExtra=container.querySelector('[aria-label="额外行距"]');
676
+ // Which colour field currently has its inline picker expanded.
677
+ let openField=null;
678
+ const specFor=mode=>rfColorSpecs(mode,state.blockStyle);
679
+ const modeColor=()=>{const key=state.mode;if(!rfHasColor(key))return null;if(!state.colors[key])state.colors[key]={};return state.colors[key];};
680
+ const entryFor=key=>state.colors?.[key]||{};
681
+ // Build the controls for the current mode from its descriptor, so every mode gets exactly the
682
+ // knobs that make sense for it and nothing generic is shared across different visual devices.
683
+ const renderColorFields=()=>{
684
+ const host=container.querySelector('.color-fields'),specs=specFor(state.mode);
685
+ host.replaceChildren();
686
+ if(!specs.length)return;
687
+ const key=state.mode,entry=entryFor(key);
688
+ const shown=specs.filter(field=>!field.onlyCustom||state.bandScheme==='custom');
689
+ for(const field of shown){
690
+ const row=document.createElement('div');row.className='color-field';
691
+ const head=document.createElement('div');head.className='color-field-head';
692
+ const title=document.createElement('strong');title.textContent=field.label;head.append(title);
693
+ if(field.hint){const hint=document.createElement('small');hint.textContent=field.hint;head.append(hint);}
694
+ if(field.kind==='scheme'){
695
+ row.append(head);
696
+ const line=document.createElement('div');line.className='scheme-row';line.setAttribute('role','group');line.setAttribute('aria-label',field.label);
697
+ for(const [id,label,colors] of RF_BAND_SCHEMES){
698
+ const b=document.createElement('button');b.type='button';b.dataset.scheme=id;
699
+ b.setAttribute('aria-pressed',String(state.bandScheme===id));
700
+ if(colors){
701
+ const dots=document.createElement('span');dots.className='scheme-dots';
702
+ for(const hexColor of colors){const dot=document.createElement('i');dot.style.background=hexColor;dots.append(dot);}
703
+ b.append(dots);b.title=label;b.setAttribute('aria-label',label);
704
+ }else b.textContent='自定义';
705
+ b.addEventListener('click',()=>{state.bandScheme=id;save();sync();queue();});
706
+ line.append(b);
707
+ }
708
+ row.append(line);
709
+ }else if(field.kind==='color'){
710
+ const value=String(entry[field.key]??RF_DEFAULT_COLORS[key]?.[field.key]??'#f0b633');
711
+ row.append(head);
712
+ const sw=document.createElement('div');sw.className='color-swatches';
713
+ const presets=field.palette||RF_PRESETS.band;
714
+ const commit=hexColor=>{const e=modeColor();if(!e)return;e[field.key]=hexColor;save();queue();};
715
+ const custom=document.createElement('button');custom.type='button';custom.className='swatch custom';
716
+ custom.append(document.createElement('i'));
717
+ custom.title='自定义颜色';custom.setAttribute('aria-label',field.label+' 自定义');
718
+ const out=document.createElement('output');out.className='color-value';out.textContent=value.toUpperCase();
719
+ custom.setAttribute('aria-pressed',String(openField===field.key));
720
+ custom.addEventListener('click',event=>{
721
+ event.stopPropagation();
722
+ // Expand the picker in place. A floating popover kept closing itself whenever the host
723
+ // re-rendered the settings page, and an inline one cannot be dismissed by accident.
724
+ openField=openField===field.key?null:field.key;
725
+ renderColorFields();
726
+ });
727
+ for(const hexColor of presets){
728
+ const b=document.createElement('button');b.type='button';b.className='swatch';
729
+ const fill=document.createElement('i');fill.style.background=hexColor;b.append(fill);
730
+ b.dataset.color=hexColor;b.setAttribute('aria-label','使用 '+hexColor.toUpperCase());
731
+ b.setAttribute('aria-pressed',String(value.toLowerCase()===hexColor.toLowerCase()));
732
+ b.addEventListener('click',()=>{commit(hexColor);openField=null;renderColorFields();});
733
+ sw.append(b);
734
+ }
735
+ sw.append(custom,out);
736
+ row.append(sw);
737
+ // Strength is its own row, always visible: picking one of the preset dots must not hide
738
+ // the only way to make the layer stronger or lighter.
739
+ if(field.alphaKey){
740
+ const alphaMin=field.alphaMin??15,alphaMax=field.alphaMax??85;
741
+ const alphaValue=Math.round((entry[field.alphaKey]??RF_DEFAULT_COLORS[key]?.[field.alphaKey]??.45)*100);
742
+ const alphaRow=document.createElement('div');alphaRow.className='alpha-row';
743
+ const alphaLabel=document.createElement('span');alphaLabel.textContent='透明度';
744
+ const alphaInput=document.createElement('input');
745
+ alphaInput.type='range';alphaInput.min=String(alphaMin);alphaInput.max=String(alphaMax);alphaInput.step='5';
746
+ alphaInput.value=String(alphaValue);alphaInput.dataset.field=field.alphaKey;
747
+ alphaInput.setAttribute('aria-label',field.label+' 透明度');
748
+ const alphaOut=document.createElement('output');alphaOut.textContent=alphaValue+'%';
749
+ alphaInput.addEventListener('input',()=>{const e=modeColor();if(!e)return;e[field.alphaKey]=Number(alphaInput.value)/100;alphaOut.textContent=alphaInput.value+'%';save();queue();});
750
+ alphaRow.append(alphaLabel,alphaInput,alphaOut);
751
+ row.append(alphaRow);
752
+ }
753
+ if(openField===field.key)row.append(buildPicker(field,value,out,sw));
754
+ }else{
755
+ const value=Math.round((entry[field.key]??RF_DEFAULT_COLORS[key]?.[field.key]??field.max/100)*100);
756
+ row.append(head);
757
+ const line=document.createElement('div');line.className='color-field-input';
758
+ const input=document.createElement('input');input.type='range';input.min=String(field.min??0);input.max=String(field.max??100);input.step='5';input.value=String(value);input.dataset.field=field.key;input.setAttribute('aria-label',field.label);
759
+ const out=document.createElement('output');out.textContent=value+'%';
760
+ input.addEventListener('input',()=>{const e=modeColor();if(!e)return;e[field.key]=Number(input.value)/100;out.textContent=input.value+'%';save();queue();});
761
+ line.append(input,out);row.append(line);
762
+ }
763
+ host.append(row);
764
+ }
765
+ };
766
+ // Inline colour picker: a disc (angle = hue, distance = saturation), a lightness slider and a
767
+ // hex field. Transparency lives on its own row outside, so it is also adjustable when the
768
+ // colour comes from one of the preset dots.
769
+ function buildPicker(field,initial,out,swatchRow){
770
+ const start=rfHexToHsl(initial);
771
+ let h=start.h,s=start.s,l=start.l;
772
+ const box=document.createElement("div");box.className="rf-picker inline";
773
+ box.innerHTML="<div class=\"rf-picker-head\"><span class=\"rf-picker-chip\"></span><input class=\"rf-picker-hex\" maxlength=\"7\" spellcheck=\"false\" aria-label=\"十六进制颜色值\"></div>"
774
+ +"<div class=\"rf-disc\" role=\"slider\" tabindex=\"0\" aria-label=\"色盘\"><span class=\"rf-disc-dot\"></span></div>"
775
+ +"<label class=\"rf-picker-field\"><span>明度</span><input class=\"rf-light\" type=\"range\" min=\"0\" max=\"100\" step=\"1\" aria-label=\"明度\"><output></output></label>";
776
+ const chip=box.querySelector(".rf-picker-chip"),hexField=box.querySelector(".rf-picker-hex");
777
+ const disc=box.querySelector(".rf-disc"),dot=box.querySelector(".rf-disc-dot");
778
+ const light=box.querySelector(".rf-light"),lightOut=light.nextElementSibling;
779
+ const commit=hexColor=>{const e=modeColor();if(!e)return;e[field.key]=hexColor;out.textContent=hexColor.toUpperCase();
780
+ for(const b of swatchRow.querySelectorAll(".swatch[data-color]"))b.setAttribute("aria-pressed",String(b.dataset.color.toLowerCase()===hexColor.toLowerCase()));
781
+ save();queue();};
782
+ const render=(notify=true)=>{
783
+ const hex=rfHslToHex(h,s,l);
784
+ chip.style.background=`hsl(${h} ${s}% ${l}%)`;
785
+ if(document.activeElement!==hexField)hexField.value=hex.toUpperCase();
786
+ const rad=(h-90)*Math.PI/180,rr=(s/100)*42;
787
+ dot.style.left=(50+Math.cos(rad)*rr)+"%";
788
+ dot.style.top=(50+Math.sin(rad)*rr)+"%";
789
+ light.value=String(l);lightOut.textContent=l+"%";
790
+ if(notify)commit(hex);
791
+ };
792
+ const setFromPointer=event=>{
793
+ const r=disc.getBoundingClientRect(),cx=r.left+r.width/2,cy=r.top+r.height/2;
794
+ const dx=event.clientX-cx,dy=event.clientY-cy;
795
+ h=(Math.atan2(dy,dx)*180/Math.PI+90+360)%360;
796
+ s=Math.max(0,Math.min(1,Math.hypot(dx,dy)/(r.width/2)))*100;
797
+ render();
798
+ };
799
+ disc.addEventListener("pointerdown",event=>{
800
+ event.preventDefault();
801
+ setFromPointer(event);
802
+ const move=ev=>setFromPointer(ev),up=()=>{document.removeEventListener("pointermove",move);document.removeEventListener("pointerup",up);};
803
+ document.addEventListener("pointermove",move);document.addEventListener("pointerup",up);
804
+ });
805
+ light.addEventListener("input",()=>{l=Number(light.value);render();});
806
+ hexField.addEventListener("input",()=>{
807
+ const raw=hexField.value.trim();
808
+ if(/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(raw)){
809
+ const norm=raw.startsWith("#")?raw:"#"+raw;
810
+ const hsl=rfHexToHsl(norm);
811
+ if(hsl){h=hsl.h;s=hsl.s;l=hsl.l;render();}
812
+ }
813
+ });
814
+ render(false);
815
+ return box;
816
+ }
817
+ const COLOR_HEADS={
818
+ ruler:'跟随鼠标的这条线用什么颜色。',
819
+ lines:'中间保持透明,只有周围压暗。',
820
+ blocks:'当前段落保持原样,其余内容按上面的方式变弱。',
821
+ bands:'三个颜色轮换,相邻色块永远不会是同一个颜色。'
822
+ };
823
+ const syncColorControls=()=>{
824
+ const specs=specFor(state.mode);
825
+ container.querySelector('.color-row').hidden=!specs.length;
826
+ container.querySelector('.color-hint').textContent=COLOR_HEADS[state.mode]||'';
827
+ renderColorFields();
828
+ };
829
+ // Font settings are typed in px with stepper arrows, the same control the DSH settings panel
830
+ // uses, so one number means the same thing in both places. `extra` is added to the host's own
831
+ // automatic line height, so 0 means "exactly like DSH".
832
+ const syncFontControls=()=>{const f=state.font;
833
+ const px=Number.isFinite(f.size)?f.size:rfHostFontSize();
834
+ const extra=Number.isFinite(f.extra)?f.extra:0;
835
+ fontSize.value=String(Math.round(px));fontExtra.value=String(Math.round(extra));};
836
+ const refresh=()=>{
837
+ const gradientMode=state.mode==='gradient',lines=state.mode==='lines';
838
+ for(const pill of palettePills){pill.setAttribute('aria-pressed',String(pill.dataset.palette===state.gradientPalette));pill.disabled=!state.enabled;}
839
+ container.querySelector('.gradient-palette').hidden=!gradientMode;
840
+ // The strength slider only drives the gradient; every other mode sets its own opacity in the
841
+ // colour section, so showing a control here that does nothing would be misleading.
842
+ container.querySelector('.strength-parameter').hidden=!gradientMode;
843
+ check.checked=state.enabled;
844
+ for (const b of container.querySelectorAll('[data-mode]')) {b.setAttribute('aria-pressed',String(b.dataset.mode===state.mode));b.disabled=!state.enabled;}
845
+ for (const b of container.querySelectorAll('[data-segment]')) {b.setAttribute('aria-pressed',String(b.dataset.segment===state.segmentStyle));b.disabled=!state.enabled;}
846
+ for (const b of container.querySelectorAll('[data-block-style]')) {b.setAttribute('aria-pressed',String(b.dataset.blockStyle===state.blockStyle));b.disabled=!state.enabled;}
847
+ for (const b of container.querySelectorAll('[data-gutter]')) {b.setAttribute('aria-pressed',String(b.dataset.gutter===(state.gutterHide?'hide':'keep')));b.disabled=!state.enabled;}
848
+ strength.disabled=size.disabled=!state.enabled;
849
+ strength.value=String(Math.round(state.gradientStrength*100));
850
+ size.max=lines?'8':'6';size.value=String(lines?state.lineCount:state.rulerLines);
851
+ size.setAttribute('aria-label',lines?'聚焦行数':'覆盖行数');
852
+ container.querySelector('.range-size strong').textContent=lines?'聚焦行数':'覆盖行数';
853
+ container.querySelector('.range-size small').textContent=lines?'按当前正文行高计算,滚动时保持整数行':'覆盖整行的高度,随当前行高自动换算';
854
+ container.querySelector('.size-value').textContent=(lines?state.lineCount:state.rulerLines)+' 行';
855
+ container.querySelector('.strength-value').textContent=Math.round(state.gradientStrength*100)+'%';
856
+ container.querySelector('.range-size').hidden=!['ruler','lines'].includes(state.mode);
857
+ container.querySelector('.segment-row').hidden=state.mode!=='bands';
858
+ container.querySelector('.block-style-row').hidden=state.mode!=='blocks';
859
+ container.querySelector('.gutter-row').hidden=!rfPointerMode(state.mode);
860
+ container.querySelector('.mode-options').hidden=!container.querySelector('.mode-options').querySelector(':scope > :not([hidden])');
861
+ // Only the last visible row keeps no separator, otherwise the group ends on a stray rule.
862
+ const optionRows=[...container.querySelector('.mode-options').children];
863
+ const lastVisible=optionRows.filter(row=>!row.hidden).pop();
864
+ for(const row of optionRows)row.style.borderBottom=row===lastVisible?'0':'';
865
+ container.querySelector('.color-row').hidden=!rfHasColor(state.mode);
866
+ syncColorControls();syncFontControls();
867
+ };
868
+ check.addEventListener('change',()=>setEnabled(check.checked));
869
+ container.addEventListener('click',e=>{
870
+ // Stepper arrows: nudge the adjacent number field, then let its own listener apply the value.
871
+ const nudge=e.target.closest('[data-nudge]');
872
+ if(nudge){
873
+ const input=nudge.closest('.stepper')?.querySelector('input[type=number]');
874
+ if(input){
875
+ const step=Number(input.step)||1,min=Number(input.min),max=Number(input.max);
876
+ const next=clamp((Number(input.value)||min||0)+step*Number(nudge.dataset.nudge),min,max);
877
+ input.value=String(next);input.dispatchEvent(new Event('change',{bubbles:true}));
878
+ }
879
+ return;
880
+ }
881
+ // Gradient palette chips are buttons of their own; handle them before the mode branches.
882
+ const pill=e.target.closest('[data-palette]');
883
+ if(pill){if(Object.hasOwn(RF_GRADIENT_PALETTES,pill.dataset.palette)){state.gradientPalette=pill.dataset.palette;gradient.invalidate();save();sync();}return;}
884
+ const b=e.target.closest('button');if(!b)return;if(b.dataset.mode){clearPointer();activeBody=null;activeBlock=null;state.mode=b.dataset.mode;openField=null;gradient.clear();gradient.scan();save();sync();queue(true);}else if(b.dataset.blockStyle){state.blockStyle=b.dataset.blockStyle;save();sync();queue();}else if(b.dataset.gutter){state.gutterHide=b.dataset.gutter==='hide';resetGutter();save();sync();queue(true);}else if(b.dataset.segment){state.segmentStyle=b.dataset.segment;save();sync();queue();}else if(b.classList.contains('open-window'))onOpenWindow();});
885
+ strength.addEventListener('input',()=>{state.gradientStrength=Number(strength.value)/100;gradient.invalidate();save();sync();queue();});
886
+ const linesMax=()=>state.mode==='lines'?8:6;
887
+ size.addEventListener('input',()=>{const v=clamp(Number(size.value)||1,1,linesMax());size.value=String(v);if(state.mode==='lines')state.lineCount=v;else state.rulerLines=v;save();sync();queue();});
888
+ // Typing must stay possible: `input` only previews values that are already usable and never
889
+ // rewrites the field, while `change` (blur or Enter) clamps and normalises what was typed.
890
+ // Rewriting on every keystroke made "18" land as 12 -> 22.
891
+ const applyFont=(commit)=>{
892
+ const sizeRaw=fontSize.value.trim(),extraRaw=fontExtra.value.trim();
893
+ const sizeNum=sizeRaw===''?NaN:Number(sizeRaw),extraNum=extraRaw===''?NaN:Number(extraRaw);
894
+ const sizeOk=Number.isFinite(sizeNum)&&sizeNum>=RF_FONT.sizeMin&&sizeNum<=RF_FONT.sizeMax;
895
+ const extraOk=Number.isFinite(extraNum)&&extraNum>=RF_FONT.extraMin&&extraNum<=RF_FONT.extraMax;
896
+ if(!commit&&(!sizeOk||!extraOk))return; // a half-typed value must not move the page
897
+ const px=clamp(Number.isFinite(sizeNum)?Math.round(sizeNum):RF_FONT.sizeDefault,RF_FONT.sizeMin,RF_FONT.sizeMax);
898
+ const extra=clamp(Number.isFinite(extraNum)?Math.round(extraNum):RF_FONT.extraMin,RF_FONT.extraMin,RF_FONT.extraMax);
899
+ state.font={size:px,extra};
900
+ rfApplyTypography(state.font);save();
901
+ if(commit)syncFontControls();
902
+ gradient.invalidate();queue();
903
+ };
904
+ for(const el of [fontSize,fontExtra]){
905
+ el.addEventListener('input',()=>applyFont(false));
906
+ el.addEventListener('change',()=>applyFont(true));
907
+ }
908
+ // Clearing the override - not writing 14px - so the host's own current setting comes back.
909
+ container.querySelector('.reset-font').addEventListener('click',()=>{state.font={};rfClearTypography();save();syncFontControls();gradient.invalidate();queue();});
910
+ // Reset only this mode's colours; other modes keep whatever the user picked for them.
911
+ container.querySelector('.reset-color').addEventListener('click',()=>{delete state.colors[state.mode];if(state.mode==='bands')state.bandScheme='vivid';openField=null;save();sync();queue();});
912
+ // Re-read the host's own size before the panel first paints: the plugin may have been switched
913
+ // off while DSH's settings changed.
914
+ adoptHostTypography();
915
+ subscribers.add(refresh);refresh();
916
+ return ()=>{subscribers.delete(refresh);container.replaceChildren();};
917
+ }
918
+ function queuePanel() { if(panel&&!panelFrame&&!disposed) panelFrame=requestAnimationFrame(()=>{panelFrame=0;placePanel();}); }
919
+ function placePanel() {
920
+ if(!panel)return;
921
+ panel.hidden=modalOpen();if(panel.hidden)return;
922
+ const r=panel.getBoundingClientRect(), m=8;
923
+ const pos=state.position||{x:innerWidth-r.width-24,y:Math.max(m,(innerHeight-r.height)/2)};
924
+ let x=clamp(pos.x,m,Math.max(m,innerWidth-r.width-m));
925
+ let y=clamp(pos.y,m,Math.max(m,innerHeight-r.height-m));
926
+ if(!state.position){
927
+ const card=document.querySelector('[data-composer-card]');
928
+ if(card){
929
+ const c=card.getBoundingClientRect();
930
+ if(rfIntersect({left:x,top:y,right:x+r.width,bottom:y+r.height},c)){
931
+ if(c.top-r.height-m>=m)y=c.top-r.height-m;
932
+ else if(c.left-r.width-m>=m)x=c.left-r.width-m;
933
+ else if(c.right+r.width+m<=innerWidth-m)x=c.right+m;
934
+ }
935
+ }
936
+ }
937
+ panel.style.left=x+'px';
938
+ panel.style.top=y+'px';
939
+ }
940
+ function closeWindow() {
941
+ if(!panel)return;
942
+ const hadFocus=!!shadow.activeElement&&panel.contains(shadow.activeElement), title=panel.querySelector('.top');
943
+ if(drag){const id=drag.id;drag=null;if(title.hasPointerCapture(id))title.releasePointerCapture(id);}
944
+ panelObserver?.disconnect();panelObserver=null;if(panelFrame)cancelAnimationFrame(panelFrame);panelFrame=0;panelControls?.();panel.remove();panel=null;panelHover=false;
945
+ if(hadFocus&&returnFocus?.isConnected&&!returnFocus.closest('dialog[open], [aria-modal="true"]'))returnFocus.focus({preventScroll:true});
946
+ returnFocus=null;
947
+ }
948
+ function openWindow() {
949
+ if(disposed)return;if(panel){queuePanel();return;}
950
+ returnFocus=document.activeElement;panel=document.createElement('section');panel.className='panel';panel.setAttribute('aria-label','实时阅读调节窗');
951
+ panel.innerHTML='<div class="top"><strong>实时阅读调节</strong><button type="button" class="close" aria-label="关闭悬浮窗">×</button></div><div class="panel-controls"></div>';
952
+ shadow.append(panel);panelControls=mountControls(panel.querySelector('.panel-controls'),true);
953
+ const title=panel.querySelector('.top');panel.querySelector('.close').addEventListener('click',closeWindow);
954
+ title.addEventListener('pointerdown',e=>{if(drag||e.target.closest('button'))return;const r=panel.getBoundingClientRect();drag={id:e.pointerId,dx:e.clientX-r.left,dy:e.clientY-r.top};title.setPointerCapture(e.pointerId);e.preventDefault();});
955
+ title.addEventListener('pointermove',e=>{if(!drag||e.pointerId!==drag.id)return;state.position={x:e.clientX-drag.dx,y:e.clientY-drag.dy};placePanel();});
956
+ const end=e=>{if(!drag||e.pointerId!==drag.id)return;const id=drag.id,r=panel.getBoundingClientRect();state.position={x:r.left,y:r.top};drag=null;save();if(title.hasPointerCapture(id))title.releasePointerCapture(id);};
957
+ title.addEventListener('pointerup',end);title.addEventListener('pointercancel',end);title.addEventListener('lostpointercapture',end);
958
+ panelObserver=new MutationObserver(records=>{if(records.some(r=>r.target!==host&&!host.contains(r.target)))queuePanel();});
959
+ panelObserver.observe(document.body,{subtree:true,childList:true,attributes:true,attributeFilter:['open','aria-modal','role']});queuePanel();
960
+ }
961
+ function addRoots(node) { if(node.nodeType!==1||node===host||host.contains(node))return;if(matchesRoot(node))roots.add(node);queryRoots(node).forEach(el=>roots.add(el)); }
962
+ function invalidate() { for(const r of roots)blockCache.delete(r); }
963
+ const gradientSizes=new WeakMap();
964
+ const resizeObserver=new ResizeObserver(entries=>{let changed=false;for(const entry of entries){if(!roots.has(entry.target))continue;const width=entry.contentRect.width;if(gradientSizes.get(entry.target)!==width){gradientSizes.set(entry.target,width);changed=true;}}if(changed)gradient.invalidate();queue(true);});
965
+ function watchRoots(){resizeObserver.disconnect();for(const root of roots)if(root.isConnected)resizeObserver.observe(root);for(const el of document.querySelectorAll('[data-composer-seat], [data-composer-card], [data-composer-dock], [data-composer-seat] [data-testid="todo-panel"]'))resizeObserver.observe(el);}
966
+ const observer=new MutationObserver(records=>{
967
+ let changed=false, structure=false;
968
+ for(const rec of records){if(rec.type==='childList'&&[...rec.addedNodes,...rec.removedNodes].length&&[...rec.addedNodes,...rec.removedNodes].every(n=>n.nodeType===1&&n.matches('[data-reading-focus-gradient]')))continue;const target=rec.target.nodeType===1?rec.target:rec.target.parentElement;if(target===host||host.contains(target)||target?.closest?.('.rf-control-root, [data-reading-focus-gradient]'))continue;
969
+ if(state.enabled&&state.mode==='gradient'){const root=closestRoot(target);if(root){const block=blocks(root).find(b=>b===target||b.contains(target));if(block)gradient.invalidate(block);else if(rec.type!=='childList')for(const item of blocks(root))gradient.invalidate(item);}else if(rec.type==='attributes'&&['class','style','data-ds-dark-theme'].includes(rec.attributeName))gradient.invalidate();}
970
+ if(rec.type==='childList'){for(const node of rec.addedNodes)if(node.nodeType===1)addRoots(node);structure=true;}
971
+ if(rec.type==='attributes'&&rec.attributeName==='class'){addRoots(target);structure=true;}
972
+ if(closestRoot(target))changed=true;
973
+ if(rec.type==='attributes')changed=true;
974
+ }
975
+ // The host's own settings write the same variable; adopt it when the write was not ours.
976
+ if(records.some(rec=>rec.type==='attributes'&&rec.target===document.body&&rec.attributeName==='style'))adoptHostTypography();
977
+ if(structure){for(const r of roots)if(!r.isConnected||!matchesRoot(r)){blockCache.delete(r);roots.delete(r);if(activeBody===r){activeBody=null;activeBlock=null;if(!rfPointerMode(state.mode))hovering=false;}}watchRoots();}
978
+ if(changed||structure){
979
+ occluderCandidates=null;
980
+ if(structure)invalidate();
981
+ if(structure&&state.mode==='gradient')gradient.scan();queue(true);queuePanel();
982
+ }
983
+ });
984
+ function startObservers(){roots.clear();occluderCandidates=null;queryRoots(document).forEach(el=>roots.add(el));watchRoots();observer.observe(document.body,{subtree:true,childList:true,characterData:true,attributes:true,attributeFilter:['open','aria-modal','role','inert','data-ds-dark-theme','data-conversation-session','hidden','class','style']});}
985
+ function stopObservers(){observer.disconnect();resizeObserver.disconnect();roots.clear();occluderCandidates=null;}
986
+ function blocks(root){
987
+ let cached=blockCache.get(root);
988
+ if(!cached){
989
+ cached=[...root.querySelectorAll(RF_BLOCK)].filter(el=>{
990
+ if(el.closest('[data-turn-process-inline], [data-code-block-banner], [role="toolbar"], [role="button"], button'))return false;
991
+ let p=el.parentElement;
992
+ while(p&&p!==root){if(p.matches(RF_BLOCK))return false;p=p.parentElement;}
993
+ return p===root;
994
+ });
995
+ blockCache.set(root,cached);
996
+ }
997
+ return cached.filter(el=>el.textContent.trim()&&el.getClientRects().length);
998
+ }
999
+ // Bands deliberately group a whole outer list, without changing blocks() navigation.
1000
+ // Code blocks are never banded: they keep their own surface and act as a hard barrier.
1001
+ // Headings are left plain for the same reason the gradient skips them; tables are banded like
1002
+ // any other reading block.
1003
+ const RF_CODE_BLOCK = 'pre, [data-code-block-content], .md-code-block';
1004
+ const RF_NO_BAND = 'h1,h2,h3,h4,h5,h6';
1005
+ function isCodeBlock(el){return el.matches('pre')||!!el.closest('[data-code-block-content], .md-code-block');}
1006
+ function codeBlockRects(root){
1007
+ const found=[],box=viewport(root);
1008
+ for(const el of root.querySelectorAll(RF_CODE_BLOCK)){
1009
+ if(el.matches('[data-code-block-content], .md-code-block')&&el.parentElement?.closest('[data-code-block-content], .md-code-block'))continue;
1010
+ const s=getComputedStyle(el);if(s.display==='none'||s.visibility==='hidden'||Number(s.opacity)===0)continue;
1011
+ const r=rfIntersect(rect(el),box);if(r)found.push(r);
1012
+ }
1013
+ return found;
1014
+ }
1015
+ function bandsBlocks(root){
1016
+ const selector=RF_BLOCK+',ul,ol';
1017
+ return [...root.querySelectorAll(selector)].filter(el=>{
1018
+ if(el.matches(RF_NO_BAND))return false;
1019
+ if(el.closest('[data-turn-process-inline], [data-code-block-banner], [role="toolbar"], [role="button"], button'))return false;
1020
+ if(isCodeBlock(el))return false;
1021
+ let p=el.parentElement;
1022
+ while(p&&p!==root){if(p.matches(selector))return false;p=p.parentElement;}
1023
+ return p===root&&el.textContent.trim()&&el.getClientRects().length;
1024
+ });
1025
+ }
1026
+ function bandsWidth(root){
1027
+ const rr=rect(root), fallback={left:rr.left-14,right:rr.right+14};
1028
+ // Handles are siblings of this root's conversation scrollport, never global.
1029
+ const scroll=root.closest('[data-conversation-scroll]');
1030
+ const body=scroll?.parentElement;
1031
+ if(!body?.matches('[data-conversation-content]'))return fallback;
1032
+ const left=body.querySelector(':scope > [data-width-handle="left"]');
1033
+ const right=body.querySelector(':scope > [data-width-handle="right"]');
1034
+ if(!left||!right||!left.getClientRects().length||!right.getClientRects().length)return fallback;
1035
+ const l=rect(left),r=rect(right);
1036
+ if(l.right<=l.left||r.right<=r.left||l.right>=r.left)return fallback;
1037
+ return {left:l.right,right:r.left};
1038
+ }
1039
+ function viewport(el){
1040
+ let box={left:0,top:0,right:innerWidth,bottom:innerHeight};
1041
+ for(let p=el;p;p=p.parentElement){const s=getComputedStyle(p), x=/(auto|scroll|hidden|clip)/.test(s.overflowX),y=/(auto|scroll|hidden|clip)/.test(s.overflowY);if(x||y){const r=p.getBoundingClientRect(),l=r.left+p.clientLeft,t=r.top+p.clientTop;box={left:x?Math.max(box.left,l):box.left,right:x?Math.min(box.right,l+p.clientWidth):box.right,top:y?Math.max(box.top,t):box.top,bottom:y?Math.min(box.bottom,t+p.clientHeight):box.bottom};}}
1042
+ return box;
1043
+ }
1044
+ function rect(el){const r=el.getBoundingClientRect();return {left:r.left,top:r.top,right:r.right,bottom:r.bottom};}
1045
+ // Real line box of the reading pane, so "N lines" means N actual text lines even when the user
1046
+ // has changed font size or line spacing. Cached per frame: draw() calls this on every scroll
1047
+ // tick and getComputedStyle would force a style recalc each time.
1048
+ let lineHeightCache=new Map(),lineHeightFrame=0;
1049
+ function lineHeight(scope){
1050
+ const now=performance.now();
1051
+ if(now-lineHeightFrame>200)lineHeightCache=new Map(),lineHeightFrame=now;
1052
+ const key=scope||document.documentElement;
1053
+ if(lineHeightCache.has(key))return lineHeightCache.get(key);
1054
+ const probe=key.querySelector?.('.xMeOpW_body p, .xMeOpW_body li');
1055
+ let value=24;
1056
+ if(probe){const s=getComputedStyle(probe);value=rfLineHeight(s.fontSize,s.lineHeight,probe.getClientRects()[0]?.height);}
1057
+ else{const s=getComputedStyle(key);value=rfLineHeight(s.fontSize,s.lineHeight,NaN);}
1058
+ lineHeightCache.set(key,value);return value;
1059
+ }
1060
+ // The composer seat and the status dock are controls, not reading text.
1061
+ function composerRect(scope){
1062
+ const seat=scope?.querySelector('[data-composer-seat]')||document.querySelector('[data-composer-seat]');
1063
+ if(!seat||!seat.getClientRects().length)return null;
1064
+ const r=rect(seat);
1065
+ return rfIntersect(r,rect(scope||document.body));
1066
+ }
1067
+ const gradient=createGradientController({state,roots,blocks,viewport,notify:sync,flowOf:root=>rootGroup(root)[0]});
1068
+ function blockRect(el, list, i, padded){
1069
+ const r=rect(el), root=closestRoot(el), rr=rect(root);
1070
+ if(el.tagName==='LI'){
1071
+ const parent=el.parentElement;
1072
+ if(parent&&/^(OL|UL)$/.test(parent.tagName)){
1073
+ const pr=rect(parent);
1074
+ if(getComputedStyle(parent).direction==='rtl')r.right=Math.max(r.right,pr.right);
1075
+ else r.left=Math.min(r.left,pr.left);
1076
+ }
1077
+ }
1078
+ if(padded){const prev=i>0?rect(list[i-1]):null,next=i+1<list.length?rect(list[i+1]):null;r.left=Math.max(rr.left,r.left-10);r.right=Math.min(rr.right,r.right+10);r.top=Math.max(prev?(prev.bottom+r.top)/2:r.top-6,r.top-6);r.bottom=Math.min(next?(r.bottom+next.top)/2:r.bottom+6,r.bottom+6);}
1079
+ return r;
1080
+ }
1081
+ function isHostOccluder(el){
1082
+ if(el===host||host.contains(el)||el.matches('[data-text-interaction-surface]'))return false;
1083
+ for(const root of roots){
1084
+ if(el===root||el.contains(root))return false;
1085
+ if(root.contains(el))return el.matches('[data-composer-seat], [data-composer-card], [data-composer-overlay], [data-composer-dock], [data-composer-input], [data-code-block-banner], [data-conversation-region="composer"], [data-slot="conversation.input.dock"], [role="toolbar"], [role="menu"], [role="dialog"], dialog[open], [aria-modal="true"]');
1086
+ }
1087
+ return true;
1088
+ }
1089
+ function occluders(){
1090
+ const found=[];
1091
+ if(!occluderCandidates)occluderCandidates=[...document.querySelectorAll(RF_OCCLUDERS)];
1092
+ for(const el of occluderCandidates){
1093
+ if(!el.isConnected||!isHostOccluder(el))continue;
1094
+ const s=getComputedStyle(el);if(el.closest('[hidden], [aria-hidden="true"]')||s.display==='none'||s.visibility==='hidden'||Number(s.opacity)===0)continue;
1095
+ const candidates=[el];
1096
+ while(candidates.length){const c=candidates.pop(),cs=getComputedStyle(c),r=rect(c);if(cs.display==='none'||cs.visibility==='hidden')continue;if(cs.display==='contents'||r.right<=r.left||r.bottom<=r.top)candidates.push(...c.children);else found.push(r);}
1097
+ }
1098
+ return found;
1099
+ }
1100
+ // Only real panels and small controls are exempt in lines mode, not structural seats.
1101
+ function lineOccluders(scope){
1102
+ const found=[], selector='[data-composer-card], [data-composer-seat] section[data-testid="todo-panel"], [role="menu"], [role="listbox"], [role="dialog"], dialog[open], [aria-modal="true"], [data-composer-overlay] > *, [role="toolbar"] button, [role="toolbar"] [role="button"], [role="toolbar"] a, [role="toolbar"] input, footer button, footer [role="button"], footer a, footer span';
1103
+ for(const dock of scope.querySelectorAll('[data-composer-dock]')){
1104
+ const card=dock.parentElement?.querySelector(':scope > [data-composer-card]');if(!card)continue;
1105
+ const children=[...dock.children],boxes=[];while(children.length){const el=children.pop(),s=getComputedStyle(el),r=rect(el);if(s.display==='none'||s.visibility==='hidden'||Number(s.opacity)===0||el.closest('[hidden], [aria-hidden="true"]'))continue;if(s.display==='contents'||r.right<=r.left||r.bottom<=r.top)children.push(...el.children);else boxes.push(r);}
1106
+ if(boxes.length){const cardBox=rect(card),box={left:Math.max(cardBox.left,Math.min(...boxes.map(r=>r.left))-2),top:Math.min(...boxes.map(r=>r.top))-1,right:Math.min(cardBox.right,Math.max(...boxes.map(r=>r.right))+2),bottom:Math.max(...boxes.map(r=>r.bottom))+1},clip=viewport(dock);if(rfIntersect(box,clip))found.push({rect:box,clip,radii:rfCornerRadii(['10px','10px','10px','10px'],box.right-box.left,box.bottom-box.top)});}
1107
+ }
1108
+ for(const el of document.querySelectorAll(selector)){
1109
+ const popup=el.matches('[role="menu"], [role="listbox"], [role="dialog"], dialog[open], [aria-modal="true"]');
1110
+ if(!el.isConnected||(!popup&&!isHostOccluder(el))||el.closest('[hidden], [aria-hidden="true"], [data-composer-dock]'))continue;
1111
+ if(!popup&&el.closest('[data-conversation-scroll]')&&!el.closest('[data-composer-seat], [data-composer-overlay], [data-conversation-region="composer"]'))continue;
1112
+ const owner=el.closest('[data-conversation-content]');if(owner&&owner!==scope)continue;
1113
+ if(el.matches('span')&&(el.children.length||!el.textContent.trim()))continue;
1114
+ const st=getComputedStyle(el),r=rect(el);if(st.display==='none'||st.visibility==='hidden'||Number(st.opacity)===0||r.right<=r.left||r.bottom<=r.top)continue;
1115
+ // Full-width overlay anchors and leaf wrappers are structural, never exempt.
1116
+ if(!el.matches('[data-composer-card], section[data-testid="todo-panel"], [data-code-block-banner], [role="menu"], [role="listbox"], [role="dialog"], dialog[open], [aria-modal="true"]') && (r.right-r.left)>(rect(scope).right-rect(scope).left)*.8)continue;
1117
+ const clip=viewport(el);if(rfIntersect(r,clip))found.push({rect:r,clip,radii:rfCornerRadii([st.borderTopLeftRadius,st.borderTopRightRadius,st.borderBottomRightRadius,st.borderBottomLeftRadius],r.right-r.left,r.bottom-r.top)});
1118
+ }
1119
+ return found;
1120
+ }
1121
+ function patchShapes(shapes){
1122
+ let i=0;for(const spec of shapes){let e=layer.children[i];if(!e){e=document.createElement('div');e.className='shape';layer.append(e);}const r=spec.rect;e.style.cssText=`left:${r.left}px;top:${r.top}px;width:${r.right-r.left}px;height:${r.bottom-r.top}px;background:${spec.color};${spec.extra||''}`;i++;}
1123
+ while(layer.children.length>i)layer.lastElementChild.remove();
1124
+ }
1125
+ // Block focus fades the text itself instead of covering the page: `::highlight()` can set a text
1126
+ // colour without touching the DOM, and one range may span a whole subtree, so a focus change
1127
+ // costs a couple of ranges rather than one per text node.
1128
+ const dimName='rf-dim-'+Math.random().toString(36).slice(2);
1129
+ let dimStyle=null,dimHighlight=null,dimRule='';
1130
+ function dimSupported(){return !!window.CSS?.highlights&&typeof Highlight==='function';}
1131
+ function clearDim(){
1132
+ if(dimHighlight&&CSS.highlights.get(dimName)===dimHighlight)CSS.highlights.delete(dimName);
1133
+ dimHighlight=null;if(dimStyle){dimStyle.remove();}dimStyle=null;dimRule='';
1134
+ }
1135
+ function paintDim(block,color){
1136
+ if(!dimSupported())return false;
1137
+ if(!dimHighlight){dimHighlight=new Highlight();CSS.highlights.set(dimName,dimHighlight);}
1138
+ if(!dimStyle){dimStyle=document.createElement('style');dimStyle.dataset.readingFocusDim='';document.head.append(dimStyle);}
1139
+ if(dimRule!==color){dimRule=color;dimStyle.textContent=`::highlight(${dimName}){color:${color}}`;}
1140
+ const highlight=dimHighlight;highlight.clear();
1141
+ for(const root of roots){
1142
+ if(!root.isConnected)continue;
1143
+ if(block&&root.contains(block)){
1144
+ const before=document.createRange();
1145
+ before.setStartBefore(root);before.setEndBefore(block);
1146
+ if(!before.collapsed)highlight.add(before);
1147
+ const after=document.createRange();
1148
+ after.setStartAfter(block);after.setEndAfter(root);
1149
+ if(!after.collapsed)highlight.add(after);
1150
+ }else{
1151
+ const whole=document.createRange();whole.selectNodeContents(root);highlight.add(whole);
1152
+ }
1153
+ }
1154
+ return true;
1155
+ }
1156
+ // All markdown roots of one assistant answer read as a single flow. A tool call interrupts the
1157
+ // answer visually - the host renders the text before and after it as separate markdown roots -
1158
+ // but it is still one continuous piece of reading, so the colour pattern must continue across
1159
+ // the interruption rather than restarting from base. Roots from a different answer (another
1160
+ // turn) stay separate, so a new answer does open at base.
1161
+ function rootGroup(root){
1162
+ const lane=root.closest('.xMeOpW_body')||root.parentElement;
1163
+ if(!lane)return [root];
1164
+ const scope=flowScope(lane)||lane;
1165
+ const all=[...scope.querySelectorAll(RF_ROOT)].filter(matchesRoot);
1166
+ if(!all.length)return [root];
1167
+ // Keep only top-level roots: a root nested inside another root already reads as part of it.
1168
+ const top=all.filter(el=>!all.some(other=>other!==el&&other.contains(el)));
1169
+ const turn=flowTurn(root);
1170
+ const group=turn===null?top:top.filter(el=>flowTurn(el)===turn);
1171
+ return group.length?group:[root];
1172
+ }
1173
+ // The element that holds every flow item of one answer, including the tool-call rows that sit
1174
+ // between two text segments. Undefined when the host does not expose it.
1175
+ function flowScope(node){
1176
+ return node.closest('[data-slot="conversation.chat.flow"]')||node.closest('[data-chat-turn]')?.parentElement||null;
1177
+ }
1178
+ // Turn number of the answer a root belongs to; null when the host does not mark it.
1179
+ function flowTurn(node){
1180
+ const turn=node.closest('[data-chat-turn]')?.getAttribute('data-chat-turn');
1181
+ return turn===undefined||turn===null||turn===''?null:turn;
1182
+ }
1183
+ function groupRegion(root,group,index){
1184
+ const r=rect(root);
1185
+ if(index>0)r.top=(rect(group[index-1]).bottom+r.top)/2;
1186
+ if(index+1<group.length)r.bottom=(r.bottom+rect(group[index+1]).top)/2;
1187
+ return rfIntersect(r,viewport(root));
1188
+ }
1189
+ // A lane is bounded by the actual scroll/clipping ancestor chain and session.
1190
+ function laneOf(root){
1191
+ const chain=[];
1192
+ for(let p=root;p;p=p.parentElement){const s=getComputedStyle(p);if(/(auto|scroll|hidden|clip)/.test(s.overflowX+' '+s.overflowY))chain.push(p);}
1193
+ const scroll=root.closest('[data-conversation-scroll]');
1194
+ return {scroll,session:root.closest('[data-conversation-session]'),fallback:scroll?null:rootGroup(root)[0],chain};
1195
+ }
1196
+ function sameLane(a,b){return a.scroll===b.scroll&&a.session===b.session&&a.fallback===b.fallback&&a.chain.length===b.chain.length&&a.chain.every((x,i)=>x===b.chain[i]);}
1197
+ function bandBarriers(rawRects){
1198
+ const selector='[data-turn-process-inline], [data-turn-process], [data-step-process], [data-chat-flow-kind="turn-process"], [data-chat-flow-kind="tool"], [data-chat-flow-kind="received-task"], [data-chat-steering-batch], .xMeOpW_body img, .xMeOpW_body video, .xMeOpW_body canvas';
1199
+ const result=[];
1200
+ const candidates=new Set(document.querySelectorAll(selector));
1201
+ for(const el of document.querySelectorAll('[data-chat-flow-kind]:not([data-chat-flow-kind="assistant-step"])'))if(!matchesRoot(el)&&!queryRoots(el).length)candidates.add(el);
1202
+ for(const body of document.querySelectorAll('.xMeOpW_body'))for(const el of body.children)if(!matchesRoot(el)&&!queryRoots(el).length)candidates.add(el);
1203
+ for(const el of candidates){
1204
+ if(!el.isConnected||el.closest('[data-text-interaction-surface], [hidden], [aria-hidden="true"]'))continue;
1205
+ const s=getComputedStyle(el),r=rect(el),image=el.matches('img,video,canvas');
1206
+ const content=!!el.textContent.trim()||!!el.querySelector('img,video,canvas');
1207
+ const visible=s.display!=='none'&&s.visibility==='visible'&&Number(s.opacity)>0&&r.right>r.left&&r.bottom>r.top;
1208
+ if(rfBarrierPolicy({known:content,image,visible,contents:s.display==='contents',overlay:/^(absolute|fixed)$/.test(s.position),overlapsText:rawRects.some(raw=>rfIntersect(raw,r))}))result.push(r);
1209
+ }
1210
+ return result;
1211
+ }
1212
+ // Last block that had focus, kept briefly so a tool-call row between two paragraphs does not
1213
+ // blank the effect. Coordinates are recomputed each frame, so scrolling is safe.
1214
+ let focusHold={block:null,at:0,scrollY:0};
1215
+ function draw(){
1216
+ const shapes=[],modal=modalOpen();layer.classList.toggle('pointer-layer',rfPointerLayer(state.enabled&&!modal,state.mode));
1217
+ // The text fade belongs to block focus alone; leaving the mode must remove it immediately.
1218
+ if(state.mode!=='blocks'&&dimHighlight)clearDim();
1219
+ if(!state.enabled||modal){if(modal)clearPointer();clearDim();patchShapes(shapes);return;}
1220
+ if(state.mode==='gradient'){patchShapes(shapes);return;}
1221
+ const dark=document.body.hasAttribute('data-ds-dark-theme');
1222
+ if(rfPointerMode(state.mode)){
1223
+ if(!pointerValid()){clearPointer();patchShapes(shapes);return;}
1224
+ if(!hasConversation(pointerScope)){resetGutter();patchShapes(shapes);return;}
1225
+ // Pointer parked in the empty gutter beside the text column: step out of the way so the page
1226
+ // is fully visible. The anchor is kept, so returning to the text restores instantly.
1227
+ if(state.gutterHide&&gutterState()){patchShapes(shapes);return;}
1228
+ const region=rfLineRegion(rect(pointerScope),viewport(pointerScope)),cuts=lineOccluders(pointerScope);
1229
+ if(region){
1230
+ // The veil dims everything outside the readable rows.
1231
+ const veil=rfVeilColor(state);
1232
+ // The composer is a control surface, not body text: keep it readable as one lit region
1233
+ // instead of punching a reading band through it. A band line across the input looks like
1234
+ // a stray highlight and hides the caret.
1235
+ const composer=composerRect(pointerScope);
1236
+ // Over the composer the pointer is on a control, not inside prose: light the whole pane
1237
+ // and skip the reading band entirely, so no stray bar floats across the input box.
1238
+ const overComposer=!!composer&&lastY>=composer.top;
1239
+ if(state.mode==='lines'){
1240
+ // Line focus: the rows under the pointer stay fully transparent at normal brightness and
1241
+ // only the surrounding area is dimmed, so the veil is the only thing colour affects.
1242
+ if(overComposer){
1243
+ shapes.push({rect:region,color:veil});
1244
+ }else{
1245
+ const hole=rfLineHole(lastY,state.lineCount,lineHeight(pointerScope),region);
1246
+ const mask=rfPaneMask(region,[{rect:hole,clip:region,radii:[[0,0],[0,0],[0,0],[0,0]]},...cuts]);
1247
+ shapes.push({rect:region,color:veil,extra:`mask-image:url("${mask}");mask-repeat:no-repeat;mask-size:100% 100%`});
1248
+ }
1249
+ }else{
1250
+ // Reading ruler: a soft tinted band spanning the reading width with a solid line along its
1251
+ // top and bottom edge. The lines are what makes the row boundaries readable; the fill is
1252
+ // deliberately faint. Both take the user's colour.
1253
+ const left=pointerScope.querySelector(':scope > [data-width-handle="left"]'),right=pointerScope.querySelector(':scope > [data-width-handle="right"]');
1254
+ const l=left?.getClientRects().length?rect(left):null,r=right?.getClientRects().length?rect(right):null;
1255
+ const width=l&&r&&l.right>l.left&&r.right>r.left&&l.right<r.left?{left:l.right,right:r.left}:{left:region.left,right:region.right};
1256
+ // Height follows whole text lines plus a little breathing room.
1257
+ const lh=lineHeight(pointerScope),inner=state.rulerLines*lh,pad=Math.max(3,Math.round(lh*.22));
1258
+ const h=inner+pad*2;
1259
+ const band=rfIntersect({left:width.left,right:width.right,top:lastY-h/2,bottom:lastY+h/2},region);
1260
+ if(band){
1261
+ const mask=rfPaneMask(band,cuts),extra=`mask-image:url("${mask}");mask-repeat:no-repeat;mask-size:100% 100%`;
1262
+ // The user's opacity drives both parts: solid edges and a correspondingly faint fill.
1263
+ const strength=rfColorValue(state,'ruler','lineOpacity',.9);
1264
+ const fill=rfRulerColor(state,Math.min(1,strength*.22));
1265
+ if(fill)shapes.push({rect:band,color:fill,extra});
1266
+ const edgeColor=rfRulerColor(state,Math.max(.25,strength));
1267
+ if(edgeColor)for(const edge of rfRulerEdges(band)){const edgeMask=rfPaneMask(edge,cuts);shapes.push({rect:edge,color:edgeColor,extra:`mask-image:url("${edgeMask}");mask-repeat:no-repeat;mask-size:100% 100%`});}
1268
+ }
1269
+ }
1270
+ }
1271
+ patchShapes(shapes);return;
1272
+ }
1273
+ const cuts=occluders();
1274
+ function add(r,clip,color,extra=''){let visible=rfIntersect(r,clip);if(!visible)return;let parts=[visible];for(const cut of cuts)parts=parts.flatMap(part=>rfSubtract(part,cut));for(const part of parts)shapes.push({rect:part,color,extra});}
1275
+ if(state.mode==='bands'){
1276
+ const bands=[], lanes=[], paragraph=state.segmentStyle==='paragraph', codeRects=[];
1277
+ // Colours cycle over the whole answer, never per markdown root: numbering that restarts
1278
+ // inside each root made a tool-split answer repeat the same hue for long runs.
1279
+ const palette=rfBandColors(state,dark);
1280
+ const bandOpacity=rfColorValue(state,'bands','opacity',.42);
1281
+ // A counter per lane keeps vertical continuity for side-by-side panes.
1282
+ const cycle=new Map();
1283
+ for(const root of roots){
1284
+ if(!root.isConnected)continue;
1285
+ const clip=viewport(root), list=bandsBlocks(root), width=bandsWidth(root), identity=laneOf(root);
1286
+ let lane=lanes.find(l=>sameLane(l.identity,identity)&&Math.abs(l.left-width.left)<.5&&Math.abs(l.right-width.right)<.5);
1287
+ if(!lane){lane={identity,left:width.left,right:width.right};lanes.push(lane);}
1288
+ codeRects.push(...codeBlockRects(root));
1289
+ list.forEach(el=>{const i=list.indexOf(el),raw=blockRect(el,list,i,false),r={...raw,left:width.left,right:width.right,top:raw.top-(paragraph?6:0),bottom:raw.bottom+(paragraph?6:0)};const n=cycle.get(lane)||0;cycle.set(lane,n+1);const hue=palette[n%palette.length];bands.push({rect:r,raw,clip,key:lane,clipKey:lane,hue,color:`rgba(${hue},${bandOpacity})`});});
1290
+ }
1291
+ // Inside <li> the blocks above still see list markers; code inside a list item is barred too.
1292
+ const barriers=[...cuts,...bandBarriers(bands.map(b=>b.raw)),...codeRects];
1293
+ bands.sort((a,b)=>a.raw.top-b.raw.top||a.raw.left-b.raw.left);
1294
+ for(const lane of lanes){
1295
+ const row=bands.filter(b=>b.key===lane);let partition={};
1296
+ if(row.length)row[0].key=partition;
1297
+ for(let i=1;i<row.length;i++){
1298
+ const a=row[i-1],b=row[i],gap=b.raw.top-a.raw.bottom;
1299
+ const corridor={left:Math.max(a.rect.left,b.rect.left),right:Math.min(a.rect.right,b.rect.right),top:Math.min(a.raw.bottom,b.raw.top),bottom:Math.max(a.raw.bottom,b.raw.top)};
1300
+ const blocked=barriers.some(c=>rfIntersect(c,{...corridor,top:corridor.top-.01,bottom:corridor.bottom+.01}));
1301
+ if(blocked||gap>24){if(a.rect.bottom>b.rect.top){const mid=(a.raw.bottom+b.raw.top)/2;a.rect.bottom=Math.min(a.rect.bottom,mid);b.rect.top=Math.max(b.rect.top,mid);}partition={};b.key=partition;continue;}
1302
+ b.key=partition;
1303
+ // Merge only neighbours that share a hue; two different hues must keep their seam.
1304
+ if(a.hue===b.hue){
1305
+ if(b.rect.top-a.rect.bottom<=(paragraph?1:0)){const mid=(a.rect.bottom+b.rect.top)/2;a.rect.bottom=mid;b.rect.top=mid;}
1306
+ }else if(paragraph){
1307
+ // Preserve as much whitespace as available, up to 6px; overlap gets a seam.
1308
+ const space=Math.min(6,Math.max(0,gap)),mid=(a.raw.bottom+b.raw.top)/2;
1309
+ a.rect.bottom=mid-space/2;b.rect.top=mid+space/2;
1310
+ }else if(a.rect.bottom>b.rect.top){const mid=(a.raw.bottom+b.raw.top)/2;a.rect.bottom=mid;b.rect.top=mid;}
1311
+ }
1312
+ }
1313
+ for(const group of rfBandGroups(bands)){
1314
+ const mask=rfBandMask(group.rects);
1315
+ // Draw union once so overlapping same-colour slices never double alpha.
1316
+ const visible=rfIntersect(mask.box,group.clip);if(!visible)continue;let parts=[visible];for(const cut of barriers)parts=parts.flatMap(part=>rfSubtract(part,cut));
1317
+ for(const part of parts){const extra=`mask-image:url("${mask.url}");mask-repeat:no-repeat;mask-size:${mask.width}px ${mask.height}px;mask-position:${mask.box.left-part.left}px ${mask.box.top-part.top}px`;shapes.push({rect:part,color:group.color,extra});}
1318
+ }
1319
+ patchShapes(shapes);return;
1320
+ }
1321
+ // Paragraph focus: the block under the pointer stays as it is and everything else recedes.
1322
+ // Two ways to make it recede - fade the other glyphs, or dim the page behind a veil.
1323
+ if(state.mode==='blocks'){
1324
+ // Crossing a tool-call row briefly leaves the prose. Reuse the last focused block for a beat
1325
+ // instead of snapping back to full contrast; a scroll invalidates it because the geometry
1326
+ // behind it has moved.
1327
+ let block=hovering&&activeBlock?.isConnected?activeBlock:null;
1328
+ const held=!block&&focusHold.block&&focusHold.block.isConnected&&performance.now()-focusHold.at<160&&focusHold.scrollY===scrollY;
1329
+ if(held)block=focusHold.block;
1330
+ if(!block){focusHold.block=null;clearDim();patchShapes(shapes);return;}
1331
+ focusHold={block,at:performance.now(),scrollY};
1332
+ if(state.blockStyle!=='veil'&&paintDim(block,rfDimColor(state))){patchShapes(shapes);return;}
1333
+ // Veil presentation, or a browser without CSS Custom Highlight.
1334
+ clearDim();
1335
+ const group=activeBody?rootGroup(activeBody):[];
1336
+ const regions=group.map((root,i)=>groupRegion(root,group,i)).filter(Boolean);
1337
+ const list=activeBody?blocks(activeBody):[],index=list.indexOf(block);
1338
+ const hole=index<0?null:blockRect(block,list,index,true);
1339
+ if(hole){
1340
+ const veil=rfVeilColor(state),tint=rfTintColor(state);
1341
+ for(const region of regions){
1342
+ for(const piece of rfSubtract(region,hole))add(piece,region,veil);
1343
+ if(tint)add(hole,region,tint);
1344
+ }
1345
+ }
1346
+ patchShapes(shapes);return;
1347
+ }
1348
+ patchShapes(shapes);
1349
+ }
1350
+ function handleScope(target){
1351
+ const handle=target?.closest?.('[data-width-handle]'),scope=handle?.closest('[data-conversation-content][data-conversation-session]');
1352
+ return handle&&scope&&handle.parentElement===scope?scope:null;
1353
+ }
1354
+ function focusHandle(scope,y){
1355
+ if(!scope)return false;
1356
+ if(pointerValid()&&pointerScope===scope)return true;
1357
+ const scroll=scope.querySelector('[data-conversation-scroll]');
1358
+ if(!scroll||scroll.closest('[data-conversation-content][data-conversation-session]')!==scope)return false;
1359
+ anchorPointer(scope,scroll);lastY=y;lastX=pointerX;return true;
1360
+ }
1361
+ function protectedScope(target){
1362
+ const control=target?.closest?.('[data-composer-card], [data-composer-seat] section[data-testid="todo-panel"], [data-composer-overlay] > *, [data-composer-dock] button, [data-composer-dock] [role="button"], [data-composer-dock] a, [data-composer-dock] span');
1363
+ return control?.closest('[data-conversation-content][data-conversation-session]')||null;
1364
+ }
1365
+ function panePolicy(target,scope,scroll){
1366
+ const targetScope=target?.closest?.('[data-conversation-content][data-conversation-session]');
1367
+ const view=scroll&&rfIntersect(rect(scroll),viewport(scroll));
1368
+ const excluded=!!target?.closest?.('[role="menu"], [role="listbox"], [role="dialog"], dialog[open], [aria-modal="true"]');
1369
+ return rfPanePolicy({sameScope:!!scope&&targetScope===scope,inScroll:!!view&&target?.closest?.('[data-conversation-scroll]')===scroll&&rfLineCandidate(view,view,pointerX,pointerY),structural:!!target?.closest?.('[data-composer-seat], [data-composer-dock], [data-conversation-region="composer"], [data-slot="conversation.input.dock"]'),protectedControl:!!protectedScope(target),excluded});
1370
+ }
1371
+ function hit(){
1372
+ const target=document.elementFromPoint(pointerX,pointerY);
1373
+ if(rfPointerMode(state.mode)){
1374
+ if(pointerScope&&!pointerValid())clearPointer();
1375
+ if(widthDrag){if(pointerValid()&&widthDrag.scope===pointerScope&&widthDrag.scroll===pointerScroll)return;clearPointer();return;}
1376
+ const scope=target?.closest?.('[data-conversation-content][data-conversation-session]');
1377
+ const handle=handleScope(target);
1378
+ if(handle){if(pointerScope&&pointerScope!==handle)clearPointer();focusHandle(handle,pointerY);return;}
1379
+ const scroll=target?.closest?.('[data-conversation-scroll]');
1380
+ const policy=panePolicy(target,scope,scroll);
1381
+ if(policy==='follow'){anchorPointer(scope,scroll);lastX=pointerX;lastY=pointerY;return;}
1382
+ if(policy==='freeze'&&pointerValid()&&pointerScope===scope)return;
1383
+ clearPointer();return;
1384
+ }
1385
+ const targetCut=target?.closest?.(RF_OCCLUDERS);
1386
+ if((targetCut&&isHostOccluder(targetCut)) || (target?.closest?.('.xMeOpW_body') && !closestRoot(target) && target.closest('.xMeOpW_body')!==target)){hovering=false;return;}
1387
+ // Read every candidate rectangle first, decide afterwards: interleaving rect reads with the
1388
+ // elementFromPoint above is what makes a scroll-costly forced layout.
1389
+ let best=null,dist=Infinity;
1390
+ for(const root of roots){
1391
+ if(!root.isConnected)continue;
1392
+ const rr=rect(root),r=rfIntersect(rr,viewport(root));
1393
+ if(!r||lastX<r.left-12||lastX>r.right+12)continue;
1394
+ let top=r.top-12,bottom=r.bottom+12;
1395
+ if(root.parentElement?.matches('.xMeOpW_body')){
1396
+ const prev=root.previousElementSibling,next=root.nextElementSibling;
1397
+ if(matchesRoot(prev))top=Math.min(top,(rect(prev).bottom+rr.top)/2);
1398
+ if(matchesRoot(next))bottom=Math.max(bottom,(rr.bottom+rect(next).top)/2);
1399
+ }
1400
+ if(lastY<top||lastY>bottom)continue;
1401
+ for(const el of blocks(root)){const b=rect(el),d=lastY<b.top?b.top-lastY:lastY>b.bottom?lastY-b.bottom:0;if(d<dist){dist=d;best={root,el};}}
1402
+ }
1403
+ if(best){activeBody=best.root;activeBlock=best.el;hovering=true;}else hovering=false;
1404
+ }
1405
+ // The paragraph hit-test feeds the pointer modes and block focus only; running it for bands and
1406
+ // gradient (which never read the result) costs a layout pass on every scroll frame.
1407
+ const modeNeedsHit=()=>rfPointerMode(state.mode)||state.mode==='blocks';
1408
+ function queue(rehit=false){if(rehit&&!panelHover&&hasPointer&&modeNeedsHit())needsHit=true;if(state.enabled&&!frame&&!disposed)frame=requestAnimationFrame(()=>{frame=0;if(needsHit){needsHit=false;hit();}draw();});}
1409
+ function onMove(e){
1410
+ if(!state.enabled)return;
1411
+ panelHover=e.composedPath().includes(host);
1412
+ if(panelHover){needsHit=false;return;}
1413
+ pointerX=e.clientX;pointerY=e.clientY;hasPointer=true;
1414
+ if(!modeNeedsHit()){lastX=e.clientX;lastY=e.clientY;return;}
1415
+ const target=document.elementFromPoint(pointerX,pointerY);
1416
+ const scope=rfPointerMode(state.mode)?handleScope(target):null;
1417
+ const freeze=rfPointerMode(state.mode)&&(widthDrag||(pointerValid()&&((scope&&pointerScope===scope)||panePolicy(target,pointerScope,pointerScroll)==='freeze')));
1418
+ if(!freeze){lastX=e.clientX;lastY=e.clientY;}
1419
+ needsHit=true;queue();
1420
+ }
1421
+ function onWidthDown(e){
1422
+ if(!state.enabled||!rfPointerMode(state.mode)||e.button!==0||modalOpen())return;
1423
+ pointerX=e.clientX;pointerY=e.clientY;const scope=handleScope(e.target);if(!scope||!focusHandle(scope,e.clientY))return;
1424
+ widthDrag=rfHandlePolicy(widthDrag,{type:'start',scope,scroll:pointerScroll,id:e.pointerId});needsHit=false;queue();
1425
+ }
1426
+ function onWidthEnd(e){
1427
+ if(!widthDrag||e.pointerId!==widthDrag.id)return;
1428
+ if(e.type==='pointercancel'){clearPointer();needsHit=false;patchShapes([]);return;}
1429
+ widthDrag=rfHandlePolicy(widthDrag,{type:'end',id:e.pointerId});
1430
+ if(e.type!=='lostpointercapture'){pointerX=e.clientX;pointerY=e.clientY;}
1431
+ const target=document.elementFromPoint(pointerX,pointerY),scope=handleScope(target);
1432
+ if((scope&&scope===pointerScope&&pointerValid())||(pointerValid()&&panePolicy(target,pointerScope,pointerScroll)==='freeze')){needsHit=false;queue();}else {lastX=pointerX;lastY=pointerY;hasPointer=true;queue(true);}
1433
+ }
1434
+ function onWidthBlur(){if(rfPointerMode(state.mode)){clearPointer();needsHit=false;patchShapes([]);}}
1435
+ function onVisibility(){if(document.hidden)onWidthBlur();}
1436
+ function widthListeners(add){const method=add?'addEventListener':'removeEventListener';document[method]('pointerdown',onWidthDown,true);for(const name of ['pointerup','pointercancel','lostpointercapture'])document[method](name,onWidthEnd,true);window[method]('blur',onWidthBlur);document[method]('visibilitychange',onVisibility);}
1437
+ function setEnabled(enabled){const changed=state.enabled!==enabled;state.enabled=enabled;if(enabled){widthListeners(true);startObservers();adoptHostTypography();gradient.scan();queue();}else{gradient.clear();clearDim();widthListeners(false);clearPointer();stopObservers();if(frame)cancelAnimationFrame(frame);frame=0;layer.classList.remove('pointer-layer');patchShapes([]);hovering=false;needsHit=false;hasPointer=false;panelHover=false;}if(changed)save();sync();}
1438
+ function onKey(e){const path=e.composedPath(),inPanel=path.includes(host),editing=path.some(n=>n?.matches?.('input,textarea,select,[contenteditable]:not([contenteditable="false"])')||n?.isContentEditable);if(e.defaultPrevented||modalOpen())return;if(e.key==='Escape'&&inPanel&&panel){e.preventDefault();e.stopPropagation();closeWindow();return;}if(e.key==='Escape'&&state.enabled&&!editing&&hovering){setEnabled(false);return;}}
1439
+ // Scrolling must repaint from the pointer position the user already has, synchronously in the
1440
+ // scroll handler: re-running elementFromPoint mid-scroll samples a stale hit target and makes
1441
+ // the overlay follow the text one frame late (text slides out, then the mask snaps back).
1442
+ function onScroll(){
1443
+ if(!state.enabled)return;
1444
+ if(rfPointerMode(state.mode)&&pointerValid()){
1445
+ // Pointer modes anchor to the pane and a fixed y, so the region is already current.
1446
+ if(!frame){frame=requestAnimationFrame(()=>{frame=0;draw();});}
1447
+ }else{
1448
+ queue(true);
1449
+ }
1450
+ queuePanel();
1451
+ }
1452
+ const onLayout=()=>{queue(true);queuePanel();};const onResize=()=>{if(state.mode==='gradient')gradient.invalidate();onLayout();};
1453
+ // Adopt a saved font on load, but never write one that was never customised.
1454
+ if(Object.keys(state.font).length)rfApplyTypography(state.font);document.addEventListener('pointermove',onMove,{passive:true});document.addEventListener('keydown',onKey);window.addEventListener('scroll',onScroll,true);window.addEventListener('resize',onResize);
1455
+ // The on/off choice is a preference like any other: restoring it means the user does not have to
1456
+ // re-enable the effect after every restart.
1457
+ if(state.enabled)setEnabled(true);else sync();
1458
+ return {mountControls,openWindow,dispose(){disposed=true;gradient.dispose();clearDim();widthListeners(false);clearPointer();stopObservers();closeWindow();rfClearTypography();subscribers.clear();if(frame)cancelAnimationFrame(frame);document.removeEventListener('pointermove',onMove);document.removeEventListener('keydown',onKey);window.removeEventListener('scroll',onScroll,true);window.removeEventListener('resize',onResize);host.remove();}};
1459
+ }
1460
+
1461
+ return {inject:['slots'],apply(ctx){ctx.effect(()=>{const controller=startReadingFocus();function SettingsSection({close}){const ref=React.useRef(null);React.useEffect(()=>controller.mountControls(ref.current,false,()=>{close();controller.openWindow();}),[close]);return React.createElement('div',{ref,style:{padding:'16px',color:'var(--dsw-alias-label-primary)',font:'14px/1.6 system-ui'}});}const off=ctx.slots.inject('settings.section',()=>ctx.slots.register({name:'settings.section',id:'reading-focus',order:65,label:()=> '阅读辅助'},SettingsSection));return ()=>{if(typeof off==='function')off();controller.dispose();};});}};
1462
+ }});