๐Ÿ“ฆ rust-lang / rust-clippy

๐Ÿ“„ script.js ยท 407 lines
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407"use strict";

const searchState = {
    lastSearch: '',
    filterLints: (updateURL = true) => {
        function matchesSearch(lint, terms, searchStr) {
            // Search by id
            if (lint.elem.id.indexOf(searchStr) !== -1) {
                return true;
            }
            // Search the description
            // The use of `for`-loops instead of `foreach` enables us to return early
            const docsLowerCase = lint.elem.textContent.toLowerCase();
            for (const term of terms) {
                // This is more likely and will therefore be checked first
                if (docsLowerCase.indexOf(term) !== -1) {
                    return true;
                }

                if (lint.elem.id.indexOf(term) !== -1) {
                    return true;
                }

                return false;
            }
            return true;
        }

        let searchStr = elements.search.value.trim().toLowerCase();
        if (searchStr.startsWith("clippy::")) {
            searchStr = searchStr.slice(8);
        }
        if (searchState.lastSearch === searchStr) {
            return;
        }
        searchState.lastSearch = searchStr;
        const terms = searchStr.split(" ");
        const cleanedSearchStr = searchStr.replaceAll("-", "_");

        for (const lint of filters.getAllLints()) {
            lint.searchFilteredOut = !matchesSearch(lint, terms, cleanedSearchStr);
            if (lint.searchFilteredOut || lint.filteredOut) {
                lint.elem.style.display = "none";
            } else {
                lint.elem.style.display = "";
            }
        }

        if (updateURL) {
            setURL();
        }
    },
};

function handleInputChanged(event) {
    if (event.target !== document.activeElement) {
        return;
    }
    searchState.filterLints();
}

function handleShortcut(ev) {
    if (ev.ctrlKey || ev.altKey || ev.metaKey || disableShortcuts) {
        return;
    }

    if (document.activeElement.tagName === "INPUT") {
        if (ev.key === "Escape") {
            document.activeElement.blur();
        }
    } else {
        switch (ev.key) {
            case "s":
            case "S":
            case "/":
                ev.preventDefault(); // To prevent the key to be put into the input.
                elements.search.focus();
                break;
            default:
                break;
        }
    }
}

/**
 * When `value` is `null` the default value is used - true for all but the `deprecated` lint group
 */
function resetCheckboxes(filter, value) {
    for (const element of elements.checkboxes[filter]) {
        const checked = value ?? element.name !== "deprecated";
        element.checked = checked;
    }
}

function onEachLazy(lazyArray, func) {
    const arr = Array.prototype.slice.call(lazyArray);
    for (const el of arr) {
        func(el);
    }
}

function expandLint(lintId) {
    const elem = document.querySelector(`#${lintId} > input[type="checkbox"]`);
    if (elem) {
        elem.checked = true;
    }
}

const clipboardTimeouts = new Map();
function copyToClipboard(event) {
    event.preventDefault();
    event.stopPropagation();

    const clipboard = event.target;

    navigator.clipboard.writeText("clippy::" + clipboard.parentElement.id.slice(5));

    clipboard.textContent = "โœ“";

    clearTimeout(clipboardTimeouts.get(clipboard));
    clipboardTimeouts.set(
        clipboard,
        setTimeout(() => {
            clipboard.textContent = "๐Ÿ“‹";
            clipboardTimeouts.delete(clipboard);
        }, 1000)
    );
}

function toggleExpansion(expand) {
    for (const checkbox of document.querySelectorAll("article input[type=checkbox]")) {
        checkbox.checked = expand;
    }
}

const filters = {
    allLints: null,
    getAllLints: () => {
        if (filters.allLints === null) {
            filters.allLints = Array.prototype.slice.call(
                document.getElementsByTagName("article"),
            ).map(elem => {
                let version = elem.querySelector(".label-version").innerText;
                // Strip the "pre " prefix for pre 1.29.0 lints
                if (version.startsWith("pre ")) {
                    version = version.slice(4);
                }
                return {
                    elem: elem,
                    group: elem.querySelector(".lint-group").innerText,
                    level: elem.querySelector(".lint-level").innerText,
                    version: parseInt(version.split(".")[1]),
                    applicability: elem.querySelector(".applicability").innerText,
                    filteredOut: false,
                    searchFilteredOut: false,
                };
            });
        }
        return filters.allLints;
    },
    filterLints: (updateURL = true) => {
        const [levels, groups, applicabilities] = ["levels", "groups", "applicabilities"].map(key => new Set(
            elements.checkboxes[key]
                .filter(checkbox => checkbox.checked)
                .map(checkbox => checkbox.name)
        ));

        const [lte, gte, eq] = ["lte", "gte", "eq"].map(key => Number(elements.versions[key].value));

        elements.counts.versions.textContent = (lte > 0) + (gte > 0) + (eq > 0);
        elements.counts.groups.textContent = groups.size;
        elements.counts.levels.textContent = levels.size;
        elements.counts.applicabilities.textContent = applicabilities.size;

        for (const lint of filters.getAllLints()) {
            lint.filteredOut = (!groups.has(lint.group)
                || !levels.has(lint.level)
                || !applicabilities.has(lint.applicability)
                || !(eq === 0 || lint.version === eq)
                || !(gte === 0 || lint.version >= gte)
                || !(lte === 0 || lint.version <= lte)
            );
            if (lint.filteredOut || lint.searchFilteredOut) {
                lint.elem.style.display = "none";
            } else {
                lint.elem.style.display = "";
            }
        }

        if (updateURL) {
            setURL();
        }
    },
};

function setupDropdown(elem) {
    const button = elem.querySelector("button");
    button.onclick = () => elem.classList.toggle("open");

    const setBlur = child => {
        child.onblur = event => {
            if (!elem.contains(document.activeElement) &&
                !elem.contains(event.relatedTarget)
            ) {
                elem.classList.remove("open");
            }
        }
    };
    onEachLazy(elem.children, setBlur);
    onEachLazy(elem.querySelectorAll("select"), setBlur);
    onEachLazy(elem.querySelectorAll("input"), setBlur);
    onEachLazy(elem.querySelectorAll("ul button"), setBlur);
}

function setURL() {
    const url = new URL(location);

    function nonDefault(filter) {
        return elements.checkboxes[filter]
            .some(element => element.checked === (element.name === "deprecated"));
    }
    function setBoolean(filter) {
        if (nonDefault(filter)) {
            const value = elements.checkboxes[filter]
                .filter(el => el.checked)
                .map(el => el.name)
                .join(",");
            url.searchParams.set(filter, value);
        }
    }

    url.search = "";
    setBoolean("groups");
    setBoolean("levels");
    setBoolean("applicabilities");

    const versions = ["eq", "gte", "lte"]
        .filter(op => elements.versions[op].value)
        .map(op => `${op}:${elements.versions[op].value}`)
        .join(",");
    if (versions) {
        url.searchParams.set("versions", versions);
    }

    const search = elements.search.value;
    if (search) {
        url.searchParams.set("search", search)
    }

    url.hash = "";

    if (!history.state) {
        history.pushState(true, "", url);
    } else {
        history.replaceState(true, "", url);
    }
}

function parseURL() {
    const params = new URLSearchParams(window.location.search);

    for (const [filter, checkboxes] of Object.entries(elements.checkboxes)) {
        if (params.has(filter)) {
            const settings = new Set(params.get(filter).split(","));

            for (const checkbox of checkboxes) {
                checkbox.checked = settings.has(checkbox.name);
            }
        } else {
            resetCheckboxes(filter, null);
        }
    }

    const versionStr = params.get("versions") ?? "";
    const versions = new Map(versionStr.split(",").map(elem => elem.split(":")));
    for (const element of Object.values(elements.versions)) {
        element.value = versions.get(element.name) ?? "";
    }

    elements.search.value = params.get("search");

    if (location.hash) {
        expandLint(location.hash.slice(1));
    }

    filters.filterLints(false);
    searchState.filterLints(false);
}

function addResetListeners(selector, value) {
    for (const button of document.querySelectorAll(selector)) {
        button.addEventListener("click", event => {
            const container = event.target.closest("[data-filter]");
            const filter = container.dataset.filter;
            resetCheckboxes(filter, value);
            filters.filterLints();
        })
    }
}

function addListeners() {
    document.getElementById("upper-filters").addEventListener("input", () => {
        filters.filterLints();
    });
    elements.search.addEventListener("input", handleInputChanged);

    elements.disableShortcuts.addEventListener("change", () => {
        disableShortcuts = elements.disableShortcuts.checked;
        storeValue("disable-shortcuts", disableShortcuts);
    });

    document.getElementById("expand-all").addEventListener("click", () => toggleExpansion(true));
    document.getElementById("collapse-all").addEventListener("click", () => toggleExpansion(false));

    // A delegated listener to avoid the upfront cost of >1000 listeners
    document.addEventListener("click", event => {
        if (!event.target instanceof HTMLAnchorElement) {
            return;
        }

        if (event.target.classList.contains("copy-to-clipboard")) {
            copyToClipboard(event);
        } else if (event.target.classList.contains("anchor")) {
            event.target.closest("article")
                .querySelector(`input[type="checkbox"]`)
                .checked = true;
        }
    });

    document.getElementById("filter-clear").addEventListener("click", () => {
        elements.search.value = "";
        searchState.filterLints();
    })

    addResetListeners(".reset-all", true);
    addResetListeners(".reset-none", false);
    addResetListeners(".reset-default", null);

    document.getElementById("reset-versions").addEventListener("click", () => {
        for (const input of Object.values(elements.versions)) {
            input.value = "";
        }
        filters.filterLints();
    });

    document.addEventListener("keypress", handleShortcut);
    document.addEventListener("keydown", handleShortcut);

    document.querySelectorAll(".dropdown").forEach(setupDropdown);

    addEventListener("popstate", parseURL);
}

// Highlight code blocks only when they approach the viewport so that clicking the "Expand All"
// button doesn't take a long time
function highlightLazily() {
    if (!'IntersectionObserver' in window) {
        return;
    }
    const observer = new IntersectionObserver((entries) => {
        for (const entry of entries) {
            if (entry.isIntersecting) {
                observer.unobserve(entry.target);
                for (const code of entry.target.querySelectorAll("pre code")) {
                    hljs.highlightElement(code);
                }
            }
        }
    });
    for (const docs of document.querySelectorAll(".lint-docs")) {
        observer.observe(docs);
    }
}

function findCheckboxes(filter) {
    return [...document.querySelectorAll(`.dropdown[data-filter="${filter}"] input[type="checkbox"]`)];
}

let disableShortcuts = loadValue("disable-shortcuts") === "true";

const elements = {
    search: document.getElementById("search-input"),
    disableShortcuts: document.getElementById("disable-shortcuts"),
    checkboxes: {
        levels: findCheckboxes("levels"),
        groups: findCheckboxes("groups"),
        applicabilities: findCheckboxes("applicabilities"),
    },
    versions: {
        gte: document.querySelector(`input[name="gte"]`),
        lte: document.querySelector(`input[name="lte"]`),
        eq: document.querySelector(`input[name="eq"]`),
    },
    counts: {
        levels: document.getElementById("levels-count"),
        groups: document.getElementById("groups-count"),
        applicabilities: document.getElementById("applicabilities-count"),
        versions: document.getElementById("versions-count"),
    },
};

elements.disableShortcuts.checked = disableShortcuts;

addListeners();
highlightLazily();
parseURL();