add varying intensity to stream tags

plus improving the tag select dropdown in general
This commit is contained in:
2026-09-25 21:26:31 +02:00
parent c49fb9bb54
commit 83cc73acff
11 changed files with 338 additions and 95 deletions
+5 -2
View File
@@ -52,8 +52,11 @@ for (const file of files) {
// Prepare attributes for insertion
const fields = Object.entries(jsonData)
.filter(([key]) => key in lookup)
// Serialize value if array
.map(([key, value]) => [lookup[key], Array.isArray(value) ? JSON.stringify(value) : value]);
// Serialize value if array or object
.map(([key, value]) => [
lookup[key],
typeof value === 'object' && value !== null ? JSON.stringify(value) : value
]);
const row = existingRow.get(jsonData.id);
if (row) {
+33
View File
@@ -0,0 +1,33 @@
<script lang="ts">
import type { TagWeights } from '$lib/types';
let { tags, highlighted = {} }: { tags: TagWeights; highlighted?: Record<string, number> } =
$props();
let sorted = $derived(Object.entries(tags).sort((a, b) => b[1] - a[1]));
</script>
{#each sorted as [tag, weight], i}{i ? ', ' : ''}<span
class="weight-{weight}"
class:highlighted={tag in highlighted}>{tag}</span
>{/each}
<style>
.weight-1 {
font-weight: normal;
}
.weight-2 {
font-weight: bold;
}
.weight-3 {
font-weight: bold;
text-decoration: underline;
}
/* translucent to take on the hover/selected bg colour tint */
.highlighted {
background: rgba(255, 220, 0, 0.18);
}
</style>
+2 -2
View File
@@ -18,7 +18,7 @@ export function getStreams(): StreamSummary[] {
stream_date: Date.parse(stream.stream_date as string),
filename: stream.filename as string,
title: stream.title as string | null,
tags: (JSON.parse(stream.tags as string) as string[]) ?? [],
tags: stream.tags ? JSON.parse(stream.tags as string) : {},
length_seconds: stream.length_seconds as number
}));
}
@@ -40,7 +40,7 @@ export function getStreamInfo(streamId: string): Stream | null {
format: streamData.format as string,
title: streamData.title as string | null,
description: streamData.description as string | null,
tags: (JSON.parse(streamData.tags as string) as string[]) ?? [],
tags: streamData.tags ? JSON.parse(streamData.tags as string) : {},
length_seconds: streamData.length_seconds as number,
tracks: JSON.parse(streamData.tracks as string)
};
+2
View File
@@ -8,6 +8,8 @@ $effect.root(() => {
});
});
export const MAX_TAG_WEIGHT = 3;
export const tagList = [
'acoustic',
'electronic',
+4 -1
View File
@@ -1,13 +1,16 @@
/** A track entry: [timestamp_seconds, artist, title] */
export type Track = [number, string, string];
// tag -> weight, 1 (light) to 3 (heavy)
export type TagWeights = Record<string, number>;
/** The summary shape used in sidebar listings. */
export interface StreamSummary {
id: string;
stream_date: number;
filename: string;
title: string | null;
tags: string[];
tags: TagWeights;
length_seconds: number;
}
+4
View File
@@ -8,6 +8,10 @@
<svelte:head>
<style>
:root {
--accent: #add8e6;
}
body,
html {
margin: 0;
+91 -28
View File
@@ -1,47 +1,88 @@
<script lang="ts">
import { untrack } from 'svelte';
import { goto } from '$app/navigation';
import { favoritedStreams } from '$lib/stores.svelte.ts';
import { favoritedStreams, tagList, MAX_TAG_WEIGHT } from '$lib/stores.svelte.ts';
import * as streamCache from '$lib/streamCache.svelte.ts';
import { getStreamContext } from '$lib/streamContext.svelte.ts';
import type { StreamSummary } from '$lib/types';
import { hashColor, shorthandCode, formatSecondsToHms, formatDate } from '$lib/utils.ts';
import { shorthandCode, formatSecondsToHms, formatDate } from '$lib/utils.ts';
import TagSelect from './TagSelect.svelte';
import WeightedTags from '$lib/components/WeightedTags.svelte';
const ctx = getStreamContext();
let filteredTags = $state([]);
// map of tag -> minimum weight
// a stream shows if it has every tag with at least the minimum weight
let filteredTags: Record<string, number> = $state({});
let favoritesOnly = $state(false);
let cachedOnly = $state(false);
let listOpen = $state(false);
let displayedStreams = $derived.by(streamsToDisplay);
let remainingTags = $derived.by(getRemainingTags);
// how many displayed streams have each unselected tag, at each weight?
// used in the tag select dropdown
let dropdownCounts = $derived.by(getDropdownCounts);
// how many displayed streams would be shown
// if filtered per each of this tag's weights,
// all other filters unchanged?
// used for the selected tag pills
let pillCounts = $derived.by(getPillCounts);
// which tags can still alter the displayed streams if selected?
// we eliminate either those which aren't present in the displayed streams
// or those present (at the same weight) in every displayed stream
// decides which tags are visible in the selection dropdown
let remainingTags = $derived(
Object.keys(dropdownCounts).filter((tag) =>
dropdownCounts[tag].some((count) => count > 0 && count < displayedStreams.size)
)
);
let cacheUsage = $derived(streamCache.usage.bytes);
$effect(() => {
if (displayedStreams.length == 1) {
listOpen = untrack(() => !listOpen);
if (displayedStreams.size == 1) {
listOpen = false;
}
});
function matchesFilter(stream: StreamSummary, filters: Record<string, number>) {
return Object.entries(filters).every(([tag, min]) => (stream.tags[tag] ?? 0) >= min);
}
function streamsToDisplay() {
return ctx.streams.filter(
(stream) =>
!('tags' in stream) || filteredTags.every((tag) => stream.tags.includes(tag))
return new Set(ctx.streams.filter((stream) => matchesFilter(stream, filteredTags)));
}
// how many of these streams have the tag at weight 1+, 2+ and 3+
// e.g. dark at weights [1, 3, 3, None] on four streams gives [3, 2, 2]
function weightCounts(streams: Iterable<StreamSummary>, tag: string) {
const counts = new Array(MAX_TAG_WEIGHT).fill(0);
for (const stream of streams) {
const weight = stream.tags[tag] ?? 0;
for (let i = 0; i < weight; i++) counts[i]++;
}
return counts;
}
function getDropdownCounts() {
const unselected = tagList.filter((tag) => !(tag in filteredTags));
return Object.fromEntries(
unselected.map((tag) => [tag, weightCounts(displayedStreams, tag)])
);
}
function getRemainingTags() {
let tagCounts = displayedStreams.reduce((tags: Record<string, number>, stream) => {
stream.tags.forEach((tag) => (tags[tag] ? (tags[tag] += 1) : (tags[tag] = 1)));
return tags;
}, {});
return Object.entries(tagCounts)
.filter((el) => el[1] != displayedStreams.length)
.map((el) => el[0]);
}
function getPillCounts() {
return Object.fromEntries(
Object.keys(filteredTags).map((tag) => {
const otherFilters = { ...filteredTags };
delete otherFilters[tag];
function getDisplayedTagsInList(streamTags: string[], remainingTags: string[]) {
return streamTags.filter((tag) => remainingTags.includes(tag));
const candidates = ctx.streams.filter((stream) =>
matchesFilter(stream, otherFilters)
);
return [tag, weightCounts(candidates, tag)];
})
);
}
function updateFavorites(stream: StreamSummary) {
@@ -52,7 +93,13 @@
</script>
<div class="tag-select">
<TagSelect bind:listOpen bind:checked={filteredTags} {remainingTags} />
<TagSelect
bind:listOpen
bind:checked={filteredTags}
{remainingTags}
{dropdownCounts}
{pillCounts}
/>
<button
onclick={() => (cachedOnly = !cachedOnly)}
class="material-icons filter-download {cachedOnly
@@ -72,7 +119,7 @@
{@const isPartial = streamCache.partials.has(stream.id)}
{@const current = ctx.current?.id === stream.id}
<li
hidden={!displayedStreams.includes(stream) ||
hidden={!displayedStreams.has(stream) ||
(favoritesOnly && !favorited) ||
(cachedOnly && !(isCached || isPartial))}
class="stream-item {current ? 'current-stream' : ''}"
@@ -88,11 +135,11 @@
<span class="stream-item-length">{formatSecondsToHms(stream.length_seconds)}</span>
<p class="stream-item-tags" hidden={!remainingTags.length}>
Tags: <span hidden={!filteredTags.length}>[...] </span>{getDisplayedTagsInList(
stream.tags,
remainingTags
).join(', ')}
<p class="stream-item-tags" hidden={!Object.keys(stream.tags).length}>
<span class="stream-item-tags-label">Tags:</span>
<span class="stream-item-tags-list"
><WeightedTags tags={stream.tags} highlighted={filteredTags} /></span
>
</p>
</button>
@@ -156,11 +203,27 @@
}
.stream-item-tags {
display: flex;
clear: both;
gap: 0.3em;
margin: 0;
font-family: Tahoma;
font-size: smaller;
}
.stream-item-tags[hidden] {
display: none;
}
.stream-item-tags-label {
flex-shrink: 0;
}
.stream-item-tags-list {
flex-grow: 1;
text-align: center;
}
.stream-item-id {
float: left;
font-family: monospace;
+129 -35
View File
@@ -1,53 +1,67 @@
<script lang="ts">
import Select from 'svelte-select';
import { tagList } from '$lib/stores.svelte.ts';
import { tagList, MAX_TAG_WEIGHT } from '$lib/stores.svelte.ts';
// type not exported in the lib itself
type SelectItem = Record<string, unknown>;
let { checked = $bindable([]), remainingTags = [], listOpen = $bindable() } = $props();
type Props = {
// tag -> minimum weight
checked: Record<string, number>;
// unselected tags that can still narrow the list
remainingTags: string[];
// unselected tag -> [displayed streams with it at weight 1+, 2+, 3+]
dropdownCounts: Record<string, number[]>;
// selected tag -> [streams shown if its minimum weight were 1, 2, 3]
pillCounts: Record<string, number[]>;
listOpen: boolean;
};
let {
checked = $bindable({}),
remainingTags = [],
dropdownCounts = {},
pillCounts = {},
listOpen = $bindable()
}: Props = $props();
let items = $state(tagList.map((x) => ({ value: x, label: x })));
let isChecked = $derived.by(computeIsChecked);
let value = $derived.by(computeValue);
function computeIsChecked() {
return checked.reduce((acc, c) => {
acc[c] = true;
return acc;
}, {});
}
function computeValue() {
return checked.map((c) => items.find((i) => i.value === c));
return Object.keys(checked).map((c) => items.find((i) => i.value === c));
}
function handleSelectable() {
items = items.map((item) => {
return { ...item, selectable: !checked.includes(item.value) };
return { ...item, selectable: !(item.value in checked) };
});
}
function toggle(tag: string) {
checked = checked.includes(tag) ? checked.filter((i) => i != tag) : [...checked, tag];
// item selected or deleted => passes every selected item as a list
// removing last pill or clearing all => passes undefined
function handleInput(selected: unknown) {
const tags = ((selected ?? []) as SelectItem[]).map((item) => item.value as string);
checked = Object.fromEntries(tags.map((tag) => [tag, checked[tag] ?? 1]));
handleSelectable();
}
function handleSelect(item: SelectItem) {
toggle(item.value as string);
// maximum weight that matches at least one stream for this tag with the current filters
function ceilingOf(tag: string) {
return pillCounts[tag].filter((count) => count > 0).length;
}
// clear can either be sent by the clear-all button, which sends the whole array
// or by removing a single item, which passes it in isolation
function handleClear(removed: unknown) {
if (Array.isArray(removed)) {
checked = [];
handleSelectable();
} else toggle((removed as SelectItem).value as string);
// increment the weight threshold for this tag
// and cycles back to 1 once we hit ceilingOf
function cycle(tag: string, back: boolean) {
const min = checked[tag];
const ceiling = ceilingOf(tag);
const next = back ? (min > 1 ? min - 1 : ceiling) : min < ceiling ? min + 1 : 1;
checked = { ...checked, [tag]: next };
}
let itemFilter = function (label: unknown, filterText: string, option: SelectItem) {
return (
remainingTags.includes(option['value']) &&
remainingTags.includes(option.value as string) &&
String(label).toLowerCase().includes(filterText.toLowerCase())
);
};
@@ -61,29 +75,109 @@
placeholder="Tag Filter..."
filterSelectedItems={true}
closeListOnChange={false}
onselect={handleSelect}
onclear={handleClear}
oninput={handleInput}
{itemFilter}
--max-height="42px"
--background="rgba(255, 255, 255, 0.1)"
--border="1px solid rgba(255, 255, 255, 0.3)"
--border-hover="1px solid rgba(255, 255, 255, 0.3)"
--border-focused="1px solid var(--accent)"
--item-color="white"
--placeholder-color="rgba(255, 255, 255, 0.5)"
--icons-color="rgba(255, 255, 255, 0.6)"
--list-background="#3a3a3a"
--list-border="1px solid rgba(255, 255, 255, 0.3)"
--list-shadow="none"
--item-hover-bg="rgba(255, 255, 255, 0.15)"
--item-hover-color="white"
--item-transition="none"
--item-height="30px"
--item-line-height="30px"
--item-active-background="rgba(173, 216, 230, 0.3)"
--multi-item-bg="rgba(255, 255, 255, 0.15)"
--multi-item-outline="none"
--multi-item-clear-icon-color="white"
listOffset={0}
>
{#snippet item({ item }: { item: SelectItem })}
{@const tag = item.value as string}
<div class="item">
<label for={tag}>
<input type="checkbox" id={tag} checked={isChecked[tag]} />
{item.label}
</label>
</div>
{item.label}<span class="count">{dropdownCounts[item.value as string][0]}</span>
{/snippet}
{#snippet empty()}
<div class="empty">(´・ω・`)</div>
{/snippet}
{#snippet selection({ selection }: { selection: SelectItem })}
{@const tag = selection.value as string}
{#if tag in checked}
{@const min = checked[tag]}
{@const ceiling = ceilingOf(tag)}
<button
type="button"
class="weight"
onpointerup={(e) => e.stopPropagation()}
onclick={(e) => cycle(tag, e.shiftKey)}
>
{selection.label}<span class="dots"
>{#each { length: MAX_TAG_WEIGHT }, i}<span
class:headroom={i >= min}
class:spacer={i >= ceiling}>·</span
>{/each}</span
>
</button>
{:else}
{selection.label}
{/if}
{/snippet}
</Select>
<style>
.item {
pointer-events: none;
.count {
float: right;
opacity: 0.4;
}
.empty {
text-align: center;
padding: 6px 0;
color: rgba(255, 255, 255, 0.5);
}
.weight {
background: none;
border: none;
padding: 0;
font: inherit;
color: inherit;
cursor: pointer;
}
.weight:hover {
color: var(--accent);
}
.dots {
margin-left: 3px;
color: var(--accent);
font-weight: bold;
letter-spacing: 1px;
}
/* to avoid pills' size shifting as tags are selected */
.headroom {
opacity: 0.3;
}
.spacer {
visibility: hidden;
}
:global(.svelte-select:hover) {
max-height: unset !important;
}
:global(.svelte-select-list) {
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
}
</style>
@@ -5,6 +5,7 @@ import { getStreamInfo } from '$lib/database.ts';
import { dev } from '$app/environment';
import { STREAM_JSON_LOCATION } from '$env/static/private';
import type { Actions } from './$types';
import type { TagWeights } from '$lib/types';
type SideloadJson = { title: unknown; description: unknown; tags: unknown };
@@ -22,7 +23,7 @@ if (dev) {
const jsonString = fs.readFileSync(filePath, 'utf8');
return jsonString;
} else {
return JSON.stringify({ title: '', description: '', tags: [] });
return JSON.stringify({ title: '', description: '', tags: {} });
}
};
@@ -34,10 +35,12 @@ if (dev) {
actions = {
default: async ({ params, request }) => {
const data = await request.formData();
const weights = JSON.parse(String(data.get('tags'))) as TagWeights;
const newJson: SideloadJson = {
title: data.get('title'),
description: data.get('description'),
tags: data.getAll('tags')
// weight 0 means the tag is off
tags: Object.fromEntries(Object.entries(weights).filter(([, weight]) => weight > 0))
};
writeSideloadJson(params.stream_id, newJson);
}
@@ -1,24 +1,20 @@
<script lang="ts">
import { page } from '$app/stores';
import { tagList } from '$lib/stores.svelte.ts';
import { page } from '$app/state';
import { tagList, MAX_TAG_WEIGHT } from '$lib/stores.svelte.ts';
import type { TagWeights } from '$lib/types';
let { original = $bindable() } = $props();
let tagMap = new Map<string, boolean>();
let weights: TagWeights = $derived({ ...original.tags });
// Create a mapping of tags and their checked status
let reloadTags = (original: { tags: string[] }) => {
tagList.forEach((tag) => {
tagMap.set(tag, original.tags.includes(tag));
});
};
$effect.pre(() => {
reloadTags(original);
});
// off -> light -> medium -> heavy -> off, backwards with shift
function cycle(tag: string, back: boolean) {
const step = back ? MAX_TAG_WEIGHT : 1;
weights = { ...weights, [tag]: ((weights[tag] ?? 0) + step) % (MAX_TAG_WEIGHT + 1) };
}
</script>
{#key $page.url.pathname}
{#key page.url.pathname}
<form method="POST">
<br />
<label>
@@ -36,17 +32,23 @@
></textarea>
</label>
<br />
<label>
<div class="tags">
<p>Tags:</p>
<div class="checkboxContainer">
<input type="hidden" name="tags" value={JSON.stringify(weights)} />
<div class="tag-pills">
{#each tagList as tag}
<label>
<input type="checkbox" name="tags" value={tag} checked={tagMap.get(tag)} />
{tag}
</label>
{@const weight = weights[tag] ?? 0}
<button
type="button"
class="tag-pill"
class:off={!weight}
onclick={(e) => cycle(tag, e.shiftKey)}
>
{tag}<span class="dots">{'·'.repeat(weight)}</span>
</button>
{/each}
</div>
</label>
</div>
<br />
<button type="submit">Submit</button>
@@ -58,19 +60,54 @@
margin-left: 10px;
}
label {
label,
.tags {
display: flex;
align-items: center;
}
label > p {
label > p,
.tags > p {
margin-right: 5px;
}
.checkboxContainer {
.tag-pills {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 1px;
max-width: 50%;
padding: 4px 8px;
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
}
.tag-pill {
background: none;
border: none;
padding: 2px 0;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
user-select: none;
}
.tag-pill.off {
opacity: 0.35;
}
.tag-pill:hover {
color: var(--accent);
}
.tag-pill.off:hover {
opacity: 0.65;
color: inherit;
}
.dots {
margin-left: 2px;
color: var(--accent);
font-weight: bold;
}
</style>
@@ -2,6 +2,7 @@
import { getStreamContext } from '$lib/streamContext.svelte.ts';
import { shorthandCode, formatTrackTime, formatDate } from '$lib/utils.ts';
import { jumpToTrack } from './Player.svelte';
import WeightedTags from '$lib/components/WeightedTags.svelte';
const ctx = getStreamContext();
@@ -18,7 +19,7 @@
<h3 class="stream-id">ID: {shorthandCode(ctx.current.id)}</h3>
<h1 class="stream-date">{formattedStreamDate}</h1>
</div>
<h5 class="stream-tags"><u>Tags</u>: {ctx.current.tags.join(', ')}</h5>
<h5 class="stream-tags"><u>Tags</u>: <WeightedTags tags={ctx.current.tags} /></h5>
</div>
<div class="description-bubble">