feat(nodes): edit a subscription's name and URL

This commit is contained in:
Zakk committed 2026-09-30 00:49:30 +10:00
1 parent f7b1de6e9c
commit 97006273dc
11 files changed
+325 -31

No files matched your search

+93 -1
View File
@@ -1,5 +1,5 @@
import type {Locator} from '@playwright/test';
import {expect, mockBackend, query, test, moreAction} from './fixtures';
import {expect, mockBackend, query, test, moreAction, moreItem} from './fixtures';
import {createMockApi} from '../src/api/mock';
import {ApiError} from '../src/api/error';
import type {ProbeResult, Provider} from '../src/api/model';
@@ -559,3 +559,95 @@ test('a node write conflict names its cause, and only a delete without groups re
await expect(dialog.getByRole('alert')).toContainText('A resource with this name already exists');
await expect(dialog.getByRole('alert')).not.toContainText('changed or another write');
});
test("a subscription's URL is edited where its entry is written", async ({page}) => {
await page.goto('/#/nodes?tab=list');
await moreAction(page.locator('body'), 'Edit sub-c', 'More actions for sub-c');
const dialog = page.getByRole('dialog', {name: 'Edit subscription sub-c'});
await expect(dialog.getByRole('textbox', {name: 'Name', exact: true})).toHaveValue('sub-c');
await dialog.getByRole('textbox', {name: 'Subscription URL', exact: true}).fill('https://updated.example.net/sub?token=new');
// The URL alone changed, so the groups citing the tag are not offered.
await expect(dialog.getByRole('switch')).toHaveCount(0);
await dialog.getByRole('button', {name: 'Apply', exact: true}).click();
await expect(dialog).toHaveCount(0);
await expect(page.locator('.rp-toast.positive')).toContainText('Saved sub-c');
await page.goto('/#/config?tab=source');
await expect(page.locator('.cm-content')).toContainText("sub-c: 'https://updated.example.net/sub?token=new'");
});
test('renaming a subscription carries the groups whose subtag filter names it', async ({page}) => {
const {api} = await mockBackend(page);
const main = (await api.config()).sources.find(source => source.kind === 'main')!;
const added = main.content!.replace('subscription {\n', "subscription {\n sub-d: 'https://other.example.org/sub'\n");
await api.pollOperation(await api.replaceConfigSource(main.id, added, `"${main.content_sha256}"`));
await page.goto('/#/nodes?tab=list');
await moreAction(page.locator('body'), 'Edit sub-c', 'More actions for sub-c');
const dialog = page.getByRole('dialog', {name: 'Edit subscription sub-c'});
const name = dialog.getByRole('textbox', {name: 'Name', exact: true});
// A tag another subscription uses is refused.
await name.fill('sub-d');
// The clash is named once, on the field.
await expect(dialog.getByText('Another subscription already uses this name', {exact: true})).toHaveCount(1);
await expect(dialog.getByRole('button', {name: 'Apply', exact: true})).toBeDisabled();
await name.fill('skylink-sub');
await expect(dialog.getByRole('switch', {name: 'Also update the subscription filter in skylink', exact: true})).toBeChecked();
await dialog.getByRole('button', {name: 'Apply', exact: true}).click();
await expect(dialog).toHaveCount(0);
await page.goto('/#/config?tab=source');
const editor = page.locator('.cm-content');
await expect(editor).toContainText("skylink-sub: 'https://sub.example.net/api/v1/client/subscribe?token=demo'");
await expect(editor).toContainText('filter: subtag(skylink-sub)');
await expect(editor).not.toContainText('subtag(sub-c)');
});
test('a subscription in a read-only source offers its source file instead of an edit', async ({page}) => {
const {api, handlers} = await mockBackend(page);
handlers['GET config'] = async () => {
const config = await api.config();
for (const source of config.sources) if (source.kind === 'main') source.writable = false;
return config;
};
await page.goto('/#/nodes?tab=list');
const sources = page.locator('.rp-table').first();
const open = await moreItem(sources, 'Open source', 'More actions for sub-c');
await expect(page.getByRole('menu', {name: 'More actions for sub-c'}).getByRole('menuitem', {name: 'Edit sub-c', exact: true})).toHaveCount(0);
await open.click();
await expect(page).toHaveURL(/#\/config\?tab=source&source=[^&]+&line=\d+/);
});
test('a subscription not fetched yet is edited through its name', async ({page}) => {
const {api} = await mockBackend(page);
const main = (await api.config()).sources.find(source => source.kind === 'main')!;
const added = main.content!.replace('subscription {\n', "subscription {\n sub-d: 'https://wrong.example.org/sub'\n");
await api.pollOperation(await api.replaceConfigSource(main.id, added, `"${main.content_sha256}"`));
await page.goto('/#/nodes?tab=list');
await moreAction(page.locator('body'), 'Edit sub-d', 'More actions for sub-d');
const dialog = page.getByRole('dialog', {name: 'Edit subscription sub-d'});
await dialog.getByRole('textbox', {name: 'Subscription URL', exact: true}).fill('https://right.example.org/sub');
await dialog.getByRole('button', {name: 'Apply', exact: true}).click();
await expect(dialog).toHaveCount(0);
await page.goto('/#/config?tab=source');
await expect(page.locator('.cm-content')).toContainText("sub-d: 'https://right.example.org/sub'");
});
test('a group in another source naming the tag blocks a rename but not a URL edit', async ({page}) => {
const {api, handlers} = await mockBackend(page);
handlers['GET config'] = async () => {
const config = await api.config();
const main = config.sources.find(source => source.kind === 'main')!;
const content = 'group {\n roaming { filter: subtag(sub-c) policy: min_moving_avg }\n}\n';
config.sources.push({...main, id: 'extra-groups', kind: 'include', path: 'groups.dae', content});
return config;
};
await page.goto('/#/nodes?tab=list');
await moreAction(page.locator('body'), 'Edit sub-c', 'More actions for sub-c');
const dialog = page.getByRole('dialog', {name: 'Edit subscription sub-c'});
await dialog.getByRole('textbox', {name: 'Name', exact: true}).fill('skylink-sub');
await expect(dialog.getByText('Groups in groups.dae also filter on sub-c. Edit them in their source file before renaming.', {exact: true})).toBeVisible();
await expect(dialog.getByRole('switch')).toHaveCount(0);
await expect(dialog.getByRole('button', {name: 'Apply', exact: true})).toBeDisabled();
// Keeping the name leaves a URL edit free.
await dialog.getByRole('textbox', {name: 'Name', exact: true}).fill('sub-c');
await dialog.getByRole('textbox', {name: 'Subscription URL', exact: true}).fill('https://updated.example.net/sub');
await expect(dialog.getByRole('button', {name: 'Apply', exact: true})).toBeEnabled();
});
+1 -1
View File
@@ -73,7 +73,7 @@ describe('writeSubscriptionEntry', () => {
it('renames, keeping the form, the options and quotes where the tag had them', () => {
expect(edit('agent', {tag: 'agent2', url: 'https://example.net/sub'})).toBe(text.replace(' agent:', ' agent2:'));
expect(edit('old', {tag: 'fresh', url: 'https://example.org/x'})).toBe(
text.replace(' old: {\n url: \'https://example.org/old\'', " fresh: {\n url: 'https://example.org/x'")
text.replace(" old: {\n url: 'https://example.org/old'", " fresh: {\n url: 'https://example.org/x'")
);
expect(edit('quoted tag', {tag: 'plain', url: 'https://example.org/new'})).toBe(text.replace("'quoted tag':", "'plain':"));
expect(edit('short', {tag: 'two words', url: 'https://example.com/sub'})).toBe(text.replace(' short:', " 'two words':"));
+40 -2
View File
@@ -1,5 +1,5 @@
import {useT} from '../../i18n';
import {Button, ConfirmDialog, ErrorMessage, InlineAlert, LabeledSelect, ModalDialog, Switch, Tabs, TextField} from '../../ui/ui';
import {Button, ConfirmDialog, ErrorMessage, InlineAlert, LabeledSelect, ModalDialog, StaticField, Switch, Tabs, TextField} from '../../ui/ui';
import {NodeLatency} from './Latency';
import type {PageProps} from '../../shell/routes';
import {ProviderTable} from './ProviderTable';
@@ -34,7 +34,14 @@ export function Nodes(props: PageProps) {
agentError,
options,
policy,
setPolicy
setPolicy,
editNameError,
editOptions,
renameGroups,
renameFrom,
renameBlocked,
updateGroups,
setUpdateGroups
} = useNodesPage(props);
const list = (
<>
@@ -116,6 +123,37 @@ export function Nodes(props: PageProps) {
)}
</div>
)}
{dialog?.kind === 'editProvider' && (
<div className="rp-list">
<span className="rp-label">{t('nodes.editProviderHelp')}</span>
<TextField
isDisabled={pending}
label={t('nodes.name')}
value={form.name}
spellCheck={false}
error={editNameError ?? undefined}
onChange={name => setForm({...form, name})}
/>
<TextField isDisabled={pending} label={t('nodes.url')} value={form.value} spellCheck={false} onChange={value => setForm({...form, value})} />
{renameGroups && (
<>
<Switch isSelected={updateGroups} isDisabled={pending} onChange={setUpdateGroups}>
{t('nodes.renameGroups', {groups: renameGroups})}
</Switch>
{!updateGroups && <span className="rp-label">{t('nodes.renameGroupsHelp', {name: renameFrom})}</span>}
</>
)}
{renameBlocked && <span className="rp-label">{t('nodes.renameBlocked', {files: renameBlocked, name: renameFrom})}</span>}
{editOptions.length > 0 && (
<>
<span className="rp-label">{t('nodes.editOptions')}</span>
{editOptions.map(option => (
<StaticField key={option.name} label={option.name} value={option.value} />
))}
</>
)}
</div>
)}
{dialog?.kind === 'group' && (
<div className="rp-list">
<span className="rp-label">{groupHelp}</span>
+10 -3
View File
@@ -94,7 +94,7 @@ export function ProviderTable({model: m}: {model: ProviderTableView}) {
{
id: 'actions',
label: t('ui.actions'),
minWidth: m.canManage ? 112 : 88,
minWidth: (m.canManage ? 112 : 88) + (m.editing ? 40 : 0),
grow: 0,
render: row => (
<span className="rp-chain">
@@ -103,12 +103,19 @@ export function ProviderTable({model: m}: {model: ProviderTableView}) {
<Refresh className="rp-spin-on-press" />
</Button>
)}
{row.removable && (
{(row.action || row.removable) && (
<MoreMenu
small
quiet
label={t('ui.moreActionsFor', {name: row.name})}
actions={[{id: 'remove', label: row.removeLabel, negative: true, isDisabled: m.busy, onAction: row.remove}]}
actions={[
...(row.action?.kind === 'edit'
? [{id: 'edit', label: row.editLabel, isDisabled: m.busy || m.sourceBusy, onAction: row.action.run}]
: row.action?.kind === 'open'
? [{id: 'open', label: t('rule.openSource'), onAction: row.action.run}]
: []),
...(row.removable ? [{id: 'remove', label: row.removeLabel, negative: true, isDisabled: m.busy, onAction: row.remove}] : [])
]}
/>
)}
</span>
+130 -20
View File
@@ -1,16 +1,33 @@
import {useCallback, useLayoutEffect, useMemo, useRef, useState} from 'react';
import {useT, useLang, LOCALE, formatNumber} from '../../i18n';
import {useCapabilities, useNodeManage, useNodes, useOutboundNames, useProviderRefresh, useProviders} from '../../store';
import type {Node, Provider} from '../../api/model';
import {useT, useLang, LOCALE, formatList, formatNumber} from '../../i18n';
import {useCapabilities, useNodeManage, useNodes, useOutboundNames, useProviderRefresh, useProviders, useVersion} from '../../store';
import {useCompleteness, useConfig} from '../../store/config';
import type {ConfigSource, Node, Provider} from '../../api/model';
import {toast, toastFailure} from '../../ui/ui';
import {editProblem, useMainSourceEdit} from '../../store/mainSource';
import {addNamesToGroup, applyChanges, readGroupEntries} from '../../dae/groups';
import {isBareName} from '../../dae/text';
import {addNamesToGroup, addSubtagsToGroup, applyChanges, readGroupEntries, removeSubtagsFromGroup} from '../../dae/groups';
import {isBareName, isQuotable} from '../../dae/text';
import {readSubscriptionEntries, writeSubscriptionEntry, type SubscriptionText} from '../../dae/subscriptions';
import {engineOf} from '../../api/engines';
import {groupNameError} from '../shared/policyText';
import {newGroupPolicies} from '../../dae/vocab';
import type {PageProps} from '../../shell/routes';
import {readSubscriptions} from './subscriptions';
import {intervalItems, isNodeLink, nodeFormReason, nodeSource, ownedNodes, providerCreate, providerRows, selectedProvider, type ProviderForm} from './view';
import {fileName} from '../../dae/sources';
import {
citingGroups,
intervalItems,
isNodeLink,
nodeFormReason,
nodeSource,
ownedNodes,
providerCreate,
providerRows,
renameReferences,
selectedProvider,
type ProviderForm,
type ProviderRow
} from './view';
import {useProviderTable} from './useProviderTable';
import {useRefreshAll} from '../shared/useRefreshAll';
import {useNodeTable} from './useNodeTable';
@@ -25,19 +42,26 @@ import {nodesTabs} from './nav';
const blank: ProviderForm = {name: '', value: '', interval: '', agent: '', cache: null};
type NodeDialog =
{kind: 'provider'} | {kind: 'node'} | {kind: 'group'; item: Node} | {kind: 'removeProvider'; item: Provider} | {kind: 'removeNode'; item: Node};
| {kind: 'provider'}
| {kind: 'node'}
| {kind: 'group'; item: Node}
| {kind: 'removeProvider'; item: Provider}
| {kind: 'removeNode'; item: Node}
| {kind: 'editProvider'; item: ProviderRow; source: ConfigSource; entry: SubscriptionText};
export function useNodesPage({go, query}: PageProps) {
const t = useT();
const [dialog, setDialog] = useState<NodeDialog | null>(null);
const [form, setForm] = useState<ProviderForm>(blank);
const [policy, setPolicy] = useState(newGroupPolicies[0].id);
const [updateGroups, setUpdateGroups] = useState(true);
const session = useRef(0);
const submitting = useRef<NodeDialog | null>(null);
const [pendingDialog, setPendingDialog] = useState<NodeDialog | null>(null);
// Why the last submit did not land; `id` changes with each refusal so the alert takes focus again.
const [problem, setProblem] = useState<{id: number; text: string} | null>(null);
const guard = useDraftGuard(!!dialog && !!(form.name || form.value), () => {
const edited = dialog?.kind === 'editProvider' ? form.name !== dialog.entry.tag || form.value !== dialog.entry.url : !!(form.name || form.value);
const guard = useDraftGuard(!!dialog && edited, () => {
session.current++;
setDialog(null);
});
@@ -45,10 +69,13 @@ export function useNodesPage({go, query}: PageProps) {
session.current++;
setForm(blank);
setPolicy(newGroupPolicies[0].id);
setUpdateGroups(true);
setProblem(null);
if (next.kind === 'editProvider') setForm({...blank, name: next.entry.tag, value: next.entry.url});
setDialog(next);
}, []);
const locale = LOCALE[useLang()];
const lang = useLang();
const locale = LOCALE[lang];
const resources = useCapabilities().data?.resources;
const providers = useProviders(offered(resources, 'providers', {whileLoading: true}));
const nodes = useNodes(offered(resources, 'nodes', {whileLoading: true}));
@@ -63,6 +90,26 @@ export function useNodesPage({go, query}: PageProps) {
const refreshing = useProviderRefresh(reload);
const refreshAll = useRefreshAll(providers, refreshing);
const source = useMainSourceEdit();
// A subscription is edited in whichever source declares it, and only in dae text this page knows how to write.
const daeText = engineOf(useVersion().data).daeText;
const config = useConfig(offered(resources, 'config', {whileLoading: false}));
const sources = useMemo(() => config.data?.sources ?? [], [config.data]);
const isComplete = useCompleteness(sources);
const declared = useMemo(() => {
const found = new Map<string, Array<{source: ConfigSource; entry: SubscriptionText}>>();
for (const item of sources)
for (const entry of readSubscriptionEntries(item.content)) found.set(entry.tag, [...(found.get(entry.tag) ?? []), {source: item, entry}]);
return found;
}, [sources]);
const editAction = (item: ProviderRow) => {
const place = item.sourceTag ? declared.get(item.sourceTag) : undefined;
if (place?.length !== 1) return null;
const [{source: origin, entry}] = place;
// A source whose listener secrets came back masked would be saved with the masks, so it only opens.
if (daeText && source.writable && origin.writable && isComplete(origin) === true)
return {kind: 'edit' as const, run: () => open({kind: 'editProvider', item, source: origin, entry})};
return {kind: 'open' as const, run: () => go('config', within('', {tab: 'source', source: origin.id, line: String(entry.line)}))};
};
const entries = useMemo(() => readSubscriptions(source.main?.content ?? ''), [source.main?.content]);
const groupNames = useMemo(() => new Set(readGroupEntries(source.main?.content ?? '').map(entry => entry.name)), [source.main?.content]);
const {list} = useMemo(() => providerRows(providers.data?.providers ?? [], nodes.data ?? [], entries, t), [providers.data, nodes.data, entries, t]);
@@ -157,6 +204,22 @@ export function useNodesPage({go, query}: PageProps) {
if (problem) refuse(noticeText(problem, t));
if (result.kind !== 'ok') return;
toast('positive', t('nodes.joined', {name: node, group}), {action: viewGroup(group)});
} else if (dialog.kind === 'editProvider') {
const from = dialog.entry.tag;
const tag = form.name.trim();
const url = form.value.trim();
const follow = tag !== from && updateGroups;
// Filters are read from the text being written, so a group changed meanwhile is still found.
const result = await apply(text => {
const written = writeSubscriptionEntry(text, from, {tag, url});
if (!follow) return written;
return citingGroups(written, from).reduce((out, group) => removeSubtagsFromGroup(addSubtagsToGroup(out, group, [tag]), group, [from]), written);
}, dialog.source);
const problem = editProblem(result, t);
if (problem) refuse(noticeText(problem, t));
if (result.kind !== 'ok') return;
refetchProviders();
toast('positive', t('nodes.edited', {name: tag}));
} else if (dialog.kind === 'removeProvider') {
if (!(await manage.removeProvider(dialog.item.id))) return;
toast('positive', t('nodes.removed', {name: dialog.item.name}));
@@ -185,19 +248,40 @@ export function useNodesPage({go, query}: PageProps) {
? t('nodes.addNode')
: dialog.kind === 'group'
? t('nodes.newGroup')
: t(dialog.kind === 'removeProvider' ? 'nodes.removeProviderTitle' : 'nodes.removeNodeTitle', {name: dialog.item.name});
: dialog.kind === 'editProvider'
? t('nodes.editProviderTitle', {name: dialog.entry.tag})
: t(dialog.kind === 'removeProvider' ? 'nodes.removeProviderTitle' : 'nodes.removeNodeTitle', {name: dialog.item.name});
const nameError = dialog?.kind === 'group' ? groupNameError(form.name.trim(), groupNames, t) : null;
const createOptions = resources?.providers.create_options;
// The contract's User-Agent bound: up to 256 printable ASCII characters.
const agentError = /^[\x20-\x7E]{0,256}$/.test(form.agent.trim()) ? null : t('nodes.agentInvalid');
// A kept name is valid as written; a new one is bare, as doona writes names, and free among the subscriptions.
const editName = form.name.trim();
const editNameError =
dialog?.kind !== 'editProvider' || editName === dialog.entry.tag || !editName
? null
: !isBareName(editName)
? t('nodes.nameInvalid')
: declared.has(editName)
? t('nodes.tagTaken')
: null;
const editUrlValid = isSubscriptionUrl(form.value) && isQuotable(form.value.trim());
const references =
dialog?.kind === 'editProvider' && editName !== dialog.entry.tag ? renameReferences(sources, dialog.source, dialog.entry.tag) : {here: [], elsewhere: []};
const formValid =
dialog?.kind === 'provider'
? isBareName(form.name.trim()) && isSubscriptionUrl(form.value) && !agentError
: dialog?.kind === 'node'
? form.name.trim() !== '' && isNodeLink(form.value)
: dialog?.kind === 'group'
? nameError === null
: true;
dialog?.kind === 'editProvider'
? !!editName &&
editNameError === null &&
editUrlValid &&
!references.elsewhere.length &&
(editName !== dialog.entry.tag || form.value.trim() !== dialog.entry.url)
: dialog?.kind === 'provider'
? isBareName(form.name.trim()) && isSubscriptionUrl(form.value) && !agentError
: dialog?.kind === 'node'
? form.name.trim() !== '' && isNodeLink(form.value)
: dialog?.kind === 'group'
? nameError === null
: true;
const providerTable = useProviderTable({
rows: list,
loading: providers.loading && !providers.data,
@@ -218,7 +302,8 @@ export function useNodesPage({go, query}: PageProps) {
refresh: refreshing,
refreshAll,
onAdd: () => open({kind: 'provider'}),
onRemove: item => open({kind: 'removeProvider', item})
onRemove: item => open({kind: 'removeProvider', item}),
editAction
});
const nodeTable = useNodeTable({
nodes: owned,
@@ -267,12 +352,37 @@ export function useNodesPage({go, query}: PageProps) {
removing,
dialogTitle,
formValid,
formReason: nodeFormReason(dialog?.kind, form.name, form.value, t),
formReason:
dialog?.kind === 'editProvider'
? !editName
? t('nodes.nameMissing')
: // A name error is shown on its field alone.
editUrlValid
? null
: t('nodes.urlInvalid')
: nodeFormReason(dialog?.kind, form.name, form.value, t),
submit,
pending: dialog !== null && pendingDialog === dialog,
// A write abandoned by Cancel still holds the node actions until it settles, so no dialog can submit meanwhile.
submitting: pendingDialog !== null,
submitLabel: removing ? t('nodes.remove', {name: dialog.item.name}) : dialog?.kind === 'group' ? t('nodes.join') : t('nodes.add'),
submitLabel: removing
? t('nodes.remove', {name: dialog.item.name})
: dialog?.kind === 'group'
? t('nodes.join')
: dialog?.kind === 'editProvider'
? t('policy.save')
: t('nodes.add'),
editNameError: editName ? editNameError : null,
editOptions: dialog?.kind === 'editProvider' ? dialog.entry.options : [],
// Renaming offers to carry the groups whose subtag filter names the old tag along in the same write,
// unless another source names it too: a write across sources is not atomic, so those files block the rename.
renameGroups: references.here.length && !references.elsewhere.length ? formatList(lang, references.here) : null,
renameBlocked: references.elsewhere.length ? formatList(lang, references.elsewhere.map(fileName)) : null,
renameFrom: dialog?.kind === 'editProvider' ? dialog.entry.tag : '',
updateGroups,
setUpdateGroups: (next: boolean) => {
if (submitting.current !== dialog) setUpdateGroups(next);
},
groupHelp: dialog?.kind === 'group' ? t('nodes.newGroupHelp', {name: dialog.item.name}) : '',
// Only a name already typed is judged; an empty field is simply not ready.
groupNameError: form.name.trim() ? nameError : null,
+8
View File
@@ -23,6 +23,8 @@ type ProviderTableInput = {
refreshAll: ReturnType<typeof useRefreshAll>;
onAdd: () => void;
onRemove: (item: Provider) => void;
// Edit where the declaring source takes the write, otherwise the source file to open; null when neither applies.
editAction: (item: ProviderRow) => {kind: 'edit' | 'open'; run: () => void} | null;
};
export function useProviderTable(input: ProviderTableInput) {
const t = useT();
@@ -31,6 +33,8 @@ export function useProviderTable(input: ProviderTableInput) {
const intervals = new Map(input.entries.map(entry => [entry.tag, entry.interval]));
const rows = input.rows.map(item => ({
...providerRowView(item, item.configTag ? intervals.get(item.configTag) : undefined, locale, t),
action: input.editAction(item),
editLabel: t('nodes.edit', {name: item.displayName ?? item.name}),
refreshable: item.kind === 'subscription' && input.canRefresh,
refreshing: refresh.busy === item.id,
refreshDisabled: !!refresh.busy,
@@ -67,6 +71,7 @@ export function useProviderTable(input: ProviderTableInput) {
canManage: input.canManage,
busy: input.busy,
writable: input.source.writable,
editing: rows.some(row => row.action !== null),
sourceBusy: input.source.busy || !input.source.main,
sourceTip: input.source.error ? errorText(input.source.error, t) : undefined,
// Refreshing every subscription, as Settings offers it, where the backend can refresh them.
@@ -95,6 +100,8 @@ export type ProviderTableView = {
error?: string;
refreshLabel: string;
removeLabel: string;
action: {kind: 'edit' | 'open'; run: () => void} | null;
editLabel: string;
refreshable: boolean;
refreshing: boolean;
refreshDisabled: boolean;
@@ -109,6 +116,7 @@ export type ProviderTableView = {
canManage: boolean;
busy: boolean;
writable: boolean;
editing: boolean;
sourceBusy: boolean;
sourceTip?: string;
refreshAll: ReturnType<typeof useRefreshAll> | null;
+16 -1
View File
@@ -1,5 +1,5 @@
import {describe, expect, it} from 'vitest';
import type {Node, Provider} from '../../api/model';
import type {ConfigSource, Node, Provider} from '../../api/model';
import {readSubscriptions} from './subscriptions';
import {
nodeFormReason,
@@ -12,6 +12,7 @@ import {
intervalText,
intervalItems,
providerCreate,
renameReferences,
selectedProvider
} from './view';
import {translate, type Translator} from '../../i18n';
@@ -276,3 +277,17 @@ it('says why the add dialog cannot submit, first applicable, and nothing while i
// A group name's problem is shown at its field.
expect(nodeFormReason('group', 'bad name', '', t)).toBeNull();
});
it('a subscription is matched to its entry by its name, before any node is fetched', () => {
const {list} = providerRows([provider('a', {name: 'primary'}), provider('file', {kind: 'file'})], [], entries, t);
expect(list.map(item => item.sourceTag)).toEqual(['primary', undefined]);
});
it('a rename finds the groups naming the tag in the declaring source and every other source', () => {
const source = (id: string, content: string) => ({id, content}) as ConfigSource;
const main = source('main', `subscription {\n sub-c: 'https://a.example/sub'\n}\ngroup {\n here { filter: subtag(sub-c)\n policy: min }\n}`);
const other = source('other', `group {\n there { filter: subtag(sub-c)\n policy: min }\n}`);
const unrelated = source('unrelated', `group {\n loose { filter: subtag(sub-d)\n policy: min }\n}`);
expect(renameReferences([main, unrelated], main, 'sub-c')).toEqual({here: ['here'], elsewhere: []});
expect(renameReferences([main, other, unrelated], main, 'sub-c')).toEqual({here: ['here'], elsewhere: [other]});
});
+24 -3
View File
@@ -1,4 +1,4 @@
import type {Capabilities, Node, Provider, ProviderCreate} from '../../api/model';
import type {Capabilities, ConfigSource, Node, Provider, ProviderCreate} from '../../api/model';
import {enumLabel} from '../../i18n/enum';
import {compareLatency, healthMillis, nodeOwner, preferredHealth, pseudoOwner, pseudoOwnerId, type PseudoOwner} from '../../api/selectors';
import type {TableSort} from '../../ui/ui';
@@ -12,6 +12,7 @@ import {backendMessage, oneLine} from '../../i18n/backend';
import {latencyTone} from '../../ui/ui';
import {isBareName} from '../../dae/text';
import {isSubscriptionUrl} from '../../dae/setup';
import {classifyFilters, readGroupEntries} from '../../dae/groups';
export function nodeRowView(node: Node, names: OutboundNames, lang: Lang, t: Translator) {
const health = preferredHealth(node);
@@ -34,9 +35,27 @@ export function nodeRowView(node: Node, names: OutboundNames, lang: Lang, t: Tra
};
}
export type ProviderRow = (Provider | (Omit<Provider, 'kind'> & {kind: 'builtin' | 'unattributed'})) & {displayName?: string; configTag?: string};
export type ProviderRow = (Provider | (Omit<Provider, 'kind'> & {kind: 'builtin' | 'unattributed'})) & {
displayName?: string;
configTag?: string;
sourceTag?: string;
};
const latencyOf = (node: Node) => healthMillis(preferredHealth(node));
// The groups of a source whose exact subtag filter names a subscription tag.
export const citingGroups = (text: string, tag: string) =>
readGroupEntries(text)
.filter(group => classifyFilters(group).subtags.includes(tag))
.map(group => group.name);
// A rename rewrites only the declaring source, so groups elsewhere that name the tag are left for the person to edit.
export function renameReferences(sources: ConfigSource[], declaring: ConfigSource, tag: string) {
return {
here: citingGroups(declaring.content ?? '', tag),
elsewhere: sources.filter(item => item.id !== declaring.id && citingGroups(item.content ?? '', tag).length > 0)
};
}
export function providerRows(providers: Provider[], nodes: Node[], entries: SubscriptionEntry[], t: Translator) {
// Node metadata authorizes a tag; URL and unmatched-entry guesses are display-only.
const tags = new Map<string, Set<string>>();
@@ -70,7 +89,9 @@ export function providerRows(providers: Provider[], nodes: Node[], entries: Subs
return {
...item,
displayName: named.get(item.id) ?? item.name,
configTag: item.kind === 'subscription' && tag && entries.filter(entry => entry.tag === tag).length === 1 ? tag : undefined
configTag: item.kind === 'subscription' && tag && entries.filter(entry => entry.tag === tag).length === 1 ? tag : undefined,
// A subscription provider is named by its tag, so an entry is found before any fetch has tagged a node.
sourceTag: item.kind === 'subscription' ? item.name : undefined
};
});
const counts: Record<PseudoOwner, number> = {builtin: 0, unattributed: 0};
+1
View File
@@ -1000,6 +1000,7 @@
"nodes.removeProviderHelp": "Deletes this source and its nodes from the main configuration and reloads.",
"nodes.removeProviderTitle": "Remove source {name}",
"nodes.removed": "{name} removed",
"nodes.renameBlocked": "Groups in {files} also filter on {name}. Edit them in their source file before renaming.",
"nodes.renameGroups": "Also update the subscription filter in {groups}",
"nodes.renameGroupsHelp": "Otherwise these groups lose the nodes of {name}.",
"nodes.scope": "Showing nodes from {name}. Choose another source above to view its nodes.",
+1
View File
@@ -838,6 +838,7 @@
"nodes.removeProviderHelp": "从主配置删除此来源及其节点,并重载。",
"nodes.removeProviderTitle": "移除来源 {name}",
"nodes.removed": "{name} 已移除",
"nodes.renameBlocked": "{files} 中也有按 {name} 筛选的组。请先在来源文件中修改这些组,再重命名。",
"nodes.renameGroups": "同时更新 {groups} 中的订阅筛选条件",
"nodes.renameGroupsHelp": "否则这些组将失去 {name} 的节点。",
"nodes.scope": "当前显示 {name} 的节点。可在上方选择其他来源。",
+1
View File
@@ -838,6 +838,7 @@
"nodes.removeProviderHelp": "從主組態刪除此來源及其節點,並重載。",
"nodes.removeProviderTitle": "移除來源 {name}",
"nodes.removed": "{name} 已移除",
"nodes.renameBlocked": "{files} 中也有按 {name} 篩選的群組。請先在來源檔案中修改這些群組,再重新命名。",
"nodes.renameGroups": "同時更新 {groups} 中的訂閱篩選條件",
"nodes.renameGroupsHelp": "否則這些群組將失去 {name} 的節點。",
"nodes.scope": "目前顯示 {name} 的節點。可從上方清單選取其他來源。",