File size: 2,068 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { useCallback, useEffect, useState } from '@wordpress/element';

export const useHelpCenterArticleTabComponent = ( postContent: string | undefined ) => {
	const [ tabHash, setTabHash ] = useState( '' );

	const toggleTab = ( element: Element, show: boolean ) => {
		( element as HTMLElement ).style.display = show ? 'block' : 'none';
		element.setAttribute( 'aria-hidden', show ? 'false' : 'true' );
	};

	const toggleTabTitle = ( element: Element, show: boolean ) => {
		element.setAttribute( 'aria-selected', show ? 'true' : 'false' );
	};

	const activateTab = useCallback( () => {
		const hash = tabHash;

		const tabs = Array.from( document.querySelectorAll( '.wp-block-wpsupport3-tabs' ) );

		tabs.forEach( ( tab ) => {
			const titles = Array.from( tab.querySelectorAll( '.wpsupport3-tab__title' ) );
			const bodies = Array.from(
				tab.querySelectorAll( '.wp-block-wpsupport3-tab:not(.invisible_tabpanel)' )
			);

			const match = titles.findIndex( ( titles ) => titles.id === hash?.substring( 1 ) );

			// Reset selection
			titles.forEach( ( title ) => toggleTabTitle( title, false ) );
			bodies.forEach( ( body ) => toggleTab( body, false ) );

			if ( hash && match !== -1 ) {
				toggleTabTitle( titles[ match ], true );
				toggleTab( bodies[ match ], true );
			} else {
				// If the first tab is invisible from the editor, we set the first tab as active.
				toggleTabTitle( titles[ 0 ], true );
				toggleTab( bodies[ 0 ], true );
			}
		} );
	}, [ tabHash ] );

	useEffect( () => {
		if ( tabHash || postContent ) {
			activateTab();
		}
	}, [ activateTab, tabHash, postContent ] );

	useEffect( () => {
		if ( postContent ) {
			const titles = Array.from(
				document.querySelectorAll( '.wp-block-wpsupport3-tabs .wpsupport3-tab__title' )
			);
			titles.forEach( ( title ) => {
				title.addEventListener( 'click', ( e ) => {
					e.preventDefault();
					setTabHash( `#${ title?.id }` );
					setTimeout( () => {
						window.scroll( 0, document.documentElement.scrollTop );
					} );
				} );
			} );
		}
	}, [ postContent ] );
};