All files / src/elements HeadElement.tsx

94.73% Statements 18/19
89.47% Branches 17/19
100% Functions 2/2
94.73% Lines 18/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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      1x 8x 8x 8x   8x 8x 8x 8x 3x   8x 1x   8x 1x   8x     8x 5x 5x     8x    
import React, { type ElementType, type ComponentPropsWithoutRef, useMemo } from 'react';
import { createPortal } from 'react-dom';
 
export const HeadElement = <T extends ElementType<any> = 'link'>(props: { as?: T } & ComponentPropsWithoutRef<T>) => {
  const { as: Com = 'link', ...other } = props;
  const reset = other as ComponentPropsWithoutRef<T>;
  const comp = <Com data-head={true} {...reset} />;
 
  useMemo(() => {
    const name = props.name;
    let selector = '';
    if (props.as && /(base|title)/.test(props.as as string)) {
      selector = `${props.as}:not([data-head])`;
    }
    if (props.as === 'meta' && name) {
      selector = `meta[name="${name}"]:not([data-head])`;
    }
    if (props.as === 'meta' && props.charSet) {
      selector = `meta[charset]:not([data-head])`;
    }
    Iif (props.as === 'link' && props.rel == 'icon') {
      selector = `link[rel="icon"]:not([data-head])`;
    }
    if (selector) {
      const dom = document.querySelector(selector);
      dom?.remove();
    }
  }, []);
  return createPortal(comp, document.head);
};