TypeScript

by Jose A

HTML

<div id="app"></div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
  text-align: center;
}

TypeScript

type BaseElement = {
  path: string;
  className?: string[];
  href?: string;
  text?: string;
  ariaLabel?: string;
  role?: string;
  type?: string;
  id?: string;
  // Add other fields as needed, all optional to handle variability
};
type ElementInfo = {
  tagName: string;
  id?: string;
  dataTestId?: string;
  className?: string[];
  type?: string;
  href?: string;
  role?: string;
  ariaLabel?: string;
  text?: string;
  path: string;
};

type ElementsByTagName = {
  [tagName: string]: BaseElement[];
};

function groupElementsByTagName(input: { elements: any[] }): ElementsByTagName {
  const grouped: ElementsByTagName = {};

  for (const el of input.elements) {
    // Extract only the relevant properties
    const {
      tagName,
      path,
      className,
      href,
      text,
      ariaLabel,
      role,
      type,
      id
    } = el;

    if (!tagName) {
      // If no tagName is found, skip or handle differently
      continue;
    }

    // Construct a minimal element object, omitting isInteractive since it's always true
    const baseElement: BaseElement = {
      path,
      ...(className ? { className } : {}),
      ...(href ? { href } : {}),
      ...(text ? { text } : {}),
      ...(ariaLabel ? { ariaLabel } : {}),
      ...(role ? { role } : {}),
      ...(type ? { type } : {}),
      ...(id ? { id } : {})
    };

    // Initialize the array for this tagName if it doesn't exist
    if (!grouped[tagName]) {
      grouped[tagName] = [];
    }

    grouped[tagName].push(baseElement);
  }

  return grouped;
}

// Example usage:
const originalData = {
  "elements": [
    {
      "tagName": "a",
      "path": "body > noscript > div > a",
      "href": "/?sca_esv=14988c4722c11c49&output=search&gbv=1&sei=y1ddZ8DDD7qakdUPtfCY-AY",
      "text": "aquí"
    },
    {
      "tagName": "a",
      "path": "body > div > div > a",
      "className": ["MV3Tnb"],
      "href":...