Skip to content

Commit

Permalink
Use context for cleanup pattern and misc changes
Browse files Browse the repository at this point in the history
  • Loading branch information
elamperti committed Sep 15, 2024
1 parent f02a5ab commit 10a18f4
Show file tree
Hide file tree
Showing 15 changed files with 345 additions and 268 deletions.
2 changes: 1 addition & 1 deletion public/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"customTimestamp": "Custom timestamp",
"albumTimestampLogicDescription": "Scrobbling tracks \"now\" will scrobble the last track at the current time, backdating the previous ones accordingly (as if you had just finished listening). The \"custom timestamp\" will define the timestamp of the first track and add time to the following tracks from there (i.e. you specify the time you started listening to this album).",
"albumArtist": "Album artist",
"albumCleanupPattern": "Removable text pattern from every track name",
"filter": "Filter",
"albumCleanupPatternDescription": "Some albums tracks are displayed with some repeated text (i.e. Demo, Live, Remastered, ...). These are patterns that could be considered annoying to scrobble, for some users. Set the full pattern (including paranthesis, dashes, ...) that you would like to be removed, from the track names.",
"history": "History",
"yourProfile": "Your profile",
Expand Down
1 change: 0 additions & 1 deletion public/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
"customTimestamp": "Timestamp personalizzato",
"albumTimestampLogicDescription": "Scrobblando le canzoni \"adesso\" scrobblerà l'ultima canzone in questo momento, anticipando relativamente le precedenti (come se avessi appena finito di ascoltarle). Il \"timestamp personalizzato\" definirà il timestamp di ascolto della prima traccia ed agginguerà il relativo tempo alle canzoni successive (come se avessi iniziato ad ascoltare l'album nel timestamp selezionato)",
"albumArtist": "Artista di un Album",
"albumCleanupPattern": "Pattern removibile da ogni nome di canzone",
"albumCleanupPatternDescription": "Alcune canzoni di album sono visualizzate con un certo testo ripetuto (ad esempio Demo, Live, Remastered, ...). Questi sono pattern che potrebbero risultare fastidiosi da scrobblare, per alcuni utenti. Imposta il pattern completo (incluse parentesi, trattini, ...) che desideri venga rimosso dai nomi delle canzoni.",
"history": "Storico",
"yourProfile": "Tuo profilo",
Expand Down
4 changes: 2 additions & 2 deletions src/components/ScrobbleItem.css
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@
padding-right: 1.15rem;
}

.scrobbled-item-cleanup {
.scrobbled-item del {
color: var(--bs-secondary-color) !important;
text-decoration: line-through;
background-color: rgba(255, 32, 0, 0.2);
}
51 changes: 20 additions & 31 deletions src/components/ScrobbleItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import isToday from 'date-fns/isToday';
import getYear from 'date-fns/getYear';

import { Button, Input, Dropdown, DropdownToggle, DropdownMenu, DropdownItem, FormGroup, Label } from 'reactstrap';
import { useState } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { Fragment, useState } from 'react';
import { LazyLoadImage } from 'react-lazy-load-image-component';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
Expand All @@ -27,16 +26,16 @@ import {
} from '@fortawesome/free-solid-svg-icons';
import { faClock, faCopy } from '@fortawesome/free-regular-svg-icons';
import { getAmznLink } from 'Constants';
import { breakStringUsingPattern, cleanTitleWithPattern } from 'domains/scrobbleAlbum/CleanupContext';

import type { Scrobble } from 'utils/types/scrobble';
import { replaceLastOccurrence } from 'utils/common';

import './ScrobbleItem.css';
import { useSettings } from 'hooks/useSettings';

interface ScrobbleItemProps {
scrobble: Scrobble;
cleanupPattern?: string;
cleanupPattern?: RegExp;
compact?: boolean;
hideArtist?: boolean;
muteArtist?: boolean;
Expand All @@ -51,7 +50,7 @@ interface ScrobbleItemProps {

export default function ScrobbleItem({
scrobble,
cleanupPattern = '',
cleanupPattern,
compact = false,
hideArtist = false,
muteArtist = false,
Expand Down Expand Up @@ -90,8 +89,9 @@ export default function ScrobbleItem({
enqueueScrobble(dispatch)([
{
...scrobble,
title: cleanupPattern ? scrobble.title.replaceAll(cleanupPattern, '').trim() : scrobble.title,
title: cleanTitleWithPattern(scrobble.title, cleanupPattern),
timestamp: useOriginalTimestamp ? scrobble.timestamp : new Date(),
cleanupPattern: cleanupPattern || undefined,
},
]);
setHasScrobbledAgain(true);
Expand All @@ -109,20 +109,10 @@ export default function ScrobbleItem({
});
};

const getCompleteItem = (item: string, highlight?: string) => {
const parsedItem = item;

if (!highlight || !item.endsWith(highlight)) {
return parsedItem;
}

const parsedComplete = highlight;

const textComplete = renderToStaticMarkup(<span className="scrobbled-item-cleanup">{parsedComplete}</span>);

const itemComplete = replaceLastOccurrence(parsedItem, parsedComplete, textComplete);

return itemComplete;
const strikethroughMatch = (text: string, pattern?: RegExp) => {
return breakStringUsingPattern(text, pattern).map(({ value, isMatch }, index) => (
<Fragment key={index}>{!isMatch ? value : <del>{value}</del>}</Fragment>
));
};

let albumArt;
Expand Down Expand Up @@ -220,18 +210,23 @@ export default function ScrobbleItem({
</small>
);

const formattedTitle = strikethroughMatch(properCase(scrobble.title, true), cleanupPattern);
if (!hideArtist) {
if (muteArtist) {
songFullTitle = (
<>
{properCase(scrobble.title, true)} <span className="text-muted">{properCase(scrobble.artist)}</span>
{formattedTitle} <span className="text-muted">{properCase(scrobble.artist)}</span>
</>
);
} else {
songFullTitle = `${properCase(scrobble.artist)} - ${properCase(scrobble.title, true)}`;
songFullTitle = (
<>
{properCase(scrobble.artist)} - {formattedTitle}
</>
);
}
} else {
songFullTitle = properCase(scrobble.title, true);
songFullTitle = formattedTitle;
}

const scrobbleItemInputId = `ScrobbleItem-checkbox-${scrobble.uuid}`;
Expand All @@ -241,21 +236,15 @@ export default function ScrobbleItem({
songInfo = (
<Label className="d-flex align-items-center mb-0" htmlFor={scrobbleItemInputId}>
{!!settings?.showTrackNumbers && scrobble.trackNumber && <span className="me-1">{scrobble.trackNumber}.</span>}
<span
className="song flex-grow-1 pe-2 truncate"
dangerouslySetInnerHTML={{ __html: getCompleteItem(songFullTitle, cleanupPattern) }}
></span>
<span className="song flex-grow-1 pe-2 truncate">{songFullTitle}</span>
{timeOrDuration}
</Label>
);
} else {
// FULL view
songInfo = (
<>
<span
className="song"
dangerouslySetInnerHTML={{ __html: getCompleteItem(songFullTitle, cleanupPattern) }}
></span>
<span className="song flex-grow-1 pe-2 truncate">{songFullTitle}</span>
<Label className="d-flex mb-0" htmlFor={scrobbleItemInputId}>
<small className="text-muted flex-grow-1 truncate album">
{scrobble.album && (
Expand Down
8 changes: 4 additions & 4 deletions src/components/ScrobbleList.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { useContext } from 'react';
import { useContext, useEffect } from 'react';

Check warning on line 1 in src/components/ScrobbleList.tsx

View workflow job for this annotation

GitHub Actions / Setup and quick checks

'useEffect' is defined but never used

import ScrobbleItem from 'components/ScrobbleItem';
import Spinner from 'components/Spinner';
import { ScrobbleCloneContext } from 'domains/scrobbleSong/ScrobbleSong';

import type { ReactNode } from 'react';
import { CleanupPatternContext } from 'domains/scrobbleAlbum/CleanupContext';

interface ScrobbleListProps {
analyticsEventForScrobbles?: string;
Expand All @@ -16,7 +17,6 @@ interface ScrobbleListProps {
onSelect?: (scrobble: any) => void;
selected?: Set<string>;
scrobbles?: any[];
scrobblesCleanupPattern?: string;
}

export default function ScrobbleList({
Expand All @@ -29,9 +29,9 @@ export default function ScrobbleList({
onSelect,
selected,
scrobbles = [],
scrobblesCleanupPattern,
}: ScrobbleListProps) {
const { cloneFn, setCloneFn } = useContext(ScrobbleCloneContext);
const cleanupCtx = useContext(CleanupPatternContext); // this may be undefined
let albumHasVariousArtists = !isAlbum;

if (loading) {
Expand All @@ -54,8 +54,8 @@ export default function ScrobbleList({
return (
<ScrobbleItem
scrobble={scrobble}
cleanupPattern={scrobblesCleanupPattern}
analyticsEvent={analyticsEventForScrobbles}
cleanupPattern={cleanupCtx?.cleanupPattern}
cloneScrobbleTo={setCloneFn ? cloneFn : undefined}
compact={compact}
noMenu={noMenu}
Expand Down
125 changes: 125 additions & 0 deletions src/domains/scrobbleAlbum/CleanupContext.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { cleanTitleWithPattern, breakStringUsingPattern, strToCleanupPattern } from './CleanupContext';

describe('cleanTitleWithPattern', () => {
it('removes pattern from title', () => {
const title = 'Song Title live';
const pattern = strToCleanupPattern('LIVE');
expect(cleanTitleWithPattern(title, pattern)).toBe('Song Title');
});

it('returns the original title if pattern is not found', () => {
const title = 'Song Title (live)';
const pattern = strToCleanupPattern('remix');
expect(cleanTitleWithPattern(title, pattern)).toBe('Song Title (live)');
});

it('returns the original title if pattern is null', () => {
const title = 'Song Title (2024)';
expect(cleanTitleWithPattern(title, null)).toBe('Song Title (2024)');
});

it('skips patterns of less than 3 characters', () => {
const title = 'Song Title (20)';
const pattern = strToCleanupPattern('20');
expect(cleanTitleWithPattern(title, pattern)).toBe('Song Title (20)');
});

it('removes trailing dashes', () => {
const title = 'Song Title - Live';
const pattern = strToCleanupPattern('live');
expect(cleanTitleWithPattern(title, pattern)).toBe('Song Title');
});

it('removes empty parenthesis', () => {
const title = 'Song Title (remix)';
const pattern = strToCleanupPattern('remix');
expect(cleanTitleWithPattern(title, pattern)).toBe('Song Title');
});

it('removes empty brackets', () => {
const title = 'Song Title [fOoB4r]';
const pattern = strToCleanupPattern('fOoB4r');
expect(cleanTitleWithPattern(title, pattern)).toBe('Song Title');
});

it("doesn't match partial end of words", () => {
const title = 'Song Title remix';
const pattern = strToCleanupPattern('mix');
expect(cleanTitleWithPattern(title, pattern)).toBe('Song Title remix');
});

it("doesn't match partial beginning of words", () => {
const title = 'Love (Sweet Love) (Dopamine Remix)';
const pattern = strToCleanupPattern('dopa');
expect(cleanTitleWithPattern(title, pattern)).toBe(title);
});

it('auto-closes parenthesis', () => {
const title = 'Song Title (remix) [1984]';
const pattern = strToCleanupPattern('(remix');
expect(cleanTitleWithPattern(title, pattern)).toBe('Song Title [1984]');
});

it('auto-closes brackets', () => {
const title = 'Song Title (remix) [1984]';
const pattern = strToCleanupPattern('[1984');
expect(cleanTitleWithPattern(title, pattern)).toBe('Song Title (remix)');
});

it('matches words starting with symbols', () => {
const title = 'Song Title $remix';
const pattern = strToCleanupPattern('$remix');
expect(cleanTitleWithPattern(title, pattern)).toBe('Song Title');
});

it('supports several words in the pattern', () => {
const title = "I can't quit you baby - Live in paris, 1969";
const pattern = strToCleanupPattern('live in paris, 1969');
expect(cleanTitleWithPattern(title, pattern)).toBe("I can't quit you baby");
});
});

describe('breakStringUsingPattern', () => {
it('breaks down the string into parts matching the pattern', () => {
const str = 'Song Title (remix) (live) (2024)';
const pattern = /\(remix\)|\(live\)|\(2024\)/gi;
const result = breakStringUsingPattern(str, pattern);
expect(result).toEqual([
{ value: 'Song Title', isMatch: false },
{ value: ' (remix)', isMatch: true },
{ value: ' (live)', isMatch: true },
{ value: ' (2024)', isMatch: true },
]);
});

it('marks extra spaces', () => {
const str = 'Song Title (remix) - More';
const pattern = /\(remix\)/gi;
const result = breakStringUsingPattern(str, pattern);
expect(result).toEqual([
{ value: 'Song Title', isMatch: false },
{ value: ' (remix)', isMatch: true },
{ value: ' - More', isMatch: false },
]);
});

it('returns the whole string as non-matching if pattern is not found', () => {
const str = 'Song Title (remix)';
const pattern = /\(live\)/gi;
const result = breakStringUsingPattern(str, pattern);
expect(result).toEqual([{ value: 'Song Title (remix)', isMatch: false }]);
});

it('returns the whole string as non-matching if pattern is null', () => {
const str = 'Song Title (2024)';
const result = breakStringUsingPattern(str, null);
expect(result).toEqual([{ value: 'Song Title (2024)', isMatch: false }]);
});

it('returns an empty array if the string is empty', () => {
const str = '';
const pattern = /\(remix\)/gi;
const result = breakStringUsingPattern(str, pattern);
expect(result).toEqual([]);
});
});
Loading

0 comments on commit 10a18f4

Please sign in to comment.