TS + HTML code

Hopefully you're able to see this!

by AriannaC

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>JS Bin</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

TypeScript

// 1. How do we reorder the list when we drop an item? Why do we need to reverse items?

// 2. What is the purpose of updateView(), and how does it accomplish that purpose?
//    Why does updateView() have special handling for the "lifted" item?
//    How many times does updateView() remove or add an element to the document
//    each time it runs? Does the answer depend on whether or not state.items has
//    changed?

// 3. What would go wrong if we moved the line `itemDiv.id = itemId` from
// `updateView()` into `createItem()`?

type ItemId = string;

type State = {
  items: ItemId[];
  liftedItem: { itemId: ItemId; posx: number; posy: number } | undefined;
};

let state: State = {
  items: ["a", "b", "c", "d", "e", "f", "g"],
  liftedItem: undefined,
};

function updateView() {
  const root = document.getElementById("root");

  if (!root) {
    throw new Error("No root element found.");
  }

  while (root.firstChild) {
    root.firstChild.remove();
  }

  for (const itemId of state.items) {
    const itemDiv = createItem(itemId);
    if (state.liftedItem && state.liftedItem.itemId == itemId) {
      root.appendChild(createPlaceholder());
      hoverDiv(itemDiv, state.liftedItem.posx, state.liftedItem.posy);
      root.appendChild(itemDiv);
    } else {
      // label div with item id so we can look up its position for drop
      itemDiv.id = itemId;
      root.appendChild(itemDiv);
    }
  }
}
updateView();

function hoverDiv(div: HTMLDivElement, posx: number, posy: number) {
  div.style.position = "absolute";
  div.style.top = posy + "px";
  div.style.left = posx + "px";
}

function createItem(itemId: ItemId) {
  const itemDiv = document.createElement("div");
  itemDiv.innerText = itemId.toString();
  itemDiv.addEventListener("mousedown", (evt) => pickupItem(itemId, evt));

  return itemDiv;
}

function createPlaceholder() {
  const placeholderDiv = document.createElement("div");
  placeholderDiv.innerText = "_";
  return placeholderDiv;
}

function...