mirror of
https://github.com/vatesfr/xen-orchestra.git
synced 2026-11-24 07:48:01 -06:00
Compare commits
4 Commits
rest-api/p
...
docs/sdn-c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f49398d5de | ||
|
|
507b4477b5 | ||
|
|
fc16175dbb | ||
|
|
f3d12a9171 |
27
.eslintrc.js
27
.eslintrc.js
@@ -59,33 +59,6 @@ module.exports = {
|
||||
'n/no-unpublished-import': 'off',
|
||||
},
|
||||
},
|
||||
// The XO 6 test files share their modules (no isolation): mocking or resetting a module from one file would leak
|
||||
// into the others. See @xen-orchestra/web/docs/tests/mocking.md
|
||||
{
|
||||
files: ['@xen-orchestra/web/src/**/*.unit.test.ts'],
|
||||
rules: {
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
{
|
||||
selector: "CallExpression[callee.object.name='vi'][callee.property.name=/^(mock|doMock|unmock|doUnmock)$/]",
|
||||
message: 'Mock a module with `mockModule` from `@/test/spy-on-module.ts`, never `vi.mock`.',
|
||||
},
|
||||
{
|
||||
selector: "CallExpression[callee.object.name='vi'][callee.property.name='resetModules']",
|
||||
message: 'The test files share their modules: never reset them.',
|
||||
},
|
||||
{
|
||||
selector: "CallExpression[callee.object.name='vi'][callee.property.name='hoisted']",
|
||||
message: '`mockModule` is not hoisted: declare the stubs as plain constants.',
|
||||
},
|
||||
{
|
||||
selector: "CallExpression[callee.object.name='vi'][callee.property.name='resetAllMocks']",
|
||||
message:
|
||||
'Reset the stubs with `resetStubs` from `@/test/reset-stubs.ts`: `vi.resetAllMocks()` also resets the module mocks.',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['@xen-orchestra/{web-core,lite,web}/**/*.{vue,ts}'],
|
||||
parser: 'vue-eslint-parser',
|
||||
|
||||
@@ -759,10 +759,6 @@ export type TrafficRuleProtocol = (typeof TRAFFIC_RULE_PROTOCOLS)[number]
|
||||
export const SDN_CONTROLLER_OF_RULES_KEY = 'xo:sdn-controller:of-rules'
|
||||
export const SDN_CONTROLLER_OF_METHOD_KEY = 'xo:sdn-controller:of-method'
|
||||
export const SDN_CONTROLLER_OF_FORMAT_KEY = 'xo:sdn-controller:of-format'
|
||||
export const SDN_CONTROLLER_PRIVATE_NETWORK_UUID_KEY = 'xo:sdn-controller:private-network-uuid'
|
||||
export const SDN_CONTROLLER_ENCRYPTED_KEY = 'xo:sdn-controller:encrypted'
|
||||
export const SDN_CONTROLLER_ENCAPSULATION_KEY = 'xo:sdn-controller:encapsulation'
|
||||
export const SDN_CONTROLLER_PREFERRED_CENTER_KEY = 'xo:sdn-controller:preferred-center'
|
||||
export const TRAFFIC_RULE_PROTOCOLS = ['ARP', 'ICMP', 'IP', 'TCP', 'UDP'] as const
|
||||
export const TRAFFIC_RULE_PROTOCOLS_WITH_PORT: readonly TrafficRuleProtocol[] = ['TCP', 'UDP']
|
||||
|
||||
|
||||
@@ -155,80 +155,26 @@ export type PoolRollingUpdateRecoveryError = {
|
||||
}
|
||||
|
||||
export type PoolRollingUpdateRecoveryHost = {
|
||||
/** `interrupted`: left in progress by a run that is over */
|
||||
status: 'pending' | 'running' | 'interrupted' | 'succeeded' | 'failed' | 'not-needed'
|
||||
status: 'pending' | 'running' | 'succeeded' | 'failed' | 'not-needed'
|
||||
steps: Record<RPU_RECOVERY_STEP_NAME, PoolRollingUpdateRecoveryStep>
|
||||
lastError: PoolRollingUpdateRecoveryError | null
|
||||
}
|
||||
|
||||
/** a VM the last migrate back of the run could not bring to its original host */
|
||||
export type PoolRollingUpdateRecoveryVmConflict = {
|
||||
vmId: string
|
||||
/** unknown for a VM deleted before the run could read it */
|
||||
vmName?: string
|
||||
/** UUID of the host the VM was running on before the run */
|
||||
hostId: string
|
||||
/** `stopped` and `deleted`: left to the operator; `migration-failed`: retried by a resume */
|
||||
reason: 'stopped' | 'deleted' | 'migration-failed'
|
||||
/** XAPI error of the last migration, `migration-failed` only */
|
||||
message?: string
|
||||
}
|
||||
|
||||
/** what an operator changed, since the run, on a setting the run left changed or on an object of the run */
|
||||
export type PoolRollingUpdateRecoveryOperatorChange = {
|
||||
/** `haHeartbeatSr`: a heartbeat SR needed to enable HA again no longer exists */
|
||||
type: 'ha' | 'autoPowerOn' | 'wlb' | 'schedule' | 'haHeartbeatSr' | 'host' | 'vm'
|
||||
/** pool, schedule, SR, host or VM UUID */
|
||||
id: string
|
||||
/** schedules enabled again only */
|
||||
name?: string
|
||||
/** `disabled` as the run left it, `present` for a heartbeat SR, a host or a VM */
|
||||
expected: 'disabled' | 'present'
|
||||
/** `missing` for a deleted schedule, heartbeat SR, host or VM */
|
||||
observed: 'enabled' | 'missing'
|
||||
}
|
||||
|
||||
/** hosts resumes added to the plan of the run: patches released since it started, or hosts new to the pool */
|
||||
export type PoolRollingUpdateRecoveryPlanChange = {
|
||||
/** the last resume which added hosts */
|
||||
attempt: number
|
||||
/** UUIDs of hosts the run did not plan to update, or had finished, added by any resume */
|
||||
addedHostIds: string[]
|
||||
}
|
||||
|
||||
export type PoolRollingUpdateRecoveryRun = {
|
||||
runId: string
|
||||
poolId: string
|
||||
/** `awaiting-acceptance`: a resume found operator changes and waits for them to be accepted */
|
||||
status:
|
||||
| 'preparing'
|
||||
| 'running'
|
||||
| 'interrupted'
|
||||
| 'resuming'
|
||||
| 'failed'
|
||||
| 'cleaning'
|
||||
| 'succeeded'
|
||||
| 'awaiting-acceptance'
|
||||
status: 'preparing' | 'running' | 'interrupted' | 'resuming' | 'failed' | 'cleaning' | 'succeeded'
|
||||
startedAt: string
|
||||
updatedAt: string
|
||||
finishedAt?: string
|
||||
interruptedAt?: string
|
||||
taskId?: string
|
||||
variant?: 'xcp' | 'xs-cdn'
|
||||
/** 1 for the first attempt, incremented by each resume of the run */
|
||||
attempt?: number
|
||||
/** whether a resume would be accepted: run failed, interrupted or awaiting the acceptance of operator changes */
|
||||
resumable?: boolean
|
||||
hostOrder?: string[]
|
||||
hosts: Record<string, PoolRollingUpdateRecoveryHost>
|
||||
lastError: PoolRollingUpdateRecoveryError | null
|
||||
/** VM UUID -> UUID of the host it must be started on */
|
||||
haltedPinnedVms: Record<string, string>
|
||||
vmConflicts: PoolRollingUpdateRecoveryVmConflict[]
|
||||
/** found by the last resume, the run stays `awaiting-acceptance` until they are accepted */
|
||||
operatorChanges: PoolRollingUpdateRecoveryOperatorChange[]
|
||||
/** absent when no resume changed the plan */
|
||||
planChange?: PoolRollingUpdateRecoveryPlanChange
|
||||
}
|
||||
|
||||
/** record unreadable or of an unknown schema version: recovery needs a human */
|
||||
@@ -357,8 +303,6 @@ export type XoApp = EventEmitter & {
|
||||
checkFeatureAuthorization(featureCode: FeatureCode): Promise<void>
|
||||
/* whether this machine can run the tools of an import from VMware */
|
||||
checkEsxiDependencies(): Promise<XoV2vStatus>
|
||||
/* Throw if the proxy cannot be reached */
|
||||
checkProxyHealth(id: XoProxy['id']): Promise<void>
|
||||
/* validate, apply and persist the configuration of a plugin */
|
||||
configurePlugin(id: string, configuration: unknown, mergeWithExisting?: boolean): Promise<void>
|
||||
/* connect a server (XCP-ng/XenServer) */
|
||||
@@ -472,10 +416,6 @@ export type XoApp = EventEmitter & {
|
||||
getPlugin(id: XoPlugin['id']): Promise<XoPlugin>
|
||||
getPlugins(): Promise<XoPlugin[]>
|
||||
getProxy(id: XoProxy['id']): Promise<XoProxy>
|
||||
updateProxy(
|
||||
id: XoProxy['id'],
|
||||
updates: { address?: string | null; authenticationToken?: string; name?: string; vmUuid?: XoVm['id'] | null }
|
||||
): Promise<XoProxy>
|
||||
getRemote(id: XoBackupRepository['id']): Promise<XoBackupRepository>
|
||||
getAllRemotes(): Promise<XoBackupRepository[]>
|
||||
removeRemote(id: XoBackupRepository['id']): Promise<void>
|
||||
@@ -507,7 +447,10 @@ export type XoApp = EventEmitter & {
|
||||
* `assertBrowserMediaInsertable` reports the predictable failures synchronously, e.g. before
|
||||
* starting a task.
|
||||
*/
|
||||
insertBrowserMedia(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): Promise<{ vdiId: XoVdi['id'] }>
|
||||
insertBrowserMedia(params: {
|
||||
id: XoBrowserMediaSession['id']
|
||||
vmId: XoVm['id']
|
||||
}): Promise<{ vdiId: XoVdi['id'] }>
|
||||
assertBrowserMediaInsertable(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): void
|
||||
/** Eject the ISO of a browser media session, release its storage, and disconnect the browser */
|
||||
ejectBrowserMedia(id: XoBrowserMediaSession['id']): Promise<void>
|
||||
@@ -674,10 +617,6 @@ export type XoApp = EventEmitter & {
|
||||
): Promise<void>
|
||||
getRollingUpdateRecovery(poolId: XoPool['id']): Promise<PoolRollingUpdateRecovery | undefined>
|
||||
finalizeRollingUpdate(pool: XoPool, opts?: { force?: boolean; parentTask?: VatesTask }): Promise<void>
|
||||
resumeRollingPoolUpdate(
|
||||
pool: XoPool,
|
||||
opts?: { acceptOperatorChanges?: boolean; bypassBackupCheck?: boolean; parentTask?: VatesTask }
|
||||
): Promise<void>
|
||||
setVmResourceSet(vmId: XoVm['id'], resourceSetId: string | null, force?: boolean): Promise<void>
|
||||
shareVmResourceSet(vmId: XoVm['id']): Promise<void>
|
||||
removeUserFromGroup(userId: XoUser['id'], id: XoGroup['id']): Promise<void>
|
||||
|
||||
@@ -579,9 +579,6 @@ export type XoBrowserMediaSession = {
|
||||
|
||||
export type XoProxy = {
|
||||
id: Branded<'proxy'>
|
||||
/**
|
||||
* @deprecated no replacement for this field
|
||||
*/
|
||||
url: string
|
||||
version?: string
|
||||
name: string
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
export default {
|
||||
read: true,
|
||||
update: {
|
||||
name: true,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -3,16 +3,7 @@ export default {
|
||||
delete: true,
|
||||
forget: true,
|
||||
import: {
|
||||
vdi: {
|
||||
upload: true,
|
||||
/**
|
||||
* Warning: lets the holder make XO send a GET request to any HTTP(S) URL, including internal addresses
|
||||
* reachable from the XO server (localhost, management network, etc.).
|
||||
*
|
||||
* Covered by `import:vdi`, `import` and `*`: only grant these to trusted users.
|
||||
*/
|
||||
url: true,
|
||||
},
|
||||
vdi: true,
|
||||
vm: true,
|
||||
},
|
||||
'migrate-receive': true,
|
||||
|
||||
@@ -38,10 +38,33 @@ export class Privilege<T extends SupportedResource> {
|
||||
}
|
||||
|
||||
#matchAction<Resource extends SupportedResource = T>(action: SupportedActions<Resource>) {
|
||||
// A privilege allows its own action and every action below it in the tree:
|
||||
// e.g. `*`, `import`, `import:vdi` and `import:vdi:url` all allow `import:vdi:url`,
|
||||
// but `import:vdi:upload` does not (it is a sibling, not a parent)
|
||||
return this.#action === '*' || this.#action === action || action.startsWith(`${this.#action}:`)
|
||||
// read:name_label - read:name_label
|
||||
if (this.#action === action) {
|
||||
return true
|
||||
}
|
||||
|
||||
const [namespaceToMatch, actionToMatch] = action.split(':')
|
||||
const [thisNamespace, thisAction] = this.#action.split(':')
|
||||
|
||||
if (thisNamespace === '*') {
|
||||
return true
|
||||
}
|
||||
|
||||
// update:vm - read:name_label
|
||||
if (thisNamespace !== namespaceToMatch) {
|
||||
return false
|
||||
}
|
||||
|
||||
// read - read:name_label
|
||||
if (thisAction === undefined) {
|
||||
return true
|
||||
}
|
||||
// read:name_decription - read:name_label
|
||||
if (thisAction !== actionToMatch) {
|
||||
return false
|
||||
}
|
||||
|
||||
throw new Error(`Unable to verify if ${this.#action} match ${action} `)
|
||||
}
|
||||
|
||||
#matchSelector(object: object) {
|
||||
|
||||
@@ -27,12 +27,6 @@ suite('Privilege.checkActionIsValid behavior', () => {
|
||||
test('should work', () => {
|
||||
assert.doesNotThrow(() => Privilege.checkActionIsValid('vm', 'read'))
|
||||
})
|
||||
|
||||
test('should work with 3-level actions', () => {
|
||||
assert.doesNotThrow(() => Privilege.checkActionIsValid('sr', 'import:vdi:url'))
|
||||
// @ts-expect-error test invalid action
|
||||
assert.throws(() => Privilege.checkActionIsValid('sr', 'import:vdi:foo'))
|
||||
})
|
||||
})
|
||||
|
||||
suite('Privilege.match behavior', () => {
|
||||
@@ -65,22 +59,6 @@ suite('Privilege.match behavior', () => {
|
||||
const cleanShutdownPrivilege = new Privilege({ action: 'shutdown:clean', resource: 'vm', effect: 'allow' })
|
||||
assert.strictEqual(cleanShutdownPrivilege.match({ resource: 'vm', action: 'shutdown', object }), false)
|
||||
})
|
||||
|
||||
test('Should match 3-level actions with any parent action', () => {
|
||||
for (const action of ['*', 'import', 'import:vdi', 'import:vdi:url'] as const) {
|
||||
const srPrivilege = new Privilege({ action, resource: 'sr', effect: 'allow' })
|
||||
assert.strictEqual(srPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), true, action)
|
||||
}
|
||||
})
|
||||
|
||||
test('Should not match 3-level actions with a sibling or a child action', () => {
|
||||
const uploadPrivilege = new Privilege({ action: 'import:vdi:upload', resource: 'sr', effect: 'allow' })
|
||||
assert.strictEqual(uploadPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
|
||||
assert.strictEqual(uploadPrivilege.match({ resource: 'sr', action: 'import:vdi', object }), false)
|
||||
|
||||
const vmImportPrivilege = new Privilege({ action: 'import:vm', resource: 'sr', effect: 'allow' })
|
||||
assert.strictEqual(vmImportPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
|
||||
})
|
||||
})
|
||||
|
||||
suite('ACL V2 behavior', async () => {
|
||||
@@ -280,23 +258,6 @@ suite('ACL V2 behavior', async () => {
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should allow VDI upload but not URL import with import:vdi allowed and import:vdi:url denied', () => {
|
||||
const sr = { id: 'sr-id' }
|
||||
const userPrivileges = [
|
||||
{ id: privilegeId, action: 'import:vdi', resource: 'sr', effect: 'allow', roleId },
|
||||
{ id: privilegeId, action: 'import:vdi:url', resource: 'sr', effect: 'deny', roleId },
|
||||
] satisfies TPrivilege<'sr'>[]
|
||||
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({ user, action: 'import:vdi:upload', resource: 'sr', objects: sr, userPrivileges }),
|
||||
true
|
||||
)
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({ user, action: 'import:vdi:url', resource: 'sr', objects: sr, userPrivileges }),
|
||||
false
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
suite('getMissingPrivileges behavior', () => {
|
||||
@@ -414,12 +375,4 @@ suite('getActionStrings', () => {
|
||||
assert.ok(actions.includes('shutdown:clean'))
|
||||
assert.ok(actions.includes('shutdown:hard'))
|
||||
})
|
||||
|
||||
test('3-level actions are included alongside their parents', () => {
|
||||
const actions = getActionStrings('sr')
|
||||
assert.ok(actions.includes('import'))
|
||||
assert.ok(actions.includes('import:vdi'))
|
||||
assert.ok(actions.includes('import:vdi:upload'))
|
||||
assert.ok(actions.includes('import:vdi:url'))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
## **next**
|
||||
|
||||
- [Web-Core/UiCircleProgressBar] Add a brand accent and an option to hide the value (PR [#10849](https://github.com/vatesfr/xen-orchestra/pull/10849))
|
||||
- [Tables] Cells fit on one line: long names are cut in the middle, extra tags go under "+N" and long texts end with "…" (PR [#10850](https://github.com/vatesfr/xen-orchestra/pull/10850))
|
||||
- [Pages] The page header and tabs now stay in place on every page: dashboards, System tabs, consoles, tasks, settings and creation forms scroll under them instead of scrolling with them (PR [#10822](https://github.com/vatesfr/xen-orchestra/pull/10822))
|
||||
- [VM/Host] Main actions (shutdown, reboot, start, resume, migrate, snapshot) are shown as buttons in the VM and host headers and move one by one into "More actions" when space runs out; "More actions" groups them under "Change state" and "Actions" sections, and VMs without guest tools get force shutdown and force reboot instead (PR [#10815](https://github.com/vatesfr/xen-orchestra/pull/10815))
|
||||
- [Web-Core/UiButtonIcon] Update icon buttons design, with a counter replacing the notification dot (PR [#10799](https://github.com/vatesfr/xen-orchestra/pull/10799))
|
||||
@@ -14,8 +12,6 @@
|
||||
- [Web-Core/UiDropdownButton] Update dropdown buttons design (PR [#9850](https://github.com/vatesfr/xen-orchestra/pull/9850))
|
||||
- [Tables] Tables are filtered as you type, half a second after the last keystroke, or right away with Enter; the "Search" button is removed (PR [#10797](https://github.com/vatesfr/xen-orchestra/pull/10797))
|
||||
- [Side panels] Fix the double scrollbar when the side panel content is taller than the screen: the page header now stays in place, and the list and the side panel each scroll on their own. All scrollbars are now thin, like the side panel one (PR [#10807](https://github.com/vatesfr/xen-orchestra/pull/10807))
|
||||
- [Mobile] Searchable dropdown lists no longer overflow the screen (PR [#10854](https://github.com/vatesfr/xen-orchestra/pull/10854))
|
||||
- [New/VM] Fix the storage table overflowing horizontally, which hid part of the delete button (PR [#10851](https://github.com/vatesfr/xen-orchestra/pull/10851))
|
||||
|
||||
## **0.27.0** (2026-10-29)
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
<div class="collection-filter-row">
|
||||
<span class="or">{{ t('or') }}</span>
|
||||
<div class="inputs">
|
||||
<UiInput v-if="newFilter.isAdvanced" v-model="filterContent" accent="neutral" class="advanced-input" />
|
||||
<UiInput v-if="newFilter.isAdvanced" v-model="filterContent" accent="brand" class="advanced-input" />
|
||||
<template v-else>
|
||||
<VtsSelect :id="builderPropertySelectId" accent="neutral" />
|
||||
<VtsSelect v-if="hasComparisonSelect" :id="builderComparisonSelectId" accent="neutral" />
|
||||
<VtsSelect v-if="currentFilter?.type === 'enum'" :id="builderValueSelectId" accent="neutral" />
|
||||
<UiInput v-else-if="hasValueInput" v-model="newFilter.builder.value" accent="neutral" />
|
||||
<VtsSelect :id="builderPropertySelectId" accent="brand" />
|
||||
<VtsSelect v-if="hasComparisonSelect" :id="builderComparisonSelectId" accent="brand" />
|
||||
<VtsSelect v-if="currentFilter?.type === 'enum'" :id="builderValueSelectId" accent="brand" />
|
||||
<UiInput v-else-if="hasValueInput" v-model="newFilter.builder.value" accent="brand" />
|
||||
</template>
|
||||
</div>
|
||||
<div class="buttons">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<VtsSelect v-if="isSelectWidget(widget)" :id="selectId" accent="neutral" />
|
||||
<VtsSelect v-if="isSelectWidget(widget)" :id="selectId" accent="brand" />
|
||||
<UiRadioButtonGroup v-else-if="isRadioWidget(widget)" accent="brand" gap="wide">
|
||||
<UiRadioButton
|
||||
v-for="choice in widget.choices"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<VtsInputGroup>
|
||||
<UiInput v-model.number="sizeInput" accent="neutral" type="number" :max-decimals="3" />
|
||||
<VtsSelect :id="prefixSelectId" accent="neutral" />
|
||||
<UiInput v-model.number="sizeInput" accent="brand" type="number" :max-decimals="3" />
|
||||
<VtsSelect :id="prefixSelectId" accent="brand" />
|
||||
</VtsInputGroup>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
<UiModal accent="info" @dismiss="emit('cancel')" @confirm="handleSubmit()">
|
||||
<template #content>
|
||||
<div class="form-selects">
|
||||
<VtsSelect :id="sortPropertySelectId" accent="neutral" />
|
||||
<VtsSelect :id="isAscendingSelectId" accent="neutral" />
|
||||
<VtsSelect :id="sortPropertySelectId" accent="brand" />
|
||||
<VtsSelect :id="isAscendingSelectId" accent="brand" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
@dismiss="emit('cancel')"
|
||||
>
|
||||
<template #content>
|
||||
<UiTextarea v-model="editedJson" accent="neutral" class="modal-textarea" />
|
||||
<UiTextarea v-model="editedJson" accent="brand" class="modal-textarea" />
|
||||
<VtsOverlayButton variant="tertiary" @click="formatJson()">
|
||||
{{ t('action:reformat') }}
|
||||
</VtsOverlayButton>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
:label="t('select-compression')"
|
||||
learn-more-url="https://xcp-ng.org/blog/2018/12/19/zstd-compression-for-xcp-ng/"
|
||||
>
|
||||
<VtsSelect :id="compressionSelectId" accent="neutral" />
|
||||
<VtsSelect :id="compressionSelectId" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
</template>
|
||||
<template #buttons>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<template #content>
|
||||
<div>
|
||||
<VtsInputWrapper :label="t('select-destination-host')">
|
||||
<VtsSelect :id="hostSelectId" accent="neutral" />
|
||||
<VtsSelect :id="hostSelectId" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -45,7 +45,6 @@ const emit = defineEmits<{
|
||||
const { t } = useI18n()
|
||||
|
||||
const { HeadCells, BodyCells, colspan } = useNewVmNetworkColumns({
|
||||
exclude: ['rank'],
|
||||
body: ({ networkInterface, onRemove }: { networkInterface: NetworkInterface; onRemove: () => void }) => {
|
||||
const { id: interfaceSelectId } = useFormSelect(networks, {
|
||||
model: toRef(networkInterface, 'interface'),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<VtsTable class="new-vm-sr-table" fixed>
|
||||
<VtsTable>
|
||||
<thead>
|
||||
<tr>
|
||||
<HeadCells />
|
||||
@@ -49,7 +49,6 @@ const emit = defineEmits<{
|
||||
const { t } = useI18n()
|
||||
|
||||
const { HeadCells, BodyCells, colspan } = useNewVmSrColumns({
|
||||
exclude: ['rank'],
|
||||
body: ({ vdi, onRemove }: { vdi: Vdi; onRemove?: () => void }) => {
|
||||
const { id: srSelectId } = useFormSelect(() => srs, {
|
||||
model: toRef(vdi, 'SR'),
|
||||
@@ -77,9 +76,3 @@ const { HeadCells, BodyCells, colspan } = useNewVmSrColumns({
|
||||
},
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.new-vm-sr-table {
|
||||
--vts-table-min-width: 80rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -59,7 +59,7 @@ const useTaskColumns = defineColumns(() => {
|
||||
const { t } = useI18n()
|
||||
|
||||
return {
|
||||
name: useTextColumn({ headerLabel: t('name'), flexible: true }),
|
||||
name: useTextColumn({ headerLabel: t('name') }),
|
||||
host: useLinkColumn({ headerLabel: t('host') }),
|
||||
progress: useProgressBarColumn({ headerLabel: t('progress') }),
|
||||
started: useDateColumn({ headerLabel: t('started') }),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<VtsInputWrapper :label :message="error">
|
||||
<VtsSelect :id accent="neutral" />
|
||||
<VtsSelect :id accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<VtsInputWrapper :label :message="error">
|
||||
<UiInput v-model.trim="model" accent="neutral" :required :disabled />
|
||||
<UiInput v-model.trim="model" accent="brand" :required :disabled />
|
||||
</VtsInputWrapper>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<UiTextarea v-model.trim="model" accent="neutral">
|
||||
<UiTextarea v-model.trim="model" accent="brand">
|
||||
{{ t('description') }}
|
||||
</UiTextarea>
|
||||
</template>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<UiTextarea v-model.trim="model" :accent="errorMessage !== undefined ? 'danger' : 'neutral'">
|
||||
<UiTextarea v-model.trim="model" :accent="errorMessage !== undefined ? 'danger' : 'brand'">
|
||||
{{ t('allowed-ips') }}
|
||||
|
||||
<template #info>{{ t('allowed-ips-example') }}</template>
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
<template>
|
||||
<VtsInputWrapper :label="t('mac-address')" :message="messages" wrap-message>
|
||||
<UiInput
|
||||
v-model.trim="model"
|
||||
accent="neutral"
|
||||
:required
|
||||
:placeholder="required ? undefined : t('auto-generated')"
|
||||
/>
|
||||
<UiInput v-model.trim="model" accent="brand" :required :placeholder="required ? undefined : t('auto-generated')" />
|
||||
</VtsInputWrapper>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<VtsInputWrapper :label="t('network')" :message="error">
|
||||
<VtsSelect :id accent="neutral">
|
||||
<VtsSelect :id accent="brand">
|
||||
<template v-if="slots.option" #default="slotProps">
|
||||
<slot name="option" v-bind="slotProps" />
|
||||
</template>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<VtsInputWrapper :label="t('rate-limit')" :message="error">
|
||||
<UiInput v-model.number="model" accent="neutral" type="number">
|
||||
<UiInput v-model.number="model" accent="brand" type="number">
|
||||
<template #right-icon>
|
||||
<span class="unit typo-body-regular">{{ t('bytes:kbs') }}</span>
|
||||
</template>
|
||||
|
||||
@@ -103,7 +103,7 @@
|
||||
<VtsKeyValueList>
|
||||
<VtsKeyValueRow>
|
||||
<template #label>
|
||||
<VtsSelect :id="localeSelectId" accent="neutral" />
|
||||
<VtsSelect :id="localeSelectId" accent="brand" />
|
||||
</template>
|
||||
<template #value>
|
||||
<UiLink size="medium" href="https://translate.vates.tech/engage/xen-orchestra/">
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<UiTitle>{{ t('template') }}</UiTitle>
|
||||
<div class="template-container">
|
||||
<VtsInputWrapper :label="t('action:pick-template')">
|
||||
<VtsSelect :id="templateSelectId" accent="neutral" />
|
||||
<VtsSelect :id="templateSelectId" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
</div>
|
||||
<div v-if="vmState.new_vm_template" class="form-container">
|
||||
@@ -30,7 +30,7 @@
|
||||
{{ t('iso-dvd') }}
|
||||
</UiRadioButton>
|
||||
</UiRadioButtonGroup>
|
||||
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="neutral" />
|
||||
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="brand" />
|
||||
</div>
|
||||
<div v-else class="install-settings-container">
|
||||
<UiRadioButtonGroup
|
||||
@@ -45,7 +45,7 @@
|
||||
{{ t('pxe') }}
|
||||
</UiRadioButton>
|
||||
</UiRadioButtonGroup>
|
||||
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="neutral" />
|
||||
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="brand" />
|
||||
</div>
|
||||
</div>
|
||||
<!-- SYSTEM SECTION -->
|
||||
@@ -54,11 +54,11 @@
|
||||
<div class="system-container">
|
||||
<div class="column">
|
||||
<VtsInputWrapper :label="t('new-vm:name')">
|
||||
<UiInput v-model.trim="vmState.name" accent="neutral" />
|
||||
<UiInput v-model.trim="vmState.name" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
<VtsInputWrapper :label="t('tags')">
|
||||
<!-- TODO Change input text into select when Thierry's component is available -->
|
||||
<UiInput v-model.trim="vmState.tag" accent="neutral" @keydown.enter.prevent="addTag" />
|
||||
<UiInput v-model.trim="vmState.tag" accent="brand" @keydown.enter.prevent="addTag" />
|
||||
</VtsInputWrapper>
|
||||
<div v-if="vmState.tags.length > 0" class="chips">
|
||||
<UiChip v-for="(tag, index) in vmState.tags" :key="index" accent="info" @remove="removeTag(index)">
|
||||
@@ -66,7 +66,7 @@
|
||||
</UiChip>
|
||||
</div>
|
||||
<VtsInputWrapper :label="t('boot-firmware')">
|
||||
<VtsSelect :id="bootFirmwareSelectId" accent="neutral" />
|
||||
<VtsSelect :id="bootFirmwareSelectId" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
<div
|
||||
v-if="vmState.boot_firmware !== 'uefi'"
|
||||
@@ -93,11 +93,11 @@
|
||||
</UiCheckboxGroup>
|
||||
</div>
|
||||
<div class="column">
|
||||
<UiTextarea v-model="vmState.description" accent="neutral">
|
||||
<UiTextarea v-model="vmState.description" accent="brand">
|
||||
{{ t('new-vm:description') }}
|
||||
</UiTextarea>
|
||||
<VtsInputWrapper :label="t('affinity-host')">
|
||||
<VtsSelect :id="affinityHostSelectId" accent="neutral" />
|
||||
<VtsSelect :id="affinityHostSelectId" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
</div>
|
||||
</div>
|
||||
@@ -105,15 +105,15 @@
|
||||
<UiTitle>{{ t('resource-management') }}</UiTitle>
|
||||
<div class="resource-management-container">
|
||||
<VtsInputWrapper :label="t('vcpus')">
|
||||
<UiInput v-model.number="vmState.vCPU" type="number" accent="neutral" />
|
||||
<UiInput v-model.number="vmState.vCPU" type="number" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
<!-- TODO remove (GB) when we can use new selector -->
|
||||
<VtsInputWrapper :label="`${t('ram')} (GB)`">
|
||||
<UiInput v-model.number="ramFormatted" type="number" accent="neutral" />
|
||||
<UiInput v-model.number="ramFormatted" type="number" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
<VtsInputWrapper :label="t('topology')">
|
||||
<div class="topology">
|
||||
<VtsSelect :id="topologySelectId" accent="neutral" />
|
||||
<VtsSelect :id="topologySelectId" accent="brand" />
|
||||
</div>
|
||||
</VtsInputWrapper>
|
||||
</div>
|
||||
|
||||
@@ -62,12 +62,12 @@
|
||||
<FormSection :label="t('configuration')">
|
||||
<div class="row">
|
||||
<VtsInputWrapper :label="t('storage')" :message="t('n-gb-required', { n: REQUIRED_GB })">
|
||||
<VtsSelect :id="srSelectId" accent="neutral" />
|
||||
<VtsSelect :id="srSelectId" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
</div>
|
||||
<div class="row">
|
||||
<VtsInputWrapper :label="t('network')">
|
||||
<VtsSelect :id="networkSelectId" accent="neutral" />
|
||||
<VtsSelect :id="networkSelectId" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
<VtsInputWrapper
|
||||
:label="t('deploy-xoa-custom-ntp-servers')"
|
||||
|
||||
65
@xen-orchestra/lite/src/route-map.d.ts
vendored
65
@xen-orchestra/lite/src/route-map.d.ts
vendored
@@ -492,13 +492,6 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/middle-ellipsis/vts-middle-ellipsis': RouteRecordInfo<
|
||||
'/story/web-core/middle-ellipsis/vts-middle-ellipsis',
|
||||
'/story/web-core/middle-ellipsis/vts-middle-ellipsis',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/number-input/vts-number-input': RouteRecordInfo<
|
||||
'/story/web-core/number-input/vts-number-input',
|
||||
'/story/web-core/number-input/vts-number-input',
|
||||
@@ -562,13 +555,6 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/select/vts-detailed-option': RouteRecordInfo<
|
||||
'/story/web-core/select/vts-detailed-option',
|
||||
'/story/web-core/select/vts-detailed-option',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/select/vts-select': RouteRecordInfo<
|
||||
'/story/web-core/select/vts-select',
|
||||
'/story/web-core/select/vts-select',
|
||||
@@ -632,20 +618,6 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/tag/vts-tag': RouteRecordInfo<
|
||||
'/story/web-core/tag/vts-tag',
|
||||
'/story/web-core/tag/vts-tag',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/tag-select/vts-tag-select': RouteRecordInfo<
|
||||
'/story/web-core/tag-select/vts-tag-select',
|
||||
'/story/web-core/tag-select/vts-tag-select',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/tags-input/vts-tags-input': RouteRecordInfo<
|
||||
'/story/web-core/tags-input/vts-tags-input',
|
||||
'/story/web-core/tags-input/vts-tags-input',
|
||||
@@ -989,13 +961,6 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/overridden/ui-overridden': RouteRecordInfo<
|
||||
'/story/web-core/ui/overridden/ui-overridden',
|
||||
'/story/web-core/ui/overridden/ui-overridden',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/panel/ui-panel': RouteRecordInfo<
|
||||
'/story/web-core/ui/panel/ui-panel',
|
||||
'/story/web-core/ui/panel/ui-panel',
|
||||
@@ -1696,12 +1661,6 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/middle-ellipsis/vts-middle-ellipsis.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/middle-ellipsis/vts-middle-ellipsis'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/number-input/vts-number-input.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/number-input/vts-number-input'
|
||||
@@ -1756,12 +1715,6 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/select/vts-detailed-option.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/select/vts-detailed-option'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/select/vts-select.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/select/vts-select'
|
||||
@@ -1816,18 +1769,6 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/tag/vts-tag.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/tag/vts-tag'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/tag-select/vts-tag-select.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/tag-select/vts-tag-select'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/tags-input/vts-tags-input.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/tags-input/vts-tags-input'
|
||||
@@ -2122,12 +2063,6 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/overridden/ui-overridden.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/overridden/ui-overridden'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/panel/ui-panel.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/panel/ui-panel'
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
<div class="row">
|
||||
Choose a component
|
||||
<VtsSelect :id="componentSelectId" accent="neutral" />
|
||||
<VtsSelect :id="componentSelectId" accent="brand" />
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<template #content>
|
||||
<div class="demo-rename-modal-content">
|
||||
<VtsInputWrapper label="New name">
|
||||
<UiInput v-model.trim="newName" accent="neutral" required />
|
||||
<UiInput v-model.trim="newName" accent="brand" required />
|
||||
</VtsInputWrapper>
|
||||
<p>
|
||||
Tip: name the VM "fail" to make the fake API call fail: the confirmation modal closes and this modal stays
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('text')
|
||||
.str()
|
||||
.required()
|
||||
.preset('prod-web-frontend-eu-west-01')
|
||||
.widget()
|
||||
.help('Rendered as is when it fits, cut in the middle otherwise, with the full text in a tooltip'),
|
||||
prop('tailLength').num().default(10).widget().help('Number of characters kept visible at the end of a cut text'),
|
||||
setting('width').widget(number()).preset(15).help('Available width, in rem'),
|
||||
]"
|
||||
>
|
||||
<VtsMiddleEllipsis v-bind="properties" :style="{ width: `${settings.width}rem` }" />
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { prop, setting } from '@/libs/story/story-param.ts'
|
||||
import { number } from '@/libs/story/story-widget.ts'
|
||||
import VtsMiddleEllipsis from '@core/components/middle-ellipsis/VtsMiddleEllipsis.vue'
|
||||
</script>
|
||||
@@ -1,53 +0,0 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
prop('option')
|
||||
.required()
|
||||
.obj('FormOption<{ accent?: DropdownAccent }>')
|
||||
.help('Given by the default slot of VtsSelect'),
|
||||
iconProp().preset('object:network'),
|
||||
prop('iconTooltip').str().widget(),
|
||||
prop('details').str().widget().preset('eth0').help('Displayed after a dash'),
|
||||
]"
|
||||
:presets="{
|
||||
'PIF with VLAN': {
|
||||
props: {
|
||||
icon: 'object:network',
|
||||
details: 'eth1, VLAN 20',
|
||||
},
|
||||
},
|
||||
'Disabled VM': {
|
||||
props: {
|
||||
icon: 'object:vm:running',
|
||||
iconTooltip: 'Running',
|
||||
details: 'No VIF detected',
|
||||
},
|
||||
},
|
||||
'Without details': {
|
||||
props: {
|
||||
icon: 'object:network',
|
||||
details: undefined,
|
||||
},
|
||||
},
|
||||
}"
|
||||
>
|
||||
<VtsSelect :id="optionSelectId" accent="neutral">
|
||||
<template #default="{ option }">
|
||||
<VtsDetailedOption v-bind="properties" :option />
|
||||
</template>
|
||||
</VtsSelect>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { iconProp, prop } from '@/libs/story/story-param.ts'
|
||||
import VtsDetailedOption from '@core/components/select/VtsDetailedOption.vue'
|
||||
import VtsSelect from '@core/components/select/VtsSelect.vue'
|
||||
import { useFormSelect } from '@core/packages/form-select'
|
||||
|
||||
const optionLabels = ['Pool-wide network associated with eth0', 'Storage network']
|
||||
|
||||
const { id: optionSelectId } = useFormSelect(optionLabels)
|
||||
</script>
|
||||
@@ -2,7 +2,7 @@
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
prop('accent').required().enum('neutral', 'warning', 'danger').preset('neutral').widget(),
|
||||
prop('accent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
|
||||
prop('options').required().arr('FormOption<TEntry, TValue>').widget().preset(options),
|
||||
prop('selectedLabel').str(),
|
||||
prop('required').bool().widget(),
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
prop('tags').arr('string').required().help('Currently selected tags. The component never mutates it'),
|
||||
prop('suggestions').arr('TagSelectSuggestion').preset(suggestions).widget(),
|
||||
prop('iconOnly').bool().widget().help('Displays the `Add`/`Edit` trigger as an icon with a tooltip'),
|
||||
prop('busy').bool().widget().help('Displays the trigger as busy, e.g. while the tags are being saved'),
|
||||
event('save')
|
||||
.args({ changes: 'TagSelectChanges' })
|
||||
.help('Emitted with the added and removed tags when clicking `Save`. `Cancel` discards the changes'),
|
||||
]"
|
||||
>
|
||||
<UiTagsList>
|
||||
<VtsTag v-for="tag of tags" :key="tag" :value="tag" accent="brand" />
|
||||
<VtsTagSelect v-bind="properties" :tags @save="changes => saveTags(changes)" />
|
||||
</UiTagsList>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, prop } from '@/libs/story/story-param.ts'
|
||||
import VtsTag from '@core/components/tag/VtsTag.vue'
|
||||
import VtsTagSelect, {
|
||||
type TagSelectChanges,
|
||||
type TagSelectSuggestion,
|
||||
} from '@core/components/tag-select/VtsTagSelect.vue'
|
||||
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const tags = ref(['production', 'env=prod'])
|
||||
|
||||
const suggestions: TagSelectSuggestion[] = [
|
||||
{ tag: 'production' },
|
||||
{ tag: 'staging' },
|
||||
{ tag: 'env=prod' },
|
||||
{ tag: 'env=dev' },
|
||||
{ tag: 'xo:no-bak', info: 'Excludes the VM from backups' },
|
||||
{ tag: 'xo:notify-on-snapshot', info: 'Notifies when a snapshot is created' },
|
||||
]
|
||||
|
||||
function saveTags({ added, removed }: TagSelectChanges) {
|
||||
tags.value = [...tags.value.filter(tag => !removed.includes(tag)), ...added]
|
||||
}
|
||||
</script>
|
||||
@@ -1,36 +0,0 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
prop('value')
|
||||
.str()
|
||||
.required()
|
||||
.preset('env=prod')
|
||||
.widget()
|
||||
.help('Tags in the `term=label` form are displayed as a tertiary tag'),
|
||||
prop('accent')
|
||||
.type('TagAccent')
|
||||
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
|
||||
.default('info')
|
||||
.widget(),
|
||||
prop('variant')
|
||||
.type('TagVariant')
|
||||
.enum('primary', 'secondary')
|
||||
.default('secondary')
|
||||
.widget()
|
||||
.help('Ignored when the tag is displayed as a tertiary tag'),
|
||||
prop('wrap')
|
||||
.bool()
|
||||
.widget()
|
||||
.help('Stacks the term above the value when they do not fit on one line (tertiary tag only)'),
|
||||
]"
|
||||
>
|
||||
<VtsTag v-bind="properties" />
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { prop } from '@/libs/story/story-param.ts'
|
||||
import VtsTag from '@core/components/tag/VtsTag.vue'
|
||||
</script>
|
||||
@@ -9,6 +9,6 @@ The label comes from the surrounding `VtsInputWrapper`.
|
||||
|
||||
```vue-template
|
||||
<VtsInputWrapper label="Values">
|
||||
<VtsTagsInput v-model="values" accent="neutral" placeholder="Add a value" />
|
||||
<VtsTagsInput v-model="values" accent="brand" placeholder="Add a value" />
|
||||
</VtsInputWrapper>
|
||||
```
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
model().type('string[]').preset(['alpha', 'beta']).help('Enter or comma adds the typed value'),
|
||||
prop('accent').enum('neutral', 'warning', 'danger').required().preset('neutral').widget(),
|
||||
prop('accent').enum('brand', 'warning', 'danger').required().preset('brand').widget(),
|
||||
prop('placeholder').str().preset('Add a value').widget(),
|
||||
]"
|
||||
>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
prop('accent')
|
||||
.type('CircleProgressBarAccent')
|
||||
.required()
|
||||
.enum('brand', 'info', 'warning', 'danger')
|
||||
.enum('info', 'warning', 'danger')
|
||||
.preset('info')
|
||||
.widget(),
|
||||
prop('size')
|
||||
@@ -16,7 +16,6 @@
|
||||
.enum('extra-small', 'small', 'medium', 'large')
|
||||
.preset('large')
|
||||
.widget(),
|
||||
prop('noValue').bool().widget(),
|
||||
]"
|
||||
:presets
|
||||
>
|
||||
@@ -36,7 +35,6 @@ const presets = {
|
||||
maxValue: 500,
|
||||
size: 'medium',
|
||||
accent: 'info',
|
||||
noValue: false,
|
||||
},
|
||||
},
|
||||
'75% of 300': {
|
||||
@@ -45,34 +43,6 @@ const presets = {
|
||||
maxValue: 300,
|
||||
size: 'medium',
|
||||
accent: 'info',
|
||||
noValue: false,
|
||||
},
|
||||
},
|
||||
'Value above max (success)': {
|
||||
props: {
|
||||
value: 150,
|
||||
maxValue: 100,
|
||||
size: 'medium',
|
||||
accent: 'info',
|
||||
noValue: false,
|
||||
},
|
||||
},
|
||||
'Value above max (warning)': {
|
||||
props: {
|
||||
value: 150,
|
||||
maxValue: 100,
|
||||
size: 'medium',
|
||||
accent: 'warning',
|
||||
noValue: false,
|
||||
},
|
||||
},
|
||||
'Brand ring without value': {
|
||||
props: {
|
||||
value: 1,
|
||||
maxValue: 3,
|
||||
size: 'small',
|
||||
accent: 'brand',
|
||||
noValue: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
model().type('string | number').preset(''),
|
||||
prop('accent').enum('neutral', 'success', 'warning', 'danger').required().preset('neutral').widget(),
|
||||
prop('accent').enum('brand', 'warning', 'danger').required().preset('brand').widget(),
|
||||
prop('id').str().widget(),
|
||||
prop('required').bool().widget(),
|
||||
prop('selected').bool().widget(),
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
model().type('string').preset(''),
|
||||
prop('accent').enum('neutral', 'warning', 'danger').required().preset('neutral').widget(),
|
||||
prop('accent').enum('brand', 'warning', 'danger').required().preset('brand').widget(),
|
||||
prop('disabled').bool().widget(),
|
||||
prop('href').str().widget(),
|
||||
prop('max-characters').num().help('When used, it will display the character count under the input').widget(),
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ settings }"
|
||||
:params="[
|
||||
slot().help('Label displayed next to the dot, leave empty to only display the dot'),
|
||||
setting('defaultSlot').widget(text()).preset('Overridden'),
|
||||
]"
|
||||
>
|
||||
<UiOverridden v-if="settings.defaultSlot">{{ settings.defaultSlot }}</UiOverridden>
|
||||
<UiOverridden v-else />
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { text } from '@/libs/story/story-widget.ts'
|
||||
import UiOverridden from '@core/components/ui/overridden/UiOverridden.vue'
|
||||
</script>
|
||||
@@ -6,7 +6,7 @@
|
||||
.type('TagAccent')
|
||||
.required()
|
||||
.preset('info')
|
||||
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
|
||||
.enum('info', 'neutral', 'success', 'warning', 'danger', 'muted')
|
||||
.widget(),
|
||||
prop('variant').type('TagVariant').required().preset('primary').enum('primary', 'secondary').widget(),
|
||||
slot(),
|
||||
|
||||
@@ -6,21 +6,15 @@
|
||||
.type('TagAccent')
|
||||
.required()
|
||||
.preset('info')
|
||||
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
|
||||
.enum('info', 'neutral', 'success', 'warning', 'danger', 'muted')
|
||||
.widget(),
|
||||
prop('truncate')
|
||||
.bool()
|
||||
.widget()
|
||||
.help('Keeps the tag on one line: the longer part ends with an ellipsis first, the shorter one stays whole'),
|
||||
prop('wrap').bool().widget().help('Stacks the term above the value when they do not fit on one line'),
|
||||
slot(),
|
||||
slot('term'),
|
||||
setting('slot').preset('Label').widget(),
|
||||
setting('term').preset('term').widget(),
|
||||
setting('maxWidth').widget(number()).help('Maximum width, in rem'),
|
||||
]"
|
||||
>
|
||||
<UiTertiaryTag v-bind="properties" :style="{ maxWidth: settings.maxWidth ? `${settings.maxWidth}rem` : undefined }">
|
||||
<UiTertiaryTag v-bind="properties">
|
||||
{{ settings.slot }}
|
||||
<template #term>
|
||||
{{ settings.term }}
|
||||
@@ -32,6 +26,5 @@
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { number } from '@/libs/story/story-widget.ts'
|
||||
import UiTertiaryTag from '@core/components/ui/tag/UiTertiaryTag.vue'
|
||||
</script>
|
||||
|
||||
@@ -11,15 +11,14 @@ const { warn } = createLogger('xo:proxy:authentication')
|
||||
const isValidToken = t => typeof t === 'string' && t.length !== 0
|
||||
|
||||
export default class Authentication {
|
||||
// kept in memory because the config is not reloaded when the token is written at construction
|
||||
#token
|
||||
#app
|
||||
|
||||
constructor(app, { appName, config: { authenticationToken: token } }) {
|
||||
this.#app = app
|
||||
|
||||
const setToken = ({ token }) => {
|
||||
assert(isValidToken(token), 'invalid authentication token: ' + token)
|
||||
|
||||
this.#token = token
|
||||
|
||||
// save this token in the automatically handled conf file
|
||||
fse.outputFileSync(
|
||||
// this file must take precedence over normal user config
|
||||
@@ -39,13 +38,6 @@ export default class Authentication {
|
||||
}
|
||||
}
|
||||
|
||||
// follow config changes (including the ones made by setToken)
|
||||
app.config.watch('authenticationToken', token => {
|
||||
if (isValidToken(token)) {
|
||||
this.#token = token
|
||||
}
|
||||
})
|
||||
|
||||
app.api.addMethod('authentication.setToken', setToken, {
|
||||
description: 'change the authentication token used by this XO Proxy',
|
||||
params: {
|
||||
@@ -58,9 +50,7 @@ export default class Authentication {
|
||||
}
|
||||
|
||||
async findProfile(credentials) {
|
||||
const token = credentials?.token
|
||||
// never match an empty/missing token, even if no valid token is known
|
||||
if (isValidToken(token) && token === this.#token) {
|
||||
if (credentials?.token === this.#app.config.get('authenticationToken')) {
|
||||
return new Profile()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,6 @@ import assert from 'node:assert'
|
||||
import { after, before, describe, it } from 'node:test'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
|
||||
import { DispatchClient } from '../client/dispatchClient.js'
|
||||
import { RestApiClient } from '../client/restApiClient.js'
|
||||
import { createTestUser, deleteTestUser } from '../utils/aclUtils.js'
|
||||
import { getRequiredEnv } from '../utils/index.js'
|
||||
import { setup, teardown } from './setup.js'
|
||||
|
||||
const log = createLogger('qa:sdn-controller')
|
||||
@@ -521,142 +517,3 @@ describe('SDN Controller REST API', { skip: !process.env.SDN_CONTROLLER_VM_ID },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// The networks go on the pools the suite already tests on: the pool of SDN_CONTROLLER_VM_ID and, when it is another
|
||||
// one, the pool of REFERENCE_VM_ID. Never any other pool XO is connected to: a private network sets the SDN controller
|
||||
// of its pools. The tunnels go through the network of the management PIF of each pool's master
|
||||
describe('SDN Controller private networks', { skip: !process.env.SDN_CONTROLLER_VM_ID }, () => {
|
||||
let dispatchClient
|
||||
let pools
|
||||
const networkIds = []
|
||||
|
||||
// RestApiClient answers only the body, and the route's statuses are checked too
|
||||
const createPrivateNetwork = async (body, client = dispatchClient.restApiClient) => {
|
||||
const response = await fetch(`${client.baseUrl}${BASE}/pools/actions/create_private_network?sync=true`, {
|
||||
method: 'POST',
|
||||
headers: client.headers,
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
const result = await response.json()
|
||||
networkIds.push(...(result.networkIds ?? []))
|
||||
return { status: response.status, result }
|
||||
}
|
||||
|
||||
const bodyFor = (pools, params) => ({
|
||||
poolIds: pools.map(pool => pool.id),
|
||||
pifIds: pools.map(pool => pool.pifId),
|
||||
name: `qa-sdn-private-network-${Date.now()}`,
|
||||
description: 'created by the qa-test suite',
|
||||
encapsulation: 'gre',
|
||||
...params,
|
||||
})
|
||||
|
||||
const networksNamed = async name =>
|
||||
(await dispatchClient.restApiClient.getObjects('/rest/v0/networks')).filter(network => network.name_label === name)
|
||||
|
||||
before(async () => {
|
||||
dispatchClient = new DispatchClient()
|
||||
await dispatchClient.initialize()
|
||||
|
||||
const { restApiClient } = dispatchClient
|
||||
const vmPoolIds = await Promise.all(
|
||||
[process.env.SDN_CONTROLLER_VM_ID, getRequiredEnv('REFERENCE_VM_ID')].map(
|
||||
async id => (await restApiClient.get(`/rest/v0/vms/${id}`)).$pool
|
||||
)
|
||||
)
|
||||
const [allPools, hosts, pifs] = await Promise.all(
|
||||
['pools', 'hosts', 'pifs'].map(collection => restApiClient.getObjects(`/rest/v0/${collection}`))
|
||||
)
|
||||
pools = [...new Set(vmPoolIds)].map(id => {
|
||||
const { master } = allPools.find(pool => pool.id === id)
|
||||
return {
|
||||
id,
|
||||
masterId: master,
|
||||
pifId: pifs.find(pif => pif.$host === master && pif.management)?.id,
|
||||
hostCount: hosts.filter(host => host.$pool === id).length,
|
||||
}
|
||||
})
|
||||
log.debug('Private network pools', { pools })
|
||||
})
|
||||
|
||||
after(async () => {
|
||||
for (const id of networkIds) {
|
||||
try {
|
||||
await dispatchClient.restApiClient.delete(`/rest/v0/networks/${id}`)
|
||||
} catch (error) {
|
||||
log.warn('Failed to delete a private network', { error, networkId: id })
|
||||
}
|
||||
}
|
||||
await dispatchClient?.close()
|
||||
})
|
||||
|
||||
// the preferred center is a host of the last pool, so that its network is not the first one asked for
|
||||
it('should create one network per pool, each with a tunnel on every host, in a single private network', async t => {
|
||||
if (pools.length === 1) {
|
||||
t.diagnostic('XO is connected to a single pool: the private network spans it alone')
|
||||
}
|
||||
const preferredCenterId = pools.at(-1).masterId
|
||||
const body = bodyFor(pools, { mtu: 1400, preferredCenterId })
|
||||
|
||||
const { status, result } = await createPrivateNetwork(body)
|
||||
assert.strictEqual(status, 201, JSON.stringify(result))
|
||||
assert.strictEqual(result.networkIds.length, pools.length)
|
||||
|
||||
const networks = await Promise.all(
|
||||
result.networkIds.map(id => dispatchClient.restApiClient.get(`/rest/v0/networks/${id}?fields=*`))
|
||||
)
|
||||
const { 'xo:sdn-controller:private-network-uuid': privateNetworkUuid, 'xo:sdn-controller:vni': vni } =
|
||||
networks[0].other_config
|
||||
assert.match(privateNetworkUuid, /^[0-9a-f-]{36}$/)
|
||||
assert.match(vni, /^\d+$/)
|
||||
assert.deepStrictEqual(networks.map(network => network.$pool).sort(), pools.map(pool => pool.id).sort())
|
||||
for (const network of networks) {
|
||||
const pool = pools.find(pool => pool.id === network.$pool)
|
||||
assert.strictEqual(network.name_label, body.name)
|
||||
assert.strictEqual(network.MTU, 1400)
|
||||
assert.strictEqual(network.PIFs.length, pool.hostCount, 'one tunnel access PIF per host')
|
||||
assert.deepStrictEqual(
|
||||
{
|
||||
encapsulation: network.other_config['xo:sdn-controller:encapsulation'],
|
||||
preferredCenter: network.other_config['xo:sdn-controller:preferred-center'],
|
||||
privateNetworkUuid: network.other_config['xo:sdn-controller:private-network-uuid'],
|
||||
vni: network.other_config['xo:sdn-controller:vni'],
|
||||
},
|
||||
{ encapsulation: 'gre', preferredCenter: preferredCenterId, privateNetworkUuid, vni }
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('should refuse an unknown pool, a pool without a PIF or an unknown encapsulation, creating no network', async () => {
|
||||
const body = bodyFor(pools.slice(0, 1))
|
||||
for (const [params, expectedStatus] of [
|
||||
[{ poolIds: ['00000000-0000-0000-0000-000000000000'] }, 404],
|
||||
[{ pifIds: [] }, 422],
|
||||
[{ encapsulation: 'ipip' }, 422],
|
||||
]) {
|
||||
const { status, result } = await createPrivateNetwork({ ...body, ...params })
|
||||
assert.strictEqual(status, expectedStatus, `${JSON.stringify(params)}: ${JSON.stringify(result)}`)
|
||||
}
|
||||
assert.deepStrictEqual(await networksNamed(body.name), [])
|
||||
})
|
||||
|
||||
it('should refuse a user who is not an admin', async () => {
|
||||
const user = await createTestUser(dispatchClient.xoClient)
|
||||
try {
|
||||
const client = new RestApiClient({
|
||||
xoUrl: getRequiredEnv('HOSTNAME'),
|
||||
username: user.email,
|
||||
password: user.password,
|
||||
})
|
||||
await client.connect()
|
||||
const body = bodyFor(pools.slice(0, 1))
|
||||
const { status, result } = await createPrivateNetwork(body, client)
|
||||
assert.strictEqual(status, 403, JSON.stringify(result))
|
||||
assert.deepStrictEqual(await networksNamed(body.name), [])
|
||||
} finally {
|
||||
await deleteTestUser(dispatchClient.xoClient, user.id)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -195,12 +195,3 @@ export const parseXml = (function () {
|
||||
export function ensureArray<T>(value: T | T[] | undefined): T[] {
|
||||
return value === undefined ? [] : Array.isArray(value) ? value : [value]
|
||||
}
|
||||
|
||||
export function getFileNameFromUrl(url: URL): string {
|
||||
const fileName = url.pathname.slice(url.pathname.lastIndexOf('/') + 1)
|
||||
try {
|
||||
return decodeURIComponent(fileName)
|
||||
} catch {
|
||||
return fileName
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,11 +57,6 @@ export const notImplementedResp = {
|
||||
description: 'Not implemented',
|
||||
} as const
|
||||
|
||||
export const proxyUnreachableResp = {
|
||||
status: 502,
|
||||
description: 'Proxy unreachable',
|
||||
} as const
|
||||
|
||||
export const resourceAlreadyExists = {
|
||||
status: 409,
|
||||
description: 'Resource already exists',
|
||||
|
||||
@@ -533,12 +533,10 @@ export const poolRollingUpdateRecovery = {
|
||||
interruptedAt: '2026-08-31T14:18:47.000Z',
|
||||
taskId: '0mf2gtitq',
|
||||
variant: 'xcp',
|
||||
attempt: 2,
|
||||
resumable: true,
|
||||
hostOrder: ['b61a5c92-700e-4966-a13b-00633f03eea8', '46522969-d891-4c48-a839-316b767b7b7b'],
|
||||
hosts: {
|
||||
'b61a5c92-700e-4966-a13b-00633f03eea8': {
|
||||
status: 'interrupted',
|
||||
status: 'running',
|
||||
steps: {
|
||||
evacuate: {
|
||||
status: 'observed-succeeded',
|
||||
@@ -561,7 +559,7 @@ export const poolRollingUpdateRecovery = {
|
||||
lastError: null,
|
||||
},
|
||||
'46522969-d891-4c48-a839-316b767b7b7b': {
|
||||
status: 'interrupted',
|
||||
status: 'running',
|
||||
steps: {
|
||||
evacuate: { status: 'running', startedAt: '2026-08-31T14:12:50.000Z' },
|
||||
update: { status: 'pending' },
|
||||
@@ -576,17 +574,4 @@ export const poolRollingUpdateRecovery = {
|
||||
haltedPinnedVms: {
|
||||
'883b6265-6d54-c48b-6a24-4b0e6d88801f': 'b61a5c92-700e-4966-a13b-00633f03eea8',
|
||||
},
|
||||
vmConflicts: [
|
||||
{
|
||||
vmId: '613f541c-4bed-fc77-7ca8-2db6b68f079c',
|
||||
vmName: 'Debian 12',
|
||||
hostId: '46522969-d891-4c48-a839-316b767b7b7b',
|
||||
reason: 'stopped',
|
||||
},
|
||||
],
|
||||
operatorChanges: [],
|
||||
planChange: {
|
||||
attempt: 2,
|
||||
addedHostIds: ['b61a5c92-700e-4966-a13b-00633f03eea8'],
|
||||
},
|
||||
}
|
||||
|
||||
@@ -22,8 +22,6 @@ export const proxy = {
|
||||
name: 'Proxy 2025-08-29T08:23:33.394Z',
|
||||
vmUuid: '7330139d-288f-2248-5986-d508ea71f12c',
|
||||
id: 'e625ea0c-a876-405a-b838-109d762efe88',
|
||||
url: 'proxy.url is no longer exposed by Xen Orchestra because it contained the proxy authentication token, see the Xen Orchestra changelog',
|
||||
url: 'https://uxxa-NIAY9W29VlGMrRcKuxx2dsYMTldJo-7l2YnMNQ@10.1.7.238/',
|
||||
version: '0.29.29',
|
||||
}
|
||||
|
||||
export const proxyHealth = { success: true }
|
||||
|
||||
@@ -84,7 +84,6 @@ import type {
|
||||
CreateVmParams,
|
||||
FinalizeRollingUpdateBody,
|
||||
PoolDashboard,
|
||||
ResumeRollingUpdateBody,
|
||||
RollingPoolActionBody,
|
||||
RollingPoolUpdateBody,
|
||||
} from './pool.type.mjs'
|
||||
@@ -795,13 +794,7 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
|
||||
/**
|
||||
* Recovery status of an incomplete rolling pool update: run and per-host
|
||||
* step statuses, last error, pinned VMs still halted, VMs the update could
|
||||
* not migrate back to their original host (`vmConflicts`), hosts a resume
|
||||
* added to the plan because of patches released since the run started or
|
||||
* because they joined the pool since (`planChange`), what an operator
|
||||
* changed since: settings the update left changed, hosts, VMs or backup
|
||||
* schedules of the update removed, which block its resume until accepted
|
||||
* (`operatorChanges`). 404 when the last
|
||||
* step statuses, last error, pinned VMs still halted. 404 when the last
|
||||
* rolling pool update completed successfully (no recovery needed), or when
|
||||
* the pool's master does not run XCP-ng or XenServer 8.4+ (no recovery
|
||||
* record is kept for those pools).
|
||||
@@ -827,20 +820,12 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the record of an incomplete rolling pool update.
|
||||
* Close the record of an incomplete rolling pool update, once the pool has been reviewed.
|
||||
*
|
||||
* What the update changed and did not restore is restored first, best effort: disabled hosts are enabled, halted
|
||||
* pinned VMs are started, displaced VMs are migrated back to their host, and HA, auto power-on, WLB, the load
|
||||
* balancer and the backup schedules are enabled again. The record is closed once nothing is left but VMs which could
|
||||
* not be migrated back: they do not keep the call refused.
|
||||
*
|
||||
* A host which was updated and not rebooted is left disabled, without its VMs: it keeps the call refused, resuming
|
||||
* the update is what finishes it.
|
||||
*
|
||||
* Refused with an `incorrect state` error listing what could not be restored while any other item remains, or when
|
||||
* the record cannot be read: the record is kept. Refused with a `forbidden operation` error while a backup runs or
|
||||
* may run on the pool and VMs are left to migrate back. Set `force` to `true` to close it anyway: the items are
|
||||
* abandoned and listed in the task, nothing is restored nor changed in the pool. 404 when the pool has no record.
|
||||
* Refused with an `incorrect state` error listing what the update changed and did not restore (HA, auto power-on,
|
||||
* WLB, load balancer, backup schedules, disabled hosts, displaced or halted VMs) while any item remains, or when
|
||||
* the record cannot be read. Displaced VMs alone do not refuse it, they are only listed in the task. Set `force` to `true` to close it anyway: the items are abandoned and listed in the
|
||||
* task, nothing is restored nor changed in the pool. 404 when the pool has no record.
|
||||
*
|
||||
* Required privilege:
|
||||
* - resource: pool, action: rolling-update
|
||||
@@ -880,64 +865,6 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume a failed or interrupted rolling pool update: the same run continues, the hosts with remaining work are
|
||||
* evacuated, updated and rebooted, and a host a previous attempt finished is updated and rebooted again if patches
|
||||
* were released since. Then the VMs are migrated back to the host they were on before the first attempt. The settings the previous attempts left disabled (HA, auto power on, backup schedules, WLB, load
|
||||
* balancer) stay disabled until the end of the run, then are restored.
|
||||
*
|
||||
* The backup check is not taken from the previous attempts: set `bypassBackupCheck` again if needed.
|
||||
*
|
||||
* 404 when the pool has no record. Refused with an `incorrect state` error when the update is neither failed,
|
||||
* interrupted nor awaiting acceptance.
|
||||
*
|
||||
* When an operator changed a setting the update left changed (HA, auto power on, WLB or a backup schedule enabled
|
||||
* again, a heartbeat SR of HA deleted) or removed a host, a VM or a backup schedule of the update, the update goes
|
||||
* to `awaiting-acceptance` and the resume is refused with an `incorrect state` error on `operatorChanges` listing
|
||||
* them. Set
|
||||
* `acceptOperatorChanges` to keep them: the update starts from the current state, as a new one would. A setting
|
||||
* enabled again is disabled while the update runs and enabled again at its end, HA whose heartbeat SR was deleted
|
||||
* stays disabled, and the removed hosts and VMs are left out.
|
||||
*
|
||||
* Required privilege:
|
||||
* - resource: pool, action: rolling-update
|
||||
*
|
||||
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
|
||||
* @example body { "bypassBackupCheck": false }
|
||||
*/
|
||||
@Example(taskLocation)
|
||||
@Extension('x-mcp-exposure', 'confirm')
|
||||
@Post('{id}/actions/resume_rolling_update')
|
||||
@Middlewares([json(), acl({ resource: 'pool', action: 'rolling-update', objectId: 'params.id' })])
|
||||
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
|
||||
@Response(noContentResp.status, noContentResp.description)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(featureUnauthorized.status, featureUnauthorized.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(incorrectStateResp.status, incorrectStateResp.description)
|
||||
resumeRollingUpdate(
|
||||
@Path() id: string,
|
||||
@Body() body?: ResumeRollingUpdateBody,
|
||||
@Query() sync?: boolean
|
||||
): CreateActionReturnType<void> {
|
||||
const poolId = id as XoPool['id']
|
||||
const action = async (task: VatesTask) => {
|
||||
const pool = this.getObject(poolId)
|
||||
await this.restApi.xoApp.resumeRollingPoolUpdate(pool, { ...body, parentTask: task })
|
||||
}
|
||||
|
||||
return this.createAction<void>(action, {
|
||||
sync,
|
||||
statusCode: noContentResp.status,
|
||||
taskProperties: {
|
||||
name: 'resume rolling pool update',
|
||||
objectId: poolId,
|
||||
params: body,
|
||||
progress: 0,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all messages that match the following privilege:
|
||||
* - resource: message, action: read
|
||||
|
||||
@@ -22,7 +22,6 @@ function createController({ v2vService = {} }: { v2vService?: object } = {}) {
|
||||
tasks: { create: (properties: unknown) => ({ id: 'task-1', properties, run: (fn: () => unknown) => fn() }) },
|
||||
xoApp: {
|
||||
finalizeRollingUpdate: record('finalizeRollingUpdate'),
|
||||
resumeRollingPoolUpdate: record('resumeRollingPoolUpdate'),
|
||||
rollingPoolReboot: record('rollingPoolReboot'),
|
||||
rollingPoolUpdate: record('rollingPoolUpdate'),
|
||||
},
|
||||
@@ -59,22 +58,6 @@ for (const [method, orchestrator] of [
|
||||
})
|
||||
}
|
||||
|
||||
describe('PoolController.resumeRollingUpdate', () => {
|
||||
it('forwards bypassBackupCheck and acceptOperatorChanges from the body to the orchestrator', async () => {
|
||||
const { calls, controller } = createController()
|
||||
|
||||
await controller.resumeRollingUpdate('pool-1', undefined, true)
|
||||
await controller.resumeRollingUpdate('pool-1', { bypassBackupCheck: true }, true)
|
||||
await controller.resumeRollingUpdate('pool-1', { acceptOperatorChanges: true }, true)
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
{ orchestrator: 'resumeRollingPoolUpdate', parentTask: 'task-1' },
|
||||
{ orchestrator: 'resumeRollingPoolUpdate', parentTask: 'task-1', bypassBackupCheck: true },
|
||||
{ orchestrator: 'resumeRollingPoolUpdate', parentTask: 'task-1', acceptOperatorChanges: true },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('PoolController.finalizeRollingUpdate', () => {
|
||||
it('forwards force from the body to the orchestrator', async () => {
|
||||
const { calls, controller } = createController()
|
||||
|
||||
@@ -151,22 +151,12 @@ export type RollingPoolActionBody = {
|
||||
|
||||
export type FinalizeRollingUpdateBody = {
|
||||
/**
|
||||
* Close the record without restoring what the update left unrestored, or when its record cannot be read: the items
|
||||
* are abandoned and listed in the task, nothing is restored nor changed in the pool. Defaults to false.
|
||||
* Close the record even though the update left items unrestored, or its record cannot be read: they are abandoned
|
||||
* and listed in the task, nothing is restored nor changed in the pool. Defaults to false.
|
||||
*/
|
||||
force?: boolean
|
||||
}
|
||||
|
||||
export type ResumeRollingUpdateBody = {
|
||||
/**
|
||||
* Keep what an operator changed since the update: the update starts from the current state, as a new one would.
|
||||
* Without it, such changes block the update. Defaults to false.
|
||||
*/
|
||||
acceptOperatorChanges?: boolean
|
||||
/** Skip the backup safety check before rebooting the hosts, asked again on each resume. Defaults to false. */
|
||||
bypassBackupCheck?: boolean
|
||||
}
|
||||
|
||||
export type RollingPoolUpdateBody = RollingPoolActionBody & {
|
||||
/**
|
||||
* Start the update even though the master is already up to date while another host is not, ie from a pool left
|
||||
|
||||
@@ -1,59 +1,22 @@
|
||||
import {
|
||||
Body,
|
||||
Example,
|
||||
Extension,
|
||||
Get,
|
||||
Middlewares,
|
||||
Patch,
|
||||
Path,
|
||||
Query,
|
||||
Request,
|
||||
Response,
|
||||
Route,
|
||||
Security,
|
||||
SuccessResponse,
|
||||
Tags,
|
||||
} from 'tsoa'
|
||||
import { Example, Extension, Get, Middlewares, Path, Query, Request, Response, Route, Security, Tags } from 'tsoa'
|
||||
import { inject } from 'inversify'
|
||||
import { json } from 'express'
|
||||
import { provide } from 'inversify-binding-decorators'
|
||||
import type { Request as ExRequest } from 'express'
|
||||
import type { XoProxy, XoVm } from '@vates/types'
|
||||
import { forbiddenOperation } from 'xo-common/api-errors.js'
|
||||
import type { XoProxy } from '@vates/types'
|
||||
|
||||
import { acl, actionFromBody } from '../middlewares/acl.middleware.mjs'
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
import { acl } from '../middlewares/acl.middleware.mjs'
|
||||
import {
|
||||
badRequestResp,
|
||||
forbiddenOperationResp,
|
||||
internalServerErrorResp,
|
||||
invalidParameters,
|
||||
noContentResp,
|
||||
notFoundResp,
|
||||
proxyUnreachableResp,
|
||||
unauthorizedResp,
|
||||
type Unbrand,
|
||||
} from '../open-api/common/response.common.mjs'
|
||||
import { partialProxies, proxy, proxyHealth, proxyIds } from '../open-api/oa-examples/proxy.oa-example.mjs'
|
||||
import { partialProxies, proxy, proxyIds } from '../open-api/oa-examples/proxy.oa-example.mjs'
|
||||
import type { SendObjects } from '../helpers/helper.type.mjs'
|
||||
import { XoController } from '../abstract-classes/xo-controller.mjs'
|
||||
import { RestApi } from '../rest-api/rest-api.mjs'
|
||||
|
||||
function isProxyUnreachable(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'PROXY_UNREACHABLE'
|
||||
}
|
||||
|
||||
async function callProxy<T>(call: Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await call
|
||||
} catch (error) {
|
||||
if (isProxyUnreachable(error)) {
|
||||
throw new ApiError(proxyUnreachableResp.description, proxyUnreachableResp.status)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@Route('proxies')
|
||||
@Security('*')
|
||||
@Response(badRequestResp.status, badRequestResp.description)
|
||||
@@ -122,83 +85,4 @@ export class ProxyController extends XoController<XoProxy> {
|
||||
getProxy(@Path() id: string): Promise<Unbrand<XoProxy>> {
|
||||
return this.getObject(id as XoProxy['id'])
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the proxy can be reached
|
||||
*
|
||||
* Required privilege:
|
||||
* - resource: proxy, action: read
|
||||
*
|
||||
* @example id "e625ea0c-a876-405a-b838-109d762efe88"
|
||||
*/
|
||||
@Example(proxyHealth)
|
||||
@Extension('x-mcp-exposure', 'allow')
|
||||
@Get('{id}/health')
|
||||
@Middlewares(
|
||||
acl({
|
||||
resource: 'proxy',
|
||||
action: 'read',
|
||||
objectId: 'params.id',
|
||||
getObject: ({ restApi }) => restApi.xoApp.getProxy,
|
||||
})
|
||||
)
|
||||
@SuccessResponse(200, 'OK')
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
@Response(proxyUnreachableResp.status, proxyUnreachableResp.description)
|
||||
async getProxyHealth(@Path() id: string): Promise<{ success: true }> {
|
||||
await callProxy(this.restApi.xoApp.checkProxyHealth(id as XoProxy['id']))
|
||||
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a proxy
|
||||
*
|
||||
* Set `address` or `vmUuid` to `null` to remove it.
|
||||
*
|
||||
* Only an administrator can change `address` or `vmUuid`
|
||||
*
|
||||
* Required privileges:
|
||||
* - resource: proxy, action: update (grants all fields)
|
||||
* - resource: proxy, action: update:name (if name is passed)
|
||||
*
|
||||
* @example id "e625ea0c-a876-405a-b838-109d762efe88"
|
||||
* @example body { "name": "My proxy" }
|
||||
*/
|
||||
@Extension('x-mcp-exposure', 'confirm')
|
||||
@Patch('{id}')
|
||||
@Middlewares([
|
||||
json(),
|
||||
acl({
|
||||
resource: 'proxy',
|
||||
action: actionFromBody<'proxy'>('update:name'),
|
||||
objectId: 'params.id',
|
||||
getObject: ({ restApi }) => restApi.xoApp.getProxy,
|
||||
}),
|
||||
])
|
||||
@SuccessResponse(noContentResp.status, noContentResp.description)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(invalidParameters.status, invalidParameters.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
async updateProxy(
|
||||
@Path() id: string,
|
||||
@Body() body: { address?: string | null; name?: string; vmUuid?: string | null }
|
||||
): Promise<void> {
|
||||
const user = this.restApi.getCurrentUser()
|
||||
if (user.permission !== 'admin' && (body.address !== undefined || body.vmUuid !== undefined)) {
|
||||
throw forbiddenOperation('update proxy', 'only an administrator can change address or vmUuid')
|
||||
}
|
||||
|
||||
if (typeof body.vmUuid === 'string') {
|
||||
this.restApi.getObject<XoVm>(body.vmUuid as XoVm['id'], 'VM')
|
||||
}
|
||||
|
||||
await this.restApi.xoApp.updateProxy(id as XoProxy['id'], {
|
||||
...body,
|
||||
vmUuid: body.vmUuid as XoVm['id'] | null | undefined,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { forbiddenOperation } from 'xo-common/api-errors.js'
|
||||
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
import { ProxyController } from './proxy.controller.mjs'
|
||||
import type { RestApi } from '../rest-api/rest-api.mjs'
|
||||
|
||||
function createController(checkProxyHealth: (id: string) => Promise<void>) {
|
||||
const calls: unknown[] = []
|
||||
const restApi = {
|
||||
xoApp: {
|
||||
checkProxyHealth: async (id: string) => {
|
||||
calls.push(['checkProxyHealth', id])
|
||||
return checkProxyHealth(id)
|
||||
},
|
||||
},
|
||||
} as unknown as RestApi
|
||||
const controller = new ProxyController(restApi)
|
||||
return { calls, controller }
|
||||
}
|
||||
|
||||
const proxyId = 'e625ea0c-a876-405a-b838-109d762efe88'
|
||||
|
||||
describe('ProxyController.getProxyHealth', () => {
|
||||
it('forwards the id and returns success when the proxy is reachable', async () => {
|
||||
const { calls, controller } = createController(async () => {})
|
||||
|
||||
assert.deepEqual(await controller.getProxyHealth(proxyId), { success: true })
|
||||
assert.deepEqual(calls, [['checkProxyHealth', proxyId]])
|
||||
})
|
||||
|
||||
it('throws a 502 ApiError when the proxy is unreachable', async () => {
|
||||
const { controller } = createController(async () => {
|
||||
throw Object.assign(new TypeError('fetch failed'), { code: 'PROXY_UNREACHABLE' })
|
||||
})
|
||||
|
||||
await assert.rejects(
|
||||
controller.getProxyHealth(proxyId),
|
||||
error => error instanceof ApiError && error.status === 502 && error.message === 'Proxy unreachable'
|
||||
)
|
||||
})
|
||||
|
||||
it('rethrows unrelated errors unchanged', async () => {
|
||||
const unrelatedError = new Error('500 Internal Server Error')
|
||||
const { controller } = createController(async () => {
|
||||
throw unrelatedError
|
||||
})
|
||||
|
||||
await assert.rejects(controller.getProxyHealth(proxyId), error => error === unrelatedError)
|
||||
})
|
||||
})
|
||||
|
||||
const vmUuid = '3d0c7bd6-8b7e-4b2a-9c1f-6f0e5d4c3b2a'
|
||||
|
||||
function createUpdateController({ permission = 'admin' }: { permission?: string } = {}) {
|
||||
const calls: unknown[] = []
|
||||
const restApi = {
|
||||
getCurrentUser: () => ({ id: 'user-id', permission }),
|
||||
getObject: (...args: unknown[]) => {
|
||||
calls.push(['getObject', ...args])
|
||||
},
|
||||
xoApp: {
|
||||
updateProxy: async (...args: unknown[]) => {
|
||||
calls.push(['updateProxy', ...args])
|
||||
},
|
||||
},
|
||||
} as unknown as RestApi
|
||||
const controller = new ProxyController(restApi)
|
||||
return { calls, controller }
|
||||
}
|
||||
|
||||
describe('ProxyController.updateProxy', () => {
|
||||
it('forwards the body to updateProxy after checking the VM exists', async () => {
|
||||
const { calls, controller } = createUpdateController()
|
||||
const body = { address: '192.168.1.10:443', name: 'My proxy', vmUuid }
|
||||
|
||||
await controller.updateProxy(proxyId, body)
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
['getObject', vmUuid, 'VM'],
|
||||
['updateProxy', proxyId, body],
|
||||
])
|
||||
})
|
||||
|
||||
it('forwards null to remove address or vmUuid', async () => {
|
||||
const { calls, controller } = createUpdateController()
|
||||
|
||||
await controller.updateProxy(proxyId, { address: null, vmUuid: null })
|
||||
|
||||
assert.deepEqual(calls, [['updateProxy', proxyId, { address: null, vmUuid: null }]])
|
||||
})
|
||||
|
||||
it('lets a non-admin change the name', async () => {
|
||||
const { calls, controller } = createUpdateController({ permission: 'none' })
|
||||
|
||||
await controller.updateProxy(proxyId, { name: 'My proxy' })
|
||||
|
||||
assert.deepEqual(calls, [['updateProxy', proxyId, { name: 'My proxy', vmUuid: undefined }]])
|
||||
})
|
||||
|
||||
for (const body of [{ address: 'attacker:443' }, { address: null }, { vmUuid }, { vmUuid: null }]) {
|
||||
it(`refuses ${JSON.stringify(body)} to a non-admin`, async () => {
|
||||
const { calls, controller } = createUpdateController({ permission: 'none' })
|
||||
|
||||
await assert.rejects(controller.updateProxy(proxyId, { name: 'My proxy', ...body }), error =>
|
||||
forbiddenOperation.is(error)
|
||||
)
|
||||
assert.deepEqual(calls, [])
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -23,7 +23,7 @@ import type { XenApiVdi, XoMessage, XoTask, XoVdi, XoAlarm, XoSr } from '@vates/
|
||||
import { SUPPORTED_VDI_FORMAT } from '@vates/types'
|
||||
import { acl } from '../middlewares/acl.middleware.mjs'
|
||||
import { AlarmService } from '../alarms/alarm.service.mjs'
|
||||
import { BASE_URL, escapeUnsafeComplexMatcher, getFileNameFromUrl } from '../helpers/utils.helper.mjs'
|
||||
import { BASE_URL, escapeUnsafeComplexMatcher } from '../helpers/utils.helper.mjs'
|
||||
import { genericAlarmsExample } from '../open-api/oa-examples/alarm.oa-example.mjs'
|
||||
import {
|
||||
asynchronousActionResp,
|
||||
@@ -46,7 +46,7 @@ import { XapiXoController } from '../abstract-classes/xapi-xo-controller.mjs'
|
||||
import { messageIds, partialMessages } from '../open-api/oa-examples/message.oa-example.mjs'
|
||||
import { taskIds, partialTasks, taskLocation } from '../open-api/oa-examples/task.oa-example.mjs'
|
||||
import type { CreateActionReturnType } from '../abstract-classes/base-controller.mjs'
|
||||
import { SrService, type CreateSrBody, type ImportVdiFromUrlBody } from './sr.service.mjs'
|
||||
import { SrService, type CreateSrBody } from './sr.service.mjs'
|
||||
|
||||
@Route('srs')
|
||||
@Security('*')
|
||||
@@ -182,7 +182,7 @@ export class SrController extends XapiXoController<XoSr> {
|
||||
* Import an exported VDI
|
||||
*
|
||||
* Required privilege:
|
||||
* - resource: sr, action: import:vdi:upload
|
||||
* - resource: sr, action: import:vdi
|
||||
*
|
||||
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
|
||||
* @example name_label "VDI_foo_import"
|
||||
@@ -192,7 +192,7 @@ export class SrController extends XapiXoController<XoSr> {
|
||||
@Example(vdiId)
|
||||
@Extension('x-mcp-exposure', 'confirm')
|
||||
@Post('{id}/vdis')
|
||||
@Middlewares(acl({ resource: 'sr', action: 'import:vdi:upload', objectId: 'params.id' }))
|
||||
@Middlewares(acl({ resource: 'sr', action: 'import:vdi', objectId: 'params.id' }))
|
||||
@Tags('vdis')
|
||||
@SuccessResponse(createdResp.status, 'VDI imported')
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@@ -440,69 +440,4 @@ export class SrController extends XapiXoController<XoSr> {
|
||||
async deleteSr(@Path() id: string): Promise<void> {
|
||||
await this.#srService.delete(id as XoSr['id'])
|
||||
}
|
||||
|
||||
/**
|
||||
* Import a VDI from a URL
|
||||
*
|
||||
* The XO server fetches the URL and streams its content straight to the SR, without storing it on the XO server.
|
||||
*
|
||||
* Requirements:
|
||||
* - The URL must be reachable by the XO server.
|
||||
* - The URL must use `http` or `https`.
|
||||
* - The URL must not contain a username/password (`https://user:password@...`).
|
||||
* - The remote server must send a `Content-Length` header.
|
||||
*
|
||||
* Only ISO SRs are supported for now.
|
||||
*
|
||||
* Warning: The XO server sends a GET request to the given URL, whatever its address. It can reach internal
|
||||
* services, and the response can then be read by exporting the imported VDI.
|
||||
*
|
||||
* Required privilege:
|
||||
* - resource: sr, action: import:vdi:url
|
||||
*
|
||||
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
|
||||
* @example body { "url": "https://example.com/debian-13.iso", "name_label": "debian-13.iso", "name_description": "Debian 13 installer" }
|
||||
*/
|
||||
@Example(vdiId)
|
||||
@Extension('x-mcp-exposure', 'confirm')
|
||||
@Post('{id}/actions/import_vdi_from_url')
|
||||
@Middlewares([json(), acl({ resource: 'sr', action: 'import:vdi:url', objectId: 'params.id' })])
|
||||
@Tags('vdis')
|
||||
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
|
||||
@Response(createdResp.status, 'VDI imported')
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(invalidParametersResp.status, invalidParametersResp.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
@Response(502, 'The remote server is unreachable or failed to provide the file')
|
||||
async srImportVdiFromUrl(
|
||||
@Path() id: string,
|
||||
@Body() body: ImportVdiFromUrlBody,
|
||||
@Query() sync?: boolean
|
||||
): CreateActionReturnType<{ id: Unbrand<XoVdi>['id'] }> {
|
||||
const srId = id as XoSr['id']
|
||||
// checked before creating the task, so that invalid parameters are rejected with a 422 even when not `sync`
|
||||
const url = this.#srService.validateImportVdiFromUrl(srId, body.url)
|
||||
|
||||
const action = async () => {
|
||||
const vdiId = await this.#srService.importVdiFromUrl(srId, url, body)
|
||||
|
||||
if (sync) {
|
||||
this.setHeader('Location', `${BASE_URL}/vdis/${vdiId}`)
|
||||
}
|
||||
return { id: vdiId }
|
||||
}
|
||||
|
||||
return this.createAction<{ id: XoVdi['id'] }>(action, {
|
||||
sync,
|
||||
statusCode: createdResp.status,
|
||||
taskProperties: {
|
||||
name: 'import VDI from URL',
|
||||
objectId: srId,
|
||||
// the full URL can contain secrets (e.g. `?token=…`) and tasks are readable with `task: read`,
|
||||
// only keep its origin and the name of the downloaded file
|
||||
params: { ...body, url: url.origin, fileName: getFileNameFromUrl(url) },
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { Readable } from 'node:stream'
|
||||
import { SUPPORTED_VDI_FORMAT } from '@vates/types'
|
||||
import type { Xapi, XenApiVdi, XenApiSr, XoHost, XoSr, XoVdi } from '@vates/types'
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
import type { Xapi, XenApiSr, XoHost, XoSr } from '@vates/types'
|
||||
import type { RestApi } from '../rest-api/rest-api.mjs'
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
import { LicenseService } from '../licenses/license.service.mjs'
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
import { getFileNameFromUrl } from '../helpers/utils.helper.mjs'
|
||||
|
||||
// Derived from `xapi.SR_create` params, renamed to stay consistent with the XO SR
|
||||
// representation returned by `GET /srs/:id`: `hostId` (XO id, not XAPI ref),
|
||||
@@ -17,13 +13,6 @@ export type CreateSrBody = Omit<Parameters<Xapi['SR_create']>[0], 'host' | 'type
|
||||
size?: number
|
||||
}
|
||||
|
||||
export type ImportVdiFromUrlBody = {
|
||||
url: string
|
||||
/** Defaults to the file name in the URL */
|
||||
name_label?: string
|
||||
name_description?: string
|
||||
}
|
||||
|
||||
// SR types backed by network/SAN storage, every other type is local to the host
|
||||
const SHARED_SR_TYPES: ReadonlySet<XoSr['SR_type']> = new Set([
|
||||
'cephfs',
|
||||
@@ -89,92 +78,4 @@ export class SrService {
|
||||
await xapi.destroySr(id)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the parameters of `importVdiFromUrl`, without any download, so that they can be rejected before
|
||||
* creating a task
|
||||
*/
|
||||
validateImportVdiFromUrl(id: XoSr['id'], urlString: string): URL {
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(urlString)
|
||||
} catch {
|
||||
throw invalidParameters('invalid URL')
|
||||
}
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
||||
throw invalidParameters(`unsupported protocol ${url.protocol}, expected http: or https:`)
|
||||
}
|
||||
// rejected by `fetch` anyway
|
||||
if (url.username !== '' || url.password !== '') {
|
||||
throw invalidParameters('credentials in the URL are not supported')
|
||||
}
|
||||
|
||||
const xapiSr = this.#restApi.getXapiObject<XoSr>(id, 'SR')
|
||||
|
||||
// XO ISO libraries (local, NFS, SMB) are all created with type and content_type `iso`,
|
||||
// this excludes the XCP-ng tools SR and the DVD drives SR (type `udev`)
|
||||
if (xapiSr.content_type !== 'iso' || xapiSr.type !== 'iso' || xapiSr.is_tools_sr) {
|
||||
throw invalidParameters(`SR ${id} is not an ISO SR`)
|
||||
}
|
||||
|
||||
return url
|
||||
}
|
||||
|
||||
/**
|
||||
* `url` must have been checked with `validateImportVdiFromUrl`
|
||||
*/
|
||||
async importVdiFromUrl(
|
||||
id: XoSr['id'],
|
||||
url: URL,
|
||||
{ name_label, name_description }: Omit<ImportVdiFromUrlBody, 'url'>
|
||||
): Promise<XoVdi['id']> {
|
||||
// never put the full URL in errors, it can contain secrets
|
||||
const { origin } = url
|
||||
|
||||
const xapiSr = this.#restApi.getXapiObject<XoSr>(id, 'SR')
|
||||
const xapi = xapiSr.$xapi
|
||||
|
||||
let response: Response
|
||||
try {
|
||||
// `fetch` transparently decompresses gzip, but `Content-Length` would still be the compressed size
|
||||
response = await fetch(url, { headers: { 'accept-encoding': 'identity' } })
|
||||
} catch (error) {
|
||||
// the remote server is unreachable (DNS, connection refused, TLS…)
|
||||
throw new ApiError(`failed to download ${origin}`, 502)
|
||||
}
|
||||
// the failures below come from the remote server, not from XO nor from the caller: 502 Bad Gateway
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel() // free the socket
|
||||
throw new ApiError(`failed to download ${origin}: ${response.status} ${response.statusText}`, 502)
|
||||
}
|
||||
if (response.body === null) {
|
||||
throw new ApiError(`failed to download ${origin}: empty response body`, 502)
|
||||
}
|
||||
|
||||
// raw imports need the size of the VDI before reading the stream
|
||||
const contentLength = response.headers.get('content-length')
|
||||
if (contentLength === null) {
|
||||
await response.body.cancel()
|
||||
throw new ApiError(`the remote server did not provide a Content-Length for ${origin}`, 502)
|
||||
}
|
||||
|
||||
const stream: Readable & { length?: number } = Readable.fromWeb(response.body)
|
||||
stream.length = +contentLength
|
||||
|
||||
let vdiRef: XenApiVdi['$ref']
|
||||
try {
|
||||
vdiRef = await xapi.SR_importVdi(xapiSr.$ref, stream, {
|
||||
format: SUPPORTED_VDI_FORMAT.raw,
|
||||
name_label: name_label ?? getFileNameFromUrl(url),
|
||||
name_description,
|
||||
})
|
||||
} catch (error) {
|
||||
// the import can fail before reading the stream (e.g. `VDI.create` fails), close the download
|
||||
stream.destroy()
|
||||
throw error
|
||||
}
|
||||
const vdiId = await xapi.getField<XenApiVdi, 'uuid'>('VDI', vdiRef, 'uuid')
|
||||
|
||||
return vdiId as XoVdi['id']
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import type { Readable } from 'node:stream'
|
||||
import { SUPPORTED_VDI_FORMAT, type XoSr } from '@vates/types'
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
|
||||
import { SrService, type CreateSrBody } from './sr.service.mjs'
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
@@ -122,240 +119,3 @@ describe('SrService.create', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('SrService.validateImportVdiFromUrl and SrService.importVdiFromUrl', () => {
|
||||
const SR_ID = 'sr-uuid' as XoSr['id']
|
||||
const ISO_SR = { content_type: 'iso', type: 'iso', is_tools_sr: false }
|
||||
|
||||
// returns the service and the calls made to XAPI
|
||||
function setup(srRecord: Record<string, unknown> = ISO_SR, { importError }: { importError?: Error } = {}) {
|
||||
const calls = {
|
||||
getXapiObject: [] as unknown[][],
|
||||
SR_importVdi: [] as unknown[][],
|
||||
getField: [] as unknown[][],
|
||||
}
|
||||
const fakeXapi = {
|
||||
SR_importVdi: async (...args: unknown[]) => {
|
||||
calls.SR_importVdi.push(args)
|
||||
if (importError !== undefined) {
|
||||
throw importError
|
||||
}
|
||||
return 'OpaqueRef:new-vdi'
|
||||
},
|
||||
getField: async (...args: unknown[]) => {
|
||||
calls.getField.push(args)
|
||||
return 'vdi-uuid-123'
|
||||
},
|
||||
}
|
||||
const restApi = {
|
||||
getXapiObject: (...args: unknown[]) => {
|
||||
calls.getXapiObject.push(args)
|
||||
return { ...srRecord, $ref: 'OpaqueRef:sr-1', $xapi: fakeXapi }
|
||||
},
|
||||
} as unknown as RestApi
|
||||
|
||||
return { calls, service: new SrService(restApi) }
|
||||
}
|
||||
|
||||
// a response whose body records whether it has been cancelled
|
||||
function createResponse({ status = 200, headers = {} }: { status?: number; headers?: Record<string, string> } = {}) {
|
||||
const body = { cancelled: false }
|
||||
const response = new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode('iso'))
|
||||
controller.close()
|
||||
},
|
||||
cancel() {
|
||||
body.cancelled = true
|
||||
},
|
||||
}),
|
||||
{ status, headers }
|
||||
)
|
||||
return { body, response }
|
||||
}
|
||||
|
||||
const isInvalidParameters = (error: unknown) => invalidParameters.is(error)
|
||||
const isBadGateway = (error: unknown): error is ApiError => error instanceof ApiError && error.status === 502
|
||||
|
||||
it('imports the URL content as a raw VDI in the ISO SR and returns the VDI uuid', async t => {
|
||||
const { response } = createResponse({ headers: { 'content-length': '3' } })
|
||||
const fetchMock = t.mock.method(globalThis, 'fetch', async () => response)
|
||||
const { calls, service } = setup()
|
||||
|
||||
const id = await service.importVdiFromUrl(SR_ID, new URL('https://example.net/isos/debian-13.iso'), {
|
||||
name_label: 'Debian',
|
||||
name_description: 'installer',
|
||||
})
|
||||
|
||||
assert.deepEqual(calls.getXapiObject, [[SR_ID, 'SR']])
|
||||
assert.equal(fetchMock.mock.callCount(), 1)
|
||||
const [fetchUrl, fetchInit] = fetchMock.mock.calls[0].arguments as [URL, RequestInit]
|
||||
assert.equal(String(fetchUrl), 'https://example.net/isos/debian-13.iso')
|
||||
// no transparent decompression, so that Content-Length matches the received data
|
||||
assert.deepEqual(fetchInit.headers, { 'accept-encoding': 'identity' })
|
||||
|
||||
assert.equal(calls.SR_importVdi.length, 1)
|
||||
const [srRef, stream, opts] = calls.SR_importVdi[0] as [string, Readable & { length?: number }, unknown]
|
||||
assert.equal(srRef, 'OpaqueRef:sr-1')
|
||||
// the size of a raw VDI comes from the Content-Length header
|
||||
assert.equal(stream.length, 3)
|
||||
assert.deepEqual(opts, {
|
||||
format: SUPPORTED_VDI_FORMAT.raw,
|
||||
name_label: 'Debian',
|
||||
name_description: 'installer',
|
||||
})
|
||||
|
||||
assert.deepEqual(calls.getField, [['VDI', 'OpaqueRef:new-vdi', 'uuid']])
|
||||
assert.equal(id, 'vdi-uuid-123')
|
||||
})
|
||||
|
||||
it('defaults name_label to the decoded file name of the URL', async t => {
|
||||
const { response } = createResponse({ headers: { 'content-length': '3' } })
|
||||
t.mock.method(globalThis, 'fetch', async () => response)
|
||||
const { calls, service } = setup()
|
||||
|
||||
await service.importVdiFromUrl(SR_ID, new URL('https://example.net/isos/my%20distro.iso?token=abc'), {})
|
||||
|
||||
const opts = calls.SR_importVdi[0][2] as { name_label: string }
|
||||
assert.equal(opts.name_label, 'my distro.iso')
|
||||
})
|
||||
|
||||
for (const [description, url] of [
|
||||
['an invalid URL', 'not a url'],
|
||||
['a non HTTP(S) URL', 'ftp://example.net/debian.iso'],
|
||||
['a file URL', 'file:///etc/passwd'],
|
||||
['a URL with credentials', 'https://alice:s3cret@example.net/debian.iso'],
|
||||
['a URL with a username only', 'https://alice@example.net/debian.iso'],
|
||||
]) {
|
||||
it(`rejects ${description} with invalid parameters, before looking up the SR`, () => {
|
||||
const { calls, service } = setup()
|
||||
|
||||
assert.throws(() => service.validateImportVdiFromUrl(SR_ID, url), isInvalidParameters)
|
||||
assert.equal(calls.getXapiObject.length, 0)
|
||||
})
|
||||
}
|
||||
|
||||
for (const [description, srRecord] of [
|
||||
['a VM SR', { content_type: 'user', type: 'nfs', is_tools_sr: false }],
|
||||
['the XCP-ng tools SR', { content_type: 'iso', type: 'iso', is_tools_sr: true }],
|
||||
['the DVD drives SR', { content_type: 'iso', type: 'udev', is_tools_sr: false }],
|
||||
] as const) {
|
||||
it(`rejects ${description} with invalid parameters`, () => {
|
||||
const { service } = setup(srRecord)
|
||||
|
||||
assert.throws(
|
||||
() => service.validateImportVdiFromUrl(SR_ID, 'https://example.net/debian.iso'),
|
||||
isInvalidParameters
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
it('returns the parsed URL for an HTTP(S) URL and an ISO SR, without any download', t => {
|
||||
const fetchMock = t.mock.method(globalThis, 'fetch', async () => createResponse().response)
|
||||
const { calls, service } = setup()
|
||||
|
||||
const url = service.validateImportVdiFromUrl(SR_ID, 'https://example.net/isos/debian-13.iso?token=abc')
|
||||
|
||||
assert.ok(url instanceof URL)
|
||||
assert.equal(url.href, 'https://example.net/isos/debian-13.iso?token=abc')
|
||||
assert.deepEqual(calls.getXapiObject, [[SR_ID, 'SR']])
|
||||
assert.equal(fetchMock.mock.callCount(), 0)
|
||||
})
|
||||
|
||||
it('rejects with 502 when the remote server returns an error, and frees the response body', async t => {
|
||||
const { body, response } = createResponse({ status: 404 })
|
||||
t.mock.method(globalThis, 'fetch', async () => response)
|
||||
const { calls, service } = setup()
|
||||
|
||||
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL('https://example.net/missing.iso'), {}), error => {
|
||||
assert.ok(isBadGateway(error))
|
||||
assert.match((error as Error).message, /404/)
|
||||
return true
|
||||
})
|
||||
assert.equal(body.cancelled, true)
|
||||
assert.equal(calls.SR_importVdi.length, 0)
|
||||
})
|
||||
|
||||
it('rejects with 502 when the download cannot start, keeping the URL origin', async t => {
|
||||
const networkError = new TypeError('fetch failed', { cause: new Error('getaddrinfo ENOTFOUND example.net') })
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
throw networkError
|
||||
})
|
||||
const { calls, service } = setup()
|
||||
|
||||
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL('https://example.net/debian.iso'), {}), error => {
|
||||
assert.ok(isBadGateway(error))
|
||||
assert.match(error.message, /https:\/\/example\.net/)
|
||||
return true
|
||||
})
|
||||
assert.equal(calls.SR_importVdi.length, 0)
|
||||
})
|
||||
|
||||
it('closes the download when the import fails', async t => {
|
||||
const { response } = createResponse({ headers: { 'content-length': '3' } })
|
||||
t.mock.method(globalThis, 'fetch', async () => response)
|
||||
const importError = new Error('VDI.create failed')
|
||||
const { calls, service } = setup(ISO_SR, { importError })
|
||||
|
||||
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL('https://example.net/debian.iso'), {}), importError)
|
||||
const stream = calls.SR_importVdi[0][1] as Readable
|
||||
assert.equal(stream.destroyed, true)
|
||||
})
|
||||
|
||||
it('rejects with 502 when there is no Content-Length, and frees the response body', async t => {
|
||||
const { body, response } = createResponse()
|
||||
t.mock.method(globalThis, 'fetch', async () => response)
|
||||
const { calls, service } = setup()
|
||||
|
||||
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL('https://example.net/debian.iso'), {}), isBadGateway)
|
||||
assert.equal(body.cancelled, true)
|
||||
assert.equal(calls.SR_importVdi.length, 0)
|
||||
})
|
||||
|
||||
it('rejects with 502 when the response has no body', async t => {
|
||||
t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 200 }))
|
||||
const { calls, service } = setup()
|
||||
|
||||
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL('https://example.net/debian.iso'), {}), isBadGateway)
|
||||
assert.equal(calls.SR_importVdi.length, 0)
|
||||
})
|
||||
|
||||
describe('never leaks the full URL, which can contain a secret, in errors', () => {
|
||||
const SECRET_URL = 'https://example.net/isos/debian.iso?token=s3cret'
|
||||
const assertNoSecret = (error: unknown) => {
|
||||
const { message } = error as Error
|
||||
assert.doesNotMatch(message, /s3cret|debian\.iso/)
|
||||
return true
|
||||
}
|
||||
|
||||
it('when the remote server returns an error', async t => {
|
||||
t.mock.method(globalThis, 'fetch', async () => createResponse({ status: 403 }).response)
|
||||
const { service } = setup()
|
||||
|
||||
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL(SECRET_URL), {}), assertNoSecret)
|
||||
})
|
||||
|
||||
it('when the download cannot start', async t => {
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
throw new TypeError('fetch failed')
|
||||
})
|
||||
const { service } = setup()
|
||||
|
||||
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL(SECRET_URL), {}), assertNoSecret)
|
||||
})
|
||||
|
||||
it('when there is no Content-Length', async t => {
|
||||
t.mock.method(globalThis, 'fetch', async () => createResponse().response)
|
||||
const { service } = setup()
|
||||
|
||||
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL(SECRET_URL), {}), assertNoSecret)
|
||||
})
|
||||
|
||||
it('when the URL is invalid', () => {
|
||||
const { service } = setup()
|
||||
|
||||
assert.throws(() => service.validateImportVdiFromUrl(SR_ID, 'not a url?token=s3cret'), assertNoSecret)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -293,6 +293,7 @@ export class VdiController extends XapiXoController<XoVdi> {
|
||||
* Create an empty VDI.
|
||||
*
|
||||
* Required privileges:
|
||||
* - resource: sr, action: import:vdi (on the target SR)
|
||||
* - resource: vdi, action: create
|
||||
*
|
||||
* @example body { "srId": "c4284e12-37c9-7967-b9e8-83ef229c3e03", "virtual_size": 10737418240, "name_label": "test VDI" }
|
||||
@@ -300,7 +301,13 @@ export class VdiController extends XapiXoController<XoVdi> {
|
||||
@Example(vdiId)
|
||||
@Extension('x-mcp-exposure', 'confirm')
|
||||
@Post('')
|
||||
@Middlewares([json(), acl([{ resource: 'vdi', action: 'create', object: ({ req }) => req.body }])])
|
||||
@Middlewares([
|
||||
json(),
|
||||
acl([
|
||||
{ resource: 'sr', action: 'import:vdi', objectId: 'body.srId' },
|
||||
{ resource: 'vdi', action: 'create', object: ({ req }) => req.body },
|
||||
]),
|
||||
])
|
||||
@SuccessResponse(createdResp.status, createdResp.description)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
- [useItemCounter](../lib/composables/item-counter.composable.md)
|
||||
- [useRouteQuery](../lib/composables/route-query.composable.md)
|
||||
- [useTable](../lib/composables/table.composable.md)
|
||||
- [useTree](../lib/packages/tree/README.md)
|
||||
- [useTree](../lib/composables/tree.composable.md)
|
||||
|
||||
# Directives
|
||||
|
||||
|
||||
@@ -1,69 +1,20 @@
|
||||
# Tests
|
||||
|
||||
These pages hold the unit-testing conventions shared by `@xen-orchestra/web-core` and `@xen-orchestra/web` (XO 6). What only XO 6 has — its factories, its remote-resource mocks, its readers of app components, its pages — is in the [XO 6 test docs](../../web/docs/tests.md).
|
||||
Testing uses **Vitest 4** with a single `unit` project (see `vitest.config.ts`): every test matches `**/*.unit.test.ts` and runs on `happy-dom`, CLI-only, no browser. Conventions follow the [XO 6 test docs](../../web/docs/tests.md).
|
||||
|
||||
**Start with [Assert behavior, not implementation](./tests/assert-behavior.md)** — it is the rule the rest of this guide serves.
|
||||
|
||||
## Which package tests what
|
||||
|
||||
A behaviour is tested once, in the package that owns it:
|
||||
|
||||
- What a web-core component, composable, store or util does **on its own** — a select opening its options, a side panel opening on a selection, a store re-expanding on a resize — is tested in web-core.
|
||||
- An XO 6 test covers what the app decides, and asserts a state it sets on a web-core component through that component's props. A test still green once the app code is removed tests web-core: write it in web-core instead, when web-core has no test for that behaviour yet.
|
||||
|
||||
## What to test first in web-core
|
||||
|
||||
1. **Logic** — `lib/utils/*.util.ts`, `lib/composables/*.composable.ts`, `lib/packages/*`, `lib/stores/*`
|
||||
2. **`Vts*` building blocks with behaviour** — props, slots and variants → rendered output, emits, derived state (responsive classes, sorting, fallbacks)
|
||||
3. **`Ui*` components** — their real branches only (a conditional slot, a derived label), never their styling
|
||||
|
||||
Every component gets tests in the medium term; until then, a change to a component adds the tests of what it touches.
|
||||
|
||||
## Shared test helpers
|
||||
|
||||
| Helper kind | Lives in | Imported as |
|
||||
| --------------------------------------------------------------------------------------------- | ------------------------------ | -------------- |
|
||||
| Generic — knows only web-core components or Vue (`mountComposable`, `createGlobalTestConfig`) | `web-core/test/` | `@core-test/…` |
|
||||
| Domain-aware — knows an XO object, an XO 6 module, a remote resource | `@xen-orchestra/web/src/test/` | `@/test/…` |
|
||||
|
||||
XO 6 tests import the generic helpers through `@core-test` too, so a helper exists once for both packages: a generic one found in `src/test/` moves to `web-core/test/` when it is next touched. The exception is the mount config: XO 6 keeps its own `createGlobalTestConfig` in `src/test/`, which installs the app configuration (form validation, real routes) and takes options; its `mountComposable` runs the web-core one with that config, and its tests import those. Never add a domain-aware helper to web-core.
|
||||
|
||||
## Writing a test
|
||||
|
||||
- [Assert behavior, not implementation](./tests/assert-behavior.md) — the one rule that outranks the others
|
||||
- [File layout and structure](./tests/file-structure.md) — where a test lives, how it is named, how it is organized
|
||||
- [Setup: prefer helpers over `beforeEach`](./tests/setup-helpers.md) — local helpers, auto-unmount
|
||||
- [Mocking dependencies](./tests/mocking.md) — the typed `vi.mock` form (`mockModule` in XO 6), shared mock modules
|
||||
- [Testing pure utilities](./tests/testing-utilities.md) — `*.util.ts`, called directly
|
||||
- [Testing composables](./tests/testing-composables.md) — mounting in a Vue context, reactivity, `useI18n`
|
||||
- [Testing components](./tests/testing-components.md) — `mount`, querying rendered output, translations, what `happy-dom` cannot do
|
||||
|
||||
## Setup in web-core
|
||||
|
||||
Testing uses **Vitest 4** with a single `unit` project (see `vitest.config.ts`): every test matches `**/*.unit.test.ts` and runs on `happy-dom`, CLI-only, no browser.
|
||||
|
||||
| Path | Role |
|
||||
| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `vitest.config.ts` | Runner config: `vue` + `vue-i18n` plugins, `@core` / `@core-test` aliases, `globals: true` |
|
||||
| `test/setup.ts` | Global setup: auto-unmounts every mounted wrapper after each test |
|
||||
| `test/create-global-test-config.ts` | `global` mount options: the real `vue-i18n`, a Pinia and a router (needed by `useUiStore`); optional `provide` |
|
||||
| `test/i18n.ts` | The `t` of that `vue-i18n` instance, to build expected texts from their translation key |
|
||||
| `test/find-accented-labels.ts` | `findAccentedTags` / `findAccentedInfos`: each `UiTag` / `UiInfo` a wrapper renders, as `{ label, accent }`, in order; `findInfoLabels`: the `UiInfo` messages alone (also used by XO 6) |
|
||||
| `test/field-events.ts` | `setFieldValue` / `blurField`: sets a field's value or moves the focus out of it as the user would, returns the `update:modelValue` / `blur` events emitted (also used by XO 6) |
|
||||
| `test/read-forwarded-flag.ts` | `readForwardedFlag`: the value a child component receives for a boolean prop, mounted with it then without it (`[true, false]` when forwarded) (also used by XO 6) |
|
||||
| `test/mount-field.ts` | `mountField`: mounts a text field component with a `neutral` accent and a `'Value'` model, attached to the document; optional slots and attributes |
|
||||
| `test/submit-confirmation-text.ts` | `submitConfirmationText(wrapper, text)`: types and submits the confirmation text of a modal, returns `{ isConfirmed, errors }` |
|
||||
| `test/mount-composable.ts` | `mountComposable`: runs a composable inside a mounted component, its result read through `wrapper.vm`; takes the `global` options, `createGlobalTestConfig()` by default |
|
||||
| `test/get-success-state.ts` | `getSuccessState`: the title, the message and the link of the `VtsSuccessStateHero` a wrapper renders, `undefined` without a title or a link (also used by XO 6) |
|
||||
| `test/find-links.ts` | `findLinks(wrapper, selector?)`: every `UiLink` of a wrapper (or every plain link matching `selector`) as its `[text, href]`, in order (also used by XO 6) |
|
||||
| `test/expect-loader.ts` | `hasLoader(wrapper)`: whether a `UiLoader` is rendered; `expectLoaderInsteadOf(wrapper, findContent)`: a `UiLoader` shown and the content it stands for empty (also used by XO 6) |
|
||||
| `test/find-title.ts` | `findTitle`: the `.title` of a `VtsSuccessStateHero` or a list item, `undefined` without one (also used by XO 6) |
|
||||
| `tsconfig.vitest.json` | Type-checks test files with the Vitest globals and the `@core-test` alias |
|
||||
| `tsconfig.app.json` | Type-checks the library, test files excluded |
|
||||
| Path | Role |
|
||||
| ----------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
||||
| `vitest.config.ts` | Runner config: `vue` + `vue-i18n` plugins, `@core` / `@core-test` aliases, `globals: true` |
|
||||
| `test/setup.ts` | Global setup: auto-unmounts every mounted wrapper after each test |
|
||||
| `test/create-global-test-config.ts` | `global` mount options: the real `vue-i18n`, a Pinia and a router (needed by `useUiStore`) |
|
||||
| `test/i18n.ts` | The `t` of that `vue-i18n` instance, to build expected texts from their translation key |
|
||||
| `test/mount-composable.ts` | `mountComposable`: runs a composable inside a mounted component, its result read through `wrapper.vm` |
|
||||
| `tsconfig.vitest.json` | Type-checks test files with the Vitest globals and the `@core-test` alias |
|
||||
| `tsconfig.app.json` | Type-checks the library, test files excluded |
|
||||
|
||||
Test files sit next to the code they test, as `lib/**/*.unit.test.ts`. Shared test infrastructure lives in `test/`, outside `lib/`. The shared `scripts/npmignore` keeps all of it out of the published package.
|
||||
|
||||
`@xen-orchestra/web` and `@xen-orchestra/lite` type-check `web-core/lib` as part of their own sources: their app tsconfigs exclude its `*.unit.test.ts`, which they would otherwise check without the Vitest globals. How XO 6 imports `web-core/test/` is in its [test runner](../../web/docs/tests/running-tests.md) page.
|
||||
`@xen-orchestra/web` and `@xen-orchestra/lite` type-check `web-core/lib` as part of their own sources: their tsconfigs exclude the web-core test files, which they would otherwise check without the Vitest globals.
|
||||
|
||||
`test.alias` maps `placement.js` to its ESM build: the package only declares a `module` entry, which the Node-style resolution used by Vitest ignores.
|
||||
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
# File layout and structure
|
||||
|
||||
## File layout and naming
|
||||
|
||||
- A test file lives **next to** the file it covers, named `<source-name>.unit.test.ts`.
|
||||
- `to-variants.util.ts` → `to-variants.util.unit.test.ts`
|
||||
- `menu-popup.composable.ts` → `menu-popup.composable.unit.test.ts`
|
||||
- `VtsSuccessStateHero.vue` → `VtsSuccessStateHero.unit.test.ts` (the `.vue` is dropped)
|
||||
- Shared test infrastructure lives apart from the code: `test/` in web-core (alias `@core-test`), `src/test/` in XO 6 (alias `@/test`) — see [Shared test helpers](../tests.md#shared-test-helpers).
|
||||
|
||||
## Structuring a test file
|
||||
|
||||
- **One `describe` block per function or exposed property**, labeled with its exact name (`describe('formatItemCount')`, `describe('status')`). A component test has no such members: group with `describe` only to separate genuinely distinct behaviors, otherwise flat `it`s read better.
|
||||
- Use `it` (not `test`).
|
||||
- The name completes the sentence the `it` starts: a **present-tense assertion**, lowercase, no trailing period, and **without a redundant prefix** — the `describe` label already carries the function name. `it('formats the selected count with the total')` reads as one sentence; `it('formatItemCount formats …')` stutters.
|
||||
|
||||
```typescript
|
||||
describe('formatItemCount', () => {
|
||||
it('formats the selected count with the total', () => {
|
||||
expect(formatItemCount({ selected: 2, total: 8 })).toBe('2 / 8')
|
||||
})
|
||||
|
||||
it('falls back to zero for missing counts', () => {
|
||||
expect(formatItemCount({})).toBe('0 / 0')
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Do not import from `vitest`
|
||||
|
||||
`globals: true` (in the package's `vitest.config.ts` / `vite.config.ts`) together with `"types": ["vitest/globals"]` make `describe`, `it`, `expect`, `vi` and `beforeEach` available globally. **Never** add `import { ... } from 'vitest'`.
|
||||
|
||||
Those types are declared in `tsconfig.vitest.json`, not in `tsconfig.app.json`, so they are ambient in test files only. A `expect()` left behind in production code is a type error rather than a runtime `ReferenceError` in the browser.
|
||||
|
||||
The two projects split on the file name:
|
||||
|
||||
| Project | Covers | Test globals |
|
||||
| ---------------------- | ----------------------------------------------------------------------------------------- | ------------ |
|
||||
| `tsconfig.app.json` | everything **except** `*.unit.test.ts` and the test infrastructure (`test/`, `src/test/`) | no |
|
||||
| `tsconfig.vitest.json` | everything, tests included; XO 6 also includes `web-core/test/` for `@core-test` | yes |
|
||||
@@ -1,37 +0,0 @@
|
||||
# Mocking dependencies
|
||||
|
||||
Keep the mock boundary tight: **mock only what reaches outside the code under test** (a remote resource, a store fed by the network, an overlay a unit test cannot answer), and let pure utilities and icon helpers run for real.
|
||||
|
||||
XO 6 test files never call `vi.mock` or `vi.hoisted`: they replace exports with `mockModule` over the global module mocks, see [XO 6 mocking](../../../web/docs/tests/mocking.md). The typed form, the partial-mock cast and the shared mock modules below apply to both packages.
|
||||
|
||||
Use the **typed** mock form — `vi.mock(import('<module>'), …)` — so a rename breaks type-check instead of silently leaving a stale mock. Create the stub functions with `vi.hoisted` (a plain `const fn = vi.fn()` referenced in the factory throws, because the mock is hoisted above imports), and reset them in `beforeEach`:
|
||||
|
||||
```typescript
|
||||
const { sendCtrlAltDel } = vi.hoisted(() => ({
|
||||
sendCtrlAltDel: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock(import('@core/composables/remote-console.composable.ts'), () => ({
|
||||
useRemoteConsole: (() => ({ sendCtrlAltDel })) as unknown as typeof useRemoteConsole,
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
sendCtrlAltDel.mockReset()
|
||||
})
|
||||
```
|
||||
|
||||
Note the cast: the typed form checks the factory return against the **whole** module, so a partial mock of a large export needs `as unknown as typeof useX` (with an `import type { useX }`).
|
||||
|
||||
When several test files mock the same module with the same shape, the mock lives once in the package's test infrastructure (`test/` in web-core, `src/test/` in XO 6) and the test file only points `vi.mock` to it; its exported state is read and changed by the tests, and reset in `beforeEach`:
|
||||
|
||||
```typescript
|
||||
vi.mock(import('@core/composables/remote-console.composable.ts'), () => import('@core-test/mock-remote-console.ts'))
|
||||
|
||||
beforeEach(() => {
|
||||
remoteConsoleMock.reset()
|
||||
})
|
||||
```
|
||||
|
||||
`vi.mock` is hoisted: it cannot be wrapped in a helper, so one `vi.mock(path, () => import(...))` line per file is the convention, not a duplication. XO 6's `mockModule` is not hoisted: each shared mock module exports the helper calling it, see [XO 6 mocking](../../../web/docs/tests/mocking.md).
|
||||
|
||||
The XO 6 shared mocks (remote-resource collections, modals, overlays) and the network stub are listed in [XO 6 mocking](../../../web/docs/tests/mocking.md).
|
||||
@@ -1,36 +0,0 @@
|
||||
# Setup: prefer helpers over `beforeEach`
|
||||
|
||||
Reserve `beforeEach` for **mock resets only**. Repeated setup goes into small local helper/factory functions at the top of the file.
|
||||
|
||||
A component or composable mounted with different props or fixtures across a file gets one helper taking them — never a `mount(...)` call repeated per test:
|
||||
|
||||
```typescript
|
||||
function mountSuccessStateHero({ title }: { title?: string } = {}) {
|
||||
return mount(VtsSuccessStateHero, {
|
||||
global: createGlobalTestConfig(),
|
||||
slots: { default: 'Message', ...(title !== undefined && { title }) },
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
A composable helper returns the mounted state, read with no `.value`:
|
||||
|
||||
```typescript
|
||||
function mountLevel({ isPopup = true, horizontal = false } = {}) {
|
||||
return mountComposable(() => useMenuLevel({ isPopup, horizontal })).wrapper.vm
|
||||
}
|
||||
```
|
||||
|
||||
A helper returning `wrapper.vm` serves a **reactivity** test too, as long as it accepts the source as a `ref` (`MaybeRefOrGetter`): `wrapper.vm` keeps following the updates. Only a test that must call a function returned by the composable, or build its expected value, _inside_ the `setup` callback stays inline (see [Testing composables](./testing-composables.md)).
|
||||
|
||||
Because mocks are read lazily, calling `getX.mockReturnValue(...)` in the test body _before_ invoking the helper still takes effect.
|
||||
|
||||
This applies to **navigation into the result** too, not only to mounting. An expression such as `result.items[0]`, repeated across a `describe` block, is repeated setup — give it a helper and assert on a named local, rather than re-deriving it in every test.
|
||||
|
||||
The exception is a **reactivity** test: it must keep reading through the mounted `vm` after reassigning the source ref. A helper returning a snapshot of the first item would defeat the test.
|
||||
|
||||
A helper used by a second test file moves to the package's test infrastructure — see [Shared test helpers](../tests.md#shared-test-helpers).
|
||||
|
||||
## Unmounting
|
||||
|
||||
Each package's `setup.ts` calls `enableAutoUnmount(afterEach)`, so every wrapper is unmounted after the test that created it. Never unmount by hand for cleanup, and never mount in `beforeAll`: that wrapper would be torn down after the first test. The one `wrapper.unmount()` allowed is the act of a test asserting what `onUnmounted` does.
|
||||
@@ -1,112 +0,0 @@
|
||||
# Testing components
|
||||
|
||||
Components run in the same `unit` project as everything else: `@vue/test-utils` `mount` on `happy-dom`, **no browser needed**. Mount with the package's `createGlobalTestConfig()` (`@core-test/create-global-test-config.ts` in web-core, `@/test/global-test-config.ts` in XO 6), and give the repeated mount a helper (see [Setup](./setup-helpers.md)):
|
||||
|
||||
```typescript
|
||||
import VtsSuccessStateHero from '@core/components/success-state-hero/VtsSuccessStateHero.vue'
|
||||
import UiAlert from '@core/components/ui/alert/UiAlert.vue'
|
||||
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
|
||||
import { mount } from '@vue/test-utils'
|
||||
|
||||
function mountSuccessStateHero() {
|
||||
return mount(VtsSuccessStateHero, {
|
||||
global: createGlobalTestConfig(),
|
||||
slots: { default: 'Message' },
|
||||
})
|
||||
}
|
||||
|
||||
it('renders the message in a success alert', () => {
|
||||
const alert = mountSuccessStateHero().getComponent(UiAlert)
|
||||
|
||||
expect(alert.props('accent')).toBe('success')
|
||||
expect(alert.text()).toBe('Message')
|
||||
})
|
||||
```
|
||||
|
||||
Where the test file lives and how it groups its tests: see [File layout and structure](./file-structure.md).
|
||||
|
||||
## What a web-core component test covers
|
||||
|
||||
A web-core component is tested for its **contract with its consumers**: what each prop, slot and variant renders, what it emits on a user action, the state it derives (responsive classes, a sort, a fallback). Not its styling — see [What `happy-dom` cannot do](#what-happy-dom-cannot-do).
|
||||
|
||||
- A variant is asserted through the class `toVariants` gives it, since that class is the contract the CSS reads — never through a style.
|
||||
- A child web-core component is asserted through its props (`getComponent(UiAlert).props('accent')`), not the DOM it renders: that child has its own test.
|
||||
- A responsive state is driven with `(window as unknown as HappyDomWindow).happyDOM.setViewport({ width })` before mounting (`import type { Window as HappyDomWindow } from 'happy-dom'`).
|
||||
|
||||
## Keep components thin
|
||||
|
||||
A component should not carry much complex logic. Non-trivial computation (series, aggregation, formatting rules) belongs in a `*.util.ts` or a composable, tested directly — that is cheaper and covers more branches than mounting. A component that is awkward to test is telling you to **extract**, not to write a heavier component test, and never to skip the test.
|
||||
|
||||
What is left to assert at the component level is what it renders: labels, formatted values, conditional rows, empty states.
|
||||
|
||||
### Extracting from a tested component
|
||||
|
||||
The extraction is a refactor, so the tests come **first** and are what proves it changed nothing:
|
||||
|
||||
1. Write the tests against the component **as it stands**, and run them green.
|
||||
2. Extract.
|
||||
3. Re-run those tests **unchanged**.
|
||||
4. Move the ones the extraction made redundant down next to the new util/composable, and delete them from the component test.
|
||||
|
||||
Step 3 is the gate. A test that has to be edited to pass is reporting a behavior change — say so, do not absorb it into the diff. Tests written only _after_ an extraction describe the new code and cannot catch what the extraction broke, which is the whole risk being taken.
|
||||
|
||||
Step 4 is selective. A test that only exercised the logic now living in the util moves; a test asserting something the component alone does — rendering, conditional rows, empty states, feeding the util's output into the template — stays.
|
||||
|
||||
## Assert what the user reads, not the markup
|
||||
|
||||
`wrapper.text()` concatenates the whole subtree **with no separators**, so `'8 B'` and `'Disabled'` run together. It is fine for `toContain` on a single component, but it cannot express "this label has this value". Query instead:
|
||||
|
||||
```typescript
|
||||
// every key/value row: `VtsKeyValuePair` renders a semantic `dt.label` and `dd.value`
|
||||
const rows = wrapper.findAll('.vts-tabular-key-value-row')
|
||||
const labelledValues = Object.fromEntries(rows.map(row => [row.get('dt.label').text(), row.get('dd.value').text()]))
|
||||
|
||||
expect(labelledValues).toEqual({ [t('name')]: 'Item 1', [t('status')]: t('enabled') })
|
||||
```
|
||||
|
||||
Prefer this shape, one assertion covering every row a user sees: it fails loudly when a value lands under the wrong label. Assert against **class names and semantic elements**, never a positional chain of child indexes.
|
||||
|
||||
The class must exist for the component's own CSS: **never add a class only for a test**, and remove one whose CSS is gone. Without a styled class, query the component (`getComponent`), a styled class of a child component, or the text the user reads.
|
||||
|
||||
A query a second test file needs becomes a shared reader (see [Shared test helpers](../tests.md#shared-test-helpers)); XO 6 already has many, listed in [XO 6 components](../../../web/docs/tests/testing-components.md).
|
||||
|
||||
### Never spell out a translation
|
||||
|
||||
A rendered label or a translated value is wording the component does not own, so [asserting behavior](./assert-behavior.md) means naming the **key**, not the English string, through the `t` of the very instance the mount installs:
|
||||
|
||||
```typescript
|
||||
// ✗ rewording the translation breaks the test although the component still picks the same key
|
||||
expect(wrapper.get('.value').text()).toBe('None')
|
||||
|
||||
// ✓ asserts the decision: the value falls back to the "none" wording
|
||||
expect(wrapper.get('.value').text()).toBe(t('none'))
|
||||
```
|
||||
|
||||
A mistyped key does not pass quietly — `t` returns a marker for a key the locale has no entry for, which matches no rendered text.
|
||||
|
||||
Where the line falls:
|
||||
|
||||
| Value | Assert as |
|
||||
| ---------------------------------------------------------- | ---------------------------------------------------------------------------------- |
|
||||
| a label, or a value that is itself a translation | `t('key')` — including a plural, `t('n-warnings', 2)` |
|
||||
| a formatted date | `formatDateTime(timestamp)` from `@core/utils/time.util.ts`, as the component does |
|
||||
| a string the component composes from several translations | a template literal of those `t(…)` calls |
|
||||
| data reaching the component (a name, an id, an IP, a tag) | the literal — it is the test's own input |
|
||||
| a number the component formats (`'8 B'`, `'4 GiB'`, `'2'`) | the literal — deriving it would copy the template |
|
||||
|
||||
## What `happy-dom` cannot do
|
||||
|
||||
There is no layout engine, and Vitest's `css` option is off, so component styles are never loaded. Out of reach:
|
||||
|
||||
- `toBeVisible()` and anything depending on real visibility — assert presence/absence instead (`expect(wrapper.find('.foo').exists()).toBe(false)`)
|
||||
- `getComputedStyle` assertions on design tokens (color, padding, `flex-direction`)
|
||||
- real event dispatch — `trigger()` simulates events
|
||||
- canvas (ECharts), `ResizeObserver`, `IntersectionObserver` — stub the component that needs them
|
||||
|
||||
`happy-dom` also **lacks some browser APIs entirely**. `EventSource` is one: mounting a component that opens an SSE subscription throws `ReferenceError: EventSource is not defined`. It surfaces as an _unhandled rejection_, so Vitest **exits non-zero while reporting every test as passed** — do not read a green test list as success. Mock the subscribing module ([Mocking dependencies](./mocking.md)) so the subscription is never opened.
|
||||
|
||||
Never claim a component is untestable because there is no browser: its behaviour is testable here, only its appearance is not.
|
||||
|
||||
### Styling and visual non-regression (planned)
|
||||
|
||||
Appearance will be covered by a separate `visual` project, not by unit tests: Vitest browser mode with Playwright, `*.visual.test.ts` files mounting each variant and state of a component in light and dark, `expect.element(…).toMatchScreenshot()` against committed baselines, run by a `test:visual` script outside `yarn test`. Until it exists, a unit test never asserts a style, and a component's variant matrix is covered through its classes.
|
||||
@@ -1,51 +0,0 @@
|
||||
# Testing composables
|
||||
|
||||
A composable that relies on a Vue context (`useI18n`, `inject`, an effect scope, plugins) must run **inside a mounted component**: a throwaway component whose `setup` calls it, mounted with the package's global test config. `mountComposable` (`@core-test/mount-composable.ts`) does it and returns `{ wrapper }`; XO 6 wraps it with its own global test config (see [XO 6 composables](../../../web/docs/tests/testing-composables.md)). `mountComposable` renders nothing, so a composable needing rendered elements (a `useTemplateRef` target, as `useMenuPopup`) is the one case mounted by hand, with a component rendering them. A composable needing no Vue context is called directly, like a [utility](./testing-utilities.md).
|
||||
|
||||
Because the real i18n instance is installed, translations resolve to actual strings, and the assertion builds its expected label with `t` instead of hard-coding the wording — see [Assert behavior](./assert-behavior.md).
|
||||
|
||||
The composable result becomes the component state, so `wrapper.vm` exposes it with refs **already unwrapped** — no `.value`. Read through it rather than destructuring it: a destructured value is a snapshot and stops following updates.
|
||||
|
||||
`mountComposable` takes the `global` mount options as a second argument, `createGlobalTestConfig()` by default: pass `createGlobalTestConfig({ provide })` for a composable injecting what a parent component provides. Without it, `inject` falls back to its default, the "no provider" case.
|
||||
|
||||
The wrapper is unmounted after the test, so `onUnmounted` and `onScopeDispose` cleanup runs and no watcher of a previous test can re-fire in the next one.
|
||||
|
||||
## Reactivity
|
||||
|
||||
To test that a composable reacts to its source, pass a `ref` and reassign it:
|
||||
|
||||
```typescript
|
||||
const source = ref(createItem({ status: 'running' }))
|
||||
const { wrapper } = mountComposable(() => useItemStatus(source))
|
||||
|
||||
expect(wrapper.vm.icon).toBe('status:running-circle')
|
||||
|
||||
source.value = createItem({ status: 'halted' })
|
||||
|
||||
expect(wrapper.vm.icon).toBe('status:halted-circle')
|
||||
```
|
||||
|
||||
## Composables whose returned function calls `useI18n` / `inject`
|
||||
|
||||
`useI18n()` must be called synchronously during a component `setup()`. If a composable returns a function that _itself_ calls `useI18n`, you cannot call that function from the test body after the mount has returned — it throws `Must be called at the top of a 'setup' function`. Invoke it **inside** the `setup` callback instead:
|
||||
|
||||
```typescript
|
||||
const startTimeInSeconds = 1660000000
|
||||
|
||||
const { wrapper } = mountComposable(() => {
|
||||
const { locale } = useI18n()
|
||||
|
||||
return {
|
||||
relativeStartTime: useItemUtils(createItem()).getRelativeStartTime(startTimeInSeconds),
|
||||
expectedRelativeTime: getRelativeTime(new Date(startTimeInSeconds * 1000), locale.value),
|
||||
}
|
||||
})
|
||||
|
||||
expect(wrapper.vm.relativeStartTime).toBe(wrapper.vm.expectedRelativeTime)
|
||||
```
|
||||
|
||||
Note the object literal: `setup()` returns the component **bindings**, so the callback must hand back an object. A lone ref is not component state and would not surface on `wrapper.vm`. Anything the assertion needs — the `t`, a `locale`, an expected value — is returned alongside, which is why the callback body is a block rather than a bare object.
|
||||
|
||||
The expected value is **derived the way production derives it** ([Assert behavior](./assert-behavior.md)): `getRelativeTime` owns the wording, and what the composable decides is which date to hand it. `expect(typeof …).toBe('string')` would pass for any string, including one built from a start time read as milliseconds instead of seconds — it asserts the type, not the behavior. Where a value is environment-dependent, name the helper production uses and call it with the same input; never assert merely that the value is non-empty or differs from some other label.
|
||||
|
||||
Functions that only touch refs/computed can be called on the returned object as usual.
|
||||
@@ -1,21 +0,0 @@
|
||||
# Testing pure utilities
|
||||
|
||||
Utility functions (`*.util.ts`) are pure — import and call them directly, and assert `input → output`. No mounting, no mocks.
|
||||
|
||||
```typescript
|
||||
describe('toVariants', () => {
|
||||
it('renders a `true` value as the bare key', () => {
|
||||
expect(toVariants({ disabled: true })).toEqual(['disabled'])
|
||||
})
|
||||
|
||||
it('drops falsy values', () => {
|
||||
expect(toVariants({ accent: undefined, disabled: false, size: '' })).toEqual([])
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
Cover the meaningful edge cases: empty input, missing samples (`NaN` propagation), `null` data, and boundary rounding.
|
||||
|
||||
> **Logic extracted from a component is tested here**, not through the component — see [Keep components thin](./testing-components.md#keep-components-thin).
|
||||
|
||||
> **A util more than one consumer needs lives once.** Generic logic belongs in `web-core/lib/utils/` (or a shared `@vates/*` package), tested there; an app or a module never forks it. Where XO 6 keeps its own shared utils, see [XO 6 utilities](../../../web/docs/tests/testing-utilities.md).
|
||||
@@ -5,10 +5,10 @@
|
||||
:message="isKeyboardLayoutDisabled ? t('console-keyboard-layout-not-applicable') : undefined"
|
||||
wrap-message
|
||||
>
|
||||
<VtsSelect :id="keyboardLayoutSelectId" accent="neutral" />
|
||||
<VtsSelect :id="keyboardLayoutSelectId" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
<UiCardTitle>{{ t('console-clipboard') }}</UiCardTitle>
|
||||
<UiTextarea v-model="clipboardText" accent="neutral" />
|
||||
<UiTextarea v-model="clipboardText" accent="brand" />
|
||||
<div class="buttons-container">
|
||||
<UiButton
|
||||
accent="brand"
|
||||
|
||||
@@ -1,32 +1,15 @@
|
||||
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
|
||||
import VtsInputWrapper, { type InputWrapperMessage } from '@core/components/input-wrapper/VtsInputWrapper.vue'
|
||||
import UiFileUploader from '@core/components/ui/file-uploader/UiFileUploader.vue'
|
||||
import UiInfo from '@core/components/ui/info/UiInfo.vue'
|
||||
import UiInput from '@core/components/ui/input/UiInput.vue'
|
||||
import UiLabel from '@core/components/ui/label/UiLabel.vue'
|
||||
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
|
||||
import { findAccentedInfos, findInfoLabels } from '@core-test/find-accented-labels.ts'
|
||||
import { mount, type VueWrapper } from '@vue/test-utils'
|
||||
import { h, nextTick, type VNode } from 'vue'
|
||||
import { h } from 'vue'
|
||||
|
||||
type InputWrapperProps = InstanceType<typeof VtsInputWrapper>['$props']
|
||||
|
||||
type InputProps = InstanceType<typeof UiInput>['$props']
|
||||
|
||||
function mountInputWrapper({
|
||||
props = {},
|
||||
input = {},
|
||||
field,
|
||||
slots = {},
|
||||
}: {
|
||||
props?: Partial<InputWrapperProps>
|
||||
input?: Partial<InputProps>
|
||||
field?: () => VNode
|
||||
slots?: Record<string, string>
|
||||
} = {}) {
|
||||
function mountInputWrapper(message?: InputWrapperMessage) {
|
||||
return mount(VtsInputWrapper, {
|
||||
global: createGlobalTestConfig(),
|
||||
props: { label: 'Name', ...props },
|
||||
slots: { default: field ?? (() => h(UiInput, { modelValue: '', accent: 'neutral', ...input })), ...slots },
|
||||
props: { label: 'Name', message },
|
||||
slots: { default: () => h(UiInput, { modelValue: '', accent: 'brand' }) },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -35,40 +18,6 @@ function findMessageIds(wrapper: VueWrapper) {
|
||||
}
|
||||
|
||||
describe('VtsInputWrapper', () => {
|
||||
it('renders the label prop', () => {
|
||||
expect(mountInputWrapper().getComponent(UiLabel).text()).toBe('Name')
|
||||
})
|
||||
|
||||
it('renders the label slot instead of the prop', () => {
|
||||
expect(
|
||||
mountInputWrapper({ slots: { label: 'Slot label' } })
|
||||
.getComponent(UiLabel)
|
||||
.text()
|
||||
).toBe('Slot label')
|
||||
})
|
||||
|
||||
it('links the label to the input with its own id, over the input id', () => {
|
||||
const wrapper = mountInputWrapper({ input: { id: 'own-id' } })
|
||||
const inputId = wrapper.get('input').attributes('id')
|
||||
|
||||
expect(inputId).not.toBe('own-id')
|
||||
expect(wrapper.getComponent(UiLabel).props('for')).toBe(inputId)
|
||||
})
|
||||
|
||||
it('passes the learn more URL to the label', () => {
|
||||
const label = mountInputWrapper({ props: { learnMoreUrl: 'https://example.com' } }).getComponent(UiLabel)
|
||||
|
||||
expect(label.props('href')).toBe('https://example.com')
|
||||
})
|
||||
|
||||
it.each([true, false])('marks the label as required when the input required is %s', async required => {
|
||||
const wrapper = mountInputWrapper({ input: { required } })
|
||||
|
||||
await nextTick()
|
||||
|
||||
expect(wrapper.getComponent(UiLabel).props('required')).toBe(required)
|
||||
})
|
||||
|
||||
it('leaves the input undescribed and valid without message', () => {
|
||||
const input = mountInputWrapper().get('input')
|
||||
|
||||
@@ -77,7 +26,7 @@ describe('VtsInputWrapper', () => {
|
||||
})
|
||||
|
||||
it('describes the input with every message', () => {
|
||||
const wrapper = mountInputWrapper({ props: { message: ['Info', { content: 'Warning', accent: 'warning' }] } })
|
||||
const wrapper = mountInputWrapper(['Info', { content: 'Warning', accent: 'warning' }])
|
||||
const messageIds = findMessageIds(wrapper)
|
||||
|
||||
expect(messageIds).toHaveLength(2)
|
||||
@@ -91,102 +40,27 @@ describe('VtsInputWrapper', () => {
|
||||
{ accent: 'muted', expected: undefined },
|
||||
{ accent: 'danger', expected: 'true' },
|
||||
] as const)('sets aria-invalid to $expected for a $accent message', ({ accent, expected }) => {
|
||||
const input = mountInputWrapper({ props: { message: { content: 'Message', accent } } }).get('input')
|
||||
const input = mountInputWrapper({ content: 'Message', accent }).get('input')
|
||||
|
||||
expect(input.attributes('aria-invalid')).toBe(expected)
|
||||
})
|
||||
|
||||
it('marks the input as invalid when a danger message sits beside other messages', () => {
|
||||
const input = mountInputWrapper({
|
||||
props: {
|
||||
message: [
|
||||
{ content: 'Error', accent: 'danger' },
|
||||
{ content: 'Warning', accent: 'warning' },
|
||||
],
|
||||
},
|
||||
}).get('input')
|
||||
const input = mountInputWrapper([
|
||||
{ content: 'Error', accent: 'danger' },
|
||||
{ content: 'Warning', accent: 'warning' },
|
||||
]).get('input')
|
||||
|
||||
expect(input.attributes('aria-invalid')).toBe('true')
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ messageAccent: undefined, labelAccent: 'neutral', inputAccent: 'neutral' },
|
||||
{ messageAccent: 'info', labelAccent: 'neutral', inputAccent: 'neutral' },
|
||||
{ messageAccent: 'muted', labelAccent: 'neutral', inputAccent: 'neutral' },
|
||||
{ messageAccent: 'success', labelAccent: 'neutral', inputAccent: 'success' },
|
||||
{ messageAccent: 'warning', labelAccent: 'warning', inputAccent: 'warning' },
|
||||
{ messageAccent: 'danger', labelAccent: 'danger', inputAccent: 'danger' },
|
||||
] as const)(
|
||||
'gives a $messageAccent message a $labelAccent label and a $inputAccent input',
|
||||
({ messageAccent, labelAccent, inputAccent }) => {
|
||||
const wrapper = mountInputWrapper({
|
||||
props: { message: messageAccent && { content: 'Message', accent: messageAccent } },
|
||||
})
|
||||
|
||||
expect(wrapper.getComponent(UiLabel).props('accent')).toBe(labelAccent)
|
||||
expect(wrapper.getComponent(UiInput).classes()).toContain(`accent--${inputAccent}`)
|
||||
}
|
||||
)
|
||||
|
||||
it('lists the messages by rank, a plain string as info, and takes its accents from the highest', () => {
|
||||
const wrapper = mountInputWrapper({
|
||||
props: { message: [{ content: 'Error', accent: 'danger' }, 'Info', { content: 'Valid', accent: 'success' }] },
|
||||
})
|
||||
|
||||
expect(findAccentedInfos(wrapper)).toEqual([
|
||||
{ label: 'Info', accent: 'info' },
|
||||
{ label: 'Valid', accent: 'success' },
|
||||
{ label: 'Error', accent: 'danger' },
|
||||
])
|
||||
expect(wrapper.getComponent(UiLabel).props('accent')).toBe('danger')
|
||||
})
|
||||
|
||||
it('renders the message slot with the content and the accent', () => {
|
||||
const wrapper = mountInputWrapper({
|
||||
props: { message: { content: 'Message', accent: 'warning' } },
|
||||
slots: { message: '<template #message="{ content, accent }">{{ content }} ({{ accent }})</template>' },
|
||||
})
|
||||
|
||||
expect(findInfoLabels(wrapper)).toEqual(['Message (warning)'])
|
||||
})
|
||||
|
||||
it.each([true, false])('passes wrapMessage %s to the messages', wrapMessage => {
|
||||
const info = mountInputWrapper({ props: { message: 'Info', wrapMessage } }).getComponent(UiInfo)
|
||||
|
||||
expect(info.props('wrap')).toBe(wrapMessage)
|
||||
})
|
||||
|
||||
it('leaves a detached input out of the wrapper', async () => {
|
||||
const wrapper = mountInputWrapper({
|
||||
props: { message: { content: 'Error', accent: 'danger' } },
|
||||
input: { detached: true, required: true },
|
||||
})
|
||||
const input = wrapper.get('input')
|
||||
|
||||
await nextTick()
|
||||
|
||||
expect(wrapper.getComponent(UiInput).classes()).toContain('accent--neutral')
|
||||
expect(input.attributes('id')).toBeUndefined()
|
||||
expect(input.attributes('aria-describedby')).toBeUndefined()
|
||||
expect(input.attributes('aria-invalid')).toBeUndefined()
|
||||
expect(wrapper.getComponent(UiLabel).props('required')).toBe(false)
|
||||
})
|
||||
|
||||
it('describes the file uploader with its messages', () => {
|
||||
const wrapper = mountInputWrapper({
|
||||
const wrapper = mount(VtsInputWrapper, {
|
||||
global: createGlobalTestConfig(),
|
||||
props: { label: 'File', message: 'Info' },
|
||||
field: () => h(UiFileUploader, { accent: 'neutral' }),
|
||||
slots: { default: () => h(UiFileUploader, { accent: 'neutral' }) },
|
||||
})
|
||||
|
||||
expect(wrapper.get('button.dropzone').attributes('aria-describedby')).toBe(findMessageIds(wrapper).join(' '))
|
||||
})
|
||||
|
||||
it('keeps the file uploader accent with a success message', () => {
|
||||
const wrapper = mountInputWrapper({
|
||||
props: { message: { content: 'Valid', accent: 'success' } },
|
||||
field: () => h(UiFileUploader, { accent: 'neutral' }),
|
||||
})
|
||||
|
||||
expect(wrapper.getComponent(UiFileUploader).find('.accent--neutral').exists()).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -29,11 +29,9 @@ import { computed, provide, reactive, useId } from 'vue'
|
||||
|
||||
export type InputWrapperMessage = MaybeArray<string | { content: string; accent?: InfoAccent }>
|
||||
|
||||
export type InputWrapperAccent = 'neutral' | 'success' | 'warning' | 'danger'
|
||||
|
||||
export type InputWrapperController = {
|
||||
id: string
|
||||
accent: InputWrapperAccent
|
||||
labelAccent: LabelAccent
|
||||
required: boolean
|
||||
describedBy: string | undefined
|
||||
invalid: boolean
|
||||
@@ -64,11 +62,11 @@ const unsortedMessages = useArrayMap(
|
||||
|
||||
const messages = useRanked(unsortedMessages, ({ accent }) => accent, ['muted', 'info', 'success', 'warning', 'danger'])
|
||||
|
||||
const messageAccent = useMapper<InfoAccent, InputWrapperAccent>(
|
||||
const labelAccent = useMapper<InfoAccent, LabelAccent>(
|
||||
() => messages.value.at(-1)?.accent,
|
||||
{
|
||||
info: 'neutral',
|
||||
success: 'success',
|
||||
success: 'neutral',
|
||||
warning: 'warning',
|
||||
danger: 'danger',
|
||||
muted: 'neutral',
|
||||
@@ -76,8 +74,6 @@ const messageAccent = useMapper<InfoAccent, InputWrapperAccent>(
|
||||
'info'
|
||||
)
|
||||
|
||||
const labelAccent = computed<LabelAccent>(() => (messageAccent.value === 'success' ? 'neutral' : messageAccent.value))
|
||||
|
||||
const messageIds = computed(() => messages.value.map((_, index) => `${id}-message-${index}`))
|
||||
|
||||
const describedBy = computed(() => (messageIds.value.length > 0 ? messageIds.value.join(' ') : undefined))
|
||||
@@ -86,7 +82,7 @@ const invalid = computed(() => messages.value.some(({ accent }) => accent === 'd
|
||||
|
||||
const wrapperController = reactive({
|
||||
id,
|
||||
accent: messageAccent,
|
||||
labelAccent,
|
||||
required: false,
|
||||
describedBy,
|
||||
invalid,
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
import VtsMiddleEllipsis from '@core/components/middle-ellipsis/VtsMiddleEllipsis.vue'
|
||||
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
|
||||
class ImmediateResizeObserver {
|
||||
constructor(private readonly callback: ResizeObserverCallback) {}
|
||||
|
||||
observe() {
|
||||
this.callback([], this as unknown as ResizeObserver)
|
||||
}
|
||||
|
||||
unobserve() {}
|
||||
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
async function mountMiddleEllipsis(text: string, tailLength?: number) {
|
||||
const wrapper = mount(VtsMiddleEllipsis, { global: createGlobalTestConfig(), props: { text, tailLength } })
|
||||
|
||||
await flushPromises()
|
||||
|
||||
return wrapper
|
||||
}
|
||||
|
||||
async function findParts(text: string, tailLength?: number) {
|
||||
const wrapper = await mountMiddleEllipsis(text, tailLength)
|
||||
const head = wrapper.find('.head')
|
||||
const tail = wrapper.find('.tail')
|
||||
|
||||
return {
|
||||
head: head.exists() ? head.text() : undefined,
|
||||
tail: tail.exists() ? tail.text() : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
describe('VtsMiddleEllipsis', () => {
|
||||
it('renders the text as is when it fits', async () => {
|
||||
const wrapper = await mountMiddleEllipsis('prod-web-frontend-eu-west-01')
|
||||
|
||||
expect(wrapper.text()).toBe('prod-web-frontend-eu-west-01')
|
||||
expect(wrapper.find('.head').exists()).toBe(false)
|
||||
expect(wrapper.findAll('[aria-hidden="true"]')).toHaveLength(0)
|
||||
})
|
||||
|
||||
describe('when the text overflows', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('ResizeObserver', ImmediateResizeObserver)
|
||||
vi.spyOn(Element.prototype, 'scrollWidth', 'get').mockReturnValue(200)
|
||||
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(100)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it.each([
|
||||
{
|
||||
label: 'keeps the last 10 characters by default',
|
||||
tailLength: undefined,
|
||||
head: 'prod-web-frontend-',
|
||||
tail: 'eu-west-01',
|
||||
},
|
||||
{ label: 'keeps the given number of characters', tailLength: 4, head: 'prod-web-frontend-eu-wes', tail: 't-01' },
|
||||
])('$label', async ({ tailLength, head, tail }) => {
|
||||
expect(await findParts('prod-web-frontend-eu-west-01', tailLength)).toEqual({ head, tail })
|
||||
})
|
||||
|
||||
it('keeps an emoji whole when it falls on the cut', async () => {
|
||||
expect(await findParts('ab🎨cd', 3)).toEqual({ head: 'ab', tail: '🎨cd' })
|
||||
})
|
||||
|
||||
it('does not cut a text that is not longer than the kept end', async () => {
|
||||
expect(await findParts('short')).toEqual({ head: undefined, tail: undefined })
|
||||
})
|
||||
|
||||
it('renders the text once, with the parts hidden from assistive technologies', async () => {
|
||||
const wrapper = await mountMiddleEllipsis('prod-web-frontend-eu-west-01')
|
||||
|
||||
expect(wrapper.text()).toBe('prod-web-frontend-eu-west-01')
|
||||
expect(wrapper.attributes('data-text')).toBe('prod-web-frontend-eu-west-01')
|
||||
expect(wrapper.findAll('[aria-hidden="true"]')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('cuts a new text that overflows', async () => {
|
||||
const wrapper = await mountMiddleEllipsis('short')
|
||||
|
||||
await wrapper.setProps({ text: 'prod-web-frontend-eu-west-01' })
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.get('.tail').text()).toBe('eu-west-01')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,67 +0,0 @@
|
||||
<template>
|
||||
<span
|
||||
ref="root"
|
||||
v-tooltip="isSplit ? text : true"
|
||||
:class="{ split: isSplit }"
|
||||
:data-text="text"
|
||||
class="vts-middle-ellipsis text-ellipsis"
|
||||
>
|
||||
<template v-if="isSplit">
|
||||
<span aria-hidden="true" class="head text-ellipsis">{{ head }}</span>
|
||||
<span aria-hidden="true" class="tail">{{ tail }}</span>
|
||||
</template>
|
||||
<template v-else>{{ text }}</template>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { useCollapseOnOverflow } from '@core/composables/collapse-on-overflow.composable.ts'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { computed, useTemplateRef, watch } from 'vue'
|
||||
|
||||
const { text, tailLength = 10 } = defineProps<{
|
||||
text: string
|
||||
tailLength?: number
|
||||
}>()
|
||||
|
||||
const characters = computed(() => Array.from(text))
|
||||
|
||||
const head = computed(() => characters.value.slice(0, -tailLength).join(''))
|
||||
|
||||
const tail = computed(() => characters.value.slice(-tailLength).join(''))
|
||||
|
||||
const rootElement = useTemplateRef('root')
|
||||
|
||||
const { collapsedCount, reset } = useCollapseOnOverflow(rootElement, rootElement, () => (head.value === '' ? 0 : 1))
|
||||
|
||||
const isSplit = computed(() => collapsedCount.value > 0)
|
||||
|
||||
watch(
|
||||
() => text,
|
||||
() => reset()
|
||||
)
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.vts-middle-ellipsis {
|
||||
display: block;
|
||||
|
||||
&.split {
|
||||
display: flex;
|
||||
white-space: pre;
|
||||
|
||||
&::before {
|
||||
content: '\200B' / attr(data-text);
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.head {
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.tail {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,6 @@
|
||||
import VtsActionModal from '@core/components/modal/VtsActionModal.vue'
|
||||
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
|
||||
import { t } from '@core-test/i18n.ts'
|
||||
import { submitConfirmationText } from '@core-test/submit-confirmation-text.ts'
|
||||
import { mount } from '@vue/test-utils'
|
||||
|
||||
function mountActionModal(confirmationText?: string) {
|
||||
@@ -32,15 +31,19 @@ describe('VtsActionModal', () => {
|
||||
it('does not confirm with a wrong text and shows the error', async () => {
|
||||
const wrapper = mountActionModal('2 VMs')
|
||||
|
||||
expect(await submitConfirmationText(wrapper, '2 VM')).toEqual({
|
||||
isConfirmed: false,
|
||||
errors: [t('form:error:must-match', { text: '2 VMs' })],
|
||||
})
|
||||
await wrapper.get('input').setValue('2 VM')
|
||||
await wrapper.get('form').trigger('submit')
|
||||
|
||||
expect(wrapper.emitted('confirm')).toBeUndefined()
|
||||
expect(wrapper.get('.ui-info').text()).toBe(t('form:error:must-match', { text: '2 VMs' }))
|
||||
})
|
||||
|
||||
it('confirms with the confirmation text', async () => {
|
||||
const wrapper = mountActionModal('2 VMs')
|
||||
|
||||
expect(await submitConfirmationText(wrapper, '2 VMs')).toEqual({ isConfirmed: true, errors: [] })
|
||||
await wrapper.get('input').setValue('2 VMs')
|
||||
await wrapper.get('form').trigger('submit')
|
||||
|
||||
expect(wrapper.emitted('confirm')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
<template>
|
||||
<UiModal accent="info" icon="status:info-picto" @dismiss="emit('cancel')">
|
||||
<template #title>
|
||||
{{ t('modal:discard-unsaved-changes?') }}
|
||||
</template>
|
||||
|
||||
<template #content>
|
||||
{{ t('modal:discard-unsaved-changes-message') }}
|
||||
</template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsOverlayButton ref="keepEditingButton" variant="secondary" @click="emit('cancel')">
|
||||
{{ t('action:keep-editing') }}
|
||||
</VtsOverlayButton>
|
||||
<VtsOverlayButton variant="primary" @click="emit('confirm')">{{ t('action:discard') }}</VtsOverlayButton>
|
||||
</template>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsOverlayButton from '@core/components/overlay/VtsOverlayButton.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import { onMounted, useTemplateRef } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: []
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const keepEditingButton = useTemplateRef('keepEditingButton')
|
||||
|
||||
onMounted(() => {
|
||||
keepEditingButton.value?.$el.focus()
|
||||
})
|
||||
</script>
|
||||
@@ -1,7 +1,6 @@
|
||||
import VtsTypeToConfirmModal from '@core/components/modal/VtsTypeToConfirmModal.vue'
|
||||
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
|
||||
import { t } from '@core-test/i18n.ts'
|
||||
import { submitConfirmationText } from '@core-test/submit-confirmation-text.ts'
|
||||
import { mount } from '@vue/test-utils'
|
||||
|
||||
function mountTypeToConfirmModal() {
|
||||
@@ -22,15 +21,19 @@ describe('VtsTypeToConfirmModal', () => {
|
||||
])('does not confirm with $label and shows the error', async ({ text }) => {
|
||||
const wrapper = mountTypeToConfirmModal()
|
||||
|
||||
expect(await submitConfirmationText(wrapper, text)).toEqual({
|
||||
isConfirmed: false,
|
||||
errors: [t('form:error:must-match', { text: '2 VMs' })],
|
||||
})
|
||||
await wrapper.get('input').setValue(text)
|
||||
await wrapper.get('form').trigger('submit')
|
||||
|
||||
expect(wrapper.emitted('confirm')).toBeUndefined()
|
||||
expect(wrapper.get('.ui-info').text()).toBe(t('form:error:must-match', { text: '2 VMs' }))
|
||||
})
|
||||
|
||||
it('confirms with the confirmation text', async () => {
|
||||
const wrapper = mountTypeToConfirmModal()
|
||||
|
||||
expect(await submitConfirmationText(wrapper, '2 VMs')).toEqual({ isConfirmed: true, errors: [] })
|
||||
await wrapper.get('input').setValue('2 VMs')
|
||||
await wrapper.get('form').trigger('submit')
|
||||
|
||||
expect(wrapper.emitted('confirm')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<VtsInputWrapper :label :message="messages" wrap-message>
|
||||
<UiInput v-model.number="model" accent="neutral" type="number" :required @blur="emit('blur')" />
|
||||
<UiInput v-model.number="model" accent="brand" type="number" :required @blur="emit('blur')" />
|
||||
</VtsInputWrapper>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ const { t } = useI18n()
|
||||
|
||||
const showResizeHandle = computed(() => !uiStore.isSmall && panelStore.isExpanded)
|
||||
|
||||
const transform = computed(() => (panelStore.isExpanded ? 'none' : `translateX(${panelStore.cssHorizontalOffset})`))
|
||||
const transform = computed(() => `translateX(${panelStore.cssHorizontalOffset})`)
|
||||
|
||||
const transformTransition = `transform ${PANEL_TRANSITION_DURATION}ms`
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<UiInput
|
||||
:id
|
||||
v-model="filter"
|
||||
:accent="isUsable ? 'neutral' : 'danger'"
|
||||
:accent="isUsable ? 'brand' : 'danger'"
|
||||
:busy
|
||||
:aria-label="uiStore.isSmall ? t('query-builder:label') : undefined"
|
||||
:placeholder="t('query-builder:placeholder')"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<template>
|
||||
<div class="vts-query-builder-filter">
|
||||
<VtsSelect :id="propertySelectId" ref="propertySelector" accent="neutral" />
|
||||
<VtsSelect :id="operatorSelectId" accent="neutral" />
|
||||
<UiInput v-if="valueType === 'input'" v-model="value" class="value" accent="neutral" />
|
||||
<VtsSelect v-else-if="valueType === 'select'" :id="valueSelectId" class="value" accent="neutral" />
|
||||
<VtsSelect :id="propertySelectId" ref="propertySelector" accent="brand" />
|
||||
<VtsSelect :id="operatorSelectId" accent="brand" />
|
||||
<UiInput v-if="valueType === 'input'" v-model="value" class="value" accent="brand" />
|
||||
<VtsSelect v-else-if="valueType === 'select'" :id="valueSelectId" class="value" accent="brand" />
|
||||
<div>
|
||||
<MenuList :placement="uiStore.isSmall ? 'bottom' : 'bottom-end'">
|
||||
<template #trigger="{ open, bindings }">
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<UiCard class="vts-query-builder-group" :class="[{ root, highlighted }, item.operator]">
|
||||
<div class="group">
|
||||
<div class="header">
|
||||
<VtsSelect :id="groupOperatorSelectId" class="group-operator" accent="neutral" />
|
||||
<VtsSelect :id="groupOperatorSelectId" class="group-operator" accent="brand" />
|
||||
<MenuList v-if="!root" placement="bottom-end">
|
||||
<template #trigger="{ open, bindings }">
|
||||
<UiButtonIcon v-bind="bindings" size="medium" accent="brand" icon="fa:ellipsis" @click="open" />
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
@duplicate="emit('duplicate')"
|
||||
@remove="keepChildren => emit('remove', keepChildren)"
|
||||
/>
|
||||
<UiInput v-else-if="!node.isValid" :model-value="node.rawFilter" class="raw-filter" disabled accent="neutral" />
|
||||
<UiInput v-else-if="!node.isValid" :model-value="node.rawFilter" class="raw-filter" disabled accent="brand" />
|
||||
<VtsQueryBuilderFilter
|
||||
v-else
|
||||
v-model:property="node.property"
|
||||
|
||||
@@ -2,13 +2,8 @@
|
||||
<UiCard class="vts-quick-info-card">
|
||||
<UiCardTitle>{{ t('quick-info') }}</UiCardTitle>
|
||||
<VtsStateHero v-if="loading" format="card" type="busy" size="medium" />
|
||||
<div v-else class="content">
|
||||
<div class="info-container">
|
||||
<slot />
|
||||
</div>
|
||||
<div v-if="slots.footer" class="footer">
|
||||
<slot name="footer" />
|
||||
</div>
|
||||
<div v-else class="info-container">
|
||||
<slot />
|
||||
</div>
|
||||
</UiCard>
|
||||
</template>
|
||||
@@ -23,22 +18,11 @@ defineProps<{
|
||||
loading: boolean
|
||||
}>()
|
||||
|
||||
const slots = defineSlots<{
|
||||
default(): any
|
||||
footer?(): any
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.vts-quick-info-card {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.6rem;
|
||||
}
|
||||
|
||||
.info-container {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(25rem, 1fr));
|
||||
|
||||
@@ -70,7 +70,7 @@ function handleArrowKey(direction: 'left' | 'right') {
|
||||
}
|
||||
|
||||
&.position--end {
|
||||
inset-inline-end: -0.8rem;
|
||||
inset-inline-end: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import VtsDetailedOption from '@core/components/select/VtsDetailedOption.vue'
|
||||
import VtsSelect from '@core/components/select/VtsSelect.vue'
|
||||
import type { IconName } from '@core/icons'
|
||||
import { type FormOption, useFormSelect } from '@core/packages/form-select'
|
||||
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
|
||||
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
||||
import { defineComponent, h } from 'vue'
|
||||
|
||||
type DetailedOptionProps = {
|
||||
icon?: IconName
|
||||
iconTooltip?: string
|
||||
details?: string
|
||||
}
|
||||
|
||||
// An option only renders inside an open select, which provides it its controller
|
||||
async function mountDetailedOption(props: DetailedOptionProps = {}) {
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
const { id } = useFormSelect(['Network'])
|
||||
|
||||
return () =>
|
||||
h(
|
||||
VtsSelect,
|
||||
{ id, accent: 'neutral' },
|
||||
{ default: ({ option }: { option: FormOption }) => h(VtsDetailedOption, { option, ...props }) }
|
||||
)
|
||||
},
|
||||
}),
|
||||
{ global: createGlobalTestConfig() }
|
||||
)
|
||||
|
||||
await flushPromises()
|
||||
await wrapper.get('.vts-select .ui-input').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
return wrapper.getComponent(VtsDetailedOption)
|
||||
}
|
||||
|
||||
// The dropdown of the option renders its own icon, a comment node without a name: only the one beside the label
|
||||
// belongs to the detailed option
|
||||
function findOptionIcons(option: Pick<VueWrapper, 'findAllComponents'>) {
|
||||
return option.findAllComponents(VtsIcon).filter(icon => {
|
||||
const element = icon.element
|
||||
|
||||
if (!(element instanceof Element)) {
|
||||
return false
|
||||
}
|
||||
|
||||
return element.closest('.vts-detailed-option') !== null
|
||||
})
|
||||
}
|
||||
|
||||
it('renders the label of the option', async () => {
|
||||
const option = await mountDetailedOption()
|
||||
|
||||
expect(option.get('.vts-detailed-option').text()).toBe('Network')
|
||||
})
|
||||
|
||||
it('renders the details after the label', async () => {
|
||||
const option = await mountDetailedOption({ details: 'eth0' })
|
||||
|
||||
expect(option.get('.em-dash-prefix').text()).toBe('eth0')
|
||||
})
|
||||
|
||||
it('renders no details when none are passed', async () => {
|
||||
const option = await mountDetailedOption()
|
||||
|
||||
expect(option.find('.em-dash-prefix').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('renders the icon with its tooltip', async () => {
|
||||
const option = await mountDetailedOption({ icon: 'object:network', iconTooltip: 'Connected' })
|
||||
|
||||
const icons = findOptionIcons(option)
|
||||
|
||||
expect(icons.map(icon => ({ name: icon.props('name'), tooltip: icon.props('tooltip') }))).toEqual([
|
||||
{ name: 'object:network', tooltip: 'Connected' },
|
||||
])
|
||||
})
|
||||
|
||||
it('renders no icon when none is passed', async () => {
|
||||
const option = await mountDetailedOption()
|
||||
|
||||
expect(findOptionIcons(option)).toEqual([])
|
||||
})
|
||||
@@ -1,32 +0,0 @@
|
||||
<template>
|
||||
<VtsOption :option>
|
||||
<span class="vts-detailed-option">
|
||||
<VtsIcon v-if="icon" :name="icon" :tooltip="iconTooltip" size="medium" />
|
||||
{{ option.properties.label }}
|
||||
<span v-if="details" class="em-dash-prefix typo-body-regular-small">{{ details }}</span>
|
||||
</span>
|
||||
</VtsOption>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import VtsOption from '@core/components/select/VtsOption.vue'
|
||||
import type { DropdownAccent } from '@core/components/ui/dropdown/UiDropdown.vue'
|
||||
import type { IconName } from '@core/icons'
|
||||
import type { FormOption } from '@core/packages/form-select/types.ts'
|
||||
|
||||
defineProps<{
|
||||
option: FormOption<{ accent?: DropdownAccent }>
|
||||
icon?: IconName
|
||||
iconTooltip?: string
|
||||
details?: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.vts-detailed-option {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
</style>
|
||||
@@ -22,7 +22,7 @@
|
||||
v-model="searchTerm"
|
||||
:placeholder="searchPlaceholder"
|
||||
right-icon="fa:magnifying-glass"
|
||||
accent="neutral"
|
||||
accent="brand"
|
||||
detached
|
||||
/>
|
||||
</div>
|
||||
@@ -58,7 +58,7 @@ import { computed, inject } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { accent, id } = defineProps<{
|
||||
accent: 'neutral' | 'warning' | 'danger'
|
||||
accent: 'brand' | 'warning' | 'danger'
|
||||
id: TSelectId
|
||||
}>()
|
||||
|
||||
@@ -117,10 +117,6 @@ defineExpose({
|
||||
.search-container {
|
||||
background-color: var(--color-neutral-background-primary);
|
||||
padding: 0.4rem;
|
||||
|
||||
.ui-input:deep(input) {
|
||||
width: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import VtsSuccessStateHero from '@core/components/success-state-hero/VtsSuccessStateHero.vue'
|
||||
import UiAlert from '@core/components/ui/alert/UiAlert.vue'
|
||||
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
|
||||
import { getSuccessState } from '@core-test/get-success-state.ts'
|
||||
import { mount, type VueWrapper } from '@vue/test-utils'
|
||||
import type { Window as HappyDomWindow } from 'happy-dom'
|
||||
|
||||
@@ -18,6 +17,12 @@ function mountSuccessStateHero({ width = 1024, title }: { width?: number; title?
|
||||
})
|
||||
}
|
||||
|
||||
function findTitle(wrapper: VueWrapper) {
|
||||
const title = wrapper.find('.title')
|
||||
|
||||
return title.exists() ? title.text() : undefined
|
||||
}
|
||||
|
||||
function findWidthClasses(wrapper: VueWrapper, selector: string) {
|
||||
return wrapper
|
||||
.get(selector)
|
||||
@@ -30,14 +35,14 @@ describe('VtsSuccessStateHero', () => {
|
||||
{ label: 'renders the title when one is passed', title: 'Title', expected: 'Title' },
|
||||
{ label: 'renders no title when none is passed', title: undefined, expected: undefined },
|
||||
])('$label', ({ title, expected }) => {
|
||||
expect(getSuccessState(mountSuccessStateHero({ title })).title).toBe(expected)
|
||||
expect(findTitle(mountSuccessStateHero({ title }))).toBe(expected)
|
||||
})
|
||||
|
||||
it('renders the message in a success alert', () => {
|
||||
const wrapper = mountSuccessStateHero()
|
||||
const alert = mountSuccessStateHero().getComponent(UiAlert)
|
||||
|
||||
expect(wrapper.getComponent(UiAlert).props('accent')).toBe('success')
|
||||
expect(getSuccessState(wrapper).message).toBe('Message')
|
||||
expect(alert.props('accent')).toBe('success')
|
||||
expect(alert.text()).toBe('Message')
|
||||
})
|
||||
|
||||
it('renders the actions', () => {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<template>
|
||||
<div class="vts-flag-legend">
|
||||
<VtsIcon name="fa:circle" size="current" class="dot" />
|
||||
<span class="typo-body-regular-small">
|
||||
<slot />
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
|
||||
defineSlots<{
|
||||
default(): any
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.vts-flag-legend {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.8rem;
|
||||
color: var(--color-info-txt-base);
|
||||
|
||||
.dot {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,20 +0,0 @@
|
||||
import VtsRow from '@core/components/table/VtsRow.vue'
|
||||
import { mount } from '@vue/test-utils'
|
||||
|
||||
function mountRow(props: { selected?: boolean; error?: boolean; warning?: boolean } = {}) {
|
||||
return mount(VtsRow, { props, attachTo: document.createElement('tbody') })
|
||||
}
|
||||
|
||||
describe('VtsRow', () => {
|
||||
it.each(['selected', 'error', 'warning'] as const)('marks the row as %s', state => {
|
||||
expect(mountRow({ [state]: true }).classes()).toContain(state)
|
||||
})
|
||||
|
||||
it.each(['error', 'warning'] as const)('marks a selected row as %s too', state => {
|
||||
expect(mountRow({ selected: true, [state]: true }).classes()).toEqual(['vts-row', 'selected', state])
|
||||
})
|
||||
|
||||
it('marks the row as nothing by default', () => {
|
||||
expect(mountRow().classes()).toEqual(['vts-row'])
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<tr class="vts-row" :class="{ selected, error, warning }">
|
||||
<tr class="vts-row" :class="{ selected, error }">
|
||||
<slot />
|
||||
</tr>
|
||||
</template>
|
||||
@@ -8,7 +8,6 @@
|
||||
defineProps<{
|
||||
selected?: boolean
|
||||
error?: boolean
|
||||
warning?: boolean
|
||||
}>()
|
||||
</script>
|
||||
|
||||
@@ -18,10 +17,6 @@ defineProps<{
|
||||
--ui-table-cell-background-color: var(--color-brand-background-selected);
|
||||
}
|
||||
|
||||
&.warning {
|
||||
--ui-table-cell-background-color: var(--color-warning-background-selected);
|
||||
}
|
||||
|
||||
&.error {
|
||||
--ui-table-cell-background-color: var(--color-danger-background-selected);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<div v-else class="table-container">
|
||||
<UiTableControlsBar v-if="controlsBarProps" v-bind="controlsBarProps" />
|
||||
<div ref="wrapper" class="wrapper">
|
||||
<table class="table" :class="{ fixed }" vertical-border>
|
||||
<table class="table" vertical-border>
|
||||
<slot />
|
||||
</table>
|
||||
</div>
|
||||
@@ -42,7 +42,6 @@ const { state, sticky, paginationBindings, selectionBindings } = defineProps<{
|
||||
paginationBindings?: PaginationBindings
|
||||
selectionBindings?: SelectionBindings
|
||||
horizontal?: boolean
|
||||
fixed?: boolean
|
||||
}>()
|
||||
|
||||
const controlsBarProps = computed<TableControlsBarProps | undefined>(() => {
|
||||
@@ -95,19 +94,9 @@ const className = computed(() =>
|
||||
}
|
||||
|
||||
.table {
|
||||
min-width: var(--vts-table-min-width, 100%);
|
||||
min-width: 100%;
|
||||
width: max-content;
|
||||
border-spacing: 0;
|
||||
|
||||
&:has(.ui-table-cell.flexible) {
|
||||
width: 100%;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&.fixed {
|
||||
table-layout: fixed;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
&.sticky--left,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<template>
|
||||
<UiTableCell align="center" class="vts-flag-cell">
|
||||
<UiOverridden v-if="flagged" />
|
||||
<VtsIcon v-if="flagged" name="fa:circle" size="current" class="dot" />
|
||||
</UiTableCell>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import UiOverridden from '@core/components/ui/overridden/UiOverridden.vue'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import UiTableCell from '@core/components/ui/table-cell/UiTableCell.vue'
|
||||
|
||||
defineProps<{
|
||||
@@ -16,5 +16,10 @@ defineProps<{
|
||||
<style lang="postcss" scoped>
|
||||
.vts-flag-cell {
|
||||
width: 4rem;
|
||||
|
||||
.dot {
|
||||
font-size: 0.8rem;
|
||||
color: var(--color-info-txt-base);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<template>
|
||||
<UiTableCell :flexible>
|
||||
<UiTableCell>
|
||||
<div class="vts-link-cell">
|
||||
<UiLink size="medium" :icon :icon-tooltip :busy :busy-tooltip :to :href :target class="link">
|
||||
<span v-tooltip class="text-ellipsis"><slot /></span>
|
||||
<slot />
|
||||
<VtsIcon v-if="rightIcon" v-tooltip="rightIcon.tooltip ?? false" :name="rightIcon.icon" size="medium" />
|
||||
</UiLink>
|
||||
<span v-if="slots.suffix" class="interpunct" />
|
||||
@@ -35,7 +35,7 @@ export type VtsLinkCellProps = LinkOptions & {
|
||||
extraCount?: number
|
||||
}
|
||||
|
||||
defineProps<VtsLinkCellProps & { flexible?: boolean }>()
|
||||
defineProps<VtsLinkCellProps>()
|
||||
|
||||
const slots = defineSlots<{
|
||||
default(): any
|
||||
@@ -57,7 +57,6 @@ const { t } = useI18n()
|
||||
}
|
||||
|
||||
.link {
|
||||
min-width: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<UiTableCell class="vts-rank-cell" :class="{ highlighted }">
|
||||
<UiTableCell class="vts-rank-cell">
|
||||
<div class="content">
|
||||
<span :class="{ 'typo-body-bold': highlighted }">{{ label }}</span>
|
||||
<span>{{ rank }}</span>
|
||||
<span v-if="shiftIcon" class="shift">
|
||||
<VtsIcon :name="shiftIcon" size="small" />
|
||||
{{ shiftCount }}
|
||||
@@ -16,18 +16,11 @@ import UiTableCell from '@core/components/ui/table-cell/UiTableCell.vue'
|
||||
import type { IconName } from '@core/icons'
|
||||
import { computed } from 'vue'
|
||||
|
||||
const {
|
||||
rank,
|
||||
shift = 0,
|
||||
highlighted,
|
||||
} = defineProps<{
|
||||
const { shift = 0 } = defineProps<{
|
||||
rank: number
|
||||
shift?: number
|
||||
highlighted?: boolean
|
||||
}>()
|
||||
|
||||
const label = computed(() => (highlighted ? `#${rank}` : rank))
|
||||
|
||||
const shiftIcon = computed<IconName | undefined>(() => {
|
||||
if (shift > 0) {
|
||||
return 'action:move-up'
|
||||
@@ -45,6 +38,8 @@ const shiftCount = computed(() => Math.abs(shift))
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.vts-rank-cell {
|
||||
width: 7rem;
|
||||
|
||||
.content {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
@@ -57,13 +52,5 @@ const shiftCount = computed(() => Math.abs(shift))
|
||||
gap: 0.4rem;
|
||||
color: var(--color-neutral-txt-secondary);
|
||||
}
|
||||
|
||||
&.highlighted {
|
||||
color: var(--color-brand-txt-base);
|
||||
|
||||
.content {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,116 +1,24 @@
|
||||
<template>
|
||||
<UiTableCell capped>
|
||||
<div :class="{ expanded: isExpanded }" class="vts-tag-cell">
|
||||
<UiTagsList v-if="isExpanded" class="tags">
|
||||
<VtsTag v-for="tagItem of tags" :key="tagItem" :value="tagItem" :accent />
|
||||
</UiTagsList>
|
||||
<div v-else ref="container" class="tags">
|
||||
<UiTagsList ref="content" nowrap class="list">
|
||||
<VtsTag
|
||||
v-for="tagItem of visibleTags"
|
||||
:key="tagItem"
|
||||
:value="tagItem"
|
||||
:accent
|
||||
:class="{ truncatable: tagItem === truncatableTag }"
|
||||
class="tag"
|
||||
/>
|
||||
</UiTagsList>
|
||||
</div>
|
||||
<UiButton
|
||||
v-if="isExpanded || hiddenTags.length > 0"
|
||||
v-tooltip="isExpanded ? t('action:show-less') : hiddenTags.join(', ')"
|
||||
:aria-label="isExpanded ? t('action:show-less') : undefined"
|
||||
:aria-expanded="isExpanded"
|
||||
accent="brand"
|
||||
size="small"
|
||||
variant="tertiary"
|
||||
class="typo-body-regular-small more"
|
||||
@click="toggleExpand()"
|
||||
>
|
||||
<VtsIcon v-if="isExpanded" size="small" name="fa:minus" />
|
||||
<template v-else>{{ t('plus-n', { n: hiddenTags.length }) }}</template>
|
||||
</UiButton>
|
||||
</div>
|
||||
<UiTableCell>
|
||||
<UiTagsList>
|
||||
<VtsTag v-for="tagItem of tags" :key="tagItem" :value="tagItem" :accent />
|
||||
</UiTagsList>
|
||||
</UiTableCell>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import VtsTag from '@core/components/tag/VtsTag.vue'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import UiTableCell from '@core/components/ui/table-cell/UiTableCell.vue'
|
||||
import type { TagAccent } from '@core/components/ui/tag/UiTag.vue'
|
||||
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
|
||||
import { useCollapseOnOverflow } from '@core/composables/collapse-on-overflow.composable.ts'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import type { MaybeArray } from '@core/types/utility.type.ts'
|
||||
import { toArray } from '@core/utils/to-array.utils.ts'
|
||||
import { useToggle } from '@vueuse/shared'
|
||||
import { computed, useTemplateRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { computed } from 'vue'
|
||||
|
||||
const { tag, accent } = defineProps<{
|
||||
tag: MaybeArray<string>
|
||||
accent: TagAccent
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const tags = computed(() => toArray(tag).filter(tagItem => tagItem.trim() !== ''))
|
||||
|
||||
const [isExpanded, toggleExpand] = useToggle()
|
||||
|
||||
const container = useTemplateRef('container')
|
||||
|
||||
const content = useTemplateRef('content')
|
||||
|
||||
const { collapsedCount, reset } = useCollapseOnOverflow(container, content, () => Math.max(tags.value.length - 1, 0))
|
||||
|
||||
const visibleCount = computed(() => tags.value.length - collapsedCount.value)
|
||||
|
||||
const visibleTags = computed(() => tags.value.slice(0, visibleCount.value))
|
||||
|
||||
const hiddenTags = computed(() => tags.value.slice(visibleCount.value))
|
||||
|
||||
const truncatableTag = computed(() => visibleTags.value.at(-1))
|
||||
|
||||
watch(
|
||||
() => tags.value.join(),
|
||||
() => reset()
|
||||
)
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.vts-tag-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
|
||||
&.expanded {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.tags {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.list {
|
||||
align-items: center;
|
||||
width: max-content;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.tag {
|
||||
flex-shrink: 0;
|
||||
|
||||
&.truncatable {
|
||||
flex: 1 0 8rem;
|
||||
max-width: max-content;
|
||||
}
|
||||
}
|
||||
|
||||
.more {
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<template>
|
||||
<UiTableCell :flexible>
|
||||
<UiTableCell>
|
||||
<div :class="{ 'with-extra-count': extraCount && extraCount > 0 }" class="content">
|
||||
<VtsIcon v-tooltip="leftIcon?.tooltip ?? false" :name="leftIcon?.icon" size="medium" />
|
||||
<span v-tooltip class="text-ellipsis"><slot /></span>
|
||||
<span><slot /></span>
|
||||
<VtsIcon v-tooltip="rightIcon?.tooltip ?? false" :name="rightIcon?.icon" size="medium" />
|
||||
<span v-if="extraCount && extraCount > 0" class="typo-body-regular-small extra-count">
|
||||
{{ t('plus-n', { n: extraCount }) }}
|
||||
@@ -30,7 +30,7 @@ export type TextCellProps = {
|
||||
extraCount?: number
|
||||
}
|
||||
|
||||
defineProps<TextCellProps & { flexible?: boolean }>()
|
||||
defineProps<TextCellProps>()
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
@@ -40,7 +40,6 @@ const { t } = useI18n()
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.8rem;
|
||||
max-width: 100%;
|
||||
|
||||
&.with-extra-count {
|
||||
display: flex;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<template>
|
||||
<UiTableCell :class="{ expanded: isExpanded }" class="vts-truncated-text-cell">
|
||||
<UiTableCell>
|
||||
<div class="content">
|
||||
<span ref="text" v-tooltip class="text text-ellipsis">
|
||||
{{ content }}
|
||||
<span class="text">
|
||||
{{ truncatedContent }}
|
||||
</span>
|
||||
|
||||
<UiButton
|
||||
v-if="isExpanded || isTruncated"
|
||||
v-if="shouldTruncate"
|
||||
accent="brand"
|
||||
size="small"
|
||||
variant="tertiary"
|
||||
@@ -22,67 +22,43 @@
|
||||
<script setup lang="ts">
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import UiTableCell from '@core/components/ui/table-cell/UiTableCell.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { hasEllipsis } from '@core/utils/has-ellipsis.util.ts'
|
||||
import { useResizeObserver } from '@vueuse/core'
|
||||
import { useToggle } from '@vueuse/shared'
|
||||
import { ref, useTemplateRef, watch } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { content } = defineProps<{
|
||||
const { content, limit } = defineProps<{
|
||||
content: string
|
||||
limit?: number
|
||||
}>()
|
||||
|
||||
const DEFAULT_TRUNCATE_LIMIT = 90
|
||||
|
||||
const TRUNCATE_TOLERANCE = 20
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const truncateLimit = computed(() => limit ?? DEFAULT_TRUNCATE_LIMIT)
|
||||
|
||||
const shouldTruncate = computed(() => content.length > truncateLimit.value + TRUNCATE_TOLERANCE)
|
||||
|
||||
const [isExpanded, toggleExpanded] = useToggle(false)
|
||||
|
||||
const textElement = useTemplateRef('text')
|
||||
const truncatedContent = computed(() => {
|
||||
if (!shouldTruncate.value || isExpanded.value) {
|
||||
return content
|
||||
}
|
||||
|
||||
const isTruncated = ref(false)
|
||||
|
||||
function updateTruncation() {
|
||||
isTruncated.value = hasEllipsis(textElement.value)
|
||||
}
|
||||
|
||||
useResizeObserver(textElement, () => updateTruncation())
|
||||
|
||||
watch(
|
||||
() => content,
|
||||
() => updateTruncation(),
|
||||
{ flush: 'post' }
|
||||
)
|
||||
return `${content.slice(0, truncateLimit.value)}…`
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.vts-truncated-text-cell {
|
||||
max-width: 30rem;
|
||||
.text {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.text {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.button {
|
||||
flex-shrink: 0;
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
|
||||
&.expanded {
|
||||
min-width: 30rem;
|
||||
|
||||
.content {
|
||||
align-items: baseline;
|
||||
}
|
||||
|
||||
.text {
|
||||
white-space: normal;
|
||||
}
|
||||
}
|
||||
.button {
|
||||
float: right;
|
||||
margin-top: -0.25rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,26 +1,22 @@
|
||||
<template>
|
||||
<UiTableCell :flexible>
|
||||
<UiTableCell>
|
||||
<div class="user-name">
|
||||
<UiUserLogo size="small" />
|
||||
<UiLink :href size="medium" class="link">
|
||||
<VtsMiddleEllipsis v-if="flexible" :text="content" />
|
||||
<span v-else v-tooltip class="text-ellipsis">{{ content }}</span>
|
||||
<UiLink :href size="medium">
|
||||
{{ content }}
|
||||
</UiLink>
|
||||
</div>
|
||||
</UiTableCell>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import VtsMiddleEllipsis from '@core/components/middle-ellipsis/VtsMiddleEllipsis.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
import UiTableCell from '@core/components/ui/table-cell/UiTableCell.vue'
|
||||
import UiUserLogo from '@core/components/ui/user-logo/UiUserLogo.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
|
||||
defineProps<{
|
||||
content: string
|
||||
href?: string
|
||||
flexible?: boolean
|
||||
}>()
|
||||
</script>
|
||||
|
||||
@@ -30,8 +26,4 @@ defineProps<{
|
||||
align-items: center;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.link {
|
||||
min-width: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,554 +0,0 @@
|
||||
import VtsTag from '@core/components/tag/VtsTag.vue'
|
||||
import VtsTagSelect, { type TagSelectSuggestion } from '@core/components/tag-select/VtsTagSelect.vue'
|
||||
import VtsTagSelectOption from '@core/components/tag-select/VtsTagSelectOption.vue'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import UiDropdown from '@core/components/ui/dropdown/UiDropdown.vue'
|
||||
import UiLoader from '@core/components/ui/loader/UiLoader.vue'
|
||||
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
|
||||
import { t } from '@core-test/i18n.ts'
|
||||
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
||||
import type { Window as HappyDomWindow } from 'happy-dom'
|
||||
|
||||
const SUGGESTIONS: TagSelectSuggestion[] = [
|
||||
{ tag: 'analytics', info: '1 VM' },
|
||||
{ tag: 'db', info: '1 VM' },
|
||||
{ tag: 'production', info: '2 VMs' },
|
||||
{ tag: 'web', info: '1 VM' },
|
||||
]
|
||||
|
||||
type TagSelectProps = {
|
||||
tags?: string[]
|
||||
suggestions?: TagSelectSuggestion[]
|
||||
iconOnly?: boolean
|
||||
busy?: boolean
|
||||
}
|
||||
|
||||
function mountTagSelect({ tags = ['production', 'web'], suggestions = SUGGESTIONS, ...props }: TagSelectProps = {}) {
|
||||
return mount(VtsTagSelect, {
|
||||
props: { tags, suggestions, ...props },
|
||||
global: createGlobalTestConfig(),
|
||||
})
|
||||
}
|
||||
|
||||
// By its accessible name: its text, or its `aria-label` for an icon button, which has no text
|
||||
function getButton(wrapper: VueWrapper, label: string) {
|
||||
const button = wrapper.findAll('button').find(button => (button.text() || button.attributes('aria-label')) === label)
|
||||
|
||||
if (button === undefined) {
|
||||
throw new Error(`No button "${label}"`)
|
||||
}
|
||||
|
||||
return button
|
||||
}
|
||||
|
||||
function getUiButton(wrapper: VueWrapper, label: string) {
|
||||
const button = wrapper.findAllComponents(UiButton).find(button => button.text() === label)
|
||||
|
||||
if (button === undefined) {
|
||||
throw new Error(`No UiButton "${label}"`)
|
||||
}
|
||||
|
||||
return button
|
||||
}
|
||||
|
||||
async function clickButton(wrapper: VueWrapper, label: string) {
|
||||
await getButton(wrapper, label).trigger('click')
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
async function openTagSelect(wrapper: VueWrapper) {
|
||||
await flushPromises()
|
||||
await wrapper.get('.ui-button, .ui-button-icon').trigger('click')
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
async function searchTag(wrapper: VueWrapper, search: string) {
|
||||
await wrapper.get('.search-container input').setValue(search)
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
function findOptions(wrapper: VueWrapper) {
|
||||
return wrapper.findAllComponents(VtsTagSelectOption).map(option => ({
|
||||
tag: option.getComponent(VtsTag).props('value'),
|
||||
dropdown: option.getComponent(UiDropdown),
|
||||
element: option,
|
||||
}))
|
||||
}
|
||||
|
||||
function findOptionTags(wrapper: VueWrapper) {
|
||||
return findOptions(wrapper).map(({ tag }) => tag)
|
||||
}
|
||||
|
||||
function findCheckedOptionTags(wrapper: VueWrapper) {
|
||||
return findOptions(wrapper)
|
||||
.filter(({ dropdown }) => dropdown.props('selected'))
|
||||
.map(({ tag }) => tag)
|
||||
}
|
||||
|
||||
async function clickTagOption(wrapper: VueWrapper, tag: string) {
|
||||
const option = findOptions(wrapper).find(option => option.tag === tag)
|
||||
|
||||
if (option === undefined) {
|
||||
throw new Error(`No option for the tag "${tag}"`)
|
||||
}
|
||||
|
||||
await option.element.trigger('click')
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
function findCurrentTags(wrapper: VueWrapper) {
|
||||
return wrapper
|
||||
.findAllComponents(VtsTag)
|
||||
.filter(tag => tag.element.closest('.current-tags') !== null)
|
||||
.map(tag => tag.props('value'))
|
||||
}
|
||||
|
||||
async function removeCurrentTag(wrapper: VueWrapper, tag: string) {
|
||||
const currentTag = wrapper
|
||||
.findAllComponents(VtsTag)
|
||||
.find(currentTag => currentTag.element.closest('.current-tags') !== null && currentTag.props('value') === tag)
|
||||
|
||||
if (currentTag === undefined) {
|
||||
throw new Error(`No current tag "${tag}"`)
|
||||
}
|
||||
|
||||
await currentTag.get('button.remove').trigger('click')
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
function findSavedChanges(wrapper: VueWrapper) {
|
||||
return wrapper.emitted('save')?.map(([changes]) => changes)
|
||||
}
|
||||
|
||||
function isDropdownOpen(wrapper: VueWrapper) {
|
||||
return wrapper.find('.dropdown-list').exists()
|
||||
}
|
||||
|
||||
const DEFAULT_VIEWPORT_WIDTH = 1024
|
||||
|
||||
function setViewportWidth(width: number) {
|
||||
;(window as unknown as HappyDomWindow).happyDOM.setViewport({ width })
|
||||
}
|
||||
|
||||
describe('trigger', () => {
|
||||
it('offers to add tags when there are none', () => {
|
||||
const wrapper = mountTagSelect({ tags: [] })
|
||||
|
||||
expect(() => getButton(wrapper, t('action:add'))).not.toThrow()
|
||||
})
|
||||
|
||||
it('offers to edit the tags when there are some', () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
expect(() => getButton(wrapper, t('action:edit'))).not.toThrow()
|
||||
})
|
||||
|
||||
it('renders an icon button labelled with its action when icon-only', () => {
|
||||
const wrapper = mountTagSelect({ iconOnly: true })
|
||||
|
||||
expect(wrapper.findComponent(UiButton).exists()).toBe(false)
|
||||
expect(wrapper.getComponent(UiButtonIcon).attributes('aria-label')).toBe(t('action:edit'))
|
||||
})
|
||||
|
||||
it('marks the text trigger as busy', () => {
|
||||
const wrapper = mountTagSelect({ busy: true })
|
||||
|
||||
expect(getUiButton(wrapper, t('action:edit')).props('busy')).toBe(true)
|
||||
})
|
||||
|
||||
it('disables the icon-only trigger and shows a loader when busy', () => {
|
||||
const wrapper = mountTagSelect({ iconOnly: true, busy: true })
|
||||
|
||||
expect(wrapper.getComponent(UiButtonIcon).props('disabled')).toBe(true)
|
||||
expect(wrapper.findComponent(UiLoader).exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('shows no loader on the icon-only trigger when not busy', () => {
|
||||
const wrapper = mountTagSelect({ iconOnly: true })
|
||||
|
||||
expect(wrapper.getComponent(UiButtonIcon).props('disabled')).toBe(false)
|
||||
expect(wrapper.findComponent(UiLoader).exists()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('options', () => {
|
||||
it('lists the tags and the suggestions in alphabetical order, with their info', async () => {
|
||||
const wrapper = mountTagSelect({ tags: ['web', 'custom'], suggestions: SUGGESTIONS.slice(0, 3) })
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
expect(findOptions(wrapper).map(({ tag, dropdown }) => [tag, dropdown.props('info')])).toEqual([
|
||||
['analytics', '1 VM'],
|
||||
['custom', undefined],
|
||||
['db', '1 VM'],
|
||||
['production', '2 VMs'],
|
||||
['web', undefined],
|
||||
])
|
||||
})
|
||||
|
||||
it('checks the current tags', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
expect(findCheckedOptionTags(wrapper)).toEqual(['production', 'web'])
|
||||
})
|
||||
|
||||
it('keeps the order of the tags while they are selected and deselected', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickTagOption(wrapper, 'db')
|
||||
await clickTagOption(wrapper, 'web')
|
||||
|
||||
expect(findOptionTags(wrapper)).toEqual(['analytics', 'db', 'production', 'web'])
|
||||
expect(findCheckedOptionTags(wrapper)).toEqual(['db', 'production'])
|
||||
})
|
||||
|
||||
it('keeps listing a created tag once deselected', async () => {
|
||||
const wrapper = mountTagSelect({ suggestions: [] })
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await searchTag(wrapper, 'brand-new')
|
||||
await clickTagOption(wrapper, 'brand-new')
|
||||
await searchTag(wrapper, '')
|
||||
await clickTagOption(wrapper, 'brand-new')
|
||||
|
||||
expect(findOptionTags(wrapper)).toEqual(['brand-new', 'production', 'web'])
|
||||
expect(findCheckedOptionTags(wrapper)).toEqual(['production', 'web'])
|
||||
})
|
||||
|
||||
it('filters the tags on the search', async () => {
|
||||
const wrapper = mountTagSelect({ suggestions: [{ tag: 'production-eu' }, { tag: 'db' }] })
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await searchTag(wrapper, 'prod')
|
||||
|
||||
expect(findOptionTags(wrapper)).toEqual(['prod', 'production', 'production-eu'])
|
||||
})
|
||||
|
||||
it('does not offer the empty tag', async () => {
|
||||
const wrapper = mountTagSelect({ suggestions: [{ tag: '' }, { tag: 'db' }] })
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
expect(findOptionTags(wrapper)).toEqual(['db', 'production', 'web'])
|
||||
})
|
||||
|
||||
it('explains how to create a scoped tag', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
expect(wrapper.get('.scoped-tag-hint').text()).toBe(t('scoped-tag-hint'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('creating a tag', () => {
|
||||
it('offers to create the trimmed searched tag when no tag matches it exactly', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await searchTag(wrapper, ' brand-new ')
|
||||
|
||||
const [createOption, ...otherOptions] = findOptions(wrapper)
|
||||
|
||||
expect(createOption.tag).toBe('brand-new')
|
||||
expect(createOption.element.text()).toContain(t('action:create'))
|
||||
expect(otherOptions).toEqual([])
|
||||
})
|
||||
|
||||
it('displays the tag to create with a "+" instead of a checkbox', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await searchTag(wrapper, 'brand-new')
|
||||
|
||||
const [{ dropdown }] = findOptions(wrapper)
|
||||
|
||||
expect(dropdown.props('checkbox')).toBe(false)
|
||||
expect(dropdown.props('icon')).toBe('action:add')
|
||||
})
|
||||
|
||||
it('does not offer to create a tag that already exists', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await searchTag(wrapper, 'db')
|
||||
|
||||
expect(findOptionTags(wrapper)).toEqual(['db'])
|
||||
expect(findOptions(wrapper)[0].dropdown.props('checkbox')).toBe(true)
|
||||
})
|
||||
|
||||
it('adds the created tag on save', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await searchTag(wrapper, 'brand-new')
|
||||
await clickTagOption(wrapper, 'brand-new')
|
||||
await clickButton(wrapper, t('action:save'))
|
||||
|
||||
expect(findSavedChanges(wrapper)).toEqual([{ added: ['brand-new'], removed: [] }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('saving', () => {
|
||||
it('emits nothing until the changes are saved', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickTagOption(wrapper, 'db')
|
||||
await clickTagOption(wrapper, 'web')
|
||||
|
||||
expect(findSavedChanges(wrapper)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the save button enabled when nothing has changed', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
expect(getUiButton(wrapper, t('action:save')).props('disabled')).toBeFalsy()
|
||||
|
||||
await clickTagOption(wrapper, 'db')
|
||||
await clickTagOption(wrapper, 'db')
|
||||
|
||||
expect(getUiButton(wrapper, t('action:save')).props('disabled')).toBeFalsy()
|
||||
})
|
||||
|
||||
it('only closes the dropdown when saving without changes', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickTagOption(wrapper, 'db')
|
||||
await clickTagOption(wrapper, 'db')
|
||||
await clickButton(wrapper, t('action:save'))
|
||||
|
||||
expect(findSavedChanges(wrapper)).toBeUndefined()
|
||||
expect(isDropdownOpen(wrapper)).toBe(false)
|
||||
})
|
||||
|
||||
it('emits the additions and removals and closes the dropdown on save', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickTagOption(wrapper, 'db')
|
||||
await clickTagOption(wrapper, 'web')
|
||||
await clickButton(wrapper, t('action:save'))
|
||||
|
||||
expect(findSavedChanges(wrapper)).toEqual([{ added: ['db'], removed: ['web'] }])
|
||||
expect(isDropdownOpen(wrapper)).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the changes in progress when the tags are updated meanwhile', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickTagOption(wrapper, 'db')
|
||||
await clickTagOption(wrapper, 'web')
|
||||
|
||||
await wrapper.setProps({ tags: ['production', 'web'] })
|
||||
await flushPromises()
|
||||
|
||||
expect(findCheckedOptionTags(wrapper)).toEqual(['db', 'production'])
|
||||
})
|
||||
|
||||
it('only emits its own changes when the tags are changed meanwhile', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickTagOption(wrapper, 'db')
|
||||
|
||||
await wrapper.setProps({ tags: ['production', 'backup'] })
|
||||
await flushPromises()
|
||||
|
||||
await clickButton(wrapper, t('action:save'))
|
||||
|
||||
expect(findSavedChanges(wrapper)).toEqual([{ added: ['db'], removed: [] }])
|
||||
})
|
||||
|
||||
it('discards the changes on cancel', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickTagOption(wrapper, 'db')
|
||||
await clickButton(wrapper, t('cancel'))
|
||||
|
||||
expect(isDropdownOpen(wrapper)).toBe(false)
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
expect(findCheckedOptionTags(wrapper)).toEqual(['production', 'web'])
|
||||
expect(findSavedChanges(wrapper)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('discards the changes when the dropdown is closed without saving', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickTagOption(wrapper, 'db')
|
||||
await wrapper.trigger('keydown', { key: 'Escape' })
|
||||
await flushPromises()
|
||||
|
||||
expect(isDropdownOpen(wrapper)).toBe(false)
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
expect(findCheckedOptionTags(wrapper)).toEqual(['production', 'web'])
|
||||
expect(findSavedChanges(wrapper)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('selecting all the tags', () => {
|
||||
it('adds all the listed tags missing from the current tags', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickButton(wrapper, t('action:select-all'))
|
||||
await clickButton(wrapper, t('action:save'))
|
||||
|
||||
expect(findSavedChanges(wrapper)).toEqual([{ added: ['analytics', 'db'], removed: [] }])
|
||||
})
|
||||
|
||||
it('only adds the tags matching the search', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await searchTag(wrapper, 'db')
|
||||
await clickButton(wrapper, t('action:select-all'))
|
||||
await clickButton(wrapper, t('action:save'))
|
||||
|
||||
expect(findSavedChanges(wrapper)).toEqual([{ added: ['db'], removed: [] }])
|
||||
})
|
||||
|
||||
it('removes all the current tags', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickButton(wrapper, t('action:deselect-all'))
|
||||
await clickButton(wrapper, t('action:save'))
|
||||
|
||||
expect(findSavedChanges(wrapper)).toEqual([{ added: [], removed: ['production', 'web'] }])
|
||||
})
|
||||
|
||||
it('cannot select all the tags when they are all already selected', async () => {
|
||||
const wrapper = mountTagSelect({ suggestions: [] })
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
expect(getUiButton(wrapper, t('action:select-all')).props('disabled')).toBe(true)
|
||||
expect(getUiButton(wrapper, t('action:deselect-all')).props('disabled')).toBe(false)
|
||||
})
|
||||
|
||||
it('cannot deselect all the tags when none of the listed tags is selected', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await searchTag(wrapper, 'db')
|
||||
|
||||
expect(getUiButton(wrapper, t('action:select-all')).props('disabled')).toBe(false)
|
||||
expect(getUiButton(wrapper, t('action:deselect-all')).props('disabled')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('current tags', () => {
|
||||
it('lists the selected tags above the search, in alphabetical order', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickTagOption(wrapper, 'db')
|
||||
|
||||
expect(findCurrentTags(wrapper)).toEqual(['db', 'production', 'web'])
|
||||
})
|
||||
|
||||
it('deselects a tag removed from the current tags', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await removeCurrentTag(wrapper, 'web')
|
||||
|
||||
expect(findCurrentTags(wrapper)).toEqual(['production'])
|
||||
expect(findCheckedOptionTags(wrapper)).toEqual(['production'])
|
||||
|
||||
await clickButton(wrapper, t('action:save'))
|
||||
|
||||
expect(findSavedChanges(wrapper)).toEqual([{ added: [], removed: ['web'] }])
|
||||
})
|
||||
|
||||
it('hides the current tags when no tag is selected', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
expect(wrapper.find('.current-tags').exists()).toBe(true)
|
||||
|
||||
await clickButton(wrapper, t('action:deselect-all'))
|
||||
|
||||
expect(wrapper.find('.current-tags').exists()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('empty tag', () => {
|
||||
it('lists the empty tag in the current tags, without offering to remove it', async () => {
|
||||
const wrapper = mountTagSelect({ tags: ['', 'production'] })
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
const emptyTag = wrapper.get('.current-tags').getComponent(VtsTag)
|
||||
|
||||
expect(emptyTag.props('value')).toBe('')
|
||||
expect(emptyTag.props('removable')).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the empty tag when deselecting all the tags', async () => {
|
||||
const wrapper = mountTagSelect({ tags: ['', 'production'] })
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickButton(wrapper, t('action:deselect-all'))
|
||||
|
||||
expect(findCurrentTags(wrapper)).toEqual([''])
|
||||
|
||||
await clickButton(wrapper, t('action:save'))
|
||||
|
||||
expect(findSavedChanges(wrapper)).toEqual([{ added: [], removed: ['production'] }])
|
||||
})
|
||||
|
||||
it('removes a whitespace-only tag unchecked in the options', async () => {
|
||||
const wrapper = mountTagSelect({ tags: [' ', 'production'], suggestions: [] })
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
await clickTagOption(wrapper, ' ')
|
||||
await clickButton(wrapper, t('action:save'))
|
||||
|
||||
expect(findSavedChanges(wrapper)).toEqual([{ added: [], removed: [' '] }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('dropdown layout', () => {
|
||||
afterEach(() => setViewportWidth(DEFAULT_VIEWPORT_WIDTH))
|
||||
|
||||
it('floats the dropdown next to its trigger on a large screen', async () => {
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
const dropdown = wrapper.get<HTMLElement>('.dropdown-list')
|
||||
|
||||
expect(dropdown.classes('fullscreen')).toBe(false)
|
||||
expect(dropdown.element.style.position).toBe('fixed')
|
||||
})
|
||||
|
||||
it('opens the dropdown fullscreen on a small screen', async () => {
|
||||
setViewportWidth(800)
|
||||
|
||||
const wrapper = mountTagSelect()
|
||||
|
||||
await openTagSelect(wrapper)
|
||||
|
||||
const dropdown = wrapper.get<HTMLElement>('.dropdown-list')
|
||||
|
||||
expect(dropdown.classes('fullscreen')).toBe(true)
|
||||
expect(dropdown.element.style.position).toBe('')
|
||||
})
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user