Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
Binary file modified screenshots/browse.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/character_details.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/discover.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/my_anime.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/one_piece_details.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/search.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/settings.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/staff_details.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified screenshots/studio_details.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
43 changes: 28 additions & 15 deletions src/AniSprinkles.Core/Converters/RainbowAccentConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,21 +65,7 @@ public object Convert(object? value, Type targetType, object? parameter, Culture
return ToTarget(Colors.Transparent, targetType);
}

// Apply key mapping if one exists (e.g., "Current" → "Watching", "Repeating" → "Rewatching")
if (_keyMappings.TryGetValue(key, out var mappedKey))
{
key = mappedKey;
}

// Use hardcoded color for known status sections; fall back to hash for everything else.
if (!_statusColors.TryGetValue(key, out var colorKey))
{
// Deterministic hash (stable across runs).
// Special-case int.MinValue: Math.Abs(int.MinValue) overflows and throws.
var hash = StableHash(key);
var idx = (hash == int.MinValue ? 0 : Math.Abs(hash)) % _rainbowKeys.Length;
colorKey = _rainbowKeys[idx];
}
var colorKey = ResourceKeyFor(key);

if (Application.Current?.Resources.TryGetValue(colorKey, out var res) == true && res is Color c)
{
Expand All @@ -98,6 +84,33 @@ public object Convert(object? value, Type targetType, object? parameter, Culture
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
=> throw new NotSupportedException();

/// <summary>
/// The palette resource key a given name maps to. Public because not every caller can go through
/// an <see cref="IValueConverter"/>: the bio-link spans (#137) are built on the Android side and
/// colour themselves per link, and they need this exact hash rather than a second one that would
/// drift — a character's name should paint the same colour wherever it appears.
/// </summary>
public static string ResourceKeyFor(string key)
{
// Apply key mapping if one exists (e.g., "Current" → "Watching", "Repeating" → "Rewatching")
if (_keyMappings.TryGetValue(key, out var mappedKey))
{
key = mappedKey;
}

// Use hardcoded color for known status sections; fall back to hash for everything else.
if (_statusColors.TryGetValue(key, out var colorKey))
{
return colorKey;
}

// Deterministic hash (stable across runs).
// Special-case int.MinValue: Math.Abs(int.MinValue) overflows and throws.
var hash = StableHash(key);
var idx = (hash == int.MinValue ? 0 : Math.Abs(hash)) % _rainbowKeys.Length;
return _rainbowKeys[idx];
}

// Borders carry an implicit style that sets Background (a Brush), and MAUI's Background always
// wins over BackgroundColor — so a Border accent must bind Background, not BackgroundColor. When
// the binding target is a Brush, hand back a SolidColorBrush; otherwise (TextColor etc.) a Color.
Expand Down
13 changes: 11 additions & 2 deletions src/AniSprinkles.Core/PageModels/CharacterDetailsPageModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ public partial class CharacterDetailsPageModel : DetailsPageModelBase<Character>
[NotifyPropertyChangedFor(nameof(BioProse))]
[NotifyPropertyChangedFor(nameof(BioStats))]
[NotifyPropertyChangedFor(nameof(AlternativeNames))]
// Truncation is measured on BioProse, so revealing a spoiler changes how much there is to
// lay out and the "Read more" affordance has to be re-evaluated with it.
[NotifyPropertyChangedFor(nameof(IsDescriptionTruncated))]
private bool _isShowingSpoilers;

[ObservableProperty]
Expand Down Expand Up @@ -146,7 +149,10 @@ public CharacterDetailsPageModel(

public bool HasBioProse => !string.IsNullOrWhiteSpace(_parsedDescription.Prose);

public bool IsDescriptionTruncated => DescriptionTruncationHeuristic.IsTruncated(_parsedDescription.Prose);
// Measured on the rendered bio, not the raw markdown: the raw string counts link URLs as
// visible text and contains no <br> by construction, so the heuristic would be reading a
// string that looks nothing like what the label lays out.
public bool IsDescriptionTruncated => DescriptionTruncationHeuristic.IsTruncated(BioProse);

public int DescriptionMaxLines => IsDescriptionExpanded
? int.MaxValue
Expand Down Expand Up @@ -345,7 +351,10 @@ private BioStatRow BuildBioStatRow(DescriptionStatRow row)
return new BioStatRow
{
LabelDisplay = labelHidden ? Bar(row.Label.Length, max: 12) : row.Label,
ValueDisplay = valueHidden ? Bar(row.Value.Length, max: 24) : row.Value,
// The value is Markdown like the prose is — AniList puts links in stat rows too, and
// Oda's "Favorite Mangaka" was rendering as a literal [name](url). The bar is the
// spoiler mask, which is plain text and must not be processed.
ValueDisplay = valueHidden ? Bar(row.Value.Length, max: 24) : AniListMarkdownProcessor.Process(row.Value),
IsLabelSpoilerHidden = labelHidden,
IsValueSpoilerHidden = valueHidden,
};
Expand Down
2 changes: 1 addition & 1 deletion src/AniSprinkles.Core/PageModels/DetailsPageModelBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ private async Task NavigateToMedia(RelatedMedia? media)
if (media is { IsAnime: false })
{
Logger.LogInformation("NAVTRACE {TracePrefix} → Media skipped non-anime {MediaId} (type={Type}).", TracePrefix, mediaId, media.Type);
await Feedback.ShowToastAsync("Manga & Novel details aren't supported yet.");
await Feedback.ShowToastAsync(BioLinkFollower.UnsupportedMediaMessage);
return;
}

Expand Down
88 changes: 9 additions & 79 deletions src/AniSprinkles.Core/PageModels/MediaDetailsPageModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Net;

namespace AniSprinkles.PageModels;

Expand Down Expand Up @@ -284,54 +283,21 @@ public string NextAiringDateDisplay

public bool HasDescription => !string.IsNullOrWhiteSpace(Media?.Description);

// Max visible lines when the description is collapsed. Used both by DescriptionMaxLines
// and by the IsDescriptionTruncated heuristic.
private const int DescriptionCollapsedMaxLines = 8;

// Approximate visible characters per line at 14sp on a typical phone (~360dp wide content area).
// Used to estimate whether stripped visible text will exceed DescriptionCollapsedMaxLines.
private const int DescriptionCharsPerLine = 45;

// Paragraph/line-break count that suggests the description will overflow the line limit even
// if its visible character count is low (e.g. several short paragraphs each wrapping 2–3 lines).
private const int DescriptionBreakCountThreshold = 3;

/// <summary>
/// True when the description text likely exceeds the collapsed line limit.
/// Uses a heuristic so the "Read more" toggle only appears when truncation
/// actually occurs — not for every short description that exists.
/// </summary>
public bool IsDescriptionTruncated
{
get
{
string? description = Media?.Description;
if (string.IsNullOrWhiteSpace(description))
{
return false;
}

// Decode HTML entities first so &amp; (5 chars) counts as & (1 char), etc.
// This keeps the visible-char estimate aligned with what TextType="Html" actually renders.
string decoded = WebUtility.HtmlDecode(description);

// Estimate visible character count by skipping HTML tags.
// Comparing visible chars to line capacity is more accurate than raw HTML length,
// which inflates due to tag markup and gives false negatives for tag-sparse descriptions.
int visibleChars = CountVisibleChars(decoded);
if (visibleChars > DescriptionCollapsedMaxLines * DescriptionCharsPerLine)
{
return true;
}

// A description with several short paragraphs can overflow the line limit even when its
// total visible character count is low, due to paragraph spacing eating visual lines.
int breakCount = CountSubstring(decoded, "<br") + CountSubstring(decoded, "</p>");
return breakCount >= DescriptionBreakCountThreshold;
}
}
/// <remarks>
/// This page used to carry its own copy of the estimate and its constants. The two drifted the
/// moment the shared one was recalibrated for Body2's real 15sp size (#138), and the label here
/// is identical to the character and staff ones — same style, same MaxLines, same
/// TailTruncation — so there was never a reason for them to differ.
/// </remarks>
public bool IsDescriptionTruncated => DescriptionTruncationHeuristic.IsTruncated(Media?.Description);

public int DescriptionMaxLines => IsDescriptionExpanded ? int.MaxValue : DescriptionCollapsedMaxLines;
public int DescriptionMaxLines
=> IsDescriptionExpanded ? int.MaxValue : DescriptionTruncationHeuristic.CollapsedMaxLines;

public string ScorePercentDisplay => Media?.AverageScore is > 0 ? $"{Media.AverageScore}%" : "--";

Expand Down Expand Up @@ -1033,42 +999,6 @@ private void ToggleDescription()
OnPropertyChanged(nameof(DescriptionMaxLines));
}

private static int CountVisibleChars(string html)
{
int count = 0;
bool inTag = false;
foreach (char c in html)
{
if (c == '<')
{
inTag = true;
}
else if (c == '>')
{
inTag = false;
}
else if (!inTag)
{
count++;
}
}

return count;
}

private static int CountSubstring(string source, string value)
{
int count = 0;
int index = 0;
while ((index = source.IndexOf(value, index, StringComparison.OrdinalIgnoreCase)) >= 0)
{
count++;
index += value.Length;
}

return count;
}

[RelayCommand]
private async Task QuickSetStatus(string value)
{
Expand Down
13 changes: 11 additions & 2 deletions src/AniSprinkles.Core/PageModels/StaffDetailsPageModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ public partial class StaffDetailsPageModel : DetailsPageModelBase<Staff>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(BioProse))]
[NotifyPropertyChangedFor(nameof(BioStats))]
// Truncation is measured on BioProse, so revealing a spoiler changes how much there is to
// lay out and the "Read more" affordance has to be re-evaluated with it.
[NotifyPropertyChangedFor(nameof(IsDescriptionTruncated))]
private bool _isShowingSpoilers;

[ObservableProperty]
Expand Down Expand Up @@ -130,7 +133,10 @@ public StaffDetailsPageModel(

public bool HasBioProse => !string.IsNullOrWhiteSpace(_parsedDescription.Prose);

public bool IsDescriptionTruncated => DescriptionTruncationHeuristic.IsTruncated(_parsedDescription.Prose);
// Measured on the rendered bio, not the raw markdown: the raw string counts link URLs as
// visible text and contains no <br> by construction, so the heuristic would be reading a
// string that looks nothing like what the label lays out.
public bool IsDescriptionTruncated => DescriptionTruncationHeuristic.IsTruncated(BioProse);

public int DescriptionMaxLines => IsDescriptionExpanded
? int.MaxValue
Expand Down Expand Up @@ -338,7 +344,10 @@ private BioStatRow BuildBioStatRow(DescriptionStatRow row)
return new BioStatRow
{
LabelDisplay = labelHidden ? Bar(row.Label.Length, max: 12) : row.Label,
ValueDisplay = valueHidden ? Bar(row.Value.Length, max: 24) : row.Value,
// The value is Markdown like the prose is — AniList puts links in stat rows too, and
// Oda's "Favorite Mangaka" was rendering as a literal [name](url). The bar is the
// spoiler mask, which is plain text and must not be processed.
ValueDisplay = valueHidden ? Bar(row.Value.Length, max: 24) : AniListMarkdownProcessor.Process(row.Value),
IsLabelSpoilerHidden = labelHidden,
IsValueSpoilerHidden = valueHidden,
};
Expand Down
122 changes: 122 additions & 0 deletions src/AniSprinkles.Core/Utilities/AniListLinkTarget.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
namespace AniSprinkles.Utilities;

/// <summary>
/// Maps an <c>anilist.co</c> URL found in a character or staff bio onto the in-app route that shows
/// the same entity (#137). Most links in these bios point back at entities the app already has pages
/// for — across the 50 most-favourited characters and staff, 162 of 235 links were AniList
/// character/anime/staff/studio URLs — so following one in-app is almost always better than handing
/// it to the browser.
/// <para>
/// A <see langword="null"/> result means "not one of ours"; the caller opens those externally. This
/// is deliberately the whole decision, kept pure and off the Android side so it can be tested.
/// </para>
/// </summary>
public sealed record AniListLinkTarget
{
private const string AniListHost = "anilist.co";
private const string WwwPrefix = "www.";

/// <summary>Shell route name, matching the registrations in <c>AppShell</c>.</summary>
public required string Route { get; init; }

/// <summary>Navigation parameter key the destination page model reads the id from.</summary>
public required string ParameterName { get; init; }

public required int Id { get; init; }

public static AniListLinkTarget? Resolve(string? url)
{
if (!TryParseEntity(url, out var kind, out var id))
{
return null;
}

var (route, parameterName) = RouteFor(kind);
if (route is null || parameterName is null)
{
return null;
}

return new AniListLinkTarget
{
Route = route,
ParameterName = parameterName,
Id = id,
};
}

/// <summary>
/// True for an AniList entity this app recognises but has no page for — currently only manga.
/// Callers show the same "not supported yet" message the rest of the app uses rather than
/// handing the link to the browser, so manga behaves the same wherever it is tapped. Remove
/// this once #12 lands and manga can route like anything else.
/// </summary>
public static bool IsUnsupportedEntity(string? url)
=> TryParseEntity(url, out var kind, out _)
&& string.Equals(kind, "manga", StringComparison.Ordinal);

/// <summary>
/// Parses an <c>anilist.co/{kind}/{id}</c> URL. <paramref name="kind"/> comes back lower-cased;
/// whether the app can show it is the callers' business.
/// </summary>
private static bool TryParseEntity(string? url, out string kind, out int id)
{
kind = string.Empty;
id = 0;

if (string.IsNullOrWhiteSpace(url)
|| !Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
return false;
}

if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
{
return false;
}

// Uri.Host is already lower-cased. Compare the whole host rather than using EndsWith, so a
// look-alike like anilist.co.example.com doesn't get treated as ours.
var host = uri.Host;
if (host.StartsWith(WwwPrefix, StringComparison.Ordinal))
{
host = host[WwwPrefix.Length..];
}

if (!string.Equals(host, AniListHost, StringComparison.Ordinal))
{
return false;
}

// AniList writes the entity name after the id (/character/725/Buggy-the-Clown), so take the
// first two segments and ignore whatever follows.
var segments = uri.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (segments.Length < 2)
{
return false;
}

if (!int.TryParse(segments[1], out id) || id <= 0)
{
id = 0;
return false;
}

kind = segments[0].ToLowerInvariant();
return true;
}

private static (string? Route, string? ParameterName) RouteFor(string kind)
=> kind switch
{
"character" => ("character-details", "characterId"),
"staff" => ("staff-details", "staffId"),
"anime" => ("media-details", "mediaId"),
"studio" => ("studio-details", "studioId"),
// Deliberately not manga. The details page queries Media(id:, type: ANIME), so a manga
// id 404s there — which is why DetailsPageModelBase.NavigateToMedia toasts "Manga &
// Novel details aren't supported yet" instead of navigating. Bio links say the same,
// via IsUnsupportedEntity, so manga answers identically wherever it is tapped (#12).
_ => (null, null),
};
}
Loading