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

feature: External link aria attributes added #28

Merged
merged 1 commit into from
Nov 1, 2023
Merged
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
25 changes: 23 additions & 2 deletions src/CollapsableExtLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,42 @@ import { Collapsable } from './Collapsable'
export class CollapsableExtLink {
private readonly collapsable: Collapsable

public readonly extLink: HTMLElement
public readonly extLink: HTMLAnchorElement
public readonly collapsableItem: CollapsableItem

private listener: EventListener | undefined
private ariaPerRole!: 'aria-expanded' | 'aria-selected' // always set by `this.prepareDOM()` called from constructor

public constructor(collapsable: Collapsable, link: HTMLAnchorElement, collapsableItem: CollapsableItem) {
this.collapsable = collapsable

if (link.tagName.toLowerCase() !== 'a') {
if (!(link instanceof HTMLAnchorElement)) {
throw new Error('Collapsable: External link has to be HTMLAnchorElement.')
}

this.extLink = link
this.collapsableItem = collapsableItem

this.prepareDOM()
this.addHandler()
}

private prepareDOM(): void {
this.extLink.setAttribute('aria-controls', this.collapsableItem.boxElements.map((box) => box.id).join(' '))

if (!this.extLink.role) {
this.extLink.role = 'button'
}

if (this.extLink.role === 'button') {
this.ariaPerRole = 'aria-expanded'
} else if (this.extLink.role === 'tab') {
this.ariaPerRole = 'aria-selected'
}

this.extLink.setAttribute(this.ariaPerRole, String(this.collapsableItem.isExpanded))
}

private addHandler(): void {
const { options } = this.collapsable

Expand All @@ -44,11 +62,14 @@ export class CollapsableExtLink {
const { options } = this.collapsable

this.extLink.classList.toggle(options.classNames.externalLinkActive, this.collapsableItem.isExpanded)
this.extLink.setAttribute(this.ariaPerRole, String(this.collapsableItem.isExpanded))
}

public destroy(): void {
if (this.listener) {
this.extLink.removeEventListener('click', this.listener)
this.extLink.removeAttribute('aria-controls')
this.extLink.removeAttribute(this.ariaPerRole)
}
}
}