dsh-clash-subscription 0.2.2 → 0.4.2-probe.5

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/client.js DELETED
@@ -1,786 +0,0 @@
1
- window.__ModuleLoader__.load({id:"dsh-clash-subscription",factory:(require)=>{
2
- const React = require('react')
3
- const h = React.createElement
4
- const { Fragment, useEffect, useMemo, useState } = React
5
-
6
- /** Locale dictionaries, registered as one namespace so every label is translated. */
7
- const en = {
8
- summary: 'Import a Clash subscription, pick the exit node, and set how often nodes are re-tested.',
9
- openPanel: 'Clash proxy',
10
- title: 'Subscription',
11
- header: 'Clash subscription proxy',
12
- close: 'Close',
13
- subscriptionLabel: 'Import link',
14
- subscriptionHint:
15
- 'Paste your subscription URL, or a clash://install-config?url=… import link. There is no default: the plugin never reads another client’s configuration.',
16
- subscriptionPlaceholder: 'https://…/api/v1/client/subscribe?token=…',
17
- probe: 'Check link',
18
- probing: 'Checking…',
19
- probeOk: 'Reachable: {format}, {count} nodes, {size} KB.',
20
- probeFailed: 'Check failed: {reason}',
21
- probeNeedsSave: 'Save first — this page writes the link, the running core reads the saved one.',
22
- routing: 'Exit node',
23
- routingHint: 'The node foreign traffic leaves through. Domestic sites stay direct either way.',
24
- autoSelect: 'Automatic (lowest latency, working nodes only)',
25
- currentNode: 'Current: {node}',
26
- noNodes: 'No node table yet — start routing first.',
27
- select: 'Use',
28
- testing: 'Measuring…',
29
- testNow: 'Re-test now',
30
- delay: '{ms} ms',
31
- unreachable: 'no answer',
32
- untested: 'not measured',
33
- testAll: 'Measure every node',
34
- cycle: 'Automatic speed test',
35
- cycleHint:
36
- 'How often the plugin re-measures its nodes and picks a working exit. 0 turns the cycle off; the button above still works.',
37
- cycleOff: 'Off',
38
- cycleEvery: 'Every {minutes} min',
39
- count: 'Nodes per cycle',
40
- countHint: 'How many nodes one cycle measures. A long subscription costs time, so the rest stay unmeasured until you pick them.',
41
- behaviour: 'Behaviour',
42
- mode: 'Routing mode',
43
- modeRule: 'Rule (domestic direct)',
44
- modeGlobal: 'Global (everything through the node)',
45
- modeHint: 'Rule mode is what keeps Chinese sites unchanged. Global sends every request through the node.',
46
- autoStart: 'Start with the Harness',
47
- autoStartHint: 'Start the private core and install the outbound policy as soon as this plugin loads.',
48
- lists: 'Domain lists',
49
- directDomains: 'Always direct',
50
- directDomainsHint: 'Comma-separated domain suffixes that must never use the node, e.g. an intranet host.',
51
- proxyDomains: 'Always proxied',
52
- proxyDomainsHint: 'Comma-separated domain suffixes that must always use the node, even if they resolve to a Chinese address.',
53
- runtime: 'Runtime',
54
- corePath: 'Core binary',
55
- corePathHint: 'Path to a mihomo/clash executable. Empty looks for one in the usual install locations.',
56
- dns: 'DNS servers',
57
- dnsHint: 'Comma-separated resolvers the core uses for its own lookups.',
58
- start: 'Start',
59
- stop: 'Stop',
60
- refresh: 'Refresh subscription',
61
- save: 'Save',
62
- saving: 'Saving…',
63
- reset: 'Reset',
64
- saved: 'Saved.',
65
- rejected: 'The host rejected the change.',
66
- loading: 'Loading…',
67
- unavailable: 'Configuration is not editable here.',
68
- statusRunning: 'Core running at {endpoint}',
69
- statusStopped: 'Core stopped',
70
- statusRouting: 'Outbound policy installed',
71
- statusDirect: 'Outbound policy not installed (direct)',
72
- measuredAt: 'Last measurement: {time}',
73
- never: 'never',
74
- readOnly: 'This panel is read-only here; open it from Settings to edit.',
75
- }
76
-
77
- const zh = {
78
- summary: '导入 Clash 订阅、指定出口节点、设定自动测速周期。',
79
- openPanel: 'Clash 代理',
80
- title: '订阅',
81
- header: 'Clash 订阅代理',
82
- close: '关闭',
83
- subscriptionLabel: '导入链接',
84
- subscriptionHint:
85
- '粘贴你的订阅地址,或 clash://install-config?url=… 这种一键导入链接。没有默认值:插件不会读取其他客户端的配置。',
86
- subscriptionPlaceholder: 'https://…/api/v1/client/subscribe?token=…',
87
- probe: '检测链接',
88
- probing: '检测中…',
89
- probeOk: '可达:{format},{count} 个节点,{size} KB。',
90
- probeFailed: '检测失败:{reason}',
91
- probeNeedsSave: '先保存——这个面板写的是配置,跑着的内核读的是已保存的那份。',
92
- routing: '出口节点',
93
- routingHint: '外网流量从这个节点出去;国内站点无论选哪个都保持直连。',
94
- autoSelect: '自动(选延迟最低的可用节点)',
95
- currentNode: '当前:{node}',
96
- noNodes: '还没有节点表——先启动一次。',
97
- select: '用这个',
98
- testing: '测速中…',
99
- testNow: '立即重测',
100
- delay: '{ms} ms',
101
- unreachable: '无响应',
102
- untested: '未测速',
103
- testAll: '测全部节点',
104
- cycle: '自动测速',
105
- cycleHint: '插件多久重新测一次节点并挑一个可用的出口。填 0 关闭周期,上面的按钮仍然可用。',
106
- cycleOff: '关闭',
107
- cycleEvery: '每 {minutes} 分钟',
108
- count: '每轮测几个节点',
109
- countHint: '一轮最多测多少个节点。节点多时全测很慢,其余的要等你手动选或重测。',
110
- behaviour: '行为',
111
- mode: '分流模式',
112
- modeRule: '规则(国内直连)',
113
- modeGlobal: '全局(全部走节点)',
114
- modeHint: '规则模式才是让国内站点完全不受影响的那个。全局会把每个请求都送进节点。',
115
- autoStart: '随 Harness 启动',
116
- autoStartHint: '插件一加载就启动私有内核并装上出网策略。',
117
- lists: '域名名单',
118
- directDomains: '始终直连',
119
- directDomainsHint: '逗号分隔的域名后缀,永远不走节点,例如内网主机。',
120
- proxyDomains: '始终走代理',
121
- proxyDomainsHint: '逗号分隔的域名后缀,即使解析到中国 IP 也走节点。',
122
- runtime: '运行时',
123
- corePath: '内核程序',
124
- corePathHint: 'mihomo/clash 可执行文件路径。留空则在常见安装位置查找。',
125
- dns: 'DNS 服务器',
126
- dnsHint: '逗号分隔,内核自己解析时使用。',
127
- start: '启动',
128
- stop: '停止',
129
- refresh: '刷新订阅',
130
- save: '保存',
131
- saving: '保存中…',
132
- reset: '重置',
133
- saved: '已保存。',
134
- rejected: '宿主拒绝了这次修改。',
135
- loading: '加载中…',
136
- unavailable: '这里无法编辑配置。',
137
- statusRunning: '内核运行中 {endpoint}',
138
- statusStopped: '内核未运行',
139
- statusRouting: '出网策略已安装',
140
- statusDirect: '出网策略未安装(直连)',
141
- measuredAt: '上次测速:{time}',
142
- never: '尚未测过',
143
- readOnly: '这里是只读预览;要修改请从设置里打开。',
144
- }
145
-
146
- /**
147
- * Format one translated string, replacing `{name}` placeholders.
148
- *
149
- * @param template - the dictionary value.
150
- * @param values - placeholder values by name.
151
- * @returns the composed string.
152
- */
153
- function fill(template, values) {
154
- if (template === undefined) return ''
155
- return String(template).replace(/\{(\w+)\}/g, (match, key) =>
156
- values !== undefined && values[key] !== undefined ? String(values[key]) : match,
157
- )
158
- }
159
-
160
- /** Read the row form's saved values as a flat object. */
161
- const readValues = (value) => (value !== null && typeof value === 'object' ? { ...value } : {})
162
-
163
- /** Page styles, registered once per mount and removed with it. */
164
- const CSS = `
165
- .clxp { display: flex; flex-direction: column; gap: 14px; font-size: 13px; line-height: 1.5; color: var(--dsh-text-primary, #1f2328); }
166
- .clxp-status { display: flex; flex-wrap: wrap; gap: 8px 14px; align-items: center; padding: 10px 12px; border: 1px solid var(--dsh-border-default, #d8dee4); border-radius: 8px; background: var(--dsh-surface-subtle, #f6f8fa); }
167
- .clxp-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--dsh-text-tertiary, #8b949e); flex: 0 0 auto; }
168
- .clxp-dot.on { background: #2da44e; }
169
- .clxp-dot.warn { background: #bf8700; }
170
- .clxp-status-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
171
- .clxp-status-actions { margin-left: auto; display: flex; gap: 6px; flex-wrap: wrap; }
172
- .clxp-card { border: 1px solid var(--dsh-border-default, #d8dee4); border-radius: 8px; padding: 13px; display: flex; flex-direction: column; gap: 11px; }
173
- .clxp-card > h4 { margin: 0; font-size: 13px; font-weight: 600; }
174
- .clxp-field { display: flex; flex-direction: column; gap: 4px; }
175
- .clxp-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 11px; }
176
- .clxp-label { font-weight: 500; }
177
- .clxp-hint { color: var(--dsh-text-secondary, #57606a); font-size: 12px; margin: 0; }
178
- .clxp-error { color: #cf222e; font-size: 12px; margin: 0; }
179
- .clxp-ok { color: #1a7f37; font-size: 12px; margin: 0; }
180
- .clxp input[type="text"], .clxp input[type="number"], .clxp select { font: inherit; padding: 5px 8px; border: 1px solid var(--dsh-border-default, #d8dee4); border-radius: 6px; background: var(--dsh-surface-default, #fff); color: inherit; min-width: 0; }
181
- .clxp input:focus, .clxp select:focus { outline: 2px solid var(--dsh-accent, #0969da); outline-offset: -1px; }
182
- .clxp-inline { display: flex; gap: 6px; align-items: center; }
183
- .clxp-inline > input { flex: 1 1 auto; }
184
- .clxp button { font: inherit; padding: 4px 10px; border-radius: 6px; border: 1px solid var(--dsh-border-default, #d8dee4); background: var(--dsh-surface-default, #fff); color: inherit; cursor: pointer; }
185
- .clxp button:hover:not(:disabled) { background: var(--dsh-surface-subtle, #f6f8fa); }
186
- .clxp button:disabled { opacity: 0.55; cursor: default; }
187
- .clxp button.clxp-primary { background: var(--dsh-accent, #0969da); border-color: var(--dsh-accent, #0969da); color: #fff; font-weight: 500; }
188
- .clxp-nodes { display: flex; flex-direction: column; max-height: 300px; overflow: auto; border: 1px solid var(--dsh-border-default, #d8dee4); border-radius: 6px; }
189
- .clxp-node { display: grid; grid-template-columns: 1fr auto auto; gap: 10px; align-items: center; padding: 5px 8px; border: 0; border-radius: 0; text-align: left; background: none; width: 100%; }
190
- .clxp-node + .clxp-node { border-top: 1px solid var(--dsh-border-muted, #eaeef2); }
191
- .clxp-node-act { padding: 1px 6px; font-size: 12px; line-height: 1.4; border-radius: 4px; }
192
- .clxp-node.current { background: var(--dsh-surface-subtle, #f6f8fa); font-weight: 600; }
193
- .clxp-node-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
194
- .clxp-delay { font-variant-numeric: tabular-nums; color: var(--dsh-text-secondary, #57606a); font-size: 12px; }
195
- .clxp-delay.good { color: #1a7f37; }
196
- .clxp-delay.bad { color: #cf222e; }
197
- .clxp-actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
198
- .clxp-savebar { position: sticky; bottom: 0; z-index: 2; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; padding: 10px 0 4px; margin-top: 4px; background: linear-gradient(to top, var(--dsh-surface-default, #fff) 72%, transparent); }
199
- .clxp-dirty { font-size: 12px; color: #bf8700; }
200
- .clxp-note { color: var(--dsh-text-secondary, #57606a); font-size: 12px; margin: 0; }
201
- .clxp-disclosure { display: flex; align-items: center; gap: 6px; background: none; border: 0; padding: 0; font-weight: 600; cursor: pointer; color: inherit; }
202
- .clxp-checkbox { display: flex; align-items: center; gap: 8px; }
203
- `
204
-
205
- /** Section definitions for the form. */
206
- function sections(t) {
207
- return [
208
- {
209
- id: 'subscription',
210
- title: t('title'),
211
- fields: [
212
- { key: 'subscriptionUrl', kind: 'text', label: t('subscriptionLabel'), hint: t('subscriptionHint'), placeholder: t('subscriptionPlaceholder'), probe: true },
213
- ],
214
- },
215
- {
216
- id: 'behaviour',
217
- title: t('behaviour'),
218
- fields: [
219
- { key: 'mode', kind: 'select', label: t('mode'), hint: t('modeHint'), options: [{ value: 'rule', label: t('modeRule') }, { value: 'global', label: t('modeGlobal') }] },
220
- { key: 'autoStart', kind: 'switch', label: t('autoStart'), hint: t('autoStartHint') },
221
- { key: 'speedTestMinutes', kind: 'number', label: t('cycle'), hint: t('cycleHint'), min: 0, max: 1440, step: 5 },
222
- { key: 'speedTestCount', kind: 'number', label: t('count'), hint: t('countHint'), min: 1, max: 40, step: 1 },
223
- ],
224
- },
225
- {
226
- id: 'lists',
227
- title: t('lists'),
228
- collapsed: true,
229
- fields: [
230
- { key: 'directDomains', kind: 'text', label: t('directDomains'), hint: t('directDomainsHint'), placeholder: 'intranet.example, corp.example' },
231
- { key: 'proxyDomains', kind: 'text', label: t('proxyDomains'), hint: t('proxyDomainsHint'), placeholder: 'openai.com, githubusercontent.com' },
232
- { key: 'dnsServers', kind: 'text', label: t('dns'), hint: t('dnsHint'), placeholder: '223.5.5.5, 119.29.29.29' },
233
- { key: 'corePath', kind: 'text', label: t('corePath'), hint: t('corePathHint'), placeholder: 'C:\\path\\to\\mihomo.exe' },
234
- ],
235
- },
236
- ]
237
- }
238
-
239
- /**
240
- * The whole panel: live status, node table, and every configurable field.
241
- *
242
- * One component serves three mounts — the row configuration page, the sidebar
243
- * entry's sheet, and (when editable) the same sheet from the footer — so a value
244
- * typed in one place renders identically in the others.
245
- *
246
- * @param props - see {@link CONFIG_FIELDS}; `editable` decides whether fields render as controls.
247
- * @returns the panel.
248
- */
249
- function Panel(props) {
250
- const { t, draft, live, delays, busy, message, probe, saving, dirty, open, editable } = props
251
- const nodes = Array.isArray(live?.nodes) ? live.nodes : []
252
- const running = live?.running === true
253
- const routingOn = live?.routing === true
254
- const [expanded, setExpanded] = useState({})
255
-
256
- // Three distinct states, not two. A node the cycle has not reached yet is "未测速",
257
- // not "无响应": a 40-node subscription is measured `speedTestCount` at a time, so
258
- // painting the unmeasured remainder as dead is a lie the panel used to tell.
259
- const delayClass = (value) => (value === undefined ? 'clxp-delay' : value === null ? 'clxp-delay bad' : value < 400 ? 'clxp-delay good' : 'clxp-delay')
260
- const delayText = (value) =>
261
- value === undefined ? t('untested') : value === null ? t('unreachable') : fill(t('delay'), { ms: value })
262
-
263
- const field = (spec) => {
264
- const value = editable ? draft[spec.key] : live?.config?.[spec.key]
265
- if (!editable) {
266
- return h('div', { className: 'clxp-field', key: spec.key }, [
267
- h('span', { key: 'l', className: 'clxp-label' }, spec.label),
268
- h('code', { key: 'v' }, value === '' || value === undefined ? '—' : String(value)),
269
- ])
270
- }
271
- const control =
272
- spec.kind === 'switch'
273
- ? h('label', { className: 'clxp-checkbox' }, [
274
- h('input', { key: 'i', type: 'checkbox', checked: value !== false, disabled: saving, onChange: (event) => props.onEdit(spec.key, event.target.checked) }),
275
- h('span', { key: 't', className: 'clxp-hint' }, spec.hint ?? ''),
276
- ])
277
- : spec.kind === 'select'
278
- ? h('select', { value: value ?? spec.options[0].value, disabled: saving, onChange: (event) => props.onEdit(spec.key, event.target.value) },
279
- spec.options.map((option) => h('option', { key: option.value, value: option.value }, option.label)))
280
- : spec.kind === 'number'
281
- ? h('input', { type: 'number', value: value ?? 0, min: spec.min, max: spec.max, step: spec.step, disabled: saving, onChange: (event) => props.onEdit(spec.key, event.target.value === '' ? '' : Number(event.target.value)) })
282
- : h('input', { type: 'text', value: value ?? '', placeholder: spec.placeholder ?? '', disabled: saving, spellCheck: false, onChange: (event) => props.onEdit(spec.key, event.target.value) })
283
-
284
- return h('div', { className: 'clxp-field', key: spec.key }, [
285
- h('span', { key: 'l', className: 'clxp-label' }, spec.label),
286
- spec.probe
287
- ? h('div', { key: 'r', className: 'clxp-inline' }, [control, h('button', { key: 'p', type: 'button', disabled: saving || busy === 'probe', onClick: () => void props.onProbe() }, busy === 'probe' ? t('probing') : t('probe'))])
288
- : control,
289
- spec.hint !== undefined && spec.kind !== 'switch' ? h('p', { key: 'h', className: 'clxp-hint' }, spec.hint) : null,
290
- spec.key === 'subscriptionUrl' && probe !== undefined
291
- ? h('p', { key: 'pr', className: probe.ok ? 'clxp-ok' : 'clxp-error', role: 'status' },
292
- probe.ok ? fill(t('probeOk'), { format: probe.format, count: probe.nodeCount, size: Math.round((probe.bytes ?? 0) / 1024) }) : fill(t('probeFailed'), { reason: probe.error ?? 'unknown' }))
293
- : null,
294
- ].filter(Boolean))
295
- }
296
-
297
- const sectionsList = sections(t)
298
-
299
- return h('div', { className: 'clxp' }, [
300
- // Live state.
301
- h('div', { key: 'status', className: 'clxp-status' }, [
302
- h('span', { key: 'd', className: `clxp-dot${running ? (routingOn ? ' on' : ' warn') : ''}` }),
303
- h('div', { key: 't', className: 'clxp-status-text' }, [
304
- h('span', { key: 'c' }, running ? fill(t('statusRunning'), { endpoint: live?.endpoint ?? '' }) : t('statusStopped')),
305
- h('span', { key: 'p', className: 'clxp-note' }, routingOn ? t('statusRouting') : t('statusDirect')),
306
- live?.measuredAt !== undefined && live.measuredAt !== null
307
- ? h('span', { key: 'm', className: 'clxp-note' }, fill(t('measuredAt'), { time: new Date(live.measuredAt).toLocaleTimeString() }))
308
- : null,
309
- ].filter(Boolean)),
310
- h('div', { key: 'a', className: 'clxp-status-actions' }, [
311
- h('button', { key: 'tg', type: 'button', className: 'clxp-primary', disabled: busy !== '', onClick: () => void props.onAction(running ? 'stop' : 'start') }, running ? t('stop') : t('start')),
312
- h('button', { key: 'rf', type: 'button', disabled: busy !== '' || !running, onClick: () => void props.onAction('refresh') }, t('refresh')),
313
- ]),
314
- ]),
315
- live?.blocker !== undefined ? h('p', { key: 'bl', className: 'clxp-error' }, live.blocker) : null,
316
-
317
- // Exit node table.
318
- h('section', { key: 'nodes', className: 'clxp-card' }, [
319
- h('h4', { key: 'ti' }, t('routing')),
320
- h('p', { key: 'hi', className: 'clxp-hint' }, t('routingHint')),
321
- h('p', { key: 'cu', className: 'clxp-note' }, fill(t('currentNode'), { node: live?.node ?? t('autoSelect') })),
322
- nodes.length === 0
323
- ? h('p', { key: 'em', className: 'clxp-note' }, t('noNodes'))
324
- : h('div', { key: 'ls', className: 'clxp-nodes', role: 'listbox', 'aria-label': t('routing') },
325
- nodes.map((name) => h('div', {
326
- key: name,
327
- className: `clxp-node${name === live?.node ? ' current' : ''}`,
328
- role: 'option',
329
- 'aria-selected': name === live?.node,
330
- }, [
331
- h('span', { key: 'n', className: 'clxp-node-name', title: name }, name),
332
- h('span', { key: 'd', className: delayClass(delays[name]) }, delayText(delays[name])),
333
- h('button', {
334
- key: 't',
335
- type: 'button',
336
- className: 'clxp-node-act',
337
- title: `${t('testNow')}: ${name}`,
338
- 'aria-label': `${t('testNow')}: ${name}`,
339
- disabled: busy !== '' || !running,
340
- onClick: () => void props.onAction('test', { node: name }),
341
- }, '⟳'),
342
- h('button', {
343
- key: 'p',
344
- type: 'button',
345
- className: 'clxp-node-act',
346
- disabled: busy !== '' || !running || name === live?.node,
347
- onClick: () => void props.onAction('select', { node: name }),
348
- }, name === live?.node ? '✓' : t('select')),
349
- ]))),
350
- h('div', { key: 'ac', className: 'clxp-actions' }, [
351
- h('button', { key: 'te', type: 'button', disabled: busy !== '' || !running, onClick: () => void props.onAction('test') }, busy === 'test' ? t('testing') : t('testNow')),
352
- h('button', { key: 'ta', type: 'button', disabled: busy !== '' || !running, onClick: () => void props.onAction('test', { all: true }) }, busy === 'test' ? t('testing') : t('testAll')),
353
- ]),
354
- ]),
355
-
356
- // Configurable fields.
357
- ...sectionsList.map((group) => {
358
- const isOpen = expanded[group.id] ?? group.collapsed !== true
359
- const head = h('h4', null, group.title)
360
- return h('section', { key: group.id, className: 'clxp-card' }, [
361
- group.collapsed === true
362
- ? h('button', { key: 'hd', type: 'button', className: 'clxp-disclosure', 'aria-expanded': isOpen, onClick: () => setExpanded({ ...expanded, [group.id]: !isOpen }) },
363
- [h('span', { key: 'c', 'aria-hidden': true }, isOpen ? '▾' : '▸'), head])
364
- : head,
365
- isOpen ? h('div', { key: 'bd', className: 'clxp-grid' }, group.fields.map(field)) : null,
366
- ])
367
- }),
368
-
369
- // A missing subscription is the one blocker a user can fix here, so it is named
370
- // explicitly next to the save control instead of only in the status blob.
371
- editable && String(props.draft?.subscriptionUrl ?? '').trim() === '' && props.live?.source !== 'configured'
372
- ? h('p', { key: 'need', className: 'clxp-error', role: 'status' }, '还没有订阅链接:粘贴到上方「导入链接」并保存,内核才会启动。')
373
- : null,
374
-
375
- editable
376
- ? h('div', { key: 'sub', className: 'clxp-savebar' }, [
377
- h('button', { key: 's', type: 'submit', className: 'clxp-primary', disabled: saving }, saving ? t('saving') : t('save')),
378
- h('button', { key: 'r', type: 'button', disabled: saving || !dirty, onClick: () => props.onReset() }, t('reset')),
379
- dirty
380
- ? h('span', { key: 'd', className: 'clxp-dirty' }, '有未保存的修改')
381
- : h('span', { key: 'c', className: 'clxp-note' }, '已保存'),
382
- message !== '' ? h('span', { key: 'm', className: 'clxp-note', role: 'status' }, message) : null,
383
- ].filter(Boolean))
384
- : null,
385
- live?.blocker === undefined && !editable ? null : null,
386
- ].filter(Boolean))
387
- }
388
-
389
- /**
390
- * The row configuration page: owns the draft, saving, and the live status poll.
391
- *
392
- * @param props - the host's slot props.
393
- * @returns the page.
394
- */
395
- function RowConfigPage(props) {
396
- const { form, t } = props
397
- const [draft, setDraft] = useState(() => readValues(form?.state.value))
398
- const [baseline, setBaseline] = useState(() => readValues(form?.state.value))
399
- const [revision, setRevision] = useState(form?.state.revision)
400
- const [dirty, setDirty] = useState(false)
401
- const [saving, setSaving] = useState(false)
402
- const [message, setMessage] = useState('')
403
- const [live, setLive] = useState()
404
- const [liveError, setLiveError] = useState()
405
- const [busy, setBusy] = useState('')
406
- const [probe, setProbe] = useState()
407
-
408
- const ready = form?.state.status === 'ready' && form.state.writable !== false
409
-
410
- useEffect(() => {
411
- if (dirty) return
412
- setDraft(readValues(form?.state.value))
413
- setBaseline(readValues(form?.state.value))
414
- setRevision(form?.state.revision)
415
- }, [form?.state.revision, form?.state.status, dirty])
416
-
417
- useEffect(() => {
418
- let alive = true
419
- const load = async () => {
420
- try {
421
- const response = await fetch('/clash-proxy/status', { credentials: 'same-origin' })
422
- if (!response.ok) throw new Error(`status ${response.status}`)
423
- const data = await response.json()
424
- if (alive) {
425
- setLive(data)
426
- setLiveError(undefined)
427
- }
428
- } catch (error) {
429
- if (alive) setLiveError(error instanceof Error ? error.message : String(error))
430
- }
431
- }
432
- void load()
433
- const timer = setInterval(() => void load(), 15000)
434
- return () => {
435
- alive = false
436
- clearInterval(timer)
437
- }
438
- }, [])
439
-
440
- const edit = (key, value) => {
441
- setDraft((current) => ({ ...current, [key]: value }))
442
- setDirty(true)
443
- setMessage('')
444
- }
445
-
446
- const save = async (event) => {
447
- event.preventDefault()
448
- if (!ready || saving || revision === undefined) return
449
- const operations = []
450
- for (const [key, value] of Object.entries(draft)) {
451
- if (value === baseline[key]) continue
452
- operations.push({ op: 'set', path: [key], value })
453
- }
454
- if (operations.length === 0) {
455
- setDirty(false)
456
- return
457
- }
458
- setSaving(true)
459
- setMessage('')
460
- try {
461
- const accepted = await form.mutate(operations, revision)
462
- setMessage(t(accepted ? 'saved' : 'rejected'))
463
- if (accepted) setDirty(false)
464
- } catch (error) {
465
- setMessage(error instanceof Error ? error.message : String(error))
466
- } finally {
467
- setSaving(false)
468
- }
469
- }
470
-
471
- const reset = () => {
472
- setDraft(readValues(form?.state.value))
473
- setBaseline(readValues(form?.state.value))
474
- setRevision(form?.state.revision)
475
- setDirty(false)
476
- setMessage('')
477
- setProbe(undefined)
478
- }
479
-
480
- const runAction = async (action, body) => {
481
- setBusy(action)
482
- setLiveError(undefined)
483
- try {
484
- const response = await fetch('/clash-proxy/action', {
485
- method: 'POST',
486
- credentials: 'same-origin',
487
- headers: { 'content-type': 'application/json' },
488
- body: JSON.stringify({ action, ...(body ?? {}) }),
489
- })
490
- const answer = await response.json()
491
- if (!response.ok) throw new Error(answer?.error ?? `status ${response.status}`)
492
- const refreshed = await fetch('/clash-proxy/status', { credentials: 'same-origin' })
493
- if (refreshed.ok) setLive(await refreshed.json())
494
- } catch (error) {
495
- setLiveError(error instanceof Error ? error.message : String(error))
496
- } finally {
497
- setBusy('')
498
- }
499
- }
500
-
501
- const checkLink = async () => {
502
- setBusy('probe')
503
- setProbe(undefined)
504
- try {
505
- const response = await fetch('/clash-proxy/probe', {
506
- method: 'POST',
507
- credentials: 'same-origin',
508
- headers: { 'content-type': 'application/json' },
509
- body: JSON.stringify({ url: draft.subscriptionUrl ?? '' }),
510
- })
511
- setProbe(await response.json())
512
- } catch (error) {
513
- setProbe({ ok: false, error: error instanceof Error ? error.message : String(error) })
514
- } finally {
515
- setBusy('')
516
- }
517
- }
518
-
519
- if (!ready) {
520
- return h('p', { role: 'status', className: 'clxp-note' }, t(form?.state.status === 'loading' ? 'loading' : 'unavailable'))
521
- }
522
-
523
- return h('form', { className: 'clxp-form', onSubmit: (event) => void save(event) },
524
- [
525
- h(Panel, {
526
- key: 'panel',
527
- t,
528
- draft,
529
- live,
530
- delays: live?.delays ?? {},
531
- busy,
532
- message,
533
- probe,
534
- saving,
535
- dirty,
536
- editable: true,
537
- onEdit: edit,
538
- onAction: runAction,
539
- onProbe: checkLink,
540
- onReset: reset,
541
- }),
542
- liveError !== undefined ? h('p', { key: 'le', className: 'clxp-error', role: 'status' }, liveError) : null,
543
- ].filter(Boolean))
544
- }
545
-
546
- /**
547
- * The settings page, mounted at `settings.section`.
548
- *
549
- * This is the page the user actually opens from the sidebar's Settings row, so it
550
- * owns its own data instead of inheriting a row form: it reads and writes through
551
- * `/clash-proxy/config`, which is the one surface that both persists to the profile
552
- * and can restart routing when a routing-relevant field changed.
553
- *
554
- * @param props - section owner props (`close`) plus the slot's `t`.
555
- * @returns the settings page.
556
- */
557
- function SettingsSection(props) {
558
- const { t } = props
559
- const [config, setConfig] = useState()
560
- const [draft, setDraft] = useState()
561
- const [baseline, setBaseline] = useState()
562
- const [live, setLive] = useState()
563
- const [loadError, setLoadError] = useState()
564
- const [statusError, setStatusError] = useState()
565
- const [busy, setBusy] = useState('')
566
- const [saving, setSaving] = useState(false)
567
- const [message, setMessage] = useState('')
568
- const [probe, setProbe] = useState()
569
-
570
- const reload = useMemo(
571
- () => async () => {
572
- try {
573
- const response = await fetch('/clash-proxy/status', { credentials: 'same-origin' })
574
- if (!response.ok) throw new Error(`status ${response.status}`)
575
- const data = await response.json()
576
- setLive(data)
577
- setStatusError(undefined)
578
- return data
579
- } catch (error) {
580
- // A status failure must not clear the configuration error: they come from
581
- // different routes, and clearing it here left a page stuck on "loading"
582
- // whenever config failed but status succeeded.
583
- setStatusError(error instanceof Error ? error.message : String(error))
584
- return undefined
585
- }
586
- },
587
- [],
588
- )
589
-
590
- const loadConfig = useMemo(
591
- () => async () => {
592
- try {
593
- const response = await fetch('/clash-proxy/config', { credentials: 'same-origin' })
594
- if (!response.ok) throw new Error(`config ${response.status}`)
595
- const data = await response.json()
596
- if (data?.config === undefined || typeof data.config !== 'object') {
597
- throw new Error('the config route returned no config object')
598
- }
599
- setConfig(data.config)
600
- setDraft(data.config)
601
- setBaseline(data.config)
602
- setLoadError(undefined)
603
- return true
604
- } catch (error) {
605
- setLoadError(error instanceof Error ? error.message : String(error))
606
- return false
607
- }
608
- },
609
- [],
610
- )
611
-
612
- useEffect(() => {
613
- let alive = true
614
- void (async () => {
615
- if (!alive) return
616
- await loadConfig()
617
- })()
618
- void reload()
619
- const timer = setInterval(() => void reload(), 15000)
620
- return () => {
621
- alive = false
622
- clearInterval(timer)
623
- }
624
- }, [loadConfig, reload])
625
-
626
- const edit = (key, value) => {
627
- setDraft((current) => ({ ...current, [key]: value }))
628
- setMessage('')
629
- }
630
-
631
- const dirty = draft !== undefined && baseline !== undefined && Object.keys(draft).some((key) => draft[key] !== baseline[key])
632
-
633
- const save = async (event) => {
634
- event.preventDefault()
635
- if (!dirty || saving) return
636
- const patch = {}
637
- for (const key of Object.keys(draft)) if (draft[key] !== baseline[key]) patch[key] = draft[key]
638
- setSaving(true)
639
- setMessage('')
640
- try {
641
- const response = await fetch('/clash-proxy/config', {
642
- method: 'POST',
643
- credentials: 'same-origin',
644
- headers: { 'content-type': 'application/json' },
645
- body: JSON.stringify({ patch }),
646
- })
647
- const answer = await response.json()
648
- if (!response.ok) throw new Error(answer?.error ?? `status ${response.status}`)
649
- setConfig(answer.config)
650
- setDraft(answer.config)
651
- setBaseline(answer.config)
652
- setMessage((answer.warnings ?? []).length > 0 ? `${t('saved')} ${answer.warnings.join('; ')}` : t('saved'))
653
- await reload()
654
- } catch (error) {
655
- setMessage(error instanceof Error ? error.message : String(error))
656
- } finally {
657
- setSaving(false)
658
- }
659
- }
660
-
661
- const reset = () => {
662
- setDraft(config)
663
- setMessage('')
664
- setProbe(undefined)
665
- }
666
-
667
- const runAction = async (action, body) => {
668
- setBusy(action)
669
- setLoadError(undefined)
670
- try {
671
- const response = await fetch('/clash-proxy/action', {
672
- method: 'POST',
673
- credentials: 'same-origin',
674
- headers: { 'content-type': 'application/json' },
675
- body: JSON.stringify({ action, ...(body ?? {}) }),
676
- })
677
- const answer = await response.json()
678
- if (!response.ok) throw new Error(answer?.error ?? `status ${response.status}`)
679
- await reload()
680
- } catch (error) {
681
- setLoadError(error instanceof Error ? error.message : String(error))
682
- } finally {
683
- setBusy('')
684
- }
685
- }
686
-
687
- const checkLink = async () => {
688
- setBusy('probe')
689
- setProbe(undefined)
690
- try {
691
- const response = await fetch('/clash-proxy/probe', {
692
- method: 'POST',
693
- credentials: 'same-origin',
694
- headers: { 'content-type': 'application/json' },
695
- body: JSON.stringify({ url: draft?.subscriptionUrl ?? '' }),
696
- })
697
- setProbe(await response.json())
698
- } catch (error) {
699
- setProbe({ ok: false, error: error instanceof Error ? error.message : String(error) })
700
- } finally {
701
- setBusy('')
702
- }
703
- }
704
-
705
- // Distinguish three states the old branch collapsed into one: still loading, the load
706
- // failed, and loaded-but-empty. The first-run render is `undefined` for both `config`
707
- // and `draft`, so testing `draft` alone made a healthy page announce "not editable
708
- // here" before its first fetch resolved.
709
- if (draft === undefined) {
710
- if (loadError !== undefined) {
711
- return h('div', { className: 'clxp' }, [
712
- h('p', { key: 'e', className: 'clxp-error', role: 'status' }, `载入配置失败:${loadError}`),
713
- h(
714
- 'p',
715
- { key: 'h', className: 'clxp-note' },
716
- `读取 /clash-proxy/config 没有成功。请在浏览器里直接打开这个地址确认它返回 JSON;若返回 401,说明页面会话已经过期,重新从桌面端打开即可。`,
717
- ),
718
- h(
719
- 'div',
720
- { key: 'a', className: 'clxp-actions' },
721
- [
722
- h('button', { key: 'r', type: 'button', className: 'clxp-primary', onClick: () => void loadConfig() }, '重试'),
723
- h('button', { key: 'f', type: 'button', onClick: () => window.location.reload() }, '刷新页面'),
724
- ],
725
- ),
726
- ])
727
- }
728
- return h('p', { className: 'clxp-note', role: 'status' }, `${t('loading')}(正在读取 /clash-proxy/config …)`)
729
- }
730
-
731
- return h('form', { className: 'clxp-form', onSubmit: (event) => void save(event) }, [
732
- h(Panel, {
733
- key: 'p',
734
- t,
735
- draft,
736
- live,
737
- delays: live?.delays ?? {},
738
- busy,
739
- message,
740
- probe,
741
- saving,
742
- dirty,
743
- editable: true,
744
- onEdit: edit,
745
- onAction: runAction,
746
- onProbe: checkLink,
747
- onReset: reset,
748
- }),
749
- loadError !== undefined ? h('p', { key: 'e', className: 'clxp-error', role: 'status' }, loadError) : null,
750
- statusError !== undefined ? h('p', { key: 'se', className: 'clxp-error', role: 'status' }, `状态接口:${statusError}`) : null,
751
- ].filter(Boolean))
752
- }
753
-
754
- return {
755
- inject: ['slots', 'locale'],
756
- apply(ctx) {
757
- ctx.effect(() => ctx.locale.register('dshClashProxy', { en, zh }), 'dsh-clash-proxy: dictionaries')
758
- ctx.effect(() => {
759
- const style = document.createElement('style')
760
- style.dataset.dshClashProxy = 'true'
761
- style.textContent = CSS
762
- document.head.append(style)
763
- return () => style.remove()
764
- }, 'dsh-clash-proxy: styles')
765
-
766
- // The row configuration page still carries the editable form (the Plugins page
767
- // reaches it through the package's row list).
768
- ctx.slots.inject('plugins.row.config', function* () {
769
- yield ctx.slots.register(
770
- { name: 'plugins.row.config', key: 'dsh-clash-subscription#clash-proxy', locale: 'dshClashProxy' },
771
- (props) => (props.view === 'summary' ? h(Fragment, null, props.t('summary')) : h(RowConfigPage, { ...props })),
772
- )
773
- })
774
-
775
- // The primary door: a page of its own inside Settings, next to General / Models /
776
- // Plugins. A settings section owns its data and its save path, so it does not
777
- // depend on the row form being reachable at all.
778
- ctx.slots.inject('settings.section', function* () {
779
- yield ctx.slots.register(
780
- { name: 'settings.section', id: 'clash-proxy', order: 32, label: () => 'Clash 代理', locale: 'dshClashProxy' },
781
- (props) => h(SettingsSection, { ...props }),
782
- )
783
- })
784
- },
785
- }
786
- }});