Skip to content

An open source design system that's fully customizable and agent ready

TypeScript
8.4 KB
Raw Blame
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
 * @file require-table-section.js
 * @description Require table rows to sit inside a table section
 * (`TableHeader` / `TableBody` / `TableFooter`, or a raw
 * `thead` / `tbody` / `tfoot`) rather than directly inside the table.
 *
 * `<table>`'s content model does not admit `<tr>`. When a row is written as a
 * direct child of a table, the HTML parser applies implied-`<tbody>`
 * insertion: it silently wraps the rows in a `<tbody>` the author never
 * wrote. React's client render does not — `appendChild` places the `<tr>`
 * exactly where the tree says. So the server's parsed markup and the client's
 * tree disagree, and the render hydration-mismatches. React flags it up front:
 *
 *   In HTML, <tr> cannot be a child of <table>. Add a <tbody>, <thead> or
 *   <tfoot> to your code to match the DOM tree generated by the browser.
 *
 * Client-only, it is still wrong: the rows are never reparented, so the table
 * ends up with `<tr>` children and no `<tbody>` at all, and any CSS or query
 * targeting `tbody` silently misses.
 *
 * `Table`'s data-driven mode (`data={...}`) renders its own `TableBody`, so it
 * is unaffected. Children mode hands the children straight to `<table>`
 * (BaseTable renders `{children ? children : <>…</>}`), which is the right API
 * — it is what makes `TableHeader`/`TableBody`/`TableFooter` composable — but
 * it means the section is the caller's job, and nothing said so.
 *
 * This is the `<table>` counterpart of no-raw-paragraph: both guard an HTML
 * content model that browsers repair on parse and React does not.
 *
 * Bad:
 *   <Table columns={columns}>
 *     <colgroup>…</colgroup>
 *     {rows.map(r => <TableRow key={r.id}>…</TableRow>)}
 *   </Table>
 *
 * Good:
 *   <Table columns={columns}>
 *     <colgroup>…</colgroup>
 *     <TableBody>
 *       {rows.map(r => <TableRow key={r.id}>…</TableRow>)}
 *     </TableBody>
 *   </Table>
 *
 * The rule walks up from each row through the wrappers that are transparent in
 * the DOM — fragments, expression containers, `&&`/ternary guards, and the
 * arrow bodies of an inline `.map()` — and reports only when the first real
 * element it reaches is the table itself. If the row's lexical parent is
 * anything else (another component, a variable, a named helper), where it
 * lands is not knowable from this file and the rule stays silent.
 */

const ROW_ELEMENTS = new Set(['TableRow', 'tr']);

const SECTION_ELEMENTS = new Set([
  'TableHeader',
  'TableBody',
  'TableFooter',
  'thead',
  'tbody',
  'tfoot',
]);

const TABLE_ELEMENTS = new Set(['Table', 'BaseTable', 'table']);

// JSX elements that render nothing of their own, so a row inside one is still
// a direct child of whatever encloses it.
const FRAGMENT_ELEMENTS = new Set(['Fragment']);

// Expression and statement nodes a row can sit inside while remaining, in the
// emitted DOM, a direct child of the enclosing element.
const TRANSPARENT_NODES = new Set([
  'JSXFragment',
  'JSXExpressionContainer',
  'JSXSpreadChild',
  'ConditionalExpression',
  'LogicalExpression',
  'ArrayExpression',
  'ReturnStatement',
  'BlockStatement',
  'IfStatement',
  'SwitchStatement',
  'SwitchCase',
  'TryStatement',
  'CatchClause',
  'ArrowFunctionExpression',
  'FunctionExpression',
  'ChainExpression',
  'TSAsExpression',
  'TSSatisfiesExpression',
  'TSNonNullExpression',
]);

// Array methods whose result is spliced straight into the JSX position the call
// occupies. Stepping out of one of these callbacks keeps the row where it looks
// like it is; stepping out of any other call does not.
const SPLICING_METHODS = new Set(['map', 'flatMap']);

/** Flatten a JSX element name to a string: `Table`, `React.Fragment`, `svg:a`. */
function nameOf(name) {
  if (!name) {
    return null;
  }
  if (name.type === 'JSXIdentifier') {
    return name.name;
  }
  if (name.type === 'JSXMemberExpression') {
    const object = nameOf(name.object);
    const property = nameOf(name.property);
    return object && property ? `${object}.${property}` : null;
  }
  if (name.type === 'JSXNamespacedName') {
    return `${name.namespace.name}:${name.name.name}`;
  }
  return null;
}

function elementName(node) {
  return node?.type === 'JSXElement' ? nameOf(node.openingElement?.name) : null;
}

/**
 * The part of an element name that identifies the component. Names arrive
 * flattened (`React.Fragment`, `Astryx.TableRow`), and the namespace is just
 * how the module was imported — `Rx.Fragment` is still a fragment. The rule
 * already trusts a bare `Table` without resolving imports, so resolving the
 * last segment is the same trade, applied consistently.
 */
function lastSegment(name) {
  return name == null ? null : name.slice(name.lastIndexOf('.') + 1);
}

/**
 * Can the walk step from `child` up through `parent` and still be describing
 * the same position in the DOM?
 *
 * A call needs more than its node type. `CallExpression` is in the walk so that
 * `{rows.map(r => <TableRow/>)}` works — the callback's return value lands
 * exactly where the call sits. But a row handed to a function as an ARGUMENT is
 * data, not placement: `wrapInBody(<TableRow/>)` and
 * `React.createElement('tbody', null, <TableRow/>)` put it somewhere the callee
 * chooses, and blaming the enclosing table for those flags correct code.
 */
function isTransparent(parent, child) {
  if (parent.type === 'CallExpression') {
    // Chained off the result: `rows.map(...).filter(Boolean)`.
    if (parent.callee === child) {
      return true;
    }
    // Stepping out of a callback, but only for the methods that splice their
    // result into this position. A callback given to some other helper is that
    // helper's to place.
    const isCallbackArg =
      parent.arguments.includes(child) &&
      (child.type === 'ArrowFunctionExpression' ||
        child.type === 'FunctionExpression');
    return (
      isCallbackArg &&
      parent.callee?.type === 'MemberExpression' &&
      SPLICING_METHODS.has(lastSegment(nameOf(parent.callee.property) ?? parent.callee.property?.name))
    );
  }
  // `rows.map(...)` inside `rows.map(...).filter(...)` — we came up the object
  // side of the chain, not out of a computed key.
  if (parent.type === 'MemberExpression') {
    return parent.object === child;
  }
  return TRANSPARENT_NODES.has(parent.type);
}

const rule = {
  meta: {
    type: 'problem',
    docs: {
      description:
        'Require TableRow/tr to sit inside TableHeader/TableBody/TableFooter — a row directly inside a table emits <table><tr>, which browsers repair on parse and React does not, producing invalid DOM and a hydration mismatch',
      category: 'Possible Errors',
      recommended: true,
    },
    messages: {
      rowOutsideSection:
        '<{{row}}> is a direct child of <{{table}}>. `<table>` cannot contain a ' +
        'row directly: the HTML parser inserts an implied <tbody> when it parses ' +
        'server-rendered markup, React does not when it renders on the client, and ' +
        'the two trees then mismatch on hydration. Wrap the rows in <TableBody> ' +
        '(or <TableHeader>/<TableFooter>), the same element the data-driven ' +
        '`data={...}` mode renders for you.',
    },
    schema: [],
  },
  create(context) {
    return {
      JSXElement(node) {
        const row = lastSegment(elementName(node));
        if (!ROW_ELEMENTS.has(row)) {
          return;
        }

        let child = node;
        for (let current = node.parent; current; current = current.parent) {
          if (current.type === 'JSXElement') {
            const parent = lastSegment(elementName(current));
            if (FRAGMENT_ELEMENTS.has(parent)) {
              child = current;
              continue;
            }
            if (SECTION_ELEMENTS.has(parent)) {
              return;
            }
            if (TABLE_ELEMENTS.has(parent)) {
              context.report({
                node,
                messageId: 'rowOutsideSection',
                data: {row, table: parent},
              });
              return;
            }
            // Some other component. What it renders is not knowable here.
            return;
          }

          if (!isTransparent(current, child)) {
            // The row has escaped its JSX position (assigned to a variable,
            // returned from a named helper, handed to a function as an
            // argument, passed as a prop). Stay silent.
            return;
          }
          child = current;
        }
      },
    };
  },
};

export default rule;