Skip to content

Commit

Permalink
[#57] Adds tabs component
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuapease committed Jan 3, 2025
1 parent ec6ff44 commit 32bfb50
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
75 changes: 75 additions & 0 deletions templates/_components/tabs.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
{# @var array{title: string, content: string}[] tabs #}
{% set tabs = tabs ?? [] %}

{# @var int activeIndex #}
{% set activeIndex = activeIndex ?? 0 %}

{# Computed attributes #}

{% set id = 'tabs-' ~ random() %}

<div
class="dark:text-white"
x-data="{
activeIndex: {{ activeIndex }},
selectTab(event) {
const tab = event.target
this.activeIndex = parseInt(tab.dataset.index, 10)
$nextTick(() => {
document.getElementById(tab.getAttribute('aria-controls')).focus()
})
},
get activeTab() {
return $root.querySelector(`button[aria-selected=true]`)
},
}"
>
<ul class="mb-16 flex border-b" role="tablist">
{% for tab in tabs %}
<li>
<button
data-index="{{ loop.index0 }}"
id="{{ id }}-tab-{{ loop.index }}"
class="group cursor-pointer bg-transparent px-8 pb-4 transition-colors aria-selected:font-bold aria-selected:shadow-[inset_0_-3px_theme(colors.blue.500)]"
role="tab"
aria-controls="{{ id }}-tabpanel-{{ loop.index }}"
:aria-selected="activeIndex === {{ loop.index0 }}"
@click="selectTab"
>
<span
class="pointer-events-none mb-4 flex items-center justify-center rounded px-8 py-0 group-hover:bg-gray-100 group-active:bg-gray-200 dark:group-hover:bg-gray-800 dark:group-active:bg-gray-700"
>
{{ tab.title }}
</span>
</button>
</li>
{% endfor %}
</ul>

{% for tab in tabs %}
<div
id="{{ id }}-tabpanel-{{ loop.index }}"
aria-labelledby="{{ id }}-tab-{{ loop.index }}"
role="tabpanel"
tabindex="0"
:hidden="activeIndex !== {{ loop.index0 }}"
{{ attr({
'x-cloak': activeIndex != loop.index0 ? '' : null,
}) }}
>
{{ tab.content }}
</div>
{% endfor %}

{{ include('_components/button.twig', {
text: 'Back to tabs list',
size: 'sm',
variant: 'text',
class: 'sr-only focus:not-sr-only focus:mt-16 focus:z-max',
attrs: {
'@click': 'activeTab.focus()',
},
}) }}
</div>

21 changes: 21 additions & 0 deletions templates/parts-kit/tabs/default.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{% extends "viget-parts-kit/layout.twig" %}

{% block main %}
<div class="container py-64">
{{ include('_components/tabs.twig', {
tabs: [
{ title: 'Tab 1', content: 'Content for Tab 1' },
{ title: 'Tab 2', content: 'Content for Tab 2' },
],
}) }}
</div>

<div class="container py-64 bg-black dark">
{{ include('_components/tabs.twig', {
tabs: [
{ title: 'Tab 1', content: 'Content for Tab 1' },
{ title: 'Tab 2', content: 'Content for Tab 2' },
],
}) }}
</div>
{% endblock %}

0 comments on commit 32bfb50

Please sign in to comment.