Skip to content
Permalink
Browse files
Merge pull request #44 from touchlesscode/aa-add-skip-to-main-content
Add skip to main content link
  • Loading branch information
productlabs committed Sep 25, 2022
2 parents 91e8420 + 8542e64 commit a99ba37e0bb5a438dbbe185e0bb6dae81cae4c63
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 0 deletions.
@@ -0,0 +1,10 @@
import { render } from '@testing-library/react';
import React from 'react'
import SkipToMainContentLink from './index';

describe('SkipToMainContentLink', () => {
it('should render successfully', () => {
const { baseElement } = render(<SkipToMainContentLink skipTo='main:first-of-type' />);
expect(baseElement).toBeTruthy();
});
});
@@ -0,0 +1,22 @@
import React from 'react'
import SkipToMainContentLink from './index';

export default {
title: 'Skip To Main Content Link',
component: SkipToMainContentLink
}
export const Basic = () => (
<>
<SkipToMainContentLink skipTo="#cta" />
<main className="focus:outline-2 space-y-10">
<div>This is main content</div>
<button
onClick={() => alert('clicked')}
id="cta"
className="px-4 py-2 bg-green-600 rounded-sm text-white focus:border-red-500 focus:outline-red-500"
>
Test
</button>
</main>
</>
);
@@ -0,0 +1,64 @@
/* eslint-disable-next-line */
import React from 'react';
import { w } from 'windstitch';

export const SkipToMainContent = w.button(
`
mr-4 absolute translate-x-[-200%] transition-transform duration-300
focus:static focus:translate-x-0
bg-violet-500
hover:bg-violet-400
dark:bg-violet-700
dark:hover:bg-violet-600
text-white
dark:text-white
ring-violet-400
px-4 py-2
`,
);
SkipToMainContent.displayName = 'Button';

interface SkipToMainProps{
className?: string;

children: React.ReactElement;
/**
* The css query aiding the selection of the
* container (main, section etc) we want to scroll to;
*/
skipTo: string;
}
export interface SkipToMainContentLinkProps extends Omit<SkipToMainProps, 'children'>{
children?: React.ReactElement;
}

const SkipToMain = (props: SkipToMainProps) => {
const onClick = (event: React.SyntheticEvent) => {
event.preventDefault();

const container: (HTMLElement | null) = document.querySelector(props.skipTo);

if (container) {
container.tabIndex = -1;
container.focus();
setTimeout(() => container.removeAttribute("tabindex"), 1000);
}
};

return React.cloneElement(props.children, { onClick, className: props.className });
}

export const SkipToMainContentLink = (props: SkipToMainContentLinkProps) => {
return (
<SkipToMain {...props}>
{props.children || <SkipToMainContent>Skip to content</SkipToMainContent>}
</SkipToMain>
)
}

SkipToMainContentLink.defaultProps = {
className: "skip-link",
skipTo: "main:first-of-type",
};

export default SkipToMainContentLink;

0 comments on commit a99ba37

Please sign in to comment.