From e2bce1904a816bf781818610adbf6430348fbbf1 Mon Sep 17 00:00:00 2001 From: Alex Gustafsson Date: Sun, 12 Jan 2025 19:11:32 +0100 Subject: [PATCH] Sort selected tags first --- web/components/ImageCard.tsx | 36 ++++++++++--------- web/components/TagSelect.tsx | 67 +++++++++++++++++++++--------------- web/tags.ts | 16 +++++++-- 3 files changed, 72 insertions(+), 47 deletions(-) diff --git a/web/components/ImageCard.tsx b/web/components/ImageCard.tsx index 683741c..5a91479 100644 --- a/web/components/ImageCard.tsx +++ b/web/components/ImageCard.tsx @@ -1,7 +1,7 @@ import type { JSX } from 'react' import { NavLink, useNavigate } from 'react-router-dom' -import { TagsByName, sortTags } from '../tags' +import { TagsByName, compareTags } from '../tags' import { formatRelativeTimeTo } from '../time' import { Badge } from './Badge' import { ImageLogo } from './ImageLogo' @@ -82,22 +82,24 @@ export function ImageCard({ )}

{description}

- {tags.toSorted(sortTags).map((x) => ( - { - e.metaKey || e.ctrlKey - ? openTab(`/?tag=${encodeURIComponent(x)}`) - : navigate(`/?tag=${encodeURIComponent(x)}`) - e.preventDefault() - }} - /> - ))} + {tags + .toSorted((a, b) => compareTags(a, b)) + .map((x) => ( + { + e.metaKey || e.ctrlKey + ? openTab(`/?tag=${encodeURIComponent(x)}`) + : navigate(`/?tag=${encodeURIComponent(x)}`) + e.preventDefault() + }} + /> + ))}
diff --git a/web/components/TagSelect.tsx b/web/components/TagSelect.tsx index 7cafa8e..5169994 100644 --- a/web/components/TagSelect.tsx +++ b/web/components/TagSelect.tsx @@ -1,6 +1,6 @@ import { type JSX, type PropsWithChildren, useRef, useState } from 'react' -import { type Tag, sortTags } from '../tags' +import { type Tag, compareTags } from '../tags' import { Badge } from './Badge' const IOS = [ @@ -39,11 +39,13 @@ export function TagSelect({ ) } > - {tags.toSorted(sortTags).map((x) => ( - - ))} + {tags + .toSorted((a, b) => compareTags(a.name, b.name)) + .map((x) => ( + + ))}
- {tags.toSorted(sortTags).map((x) => ( - - ))} + {tags + .toSorted((a, b) => + compareTags( + a.name, + b.name, + filter.includes(a.name), + filter.includes(b.name) + ) + ) + .map((x) => ( + + ))}
)} diff --git a/web/tags.ts b/web/tags.ts index bcb452c..620cb7f 100644 --- a/web/tags.ts +++ b/web/tags.ts @@ -123,8 +123,20 @@ export const TagsByName: Record = Object.fromEntries( Tags.map((x) => [x.name, x]) ) -/** Sort tags lexically, putting prefixed tags last. */ -export function sortTags(a: Tag | string, b: Tag | string): number { +/** Sort tags lexically, putting prefixed tags last, selected tags first. */ +export function compareTags( + a: string, + b: string, + aSelected?: boolean, + bSelected?: boolean +): number { + // Prioritize selected tags + if (aSelected === true && bSelected === false) { + return -1 + } else if (aSelected === false && bSelected === true) { + return 1 + } + const aString = typeof a === 'string' ? a : a.name const bString = typeof b === 'string' ? b : b.name