/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

/**
 * Asynchronously checks if the given element or any of its parents are detached from the document body.
 *
 * @param element The element to check.
 * @returns A promise that resolves to true if the element or any parent is detached, false otherwise.
 */
export async function isElementAttached( element ) {
	return new Promise( resolve => {
		// Use requestAnimationFrame to ensure the check happens after any potential DOM manipulations in the same tick.
		requestAnimationFrame( () => {
			let currentElement = element;
			while ( currentElement ) {
				if ( !document.body.contains( currentElement ) ) {
					resolve( true ); // Detached
					return;
				}
				currentElement = currentElement.parentElement;
			}

			resolve( false ); // Attached
		} );
	} );
}
