Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(store): add sorting by download count #9

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 45 additions & 2 deletions api/src/api/store/items.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,9 @@ export default function (fastify: FastifyInstance, _: unknown, done: () => void)
page?: string;
items?: string;
query?: string;
sort?: "downloads" | "name";
};
}>("/list/:type", (request, reply) => {
}>("/list/:type", async (request, reply) => {
// @ts-expect-error includes bs
if (!ADDON_TYPES.includes(request.params.type.replace(/s$/, ""))) {
reply.code(400).send({
Expand Down Expand Up @@ -191,7 +192,7 @@ export default function (fastify: FastifyInstance, _: unknown, done: () => void)
return;
}

const manifests = listAddons(type, request.query.query);
let manifests = listAddons(type, request.query.query);
const numPages = Math.ceil(manifests.length / perPage);
if (page > numPages) {
reply.code(404).send({
Expand All @@ -203,6 +204,48 @@ export default function (fastify: FastifyInstance, _: unknown, done: () => void)
const start = (page - 1) * perPage;
const end = start + perPage;

const sort = request.query.sort ?? "downloads";
if (sort === "downloads") {
const collection = fastify.mongo.db!.collection<StoreStats>("storeStats");
FedeIlLeone marked this conversation as resolved.
Show resolved Hide resolved
const aggregation = collection.aggregate([
{
$match: {
type: "install",
},
},
{
$group: {
_id: "$id",
ips: {
$addToSet: "$ipHash",
},
},
},
{
$project: {
count: {
$size: "$ips",
},
},
},
{
$sort: {
count: -1,
},
},
]);
const stats = await aggregation.toArray();

manifests = manifests.sort((a, b) => {
const aStat = stats.find((x) => x._id === a.id);
const bStat = stats.find((x) => x._id === b.id);
if (!aStat && !bStat) return 0;
if (!aStat) return 1;
if (!bStat) return -1;
return bStat.count - aStat.count;
});
}

return {
page,
numPages,
Expand Down
33 changes: 25 additions & 8 deletions web/src/components/store/Store.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { toArray } from "../util/misc";
import { getError, installAddon, useInstalledAddons } from "./utils";
import { Routes } from "../../constants";
import { RouteError } from "../../types";
import { SelectField } from "../util/Form";

type StoreKind = "plugin" | "theme";

Expand Down Expand Up @@ -238,6 +239,8 @@ export function StandaloneStoreItem({
export default function Store({ kind, installedAddons, updateAddonList }: StoreProps): VNode {
useTitle(`Replugged ${LABELS[kind]}`);

const [sort, setSort] = useState("downloads");

const [query, setQuery] = useState("");
const [debouncedQuery, setDebouncedQuery] = useState(query);

Expand All @@ -252,12 +255,13 @@ export default function Store({ kind, installedAddons, updateAddonList }: StoreP
);

const itemsQuery = useInfiniteQuery<PaginatedStore>({
queryKey: ["store", kind, debouncedQuery],
queryKey: ["store", kind, debouncedQuery, sort],
queryFn: async ({ pageParam: page }) => {
const queryString = new URLSearchParams({
page: page?.toString() ?? pageQuery ?? "1",
items: (12).toString(),
query: debouncedQuery,
sort,
});

const res = await fetch(`/api/store/list/${kind}?${queryString}`);
Expand Down Expand Up @@ -292,13 +296,26 @@ export default function Store({ kind, installedAddons, updateAddonList }: StoreP
<h1 class={style.header}>Replugged {LABELS[kind]}</h1>
<div class={style.grid}>
{items.length > 0 || debouncedQuery ? (
<input
class={`${formStyle.textField} ${style.search}`}
type="text"
placeholder="Search"
value={query}
onInput={(e) => setQuery(e.currentTarget.value)}
/>
<>
<SelectField
name="sort"
label="Sort By"
options={[
{ id: "downloads", name: "Downloads" },
{ id: "name", name: "Name" },
]}
value={sort}
fieldClassName={style.sortSelect}
onChange={(e) => setSort(e.currentTarget.value)}
/>
<input
class={`${formStyle.textField} ${style.search}`}
type="text"
placeholder="Search"
value={query}
onInput={(e) => setQuery(e.currentTarget.value)}
/>
</>
) : null}
<StoreBody
{...itemsQuery}
Expand Down
15 changes: 11 additions & 4 deletions web/src/components/store/store.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@
margin-bottom: 24px;
}

.sortSelect {
margin: 0;
padding-bottom: 0;
border-bottom: none;
}

.search {
grid-column-end: -1;
align-self: end;
}

.grid {
display: grid;
grid-template-columns: repeat(1, 1fr);
Expand All @@ -24,10 +35,6 @@
}
}

.search {
grid-column-end: -1;
}

.full-grid {
grid-column: 1 / -1;
}
Expand Down
16 changes: 13 additions & 3 deletions web/src/components/util/Form.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
type Attributes,
type ComponentChild,
type JSX,
ComponentChildren,
VNode,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand All @@ -20,6 +21,7 @@ type BaseProps = Attributes & {
error?: ComponentChild;
children: ComponentChild;
required?: boolean;
className?: string;
};

type BaseFieldProps = Attributes & {
Expand All @@ -31,6 +33,7 @@ type BaseFieldProps = Attributes & {
disabled?: boolean;
raw?: boolean;
rk?: number; // [Cynthia] this is used to force re-render of form fields, to help with errors sometimes not showing up
fieldClassName?: string;
};

type TextFieldProps = BaseFieldProps & {
Expand All @@ -42,6 +45,7 @@ type TextFieldProps = BaseFieldProps & {
};
type CheckboxFieldProps = BaseFieldProps & { value?: boolean };
type SelectFieldProps = BaseFieldProps & {
onChange: JSX.GenericEventHandler<HTMLSelectElement>;
value?: string;
options: Array<{ id: string; name: string }>;
};
Expand Down Expand Up @@ -81,7 +85,7 @@ function useField(note?: ComponentChild, error?: ComponentChild, rk?: number): F

function BaseField(props: BaseProps): VNode {
return (
<div className={style.field}>
<div className={[style.field, props.className].filter(Boolean).join(" ")}>
<label className={style.label} for={props.id}>
{props.label}
{props.required && <span className={style.required}>*</span>}
Expand Down Expand Up @@ -167,7 +171,12 @@ export function SelectField(props: SelectFieldProps): VNode {
const field = useField(props.note, props.error, props.rk);

return (
<BaseField {...field} label={props.label} required={props.required} id={field.id}>
<BaseField
{...field}
label={props.label}
required={props.required}
id={field.id}
className={props.fieldClassName}>
<select
type="checkbox"
id={field.id}
Expand All @@ -176,7 +185,8 @@ export function SelectField(props: SelectFieldProps): VNode {
required={props.required}
disabled={props.disabled}
className={style.selectField}
onClick={field.onChange}>
onClick={field.onChange}
onChange={props.onChange}>
{props.options.map(({ id, name }) => (
<option key={id} value={id}>
{name}
Expand Down