tenants2 icon indicating copy to clipboard operation
tenants2 copied to clipboard

In Django SQL dashboard, hyperlink BBLs to WoW

Open toolness opened this issue 3 years ago • 0 comments

The following snippet of code, if added to a django-sql-dashboard view, will do the trick whenever it sees a pad_bbl column:

/**
 * @param element {Element}
 * @returns {number|null}
 */
function findIndexInParent(element) {
  const parent = element.parentNode;

  if (parent) {
    for (let i = 0; i < parent.children.length; i++) {
      const child = parent.children[i];
      if (child === element) return i;
    }
  }

  return null;
}

/**
 * @param element {Element}
 * @returns {HTMLTableElement|null}
 */
function getTableAncestor(element) {
  let parent = element.parentNode;

  while (parent) {
    if (parent instanceof HTMLTableElement) {
      return parent;
    }
    parent = parent.parentNode;
  }

  return null;
}

/**
 * @param name {String}
 */
function* iterColumnValues(name) {
  const headers = document.querySelectorAll(`th[alt="${name}"]`);

  for (let header of headers) {
    const table = getTableAncestor(header);
    const index = findIndexInParent(header);
    if (index !== null && table) {
      const cells = table.querySelectorAll(`td:nth-child(${index + 1})`);
      for (let cell of cells) {
        yield cell;
      }
    }
  }
}

window.addEventListener("load", () => {
  for (let td of iterColumnValues("pad_bbl")) {
    const a = document.createElement("a");
    const bbl = td.textContent;
    // TODO: Replace origin w/ settings.WOW_ORIGIN.
    a.href = `http://whoownswhat.justfix.nyc/en/bbl/${bbl}`;
    a.target = "_blank";
    a.rel = "noopener noreferrer";
    a.textContent = td.textContent;
    td.textContent = "";
    td.appendChild(a);
  }
});

Note that we could take this same concept and extend it to other types of fields. For instance, we could make it so that any column called user_id was automatically hyperlinked to the Django admin user change view.

toolness avatar May 20 '21 18:05 toolness