iterate.com / git

git clone https://git.iterate.com/repos/git

git / public / page.jsmain at 517348b

// page.js — WHAT THE BROWSER RUNS on every page of the git app. ../pages.ts writes each page whole,
// and hands this script `data` (a JSON element of the page). The script draws, in their places:
//
//   - the file tree, and each file and README in the place of its <pre>
//   - each diff, when the reader scrolls near it, in the place of its plain text
//   - on a pull, for a member: the conversation with its reply boxes, a comment box on any line
//     of a diff, and the buttons that merge or close; on a compare page, the box that opens a pull
//   - on the page that edits a file, for a member: the box that commits the edit
//
// WHAT A MEMBER WRITES IS ONE APPEND to the repo's context (../pulls.ts says which events), through
// the member's own itx (mind.js). The page then shows what was written from what it sent: it does
// not read the pull again.
//
// Nothing here keeps state in a component. What changes is in the few arrays below, and `redraw`
// draws the roots again from them.
import { html } from "@iterate-com/ui/page";
import { createRoot } from "react-dom/client";

const data = JSON.parse(document.getElementById("data").textContent);
// The page's look is the mind's theme.css. Pierre's components would follow the visitor's system,
// so they are told.
const dark = getComputedStyle(document.documentElement).colorScheme === "dark";
const pierre = {
  theme: { light: "pierre-light", dark: "pierre-dark" },
  themeType: dark ? "dark" : "light",
  disableFileHeader: true,
};

// what is drawn in the content of a page of files, to take down when that content is replaced
let drawn = [];
function draw(place, node) {
  const root = createRoot(place);
  root.render(node);
  drawn.push(root);
}
// The <pre> stays until the component has drawn something, so the text never blinks away.
function inPlaceOf(pre, className) {
  const place = document.createElement("div");
  place.className = className;
  pre.after(place);
  const waiting = new ResizeObserver(() => {
    if (place.offsetHeight === 0) return;
    waiting.disconnect();
    pre.remove();
  });
  waiting.observe(place);
  return place;
}

// Markdown as a chat of the mind draws it: loaded once, when a page has some to draw.
let Markdown;
async function markdown() {
  Markdown ||= (await import("@iterate-com/ui/components/agent-chat/chat-parts")).Markdown;
}

/** Each <pre> of a file or a README in its richer form: with its colours, or as markdown. */
async function drawContent() {
  const files = [...document.querySelectorAll("pre[data-file]")];
  const markdowns = [...document.querySelectorAll("pre[data-markdown]")];
  if (files.length) {
    const { File } = await import("@pierre/diffs/react");
    for (const pre of files.filter((pre) => pre.isConnected)) {
      const file = { name: pre.dataset.file, contents: pre.textContent };
      draw(inPlaceOf(pre, "file"), html`<${File} file=${file} options=${pierre} />`);
    }
  }
  if (markdowns.length) {
    await markdown();
    for (const pre of markdowns.filter((pre) => pre.isConnected)) {
      const place = inPlaceOf(pre, "markdown");
      place.dataset.dir = pre.dataset.dir;
      draw(place, html`<${Markdown}>${pre.textContent}<//>`);
    }
  }
}

// ── WHAT A MEMBER WRITES ──

let mindModule;
/** The member's itx, asked for at the first write: a page that is only read opens no socket. */
const mind = () => (mindModule ||= import("/mind.js")).then((module) => module.itx);
/** One event on the repo's context, which is where its pulls are. */
const append = async (type, payload) => (await (await mind()).cd(data.repo).append({ type, payload }))[0];

/** A box that writes: its fields, the button that sends them, and what went wrong if the mind
 *  refused. `send` gets the fields by name. Cmd or Ctrl with Enter sends too. */
function Form({ button, quiet, disabled, send, cancel, children }) {
  async function submitted(event) {
    event.preventDefault();
    const form = event.currentTarget;
    const buttons = [...form.querySelectorAll("button")];
    const problem = form.querySelector(".problem");
    problem.textContent = "";
    for (const each of buttons) each.disabled = true;
    try {
      await send(Object.fromEntries(new FormData(form)));
      form.reset();
    } catch (error) {
      problem.textContent = error instanceof Error ? error.message : String(error);
    }
    for (const each of buttons) each.disabled = false;
  }
  const keyed = (event) => {
    if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) event.currentTarget.requestSubmit();
  };
  return html`<form className="box" onSubmit=${submitted} onKeyDown=${keyed}>
    ${children}
    <div className="row">
      <button className=${quiet ? null : "main"} disabled=${disabled}>${button}</button>
      ${cancel && html`<button type="button" onClick=${cancel}>Cancel</button>`}
      <span className="problem"></span>
    </div>
  </form>`;
}

// ── A PULL: its threads, in the conversation and on the lines of the diffs ──

/** The pull's threads as the page came with them, then with what this member wrote. A thread on
 *  a line has `place` and `diff`, the file of this page it is in; `outdated` says the line has
 *  changed since. */
const threads = data.threads || [];
/** The comment being written on lines of a diff, by the diff's number on the page: `{ diff, side,
 *  line, endLine }`. One for each file at a time: pierre marks one range of lines as chosen. */
const drafts = new Map();

const stamp = (at) => new Date(at).toISOString().slice(0, 16).replace("T", " ") + " UTC";
const said = (event, body) => ({ id: event.offset, by: data.me, at: event.createdAt, body });

async function comment(body, place, draft) {
  const pull = data.pull.number;
  const event = await append("pull/commented", { pull, body: body.trim(), replyTo: null, at: place });
  if (draft) drafts.delete(draft.diff);
  const diff = draft ? draft.diff : null;
  threads.push({ id: event.offset, place, diff, outdated: false, resolved: false, comments: [said(event, body.trim())] });
  redraw();
}
async function reply(thread, body) {
  const pull = data.pull.number;
  const event = await append("pull/commented", { pull, body: body.trim(), replyTo: thread.id, at: null });
  thread.comments.push(said(event, body.trim()));
  redraw();
}
async function resolve(thread) {
  await append("pull/resolved", { pull: data.pull.number, comment: thread.id });
  thread.resolved = true;
  redraw();
}

/** One thread: what was said, and for a member the box that replies and the button that
 *  resolves. `listed` is the thread in the conversation. There a thread that is read elsewhere is
 *  folded under one line that says what it is: a thread on lines, which stands under its lines in
 *  the diff, and a resolved one. A thread whose lines have changed is nowhere in the diff, so it
 *  is open here. */
function Thread({ thread, listed }) {
  const place = thread.place;
  const said = thread.comments.map(
    (each) => html`<div className="comment" key=${each.id}>
      <p className="by">${each.by}, ${stamp(each.at)}</p>
      <${Markdown}>${each.body}<//>
    </div>`,
  );
  // the reply box opens under "Reply": a thread is read far more often than answered
  const writes =
    data.me &&
    html`<div className="actions">
      <details className="reply">
        <summary>Reply</summary>
        <${Form} button="Reply" send=${({ text }) => reply(thread, text)}>
          <textarea name="text" placeholder="Reply" required></textarea>
        <//>
      </details>
      ${!thread.resolved && html`<button type="button" className="resolve" onClick=${() => resolve(thread)}>Resolve</button>`}
    </div>`;
  const look = thread.resolved ? "thread resolved" : "thread";
  if (!listed) return html`<article className=${look}>${said} ${writes}</article>`;
  const anchor = "comment-" + thread.id;
  if (!place && !thread.resolved) return html`<article className=${look} id=${anchor}>${said} ${writes}</article>`;

  const first = thread.comments[0];
  const path = place && html`<code>${place.path}</code>`;
  const what = place
    ? html`${thread.diff === null ? path : html`<a href=${"#diff-" + thread.diff}>${path}</a>`}
        ${place.endLine > place.line ? " lines " + place.line + " to " + place.endLine : " line " + place.line}`
    : first.by + ": " + first.body.split("\n")[0];
  const count = thread.comments.length + (thread.comments.length === 1 ? " comment" : " comments");
  const open = Boolean(place && thread.outdated && !thread.resolved);
  return html`<details className=${look} id=${anchor} open=${open}>
    <summary className="place">
      ${what}${thread.outdated ? ", changed since" : ""}${thread.resolved ? ", resolved" : ""}
      <span className="count">${count}</span>
    </summary>
    ${place && html`<code className="quote">${place.quote}</code>`} ${said} ${writes}
  </details>`;
}

function Conversation() {
  return html`<div>
    ${threads.length === 0 && html`<p className="note">Nobody has said anything yet.</p>`}
    ${threads.map((thread) => html`<${Thread} key=${thread.id} thread=${thread} listed />`)}
    ${data.me &&
    html`<${Form} button="Comment" send=${({ text }) => comment(text, null, null)}>
      <textarea name="text" placeholder="Say something about this pull" required></textarea>
    <//>`}
  </div>`;
}

/** The box under the lines of a diff that a member chose, where they write a comment on them. */
function Draft({ draft }) {
  const { path, before, after } = data.diffs[draft.diff];
  // the lines' own text goes with the comment: the comment stays on them while they read so
  const lines = (draft.side === "additions" ? after : before).split("\n");
  const quote = lines.slice(draft.line - 1, draft.endLine).join("\n");
  const place = { path, side: draft.side, line: draft.line, endLine: draft.endLine, quote };
  const discard = () => {
    drafts.delete(draft.diff);
    drawDiff(draft.diff);
  };
  const lineWords = draft.endLine > draft.line ? "these lines" : "this line";
  return html`<${Form} button="Comment" send=${({ text }) => comment(text, place, draft)} cancel=${discard}>
    <textarea name="text" placeholder=${"Comment on " + lineWords} required autoFocus></textarea>
  <//>`;
}

/** The lines a member chose with pierre's button beside a line (a click for one line, a drag for
 *  several), as a draft. A comment is on lines of one side of the diff: a drag that goes from the
 *  old lines to the new ones is its last line alone. */
function draftOf(diff, range) {
  const side = range.endSide || range.side || "additions";
  const oneSide = (range.side || side) === side;
  const line = oneSide ? Math.min(range.start, range.end) : range.end;
  const endLine = oneSide ? Math.max(range.start, range.end) : range.end;
  return { diff, side, line, endLine };
}

/** The buttons of an open pull. A squash is offered while the branch has main's newest commit. */
function MergeBox() {
  const merge = async () => {
    await (await mind()).config.pullMerge(data.repo, data.pull.number);
    location.reload();
  };
  const close = async () => {
    await append("pull/closed", { pull: data.pull.number });
    location.reload();
  };
  return html`<div className="merge">
    <${Form} button="Squash and merge" disabled=${!data.mergeable} send=${merge} />
    <${Form} button="Close without merging" quiet send=${close} />
  </div>`;
}

/** On a compare page: the box that opens the pull, which the server then shows in this page's
 *  place. */
function OpenPull() {
  const open = async ({ title, body }) => {
    await append("pull/opened", { branch: data.compare.branch, title: title.trim(), body });
    location.reload();
  };
  return html`<${Form} button="Open a pull" send=${open}>
    <input name="title" defaultValue=${data.compare.title} aria-label="Title" required />
    <textarea name="body" defaultValue=${data.compare.body} placeholder="What this changes, and why"></textarea>
  <//>`;
}

// ── AN EDIT: the box that commits what the member changed in the file's box ──

/** THE COMMIT OF AN EDIT, as GitHub offers it: a message that the member may change, and where
 *  the commit goes.
 *
 *    to main          one call of the member's own itx: `repos.get(repo).commitFiles`, pinned to
 *                     the commit that this page read, so an edit never lands over a commit that
 *                     the member did not see. Main is what the mind runs.
 *    to a new branch  the page makes the commit and pushes the branch as git does
 *                     (branch-commit.js), then opens the pull with one event.
 *
 *  Then the page goes to what was made: the commit, or the pull. */
function EditBox() {
  const { path, commitOid, crlf, author } = data.edit;
  const box = document.getElementById("edit-text");
  const send = async ({ title, description, where, branch }) => {
    const text = box.value;
    if (text === box.defaultValue) throw new Error("Nothing is changed.");
    // the file's own line endings, which the box showed as line feeds
    const content = crlf ? text.replace(/\n/g, "\r\n") : text;
    const body = description.trim();
    const message = title.trim() + (body ? "\n\n" + body : "");
    if (where === "main") {
      const repo = (await mind()).repos.get(data.repo);
      const made = await repo.commitFiles({ message, parent: commitOid, changes: [{ path, content }] });
      if (!made.commitOid) throw new Error("Nothing is changed.");
      edited = true;
      location.assign(data.repo + "/commit/" + made.commitOid);
      return;
    }
    const [{ default: git }, { default: http }, { commitOnBranch }] = await Promise.all([
      import("isomorphic-git"),
      import("isomorphic-git/http/web"),
      import("/branch-commit.js"),
    ]);
    const name = branch.trim();
    const edit = { parent: commitOid, branch: name, path, content, message, author };
    await commitOnBranch({ git, http, url: location.origin + data.repo, ...edit });
    edited = true;
    const pull = data.repo + "/compare/" + name.split("/").map(encodeURIComponent).join("/");
    try {
      await append("pull/opened", { branch: name, title: title.trim(), body });
    } catch (error) {
      // the branch is pushed: the compare page opens the pull
      const why = error instanceof Error ? error.message : String(error);
      throw new Error("The branch " + name + " is pushed, and the pull was not opened (" + why + "). Open it from Branches.");
    }
    location.assign(pull);
  };
  return html`<${Form} button="Commit changes" send=${send}>
    <h2>Commit changes</h2>
    <input name="title" defaultValue=${"Update " + path.split("/").at(-1)} aria-label="Commit message" required />
    <textarea name="description" placeholder="Add an extended description (optional)"></textarea>
    <label className="choice">
      <input type="radio" name="where" value="main" defaultChecked />
      <span>Commit directly to <code>main</code>. The mind runs main a few seconds later.</span>
    </label>
    <label className="choice">
      <input type="radio" name="where" value="branch" />
      <span>Create a new branch for this commit and open a pull.</span>
    </label>
    <input name="branch" defaultValue=${data.edit.branch} aria-label="The new branch's name" />
  <//>`;
}

/** True once the edit is committed: the page may then go with no question. */
let edited = false;
function drawEdit() {
  const place = document.getElementById("commit");
  if (!place || !data.edit) return;
  const box = document.getElementById("edit-text");
  createRoot(place).render(html`<${EditBox} />`);
  // a Tab in the box is a tab in the file
  box.addEventListener("keydown", (event) => {
    if (event.key !== "Tab" || event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) return;
    event.preventDefault();
    box.setRangeText("\t", box.selectionStart, box.selectionEnd, "end");
  });
  addEventListener("beforeunload", (event) => {
    if (!edited && box.value !== box.defaultValue) event.preventDefault();
  });
}

// ── THE DIFFS ──

let MultiFileDiff;
/** Each diff's root, by its number on the page, once it is drawn; and what it is drawn from. */
const diffRoots = new Map();
const diffProps = new Map();

/** WHAT THE PAGE ADDS TO PIERRE'S OWN LOOK, inside its component (`unsafeCSS`).
 *
 *  Pierre shows its button beside one line. While several lines are chosen, each of them wears
 *  the same mark, so the reader sees which lines the comment will be on.
 *
 *  And each posted comment on lines has a thin line down the left of the lines it is on, so a
 *  comment on a range shows its range. `threadsHere` are the threads shown in this diff. */
function lookOf(threadsHere) {
  const chosen = `
    [data-column-number][data-selected-line] { position: relative; }
    [data-column-number][data-selected-line]::after { content: "+"; position: absolute; top: 0;
      right: calc(1ch - 1lh); width: 1lh; height: 1lh; display: flex; align-items: center;
      justify-content: center; border-radius: 4px; background: var(--diffs-modified-base);
      color: var(--diffs-bg); font-weight: 600; z-index: 3; }
  `;
  // a line of the new side is an added line or an unchanged one, by its new number; a line of
  // the old side is a deleted line, or an unchanged one by its old number
  const rows = threadsHere.flatMap(({ place }) =>
    Array.from({ length: place.endLine - place.line + 1 }, (_, at) => place.line + at).map((line) =>
      place.side === "additions"
        ? `[data-line="${line}"]:is([data-line-type="change-addition"], [data-line-type="context"])`
        : `[data-line="${line}"][data-line-type="change-deletion"], [data-alt-line="${line}"][data-line-type="context"]`,
    ),
  );
  const commented = rows.length
    ? `${rows.join(", ")} { box-shadow: inset 3px 0 0 color-mix(in srgb, var(--diffs-modified-base) 55%, transparent); }`
    : "";
  return chosen + commented;
}

function drawDiff(index) {
  const { path, before, after } = data.diffs[index];
  const here = threads.filter((thread) => thread.diff === index && !thread.outdated && !thread.resolved);
  // What pierre is drawn from is kept, so that a redraw hands it the same objects and it does
  // not work the diff out again. Its options are made again only when the look changes.
  const kept = diffProps.get(index) || {
    oldFile: { name: path, contents: before },
    newFile: { name: path, contents: after },
    renderAnnotation: ({ metadata }) =>
      metadata.thread ? html`<${Thread} thread=${metadata.thread} />` : html`<${Draft} draft=${metadata.draft} />`,
  };
  const unsafeCSS = lookOf(here);
  if (!kept.options || kept.options.unsafeCSS !== unsafeCSS)
    kept.options = {
      ...pierre,
      diffStyle: "unified",
      unsafeCSS,
      // a member comments on lines of a pull: the button that pierre shows beside a line, which
      // a click takes for that line and a drag for every line it passes
      enableGutterUtility: Boolean(data.pull && data.me),
      enableLineSelection: Boolean(data.pull && data.me),
      onGutterUtilityClick: (range) => {
        drafts.set(index, draftOf(index, range));
        drawDiff(index);
      },
    };
  diffProps.set(index, kept);
  const draft = drafts.get(index);
  // a thread and a draft stand under the last of their lines
  const lineAnnotations = [
    ...here.map((thread) => ({ side: thread.place.side, lineNumber: thread.place.endLine, metadata: { thread } })),
    ...(draft ? [{ side: draft.side, lineNumber: draft.endLine, metadata: { draft } }] : []),
  ];
  // The lines of the draft are the chosen ones, and with no draft none is: pierre keeps its own
  // choice, and its button beside it, until it is told.
  const selectedLines = draft ? { start: draft.line, end: draft.endLine, side: draft.side, endSide: draft.side } : null;
  diffRoots.get(index).render(
    html`<${MultiFileDiff} ...${kept} lineAnnotations=${lineAnnotations} selectedLines=${selectedLines} />`,
  );
}

// Each diff is drawn when the reader scrolls near it: a commit may change many files.
async function drawDiffs() {
  const places = document.querySelectorAll("[data-diff]");
  if (places.length === 0) return;
  // a file's name in the list of changes opens that file, if the reader had folded it
  document.addEventListener("click", (event) => {
    const link = event.target.closest(".changes a");
    const file = link && document.querySelector(link.getAttribute("href"));
    if (file) file.open = true;
  });
  MultiFileDiff = (await import("@pierre/diffs/react")).MultiFileDiff;
  // a thread on a line is drawn with markdown, and only a pull has threads: a commit's diffs
  // do not wait for it
  if (data.pull && (threads.length || data.me)) await markdown();
  const near = new IntersectionObserver(
    (entries) => {
      for (const entry of entries.filter((entry) => entry.isIntersecting)) {
        near.unobserve(entry.target);
        const index = Number(entry.target.dataset.diff);
        // the plain text stays until the diff is drawn, so a diff is never an empty box
        const plain = entry.target.querySelector("pre.plain");
        const place = plain ? inPlaceOf(plain, "drawn") : entry.target;
        diffRoots.set(index, createRoot(place));
        drawDiff(index);
      }
    },
    { rootMargin: "800px" },
  );
  for (const place of places) near.observe(place);
}

let conversation;
/** Everything that shows the pull's threads, drawn again from `threads` and `drafts`. */
function redraw() {
  if (conversation) conversation.render(html`<${Conversation} />`);
  for (const index of diffRoots.keys()) drawDiff(index);
}

async function drawPull() {
  const place = document.getElementById("conversation");
  if (place) {
    await markdown();
    conversation = createRoot(place);
    redraw();
  }
  const merge = document.getElementById("merge");
  if (merge && data.pull.status === "open") createRoot(merge).render(html`<${MergeBox} />`);
  const open = document.getElementById("open-pull");
  if (open) createRoot(open).render(html`<${OpenPull} />`);
}

// ── A PAGE OF FILES: the tree, and a click that takes the next page's content alone ──

const treePlace = document.getElementById("tree");
const treeHref = (path) =>
  path ? data.repo + "/tree/main/" + path.split("/").map(encodeURIComponent).join("/") : data.repo;
const shownPath = () => decodeURIComponent(location.pathname.slice((data.repo + "/tree/main/").length));
let tree;

async function visit(href, push) {
  const answer = await fetch(href);
  const next = new DOMParser().parseFromString(await answer.text(), "text/html");
  const content = next.getElementById("content");
  // a page with no content of this kind (a sign-in, an error) is shown whole
  if (!content) return location.assign(href);
  for (const root of drawn) root.unmount();
  drawn = [];
  document.getElementById("content").replaceWith(document.adoptNode(content));
  document.title = next.title;
  if (push) history.pushState(null, "", href);
  scrollTo(0, 0);
  const item = tree && tree.getItem(shownPath());
  if (item && !item.isDirectory() && !item.isSelected()) item.select();
  await drawContent();
}

async function drawTree() {
  if (!treePlace) return;
  const { FileTree, useFileTree } = await import("@pierre/trees/react");
  const files = new Set(data.paths);
  // the folders above what is shown are open; a small repo is open whole
  const segments = data.path.split("/").filter(Boolean);
  const above = segments.map((_, index) => segments.slice(0, index + 1).join("/"));
  function Tree() {
    const { model } = useFileTree({
      paths: data.paths,
      initialExpansion: data.paths.length > 150 ? "closed" : "open",
      initialExpandedPaths: above,
      initialSelectedPaths: files.has(data.path) ? [data.path] : [],
      search: true,
      onSelectionChange: (paths) => {
        if (files.has(paths[0]) && paths[0] !== shownPath()) visit(treeHref(paths[0]), true);
      },
    });
    tree = model;
    return html`<${FileTree} model=${model} style=${{ colorScheme: "inherit", height: "100%" }} />`;
  }
  createRoot(treePlace).render(html`<${Tree} />`);

  addEventListener("popstate", () => visit(location.href, false));
  document.addEventListener("click", (event) => {
    const plain = event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey;
    const link = plain && !event.defaultPrevented && event.target.closest("#content a[href]");
    if (!link) return;
    // a link in a README is written against the folder of the file it is in
    const written = link.getAttribute("href");
    const inMarkdown = link.closest(".markdown");
    const relative = inMarkdown && !/^([a-z][a-z0-9+.-]*:|\/|#)/i.test(written);
    const dir = inMarkdown && inMarkdown.dataset.dir ? treeHref(inMarkdown.dataset.dir) + "/" : data.repo + "/tree/main/";
    const url = new URL(relative ? new URL(written, location.origin + dir) : link.href);
    const ofThisRepo = url.pathname === data.repo || url.pathname.startsWith(data.repo + "/tree/");
    if (url.origin !== location.origin || !ofThisRepo) return;
    event.preventDefault();
    visit(url.pathname + url.search, true);
  });
}

drawTree();
drawContent();
drawDiffs();
drawPull();
drawEdit();