/**
 * Ctrl/Cmd+S shortcut that calls the provided save handler.
 *
 * @param {Function} onSave
 * @param {object}   [options]
 * @param {boolean}  [options.enabled]
 */
import { useEffect, useRef } from '@wordpress/element';

export default function useSaveShortcut( onSave, { enabled = true } = {} ) {
	const saveRef = useRef( onSave );
	saveRef.current = onSave;

	useEffect( () => {
		if ( ! enabled ) {
			return undefined;
		}

		const onKeyDown = ( event ) => {
			const key = String( event.key || '' ).toLowerCase();
			if ( key !== 's' || ( ! event.metaKey && ! event.ctrlKey ) ) {
				return;
			}
			// Allow Shift+Ctrl+S / browser defaults we don't own.
			if ( event.altKey ) {
				return;
			}
			event.preventDefault();
			event.stopPropagation();
			if ( typeof saveRef.current === 'function' ) {
				saveRef.current();
			}
		};

		window.addEventListener( 'keydown', onKeyDown, true );
		return () => window.removeEventListener( 'keydown', onKeyDown, true );
	}, [ enabled ] );
}
