Skip to content

Commit

Permalink
fix(ktabs): allow tab anchors to be links [KHCP-13866] (#2532)
Browse files Browse the repository at this point in the history
* fix(kcodeblock): ts error [KHCP-11924]

* fix(ktabs): allow tab anchores to be links [KHCP-13866]

* fix: address pr feedback

* fix(ktabs): revert role navigation changes [KHCP-13866]
  • Loading branch information
portikM authored Dec 3, 2024
1 parent 1da8ca3 commit cdf5caa
Show file tree
Hide file tree
Showing 6 changed files with 141 additions and 78 deletions.
98 changes: 61 additions & 37 deletions docs/components/tabs.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,18 @@ Required prop, which is an array of tab objects with the following interface:

```ts
interface Tab {
hash: string // has to be unique, corresponds to the panel slot name
hash: string
title: string
disabled?: boolean
disabled?: boolean,
to?: string | object
}
```

* `hash` - has to be unique, corresponds to the panel slot name
* `title` - title to be displayed in the tab
* `disabled` - whether or not tab is disabled
* `to` - if present, tab will be rendered as either a `router-link` or an `a`

<KTabs :tabs="tabsWithDisabled">
<template #tab1>
<p>Tab 1 content</p>
Expand Down Expand Up @@ -75,6 +81,45 @@ interface Tab {
</KTabs>
```

#### Tabs as links

Passing the `to` property for each tab object enables rendering tabs as links. If a string is provided, it will be used as the `href` attribute in the rendered `a` element. If an object is provided, the tab will be rendered as a `router-link`.

:::tip TIP
When creating tab links, it is recommended to set the [`hidePanels` prop](#hidepanels) to `true`, as page changes typically do not involve the use of [`panel` slots](#slots).
:::

<KTabs :tabs="linkTabs" hide-panels v-model="linkTabValue" />

{{ linkTabValue }}

```vue
<template>
<KTabs :tabs="linkTabs" hide-panels />
<router-view v-slot="{ route }">
{{ route.hash }}
</router-view>
</template>
<script setup lang="ts">
import { Tab } from '@kong/kongponents'
const linkTabs = ref<Tab[]>([
{
hash: '#tab1',
title: 'Tab 1',
to: '#tab-link-1'
},
{
hash: '#tab2',
title: 'Tab 2',
to: '#tab-link-2'
},
])
</script>
```

### v-model

KTabs will set the first tab in the `tabs` array as active. You can override this by passing in the hash of any other tab to be used with `v-model`.
Expand Down Expand Up @@ -176,41 +221,6 @@ const tabChange = (hash: string): void => {
</script>
```

### anchorTabindex

This prop allows setting a custom `tabindex` for the tab anchor element. It’s useful when passing a custom interactive element, like a link, through the [`anchor` slot](#anchor-panel), ensuring that only the slotted element is focusable by resetting the default anchor `tabindex`. Default value is `0`.

#### Dynamic RouterView

Here's an example (code only) of utilizing a dynamic `router-view` component within the host app:

```html
<KTabs
hide-panels
:tabs="tabs"
>
<template
v-for="tab in tabs"
:key="`${tab.hash}-anchor`"
#[`${tab.hash}-anchor`]
>
<router-link
:to="{
name: tab.hash.split('?').shift(),
hash: `#${tab.hash.split('?').pop()}`,
}"
>
{{ tab.title }}
</router-link>
</template>
</KTabs>

<router-view v-slot="{ route }">
<h3>Router View content</h3>
<p>{{ route.path }}{{ route.hash }}</p>
</router-view>
```

## Slots

### anchor & panel
Expand Down Expand Up @@ -322,6 +332,20 @@ const slottedTabs = ref<Tab[]>([
{ hash: '#disabled', title: 'Disabled', disabled: true }
])

const linkTabValue = ref<string>('#tab-link-1')
const linkTabs = ref<Tab[]>([
{
hash: '#tab-link-1',
title: 'Tab 1',
to: '#tab-link-1',
},
{
hash: '#tab-link-2',
title: 'Tab 2',
to: '#tab-link-2',
},
])

const panelsActiveHash = ref('#gateway')

const panelsChange = (hash: string) => {
Expand Down
20 changes: 4 additions & 16 deletions sandbox/pages/SandboxTabs.vue
Original file line number Diff line number Diff line change
Expand Up @@ -111,25 +111,11 @@
/>
<SandboxSectionComponent title="Dynamic router view without panels">
<KTabs
:anchor-tabindex="-1"
hide-panels
:tabs="dynamicRouterViewItems"
@change="(hash: string) => $router.replace({ hash })"
>
<template #one-anchor>
<router-link :to="{ hash: '#one' }">
One
</router-link>
</template>
<template #two-anchor>
<router-link :to="{ hash: '#two' }">
Two
</router-link>
</template>
</KTabs>
<router-view
v-slot="{route}"
>
/>
<router-view v-slot="{ route }">
<p>{{ route.path }}{{ route.hash }}</p>
</router-view>
</SandboxSectionComponent>
Expand Down Expand Up @@ -174,10 +160,12 @@ const dynamicRouterViewItems = [
{
title: 'One',
hash: '#one',
to: { hash: '#one' },
},
{
title: 'Two',
hash: '#two',
to: { hash: '#two' },
},
]
</script>
2 changes: 1 addition & 1 deletion src/components/KCodeBlock/KCodeBlock.vue
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ const matchingLineNumbers = ref<number[]>([])
const currentLineIndex = ref<null | number>(null)
const totalLines = computed((): number[] => Array.from({ length: props.code?.split('\n').length }, (_, index) => index + 1))
const maxLineNumberWidth = computed((): string => totalLines.value[totalLines.value.length - 1]?.toString().length + 'ch')
const maxLineNumberWidth = computed((): string => totalLines.value[totalLines.value?.length - 1]?.toString().length + 'ch')
const linePrefix = computed((): string => props.id.toLowerCase().replace(/\s+/g, '-'))
const isProcessing = computed((): boolean => props.processing || isProcessingInternally.value)
const isShowingFilteredCode = computed((): boolean => isFilterMode.value && filteredCode.value !== '')
Expand Down
36 changes: 34 additions & 2 deletions src/components/KTabs/KTabs.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ describe('KTabs', () => {
})
})

it('hides the panel content when `hidePanels` is true', () => {
it('hides the panel content when hidePanels is true', () => {
const picturesSlot = 'I love pictures'
const moviesSlot = 'I love pictures'
const booksSlot = 'I love pictures'
Expand Down Expand Up @@ -75,7 +75,7 @@ describe('KTabs', () => {

// handles disabled item correctly

it('disables the tab item when `disabled` is true', () => {
it('disables the tab item when disabled is true', () => {
const tabs = [
{ hash: '#pictures', title: 'Pictures' },
{ hash: '#movies', title: 'Movies', disabled: true },
Expand All @@ -94,6 +94,38 @@ describe('KTabs', () => {
})
})

it('renders the tab as a link if tab.to is present', () => {
const tabs = [
{ hash: '#pictures', title: 'Pictures' },
{ hash: '#movies', title: 'Movies', to: '/movies' },
{ hash: '#books', title: 'Books' },
]

cy.mount(KTabs, {
props: {
tabs,
},
})

cy.get('.tab-item .tab-link').eq(1).should('have.attr', 'href', '/movies')
})

it('renders the tab as a link with no href attribute if tab.to is present and tab.disabled is true', () => {
const tabs = [
{ hash: '#pictures', title: 'Pictures' },
{ hash: '#movies', title: 'Movies', to: '/movies', disabled: true },
{ hash: '#books', title: 'Books' },
]

cy.mount(KTabs, {
props: {
tabs,
},
})

cy.get('.tab-item .tab-link').eq(1).should('not.have.attr', 'href')
})

describe('slots', () => {
it('provides the #hash slot content', () => {
const picturesSlot = 'I love pictures'
Expand Down
60 changes: 38 additions & 22 deletions src/components/KTabs/KTabs.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,24 @@
class="tab-item"
:class="{ active: activeTab === tab.hash }"
>
<div
<component
:is="tabComponent(tab).tag"
:aria-controls="hidePanels ? undefined : `panel-${tab.hash}`"
:aria-selected="hidePanels ? undefined : (activeTab === tab.hash ? 'true' : 'false')"
class="tab-link"
:class="{ 'has-panels': !hidePanels, disabled: tab.disabled }"
:class="{ disabled: tab.disabled }"
role="tab"
:tabindex="getAnchorTabindex(tab)"
v-bind="tabComponent(tab).attributes"
@click="!tab.disabled ? handleTabChange(tab.hash) : undefined"
@click.prevent="!tab.disabled ? handleTabChange(tab.hash) : undefined"
@keydown.enter.prevent="!tab.disabled ? handleTabChange(tab.hash) : undefined"
@keydown.space.prevent="!tab.disabled ? handleTabChange(tab.hash) : undefined"
>
<slot :name="`${getTabSlotName(tab.hash)}-anchor`">
<span>{{ tab.title }}</span>
</slot>
</div>
</component>
</li>
</ul>

Expand Down Expand Up @@ -75,6 +78,9 @@ const props = defineProps({
type: Boolean,
default: false,
},
/**
* @deprecated
*/
anchorTabindex: {
type: Number,
default: 0,
Expand Down Expand Up @@ -105,6 +111,18 @@ const getAnchorTabindex = (tab: Tab): string => {
return typeof props.anchorTabindex === 'number' && props.anchorTabindex >= -1 && props.anchorTabindex <= 32767 ? String(props.anchorTabindex) : '0'
}
const tabComponent = (tab: Tab) => {
if (tab.to) {
if (typeof tab.to === 'string') {
return { tag: 'a', attributes: { href: tab.disabled ? undefined : tab.to } }
} else if (typeof tab.to === 'object') {
return { tag: 'router-link', attributes: { to: tab.disabled ? undefined : tab.to } }
}
}
return { tag: 'div', attributes: {} }
}
watch(() => props.modelValue, (newTabHash) => {
activeTab.value = newTabHash
emit('change', newTabHash)
Expand All @@ -125,11 +143,7 @@ watch(() => props.modelValue, (newTabHash) => {
ul {
border-bottom: var(--kui-border-width-10, $kui-border-width-10) solid var(--kui-color-border, $kui-color-border);
display: flex;
font-family: var(--kui-font-family-text, $kui-font-family-text);
font-size: var(--kui-font-size-30, $kui-font-size-30);
font-weight: var(--kui-font-weight-semibold, $kui-font-weight-semibold);
gap: var(--kui-space-40, $kui-space-40);
line-height: var(--kui-line-height-40, $kui-line-height-40);
list-style: none;
margin-bottom: var(--kui-space-70, $kui-space-70);
margin-top: var(--kui-space-0, $kui-space-0);
Expand All @@ -148,30 +162,23 @@ watch(() => props.modelValue, (newTabHash) => {
white-space: nowrap;
.tab-link {
@include defaultButtonReset;
align-items: center;
border-radius: var(--kui-border-radius-30, $kui-border-radius-30);
color: var(--kui-color-text-neutral, $kui-color-text-neutral);
cursor: pointer;
display: inline-flex;
font-family: var(--kui-font-family-text, $kui-font-family-text);
font-size: var(--kui-font-size-30, $kui-font-size-30);
font-weight: var(--kui-font-weight-semibold, $kui-font-weight-semibold);
gap: var(--kui-space-40, $kui-space-40);
line-height: var(--kui-line-height-40, $kui-line-height-40);
padding: var(--kui-space-30, $kui-space-30) var(--kui-space-50, $kui-space-50);
text-decoration: none;
transition: color $kongponentsTransitionDurTimingFunc, background-color $kongponentsTransitionDurTimingFunc, box-shadow $kongponentsTransitionDurTimingFunc;
user-select: none;
// Applies the padding to the tab’s content when not showing panels which is typically used for placing links inside KTabs for navigational tabs. Otherwise, clicking the tab outside of the link’s box will mark it as active but won’t actually navigate.
&.has-panels,
&:not(.has-panels) :deep(> *) {
padding: var(--kui-space-30, $kui-space-30) var(--kui-space-50, $kui-space-50);
}
a, :deep(a) {
color: var(--kui-color-text-neutral, $kui-color-text-neutral);
text-decoration: none;
&:focus-visible {
@include kTabsFocus;
}
}
&:hover:not(.disabled) {
background-color: var(--kui-color-background-neutral-weaker, $kui-color-background-neutral-weaker);
}
Expand All @@ -184,6 +191,15 @@ watch(() => props.modelValue, (newTabHash) => {
color: var(--kui-color-text-disabled, $kui-color-text-disabled);
cursor: not-allowed;
}
:slotted(a) {
color: var(--kui-color-text-neutral, $kui-color-text-neutral);
text-decoration: none;
&:focus-visible {
@include kTabsFocus;
}
}
}
&.active {
Expand Down
3 changes: 3 additions & 0 deletions src/types/tabs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
export interface Tab {
/** Has to be unique, corresponds to the panel slot name */
hash: string
title: string
disabled?: boolean
/** If present, tab will be rendered as either a router-link or an anchor */
to?: string | object
}

0 comments on commit cdf5caa

Please sign in to comment.