File size: 7,288 Bytes
161cb23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1415e8
161cb23
 
 
a1415e8
161cb23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1415e8
161cb23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import { byId, el } from "./dom.js";
import { plural } from "./labels.js";

const ROW_INDENT = 12;
const NARROW = "(max-width: 640px)";

function insertPath(root, file) {
  const parts = file.path.split("/");
  let folder = root;
  parts.slice(0, -1).forEach((name, depth) => {
    const path = parts.slice(0, depth + 1).join("/");
    if (!folder.folders.has(name)) {
      folder.folders.set(name, { name, path, folders: new Map(), files: [] });
    }
    folder = folder.folders.get(name);
  });
  folder.files.push(file);
}

function buildTree(files) {
  const root = { name: "", path: "", folders: new Map(), files: [] };
  files.forEach((file) => insertPath(root, file));
  return root;
}

const byName = (left, right) => left.name.localeCompare(right.name);
const byPath = (left, right) => left.path.localeCompare(right.path);

function sortedFolders(folder) {
  return [...folder.folders.values()].sort(byName);
}

function sortedFiles(folder) {
  return [...folder.files].sort(byPath);
}

function flatten(folder) {
  return [...sortedFolders(folder).flatMap(flatten), ...sortedFiles(folder)];
}

export function fileState(file) {
  return file.result.squiggles.length > 0 ? "has-issues" : "";
}

function folderState(folder) {
  return flatten(folder).some((file) => fileState(file) === "has-issues") ? "has-issues" : "";
}

function ancestors(path) {
  const parts = path.split("/").slice(0, -1);
  return parts.map((_, index) => parts.slice(0, index + 1).join("/"));
}

export function baseName(path) {
  return path.slice(path.lastIndexOf("/") + 1);
}

function fileTitle(file) {
  const count = file.result.squiggles.length;
  return count > 0 ? `${file.path} · ${plural(count, "issue")}` : file.path;
}

function icon(href, className = "icon") {
  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.setAttribute("class", className);
  svg.setAttribute("aria-hidden", "true");
  const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
  use.setAttribute("href", href);
  svg.append(use);
  return svg;
}

function fileBadge(file) {
  const count = file.result.squiggles.length;
  return count > 0 ? el("span", { class: "tree-count", text: String(count) }) : "";
}

function rowClass(state, selected) {
  return ["tree-row", state, selected ? "is-current" : ""].filter(Boolean).join(" ");
}

function keepRowVisible(list, row) {
  const rowBox = row.getBoundingClientRect();
  const listBox = list.getBoundingClientRect();
  if (rowBox.top < listBox.top) {
    list.scrollTop -= listBox.top - rowBox.top + 8;
  } else if (rowBox.bottom > listBox.bottom) {
    list.scrollTop += rowBox.bottom - listBox.bottom + 8;
  }
}

export function createNavigator(onSelect) {
  const stage = byId("stage");
  const explorer = byId("explorer");
  const toggle = byId("explorer-toggle");
  const filter = byId("tree-filter");
  const list = byId("tree-list");
  const narrow = window.matchMedia(NARROW);
  const open = new Set();
  let files = [];
  let order = [];
  let current = null;

  function setExplorer(visible) {
    const label = visible ? "Hide files" : "Show files";
    stage.classList.toggle("is-collapsed", !visible);
    toggle.setAttribute("aria-expanded", String(visible));
    toggle.setAttribute("aria-label", label);
    toggle.title = label;
  }

  function explorerVisible() {
    return !stage.classList.contains("is-collapsed");
  }

  function choose(file) {
    if (narrow.matches) {
      setExplorer(false);
    }
    onSelect(file);
  }

  function folderRow(folder, depth, expanded) {
    return el("button", {
      class: rowClass(folderState(folder), false),
      type: "button",
      style: `--depth: ${depth * ROW_INDENT}px`,
      "aria-expanded": String(expanded),
      onclick: () => {
        if (open.has(folder.path)) {
          open.delete(folder.path);
        } else {
          open.add(folder.path);
        }
        paintList();
      },
    }, [
      icon("#i-chevron", "icon tree-chevron"),
      icon("#i-folder"),
      el("span", { class: "tree-name", text: folder.name }),
      folderState(folder) ? el("span", { class: "tree-mark" }) : "",
    ]);
  }

  function fileRow(file, depth, label) {
    const selected = file === current;
    return el("button", {
      class: rowClass(fileState(file), selected),
      type: "button",
      style: `--depth: ${depth * ROW_INDENT}px`,
      title: fileTitle(file),
      "aria-current": selected ? "true" : null,
      onclick: () => choose(file),
    }, [
      el("span", { class: "tree-spacer" }),
      icon("#i-code"),
      el("span", { class: "tree-name", text: label }),
      fileBadge(file),
    ]);
  }

  function folderRows(folder, depth) {
    const rows = [];
    for (const child of sortedFolders(folder)) {
      const expanded = open.has(child.path);
      rows.push(folderRow(child, depth, expanded));
      if (expanded) {
        rows.push(...folderRows(child, depth + 1));
      }
    }
    rows.push(...sortedFiles(folder).map((file) => fileRow(file, depth, baseName(file.path))));
    return rows;
  }

  function matchingRows(query) {
    const matches = order.filter((file) => file.path.toLowerCase().includes(query));
    if (matches.length === 0) {
      return [el("p", { class: "tree-empty", text: "No matches" })];
    }
    return matches.map((file) => fileRow(file, 0, file.path));
  }

  function paintList() {
    const query = filter.value.trim().toLowerCase();
    list.replaceChildren(...(query ? matchingRows(query) : folderRows(buildTree(files), 0)));
  }

  function revealCurrent() {
    if (current) {
      ancestors(current.path).forEach((path) => open.add(path));
    }
  }

  function showCurrentRow() {
    const row = list.querySelector(".is-current");
    if (row && explorerVisible()) {
      keepRowVisible(list, row);
    }
  }

  function step(offset) {
    if (order.length === 0) {
      return;
    }
    const index = Math.max(0, order.indexOf(current));
    onSelect(order[(index + offset + order.length) % order.length]);
  }

  setExplorer(!narrow.matches);
  toggle.addEventListener("click", () => setExplorer(!explorerVisible()));
  byId("nav-prev").addEventListener("click", () => step(-1));
  byId("nav-next").addEventListener("click", () => step(1));
  filter.addEventListener("input", paintList);
  filter.addEventListener("keydown", (event) => {
    if (event.key === "Enter") {
      list.querySelector(".tree-row:not([aria-expanded])")?.click();
    }
  });
  document.addEventListener("pointerdown", (event) => {
    const outside = !explorer.contains(event.target) && !toggle.contains(event.target);
    if (narrow.matches && explorerVisible() && outside) {
      setExplorer(false);
    }
  });

  return {
    render(nextFiles, nextCurrent) {
      files = nextFiles;
      order = flatten(buildTree(files));
      open.clear();
      current = nextCurrent;
      filter.value = "";
      revealCurrent();
      paintList();
      list.scrollTop = 0;
      showCurrentRow();
    },
    update(nextFiles, nextCurrent) {
      const moved = nextCurrent !== current;
      files = nextFiles;
      current = nextCurrent;
      if (moved) {
        revealCurrent();
      }
      paintList();
      if (moved) {
        showCurrentRow();
      }
    },
  };
}