Skip to content

Commit

Permalink
[webUI] Add a Select All button (#28)
Browse files Browse the repository at this point in the history
Co-authored-by: NSPBot911 <[email protected]>
  • Loading branch information
NSPC911 and NSPBot911 authored Oct 2, 2024
1 parent 3b3f2db commit 2464c30
Show file tree
Hide file tree
Showing 9 changed files with 874 additions and 551 deletions.
5 changes: 4 additions & 1 deletion credits.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,11 @@
[PAPISOP](https://github.com/PAPISOP) and [Arachi (Chi-a11y)](https://github.com/Chi-a11y)
- A lot of packs from [BedrockTweaks/Files](https://github.com/BedrockTweaks/Files). [PAPISOP's PRs](https://github.com/BedrockTweaks/Files/pulls/PAPISOP) and [Arachi's PRs](https://github.com/BedrockTweaks/Files/pulls/Chi-a11y)

[Tal](https://twitter.com/melamed_tal/)'s [Clear Wire Pack](https://mcpedl.com/clear-wire-texture-pack/) and NSPC911's [continuation](https://github.com/NSPC911/Clear-Vanilla)
- Most of the packs available in Utility > Clear Blocks

[HampsterChief](https://discord.com/users/1053822004211482676)
- Turned Anvls nto a Metal Pipe
- Turned Anvils into a Metal Pipe

[NSPC911](https://github.com/NSPC911)
- Yep, that's me, the one who started this all!
Expand Down
32 changes: 14 additions & 18 deletions pys/custom_functions.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
import os
import importlib
import pip
from pip import main
import time
import traceback
import os, sys, importlib, time, traceback, urllib.parse
from subprocess import run, CalledProcessError


# If I need a module that isn't installed
def check(module, module_name=""):
try:
importlib.import_module(module)
except ModuleNotFoundError:
print(f"{module} is not installed!")
if module_name == "":
# Using pip instead of subprocess as calling
# with terminal results in an error
pip.main(["install", module])
else:
# Using pip instead of subprocess as calling
# with terminal results in an error
pip.main(["install", module_name])
try:
if module_name == "":
print(f"Installing {module}...")
run([sys.executable, "-m", "pip", "install", module, "--quiet"], check=True)
else:
print(f"Installing {module_name}...")
run([sys.executable, "-m", "pip", "install", module_name, "--quiet"], check=True)
print(f"Installed {module}!")
except CalledProcessError:
print(f"Failed to install {module}!")
exit(1)
time.sleep(1)


Expand All @@ -29,7 +26,6 @@ def check(module, module_name=""):
check("ujson")
from ujson import *


# For module to be easy to use and not require
# the start of the program to be cluttered
currentdir = os.getcwd()
Expand Down Expand Up @@ -106,4 +102,4 @@ def prog_search(string: str, list_search: list):
return found_at
# There isn't anything that matches
if found != 1:
return None
return None
17 changes: 13 additions & 4 deletions pys/pre_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,15 @@
from markdown import markdown
check("bs4","beautifulsoup4")
from bs4 import BeautifulSoup
check("lzstring")
from lzstring import LZString
from json import dumps

category_start = '<div class="category"><div class="category-label" onclick="toggleCategory(this)">topic_name</div><div class="category-controlled"><div class="tweaks">'
subcategory_start = '<div class="subcategory"><div class="category-label" onclick="toggleCategory(this)">topic_name</div><div class="category-controlled"><div class="subcattweaks">'
category_start = '<div class="category"><div class="category-label" onclick="toggleCategory(this)">topic_name</div><button class="category-label-selectall" onclick="selectAll(\u0027<all_packs>\u0027,this)"><img src="images/select-all-button/chiseled_bookshelf_empty.png" class="category-label-selectall-img"><div class="category-label-selectall-hovertext">Select All</div></button><div class="category-controlled"><div class="tweaks">'
subcategory_start = '<div class="subcategory"><div class="category-label" onclick="toggleCategory(this)">topic_name</div><button class="category-label-selectall sub" onclick="selectAll(\u0027<all_packs>\u0027,this)"><img src="images/select-all-button/chiseled_bookshelf_empty.png" class="category-label-selectall-img"><div class="category-label-selectall-hovertext">Select All</div></button><div class="category-controlled"><div class="subcattweaks">'
pack_start = '<div class="tweak" onclick="toggleSelection(this)" data-category="topic_name" data-name="pack_id" data-index="pack_index">'
html_comp = '<div class="comp-hover-text">Incompatible with: <incompatible></div>'
pack_mid = '<div class="tweak-info"><input type="checkbox" id="tweaknumber" name="tweak" value="tweaknumber"><img src="https://raw.githubusercontent.com/BEComTweaks/resource-packs/main/relloctopackicon"style="width:82px; height:82px;" alt="pack_name"><br><label id="tweak" class="tweak-title">pack_name</label><div class="tweak-description">pack_description</div></div>'
pack_mid = '<div class="tweak-info"><input type="checkbox" id="tweaknumber" name="tweak" value="tweaknumber"><img src="https://raw.githubusercontent.com/BEComTweaks/resource-packs/main/relloctopackicon" style="width:82px; height:82px;" alt="pack_name" loading="lazy"><br><label id="tweak" class="tweak-title">pack_name</label><div class="tweak-description">pack_description</div></div>'
html_conf = '<div class="conf-hover-text">Conflicts with: <conflicts></div>'
pack_end = '</div>'
category_end = '</div></div></div>'
Expand Down Expand Up @@ -53,7 +56,7 @@

parser = argparse.ArgumentParser(description='Run a massive script that updates Packs to-do, Icons to-do, Compatibilities to-do and the HTML')
parser.add_argument('--format', action='store_true', help='Include flag to format files')
parser.add_argument('--use-relative-location', action='store_true', help='Use relative location')
parser.add_argument('--use-relative-location', '-rl', action='store_true', help='Use relative location')
args = parser.parse_args()

# Counts Packs and Compatibilities
Expand All @@ -68,6 +71,7 @@
incomplete_pkics[file["topic"]] = []
incomplete_packs[file["topic"]] = []
html += category_start.replace("topic_name", file["topic"])
current_category_packs = { "raw": [] }
# Runs through the packs
for i in range(len(file["packs"])):
# Updates Incomplete Packs
Expand Down Expand Up @@ -182,6 +186,8 @@
if args.use_relative_location:
to_add_pack = to_add_pack.replace("https://raw.githubusercontent.com/BEComTweaks/resource-packs/main/","../")
html += to_add_pack
current_category_packs["raw"].append(file["packs"][i]["pack_id"])
html = html.replace("<all_packs>", LZString.compressToEncodedURIComponent(dumps(current_category_packs)))
try:
if pack_list[pack_list.index(origj) + 1].startswith("\t"):
html += cat_end_w_subcat_no_end
Expand Down Expand Up @@ -214,6 +220,7 @@
incomplete_pkics[file["topic"]] = []
incomplete_packs[file["topic"]] = []
pack_html += subcategory_start.replace("topic_name", f'{file["subcategory_of"]} > <b>{file["topic"]}</b>')
current_category_packs = { "raw": [] }
for i in range(len(file["packs"])):
# Updates Incomplete Packs
try:
Expand Down Expand Up @@ -327,8 +334,10 @@
if args.use_relative_location:
to_add_pack = to_add_pack.replace("https://raw.githubusercontent.com/BEComTweaks/resource-packs/main/","../")
pack_html += to_add_pack
current_category_packs["raw"].append(file["packs"][i]["pack_id"])
pack_html += category_end
html = html.replace(f'<div class="subcat{j}"></div>',pack_html)
html = html.replace("<all_packs>", LZString.compressToEncodedURIComponent(dumps(current_category_packs)))
clrprint("Finished Counting!", clr="green")

# HTML formatting
Expand Down
119 changes: 101 additions & 18 deletions webUI/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,25 @@ function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}

function enableSelection(element, checkbox) {
element.classList.add("selected");
checkbox.checked = true;
}

function disableSelection(element, checkbox) {
element.classList.remove("selected");
checkbox.checked = false;
}

function toggleSelection(element) {
// toggle the pack
element.classList.toggle("selected");
const checkbox = element.querySelector('input[type="checkbox"]');
checkbox.checked = !checkbox.checked;
// logging
if (checkbox.checked) {
console.log(`Selected ${element.dataset.name}`);
} else {
disableSelection(element, checkbox);
console.log(`Unselected ${element.dataset.name}`);
} else {
enableSelection(element, checkbox);
console.log(`Selected ${element.dataset.name}`);
}
// send to selected tweaks
var selectedTweaks = [];
Expand Down Expand Up @@ -46,8 +55,27 @@ function toggleSelection(element) {
tweakItem.textContent = "Select some packs and see them appear here!";
document.getElementById("selected-tweaks").appendChild(tweakItem);
}
// query params
var st = getSelectedTweaks();
var selectedTweaks = getSelectedTweaks();
var dataCategory = element.dataset.category;
const selectAllElement =
element.parentElement.parentElement.parentElement.querySelector(
".category-label-selectall",
);
if (selectedTweaks[dataCategory]["packs"].length == 0) {
unselectAll("", selectAllElement);
} else if (
selectedTweaks[dataCategory]["packs"].length ==
element.parentElement.querySelectorAll(".tweak").length
) {
selectAll("", selectAllElement);
} else {
partialSelected(selectAllElement);
}
updateURL(getSelectedTweaks());
}

// query params function
function updateURL(st) {
for (var key in st) {
try {
if (st[key].packs) {
Expand All @@ -72,14 +100,13 @@ function toggleSelection(element) {
// update url
window.history.replaceState({}, "", newUrl);
}

// if query params already exists
const loadedparams = new URLSearchParams(window.location.search);
if (loadedparams.has("st_raw")) {
const st = JSON.parse(
LZString.decompressFromEncodedURIComponent(loadedparams.get("st_raw")),
);
processJsonData(st);
processJsonData(st, "select");
}
// for people who want instant stuff
const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
Expand All @@ -89,17 +116,21 @@ function getTimeoutDuration() {
}
// toggle category
function toggleCategory(label) {
const tweaksContainer = label.nextElementSibling;
const tweaksContainer = label.parentElement.querySelector(
".category-controlled",
);
const timeoutDuration = getTimeoutDuration();

const selectallbutton = label.nextElementSibling;
if (tweaksContainer.style.maxHeight) {
// close category
tweaksContainer.style.maxHeight = null;
selectallbutton.style.opacity = 0;
setTimeout(() => {
tweaksContainer.style.display = "none";
tweaksContainer.style.paddingTop = null;
tweaksContainer.style.paddingBottom = null;
label.classList.remove("open");
selectallbutton.style.display = "none";
}, timeoutDuration); // Matches the transition duration
} else {
// open category
Expand All @@ -109,12 +140,19 @@ function toggleCategory(label) {
label.classList.add("open");
tweaksContainer.style.maxHeight = tweaksContainer.scrollHeight + "px";
const outerCatLabel =
label.parentElement.parentElement.previousElementSibling;
const outerCatContainer = label.parentElement.parentElement;
if (outerCatLabel.classList.contains("category-label")) {
label.parentElement.parentElement.parentElement.querySelector(
".category-label",
);
const outerCatContainer =
label.parentElement.parentElement.parentElement.querySelector(
".category-controlled",
);
if (outerCatLabel) {
outerCatContainer.style.maxHeight =
outerCatContainer.scrollHeight + tweaksContainer.scrollHeight + "px";
}
selectallbutton.style.display = "block";
selectallbutton.style.opacity = 1;
}
}
// i wonder what this is for
Expand Down Expand Up @@ -219,15 +257,20 @@ function fetchPack(protocol, jsonData, packName, mcVersion) {
}

// process json data from url/json
function processJsonData(jsonData) {
function processJsonData(jsonData, dowhat) {
const rawPacks = jsonData.raw;

if (Array.isArray(rawPacks)) {
rawPacks.forEach(function (pack) {
const div = document.querySelector(`div.tweak[data-name="${pack}"]`);
if (div) {
toggleSelection(div);
console.log(`Toggled Selection of ${pack}`);
if (dowhat == "select") {
enableSelection(div, div.querySelector('input[type="checkbox"]'));
console.log(`Selected ${pack}`);
} else if (dowhat == "unselect") {
disableSelection(div, div.querySelector('input[type="checkbox"]'));
console.log(`Unselected ${pack}`);
}
} else {
console.error(`Div with data-name="${pack}" not found.`);
}
Expand Down Expand Up @@ -446,7 +489,7 @@ document
.then(function (content) {
try {
const jsonData = JSON.parse(content);
processJsonData(jsonData);
processJsonData(jsonData, "select");
} catch (error) {
console.error("Error parsing JSON:", error);
}
Expand Down Expand Up @@ -475,3 +518,43 @@ document
console.error("No file selected.");
}
});

// select all tweaks
function selectAll(compressedstring, element) {
if (compressedstring != "") {
const st = JSON.parse(
LZString.decompressFromEncodedURIComponent(compressedstring),
);
processJsonData(st, "select");
updateURL(st);
element.onclick = function () {
unselectAll(compressedstring, element);
};
}
element.innerHTML =
'<img src="images/select-all-button/chiseled_bookshelf_occupied.png" class="category-label-selectall-img"><div class="category-label-selectall-hovertext">Unselect All</div>';
}

function partialSelected(element) {
element.innerHTML =
'<img src="images/select-all-button/chiseled_bookshelf_has_selected.png" class="category-label-selectall-img"><div class="category-label-selectall-hovertext">Select All</div>';
const compressedstring = element.onclick.toString().split("'")[1];
element.onclick = function () {
selectAll(compressedstring, element);
};
}

function unselectAll(compressedstring, element) {
if (compressedstring != "") {
const st = JSON.parse(
LZString.decompressFromEncodedURIComponent(compressedstring),
);
processJsonData(st, "unselect");
updateURL(st);
element.onclick = function () {
selectAll(compressedstring, element);
};
}
element.innerHTML =
'<img src="images/select-all-button/chiseled_bookshelf_empty.png" class="category-label-selectall-img"><div class="category-label-selectall-hovertext">Select All</div>';
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 2464c30

Please sign in to comment.