Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds ability to sync tabs instances by group #260

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/tabs.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ application.register('tabs', Tabs)

`data-tabs-update-anchor-value="true"` can be used to update the URL anchor when the tab changes.

`data-tabs-sync-value="true"` can be used to sync deferent instances of tabs.

`data-tabs-sync-group-value="true"` can be used to sync tabs by groups.

##### Changing tabs from other places

If you'd like to change the tab from a button or link outside of the tabs, you can call the same method and assign either `data-id` or `data-index` to select the tab.
Expand Down
29 changes: 28 additions & 1 deletion src/tabs.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@ export default class extends Controller {
index: 0,
updateAnchor: Boolean,
scrollToAnchor: Boolean,
scrollActiveTabIntoView: Boolean
scrollActiveTabIntoView: Boolean,
sync: { type: Boolean, default: false },
syncGroup: { type: String, default: "default" }
}

initialize() {
if (this.updateAnchorValue && this.anchor) this.indexValue = this.tabTargets.findIndex((tab) => tab.id === this.anchor)

if (this.syncValue) {
this.syncHandlerBound = this.syncHandler.bind(this);
document.addEventListener("tabs:sync", this.syncHandlerBound);
}
}

connect() {
Expand All @@ -36,6 +43,7 @@ export default class extends Controller {
this.indexValue = this.tabTargets.indexOf(event.currentTarget)
}

if(this.syncValue) this.dispatch(`sync`, { detail: { sync_group: this.syncGroupValue, tab_index: this.indexValue } });
}

nextTab() {
Expand Down Expand Up @@ -113,6 +121,25 @@ export default class extends Controller {
if (activeTab) activeTab.scrollIntoView({ inline: 'center', })
}

syncHandler(event) {
if(!this.syncValue) return

const { sync_group, tab_index } = event.detail;
const correctTabGroup = sync_group === this.syncGroupValue;
const incorrectTab = tab_index !== this.indexValue;
const tabExists = tab_index < this.tabsCount

if(tabExists && correctTabGroup && incorrectTab) {
this.indexValue = tab_index;
}
}

disconnect() {
if (this.syncValue && this.syncHandlerBound) {
document.removeEventListener("tabs:sync", this.syncHandlerBound);
}
}

get tabsCount() {
return this.tabTargets.length
}
Expand Down