feat: in-app help, notifications panel and global search (#32)
F1 and "?" now open the wiki page of the screen inside the application (/aiuto, mockup 011) from a copy of the wiki shipped next to the program, so help works offline and always matches the installed version. Markdown is converted in-house and fully encoded; images of the repository are served from the copy. KHAEMHAT_HELP_URL sets the online wiki behind "Apri nel wiki"; "Segnala un problema" opens a new issue of that repo. A test checks that every page and menu entry has an existing wiki page. The bell opens a notifications panel (mockup 010) with all/unread filters and mark read. Broadcast notifications are now read per user through sys_notification_reads / notification_reads instead of one shared read_at. The global search asks ISearchProvider implementations through GlobalSearchService after a short pause; the first provider finds help pages and sections, # and @ say which modules will fill them. Escape also closes a side panel when the focus fell out of it. Decisions in ADR 0023. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
acb7e598d1
commit
f415dc37a8
39 files changed
+1976
-107
No files matched your search
@@ -65,6 +65,7 @@ public sealed class EnvironmentConfigurationReader
|
||||
SeedDemo = Get("KHAEMHAT_SEED_DEMO"),
|
||||
UpdateFeed = Get("KHAEMHAT_UPDATE_FEED"),
|
||||
UpdateToken = Get("KHAEMHAT_UPDATE_TOKEN"),
|
||||
HelpUrl = Get("KHAEMHAT_HELP_URL"),
|
||||
TimeZone = Get("TZ"),
|
||||
ReadErrors = errors,
|
||||
};
|
||||
|
||||
@@ -150,6 +150,12 @@ public sealed class KhaemhatOptions
|
||||
/// <summary><c>KHAEMHAT_UPDATE_TOKEN</c>: a read-only token for the feed.</summary>
|
||||
public string? UpdateToken { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// <c>KHAEMHAT_HELP_URL</c>: the online wiki opened by "Apri nel wiki" (default the project wiki). The help itself
|
||||
/// is the copy of the wiki shipped in the image, so it works offline.
|
||||
/// </summary>
|
||||
public string? HelpUrl { get; init; }
|
||||
|
||||
/// <summary><c>TZ</c>: the time zone of the container.</summary>
|
||||
public string? TimeZone { get; init; }
|
||||
|
||||
@@ -265,6 +271,11 @@ public sealed class KhaemhatOptions
|
||||
errors.Add("KHAEMHAT_PUBLIC_URL must be an absolute http or https address, for example https://gestionale.example.com.");
|
||||
}
|
||||
|
||||
if (HelpUrl is not null && !IsHttpUrl(HelpUrl))
|
||||
{
|
||||
errors.Add("KHAEMHAT_HELP_URL must be an absolute http or https address, for example https://gitea.example.com/owner/khaemhat/wiki/.");
|
||||
}
|
||||
|
||||
if (SmtpPort is not null && !(int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port) && port is > 0 and < 65536))
|
||||
{
|
||||
errors.Add("KHAEMHAT_SMTP_PORT must be a port number between 1 and 65535.");
|
||||
|
||||
@@ -90,12 +90,7 @@ public sealed class NotificationTodoSource(NotificationDispatcher notifications)
|
||||
public async Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
IReadOnlyList<NotificationRecord> unread = context.Actor switch
|
||||
{
|
||||
{ SystemUserId: { } id } => await notifications.UnreadForInstanceAsync(id, cancellationToken).ConfigureAwait(false),
|
||||
{ CompanyUserId: { } id, CompanyCode: { } company } => await notifications.UnreadForUserAsync(company, id, cancellationToken).ConfigureAwait(false),
|
||||
_ => [],
|
||||
};
|
||||
var unread = await notifications.InboxAsync(context.Actor, unreadOnly: true, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return [.. unread
|
||||
.Where(n => n.Severity >= NotificationSeverity.Warning)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
@@ -13,14 +14,27 @@ namespace Khaemhat.Application.Notifications;
|
||||
/// <param name="Link">A link inside the application.</param>
|
||||
public sealed record NotificationMessage(string Category, NotificationSeverity Severity, string Title, string? Body = null, string? Link = null);
|
||||
|
||||
/// <summary>A notification as its recipient sees it.</summary>
|
||||
/// <param name="Id">The id.</param>
|
||||
/// <param name="Category">The area.</param>
|
||||
/// <param name="Severity">The weight.</param>
|
||||
/// <param name="Title">The title.</param>
|
||||
/// <param name="Body">The text.</param>
|
||||
/// <param name="Link">A link inside the application.</param>
|
||||
/// <param name="CreatedAt">When it was sent (UTC).</param>
|
||||
/// <param name="Read">Whether this user read it.</param>
|
||||
/// <param name="Personal">Addressed to this user only, not to everyone.</param>
|
||||
public sealed record InboxItem(long Id, string Category, NotificationSeverity Severity, string Title, string? Body, string? Link, DateTime CreatedAt, bool Read, bool Personal);
|
||||
|
||||
/// <summary>
|
||||
/// Delivers in-app notifications (SPEC §9; mockup 010): to instance accounts in <c>sys_notifications</c>, to company
|
||||
/// users in the company's <c>notifications</c>. A notification without recipient goes to everyone in the scope.
|
||||
/// Delivery never breaks the caller: a failure is logged.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the databases.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, ILogger<NotificationDispatcher> logger)
|
||||
public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, TimeProvider clock, ILogger<NotificationDispatcher> logger)
|
||||
{
|
||||
/// <summary>Notifies instance accounts.</summary>
|
||||
/// <param name="message">The notification.</param>
|
||||
@@ -61,29 +75,114 @@ public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, ILogger<N
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The unread notifications of an instance account (its own and those for everyone).</summary>
|
||||
/// <param name="userId">The account.</param>
|
||||
/// <summary>The most notifications a user sees: the newest ones.</summary>
|
||||
public const int InboxSize = 100;
|
||||
|
||||
/// <summary>The notifications of a user, newest first (mockup 010).</summary>
|
||||
/// <param name="actor">The user: instance accounts read the system ones, company users those of their company.</param>
|
||||
/// <param name="unreadOnly">Only those not read yet.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The notifications, newest first.</returns>
|
||||
public async Task<IReadOnlyList<SystemNotification>> UnreadForInstanceAsync(long userId, CancellationToken cancellationToken = default)
|
||||
/// <returns>The notifications, at most <see cref="InboxSize"/>.</returns>
|
||||
public Task<IReadOnlyList<InboxItem>> InboxAsync(Actor actor, bool unreadOnly = false, CancellationToken cancellationToken = default) =>
|
||||
ScopeOf(actor) switch
|
||||
{
|
||||
({ } scope, { } user, true) => InboxAsync<SystemNotification, SystemNotificationRead>(scope, user, unreadOnly, cancellationToken),
|
||||
({ } scope, { } user, false) => InboxAsync<Notification, NotificationRead>(scope, user, unreadOnly, cancellationToken),
|
||||
_ => Task.FromResult<IReadOnlyList<InboxItem>>([]),
|
||||
};
|
||||
|
||||
/// <summary>Marks a notification as read by the user. A notification for everyone stays unread for the others.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="notificationId">The notification.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task MarkReadAsync(Actor actor, long notificationId, CancellationToken cancellationToken = default) =>
|
||||
MarkAsync(actor, [notificationId], cancellationToken);
|
||||
|
||||
/// <summary>Marks every notification of the user as read.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task MarkAllReadAsync(Actor actor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
return (await unitOfWork.Repository<SystemNotification, long>().ListAsync(
|
||||
Query.For<SystemNotification>().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
var unread = await InboxAsync(actor, unreadOnly: true, cancellationToken).ConfigureAwait(false);
|
||||
await MarkAsync(actor, [.. unread.Select(n => n.Id)], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The unread notifications of a company user.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="userId">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The notifications, newest first.</returns>
|
||||
public async Task<IReadOnlyList<Notification>> UnreadForUserAsync(string companyCode, long userId, CancellationToken cancellationToken = default)
|
||||
private Task MarkAsync(Actor actor, IReadOnlyList<long> ids, CancellationToken cancellationToken) =>
|
||||
ids.Count == 0
|
||||
? Task.CompletedTask
|
||||
: ScopeOf(actor) switch
|
||||
{
|
||||
({ } scope, { } user, true) => MarkAsync<SystemNotification, SystemNotificationRead>(scope, user, ids, cancellationToken),
|
||||
({ } scope, { } user, false) => MarkAsync<Notification, NotificationRead>(scope, user, ids, cancellationToken),
|
||||
_ => Task.CompletedTask,
|
||||
};
|
||||
|
||||
private static (DatabaseScope? Scope, long? User, bool System) ScopeOf(Actor actor)
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
return (await unitOfWork.Repository<Notification, long>().ListAsync(
|
||||
Query.For<Notification>().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100),
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
return actor switch
|
||||
{
|
||||
{ SystemUserId: { } id } => (DatabaseScope.System, id, true),
|
||||
{ CompanyUserId: { } id, CompanyCode: { } company } => (DatabaseScope.Company(company), id, false),
|
||||
_ => (null, null, false),
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<InboxItem>> InboxAsync<TNotification, TRead>(DatabaseScope scope, long userId, bool unreadOnly, CancellationToken cancellationToken)
|
||||
where TNotification : NotificationRecord, new()
|
||||
where TRead : NotificationReadRecord, new()
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
|
||||
var notifications = (await unitOfWork.Repository<TNotification, long>().ListAsync(
|
||||
Query.For<TNotification>().Where(n => n.RecipientUserId == null || n.RecipientUserId == userId).OrderByDescending(n => n.Id).Take(InboxSize),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
var everyone = notifications.Where(n => n.RecipientUserId == null).Select(n => n.Id).ToList();
|
||||
var read = everyone.Count == 0
|
||||
? []
|
||||
: (await unitOfWork.Repository<TRead, long>().ListAsync(
|
||||
Query.For<TRead>().Where(r => r.UserId == userId && everyone.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(r => r.NotificationId).ToHashSet();
|
||||
return [.. notifications
|
||||
.Select(n => new InboxItem(n.Id, n.Category, n.Severity, n.Title, n.Body, n.Link, n.CreatedAt,
|
||||
n.RecipientUserId is null ? read.Contains(n.Id) : n.ReadAt is not null, n.RecipientUserId is not null))
|
||||
.Where(n => !unreadOnly || !n.Read)];
|
||||
}
|
||||
|
||||
private async Task MarkAsync<TNotification, TRead>(DatabaseScope scope, long userId, IReadOnlyList<long> ids, CancellationToken cancellationToken)
|
||||
where TNotification : NotificationRecord, new()
|
||||
where TRead : NotificationReadRecord, new()
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
|
||||
var list = ids.ToList();
|
||||
var repository = unitOfWork.Repository<TNotification, long>();
|
||||
var notifications = (await repository.ListAsync(
|
||||
Query.For<TNotification>().Where(n => list.Contains(n.Id) && (n.RecipientUserId == null || n.RecipientUserId == userId)), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var reads = unitOfWork.Repository<TRead, long>();
|
||||
var already = (await reads.ListAsync(Query.For<TRead>().Where(r => r.UserId == userId && list.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(r => r.NotificationId).ToHashSet();
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
foreach (var notification in notifications)
|
||||
{
|
||||
if (notification.RecipientUserId is null)
|
||||
{
|
||||
if (already.Add(notification.Id))
|
||||
{
|
||||
await reads.InsertAsync(new TRead { NotificationId = notification.Id, UserId = userId }, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else if (notification.ReadAt is null)
|
||||
{
|
||||
notification.ReadAt = now;
|
||||
await repository.UpdateAsync(notification, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static T Fill<T>(T notification, NotificationMessage message, long? recipient)
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.Search;
|
||||
|
||||
/// <summary>What the search looks for, from the first character of the query (SPEC §10.2, mockup 009).</summary>
|
||||
public enum SearchScope
|
||||
{
|
||||
/// <summary>Everything: pages, records, help.</summary>
|
||||
All,
|
||||
|
||||
/// <summary><c>></c>: only the commands.</summary>
|
||||
Commands,
|
||||
|
||||
/// <summary><c>#</c>: only the documents.</summary>
|
||||
Documents,
|
||||
|
||||
/// <summary><c>@</c>: only the people.</summary>
|
||||
People,
|
||||
}
|
||||
|
||||
/// <summary>A search, split into scope and words.</summary>
|
||||
/// <param name="Scope">What it looks for.</param>
|
||||
/// <param name="Text">The words, without the prefix.</param>
|
||||
public sealed record SearchQuery(SearchScope Scope, string Text)
|
||||
{
|
||||
/// <summary>The fewest characters before records are searched.</summary>
|
||||
public const int MinimumLength = 2;
|
||||
|
||||
/// <summary>The words of the query.</summary>
|
||||
public IReadOnlyList<string> Words { get; } = Text.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
/// <summary>Reads what the user typed.</summary>
|
||||
/// <param name="input">The text of the search box.</param>
|
||||
/// <returns>The query.</returns>
|
||||
public static SearchQuery Parse(string? input)
|
||||
{
|
||||
var text = (input ?? string.Empty).Trim();
|
||||
var scope = text.Length == 0 ? SearchScope.All : text[0] switch
|
||||
{
|
||||
'>' => SearchScope.Commands,
|
||||
'#' => SearchScope.Documents,
|
||||
'@' => SearchScope.People,
|
||||
_ => SearchScope.All,
|
||||
};
|
||||
return new SearchQuery(scope, scope == SearchScope.All ? text : text[1..].Trim());
|
||||
}
|
||||
|
||||
/// <summary>Whether a text contains every word, ignoring case.</summary>
|
||||
/// <param name="value">The text.</param>
|
||||
/// <returns><see langword="true"/> if it does; always for an empty query.</returns>
|
||||
public bool Matches(string? value) =>
|
||||
Words.Count == 0 || (value is not null && Words.All(w => value.Contains(w, StringComparison.CurrentCultureIgnoreCase)));
|
||||
}
|
||||
|
||||
/// <summary>A search result.</summary>
|
||||
/// <param name="Group">The text key of the group shown above it, such as <c>Shell.Search.Help</c>.</param>
|
||||
/// <param name="Icon">The icon.</param>
|
||||
/// <param name="Title">The title.</param>
|
||||
/// <param name="Detail">A second line, such as the page a heading belongs to.</param>
|
||||
/// <param name="Href">Where it opens, relative to the application.</param>
|
||||
public sealed record SearchHit(string Group, string Icon, string Title, string? Detail, string Href);
|
||||
|
||||
/// <summary>A source of search results: each module adds its own (parties, items, documents, accounts...).</summary>
|
||||
public interface ISearchProvider
|
||||
{
|
||||
/// <summary>The scopes it answers: <see cref="SearchScope.All"/> and, for example, <see cref="SearchScope.Documents"/>.</summary>
|
||||
IReadOnlyCollection<SearchScope> Scopes { get; }
|
||||
|
||||
/// <summary>Searches.</summary>
|
||||
/// <param name="actor">Who searches: results respect permissions and company.</param>
|
||||
/// <param name="query">The query, at least <see cref="SearchQuery.MinimumLength"/> characters.</param>
|
||||
/// <param name="cancellationToken">Cancellation: the user typed something else.</param>
|
||||
/// <returns>At most <see cref="GlobalSearchService.PerProvider"/> results, best first.</returns>
|
||||
Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The records part of the global search (SPEC §10.2): asks every provider of the scope, in parallel, and puts the
|
||||
/// results together. A provider that fails or is slow is left out, the others are shown.
|
||||
/// </summary>
|
||||
public sealed class GlobalSearchService(IEnumerable<ISearchProvider> providers, ILogger<GlobalSearchService> logger)
|
||||
{
|
||||
/// <summary>The most results of one provider.</summary>
|
||||
public const int PerProvider = 8;
|
||||
|
||||
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(3);
|
||||
|
||||
private readonly ISearchProvider[] _providers = [.. providers];
|
||||
|
||||
/// <summary>Whether something answers a scope: without, the search says what it will find in a later version.</summary>
|
||||
/// <param name="scope">The scope.</param>
|
||||
/// <returns><see langword="true"/> if a provider does.</returns>
|
||||
public bool Covers(SearchScope scope) => _providers.Any(p => p.Scopes.Contains(scope));
|
||||
|
||||
/// <summary>Searches the records.</summary>
|
||||
/// <param name="actor">Who searches.</param>
|
||||
/// <param name="query">The query.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The results, grouped by provider in registration order.</returns>
|
||||
public async Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
if (query.Scope == SearchScope.Commands || query.Text.Length < SearchQuery.MinimumLength)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var results = await Task.WhenAll(_providers.Where(p => p.Scopes.Contains(query.Scope)).Select(p => AskAsync(p, actor, query, cancellationToken))).ConfigureAwait(false);
|
||||
return [.. results.SelectMany(r => r)];
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<SearchHit>> AskAsync(ISearchProvider provider, Actor actor, SearchQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(Timeout);
|
||||
try
|
||||
{
|
||||
return [.. (await provider.SearchAsync(actor, query, timeout.Token).ConfigureAwait(false)).Take(PerProvider)];
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
logger.LogWarning("Search provider {Provider} took longer than {Timeout} and was left out", provider.GetType().Name, Timeout);
|
||||
return [];
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(ex, "Search provider {Provider} failed", provider.GetType().Name);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,3 +347,23 @@ public sealed class SystemNotification : NotificationRecord;
|
||||
|
||||
/// <summary>A notification for company users (<c>notifications</c>).</summary>
|
||||
public sealed class Notification : NotificationRecord;
|
||||
|
||||
/// <summary>
|
||||
/// That a user read a notification addressed to everyone: each user reads it for themselves (<c>notification_reads</c>,
|
||||
/// <c>sys_notification_reads</c>). A notification for one user keeps its own <see cref="NotificationRecord.ReadAt"/>.
|
||||
/// The audit column <c>created_at</c> is when it was read.
|
||||
/// </summary>
|
||||
public abstract class NotificationReadRecord : Entity<long>
|
||||
{
|
||||
/// <summary>The notification.</summary>
|
||||
public long NotificationId { get; set; }
|
||||
|
||||
/// <summary>The user who read it.</summary>
|
||||
public long UserId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An instance account read a notification for everyone (<c>sys_notification_reads</c>).</summary>
|
||||
public sealed class SystemNotificationRead : NotificationReadRecord;
|
||||
|
||||
/// <summary>A company user read a notification for everyone (<c>notification_reads</c>).</summary>
|
||||
public sealed class NotificationRead : NotificationReadRecord;
|
||||
@@ -97,6 +97,13 @@ public sealed class NotificationMap : EntityMap<Notification>
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="NotificationRead"/> to <c>notification_reads</c>.</summary>
|
||||
public sealed class NotificationReadMap : EntityMap<NotificationRead>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public NotificationReadMap() => ToTable("notification_reads");
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="UserSetting"/> to <c>user_settings</c>.</summary>
|
||||
public sealed class UserSettingMap : EntityMap<UserSetting>
|
||||
{
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>Who read a notification addressed to everyone (SPEC §9, mockup 010): each user marks it for themselves.</summary>
|
||||
[Migration(20261111_009, "create_notification_reads")]
|
||||
public sealed class M20261111_009_CreateNotificationReads : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("notification_reads", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("notification_id").NotNull();
|
||||
t.Int64("user_id").NotNull();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_notification_reads_notification_user", "notification_id", "user_id");
|
||||
t.Index("ix_notification_reads_user_id", "user_id");
|
||||
});
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.SystemDatabase.Migrations;
|
||||
|
||||
/// <summary>Who read a notification addressed to everyone (SPEC §9, mockup 010): each user marks it for themselves.</summary>
|
||||
[Migration(20261111_013, "create_sys_notification_reads", Target = MigrationTarget.System)]
|
||||
public sealed class M20261111_013_CreateSysNotificationReads : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("sys_notification_reads", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("notification_id").NotNull();
|
||||
t.Int64("user_id").NotNull();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_sys_notification_reads_notification_user", "notification_id", "user_id");
|
||||
t.Index("ix_sys_notification_reads_user_id", "user_id");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -197,6 +197,13 @@ public sealed class SystemNotificationMap : EntityMap<SystemNotification>
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="SystemNotificationRead"/> to <c>sys_notification_reads</c>.</summary>
|
||||
public sealed class SystemNotificationReadMap : EntityMap<SystemNotificationRead>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public SystemNotificationReadMap() => ToTable("sys_notification_reads");
|
||||
}
|
||||
|
||||
/// <summary>The notification columns shared by <c>sys_notifications</c> and <c>notifications</c>.</summary>
|
||||
internal static class NotificationColumns
|
||||
{
|
||||
|
||||
@@ -217,10 +217,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OpenHelpAsync()
|
||||
// F1 and the "?" open the help of the screen in a tab of its own (mockup 011); on a help page they stay there.
|
||||
private Task OpenHelpAsync()
|
||||
{
|
||||
var path = TabService.PathOf(Navigation.ToBaseRelativePath(Navigation.Uri));
|
||||
await Js.InvokeVoidAsync("khaemhat.openWindow", HelpLinks.UrlFor(HelpLinks.DefaultBaseUrl, path));
|
||||
var path = TabService.PathOf("/" + Navigation.ToBaseRelativePath(Navigation.Uri));
|
||||
if (!path.StartsWith(Khaemhat.Web.Help.WikiLibrary.BasePath, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Navigation.NavigateTo(HelpLinks.LocalFor(path));
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task OnShortcutAsync(string command)
|
||||
|
||||
@@ -48,7 +48,7 @@ else
|
||||
}
|
||||
<div class="kh-actions">
|
||||
<a class="btn" href="./">@T["Common.BackHome"]</a>
|
||||
<a class="btn ghost" href="@(HelpLinks.DefaultBaseUrl + "Roadmap")" target="_blank" rel="noopener">@T["Pages.ComingSoon.Roadmap"]</a>
|
||||
<a class="btn ghost" href="@Khaemhat.Web.Help.WikiLibrary.Href("Roadmap")">@T["Pages.ComingSoon.Roadmap"]</a>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
@page "/aiuto"
|
||||
@page "/aiuto/{Name}"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Application.Configuration
|
||||
@using Khaemhat.Web.Help
|
||||
@inject WikiLibrary Wiki
|
||||
@inject KhaemhatOptions Options
|
||||
|
||||
@* The help of SPEC §17 (mockup 011): the wiki page of the screen, from the copy shipped with the application, with
|
||||
the wiki index at the side, "Apri nel wiki" for the online version and "Segnala un problema". F1 and the "?" of the
|
||||
top bar open it on the page of the current screen. *@
|
||||
<KhPageTitle Text="@T.Format("Pages.Help.TabTitle", Current?.Title ?? T["Pages.Help.Title"])" Icon="help" />
|
||||
|
||||
<div class="phead">
|
||||
<div>
|
||||
<div class="crumbs">@T["Pages.Help.Crumb"]@if (Section is { } section){<text> › @section.Title</text>} › <b>@(Current?.Title ?? Name)</b></div>
|
||||
<h1>@T.Format("Pages.Help.Heading", Current?.Title ?? T["Pages.Help.Title"])</h1>
|
||||
</div>
|
||||
<div class="grow"></div>
|
||||
<a class="btn" href="@OnlineUrl" target="_blank" rel="noopener"><KhIcon Name="external" /> @T["Pages.Help.OpenWiki"]</a>
|
||||
@if (IssuesUrl is { } issues)
|
||||
{
|
||||
<a class="btn" href="@issues" target="_blank" rel="noopener"><KhIcon Name="alert" /> @T["Pages.Help.Report"]</a>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="kh-help">
|
||||
<nav class="panel kh-help-index" aria-label="@T["Pages.Help.Index"]">
|
||||
@foreach (var group in Wiki.Sidebar)
|
||||
{
|
||||
<div class="kh-help-group">@group.Title</div>
|
||||
@foreach (var (page, label) in group.Pages)
|
||||
{
|
||||
<a class="kh-help-link @(string.Equals(page, PageName, StringComparison.OrdinalIgnoreCase) ? "on" : null)" href="@WikiLibrary.Href(page)"
|
||||
aria-current="@(string.Equals(page, PageName, StringComparison.OrdinalIgnoreCase) ? "page" : null)">
|
||||
<KhIcon Name="file" Class="sm" /> @label
|
||||
</a>
|
||||
}
|
||||
}
|
||||
</nav>
|
||||
<article class="panel kh-help-body">
|
||||
@if (!Wiki.IsAvailable)
|
||||
{
|
||||
<div class="callout warn"><KhIcon Name="alert" /> <span>@T["Pages.Help.Missing"]</span></div>
|
||||
}
|
||||
else if (Current is null)
|
||||
{
|
||||
<div class="callout warn"><KhIcon Name="alert" /> <span>@T.Format("Pages.Help.NotFound", Name ?? string.Empty)</span></div>
|
||||
}
|
||||
else
|
||||
{
|
||||
@((MarkupString)Current.Html)
|
||||
}
|
||||
</article>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
/// <summary>The wiki page, such as <c>Interfaccia-e-scorciatoie</c>; empty for the wiki home.</summary>
|
||||
[Parameter]
|
||||
public string? Name { get; set; }
|
||||
|
||||
private string PageName => string.IsNullOrWhiteSpace(Name) ? "Home" : Name;
|
||||
|
||||
private WikiPage? Current => Wiki.Get(PageName);
|
||||
|
||||
private WikiSection? Section => Wiki.Sidebar.FirstOrDefault(s => s.Pages.Any(p => string.Equals(p.Page, PageName, StringComparison.OrdinalIgnoreCase)));
|
||||
|
||||
private string BaseUrl => HelpLinks.BaseUrl(Options.HelpUrl);
|
||||
|
||||
private string OnlineUrl => BaseUrl + (Current?.Name ?? PageName);
|
||||
|
||||
private string? IssuesUrl => HelpLinks.IssuesUrl(BaseUrl);
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
@inject ShellSession Session
|
||||
@inject NavigationManager Navigation
|
||||
@inject ThemeService Theme
|
||||
@inject GlobalSearchService Search
|
||||
@implements IDisposable
|
||||
@using Khaemhat.Application.Search
|
||||
|
||||
@* The global search of SPEC §10.2 (Ctrl+K, mockup 009). Today it finds pages of the menu and commands (prefix >);
|
||||
records (parties, items, documents with #, people with @) join as their modules arrive, through
|
||||
GlobalSearchService. Arrows move, Enter opens, Escape closes. *@
|
||||
@* The global search of SPEC §10.2 (Ctrl+K, mockup 009). Pages of the menu and commands (prefix >) are found at once;
|
||||
records come from the providers of GlobalSearchService (today the help pages; parties, items, documents with #
|
||||
and people with @ join as their modules arrive), a moment after the user stops typing. Arrows move, Enter opens,
|
||||
Escape closes. *@
|
||||
@if (Open)
|
||||
{
|
||||
<div class="overlay" @onclick="CloseAsync">
|
||||
@@ -17,7 +21,11 @@
|
||||
<span class="kbdhint"><kbd>@T["Shell.Keys.Escape"]</kbd></span>
|
||||
</div>
|
||||
<div id="kh-palette-hits" role="listbox" class="hits">
|
||||
@if (Hits.Count == 0)
|
||||
@if (Soon is { } soon)
|
||||
{
|
||||
<div class="grp">@T[soon]</div>
|
||||
}
|
||||
else if (Hits.Count == 0 && !_searching)
|
||||
{
|
||||
<div class="grp">@T["Shell.Search.NoResults"]</div>
|
||||
}
|
||||
@@ -38,6 +46,10 @@
|
||||
@onclick="() => RunAsync(hit)" @onmouseover="() => _selected = i">
|
||||
<KhIcon Name="@hit.Icon" />
|
||||
<span>@hit.Title</span>
|
||||
@if (hit.Detail is not null)
|
||||
{
|
||||
<span class="d">@hit.Detail</span>
|
||||
}
|
||||
@if (hit.Hint is not null)
|
||||
{
|
||||
<span class="k">@hit.Hint</span>
|
||||
@@ -49,18 +61,24 @@
|
||||
<span class="kbdhint"><kbd>↑</kbd><kbd>↓</kbd> @T["Shell.Search.Move"]</span>
|
||||
<span class="kbdhint"><kbd>↵</kbd> @T["Shell.Search.Open"]</span>
|
||||
<span class="kbdhint"><kbd>></kbd> @T["Shell.Search.Commands"]</span>
|
||||
<span class="kbdhint"><kbd>#</kbd> @T["Shell.Search.Documents"]</span>
|
||||
<span class="kbdhint"><kbd>@@</kbd> @T["Shell.Search.People"]</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
private sealed record Hit(string Group, string Icon, string Title, string? Hint, Func<Task> Run);
|
||||
private sealed record Hit(string Group, string Icon, string Title, string? Hint, Func<Task> Run, string? Detail = null);
|
||||
|
||||
private static readonly TimeSpan Pause = TimeSpan.FromMilliseconds(200);
|
||||
|
||||
private ElementReference _input;
|
||||
private string _query = string.Empty;
|
||||
private int _selected;
|
||||
private bool _focus;
|
||||
private bool _searching;
|
||||
private CancellationTokenSource? _pending;
|
||||
|
||||
/// <summary>Whether the search is open.</summary>
|
||||
[Parameter]
|
||||
@@ -76,6 +94,14 @@
|
||||
|
||||
private List<Hit> Hits { get; set; } = [];
|
||||
|
||||
// # and @ before their modules: say when they will find something instead of "no results".
|
||||
private string? Soon => SearchQuery.Parse(_query) switch
|
||||
{
|
||||
{ Scope: SearchScope.Documents } when !Search.Covers(SearchScope.Documents) => "Shell.Search.DocumentsSoon",
|
||||
{ Scope: SearchScope.People } when !Search.Covers(SearchScope.People) => "Shell.Search.PeopleSoon",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void OnParametersSet()
|
||||
{
|
||||
@@ -84,10 +110,11 @@
|
||||
_query = string.Empty;
|
||||
_selected = 0;
|
||||
_focus = true;
|
||||
Hits = Search(_query);
|
||||
Hits = Local(_query);
|
||||
}
|
||||
else if (!Open)
|
||||
{
|
||||
Cancel();
|
||||
Hits = [];
|
||||
}
|
||||
}
|
||||
@@ -102,13 +129,52 @@
|
||||
}
|
||||
}
|
||||
|
||||
private void OnInput(ChangeEventArgs e)
|
||||
private async Task OnInput(ChangeEventArgs e)
|
||||
{
|
||||
_query = e.Value?.ToString() ?? string.Empty;
|
||||
_selected = 0;
|
||||
Hits = Search(_query);
|
||||
Hits = Local(_query);
|
||||
Cancel();
|
||||
var query = SearchQuery.Parse(_query);
|
||||
if (Session.Actor is not { } actor || query.Scope == SearchScope.Commands || query.Text.Length < SearchQuery.MinimumLength)
|
||||
{
|
||||
_searching = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for a pause in the typing, then ask the providers; a newer input cancels this one.
|
||||
var pending = _pending = new CancellationTokenSource();
|
||||
_searching = true;
|
||||
try
|
||||
{
|
||||
await Task.Delay(Pause, pending.Token);
|
||||
var found = await Search.SearchAsync(actor, query, pending.Token);
|
||||
if (pending.IsCancellationRequested || !Open)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var local = Local(_query);
|
||||
Hits = [.. (query.Scope == SearchScope.All ? local : []).Concat(found.Select(h => new Hit(h.Group, h.Icon, h.Title, null, () => Go(h.Href), h.Detail)))];
|
||||
_selected = Math.Min(_selected, Math.Max(0, Hits.Count - 1));
|
||||
_searching = false;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// The user typed something else.
|
||||
}
|
||||
}
|
||||
|
||||
private void Cancel()
|
||||
{
|
||||
_pending?.Cancel();
|
||||
_pending?.Dispose();
|
||||
_pending = null;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => Cancel();
|
||||
|
||||
private async Task OnKeyDownAsync(KeyboardEventArgs e)
|
||||
{
|
||||
switch (e.Key)
|
||||
@@ -136,21 +202,23 @@
|
||||
|
||||
private Task CloseAsync()
|
||||
{
|
||||
Cancel();
|
||||
_searching = false;
|
||||
Hits = [];
|
||||
return OpenChanged.InvokeAsync(false);
|
||||
}
|
||||
|
||||
private List<Hit> Search(string query)
|
||||
private List<Hit> Local(string input)
|
||||
{
|
||||
var text = query.Trim();
|
||||
var commandsOnly = text.StartsWith('>');
|
||||
if (commandsOnly)
|
||||
var query = SearchQuery.Parse(input);
|
||||
if (query.Scope is SearchScope.Documents or SearchScope.People)
|
||||
{
|
||||
text = text[1..].Trim();
|
||||
return [];
|
||||
}
|
||||
|
||||
var text = query.Text;
|
||||
var hits = new List<Hit>();
|
||||
if (!commandsOnly)
|
||||
if (query.Scope == SearchScope.All)
|
||||
{
|
||||
foreach (var item in MenuCatalog.All.Where(Session.CanSee))
|
||||
{
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
@using Khaemhat.Application.Notifications
|
||||
@using Khaemhat.Application.Preferences
|
||||
@using Khaemhat.Core.Instance
|
||||
@inject ShellSession Session
|
||||
@inject NotificationDispatcher Notifications
|
||||
@inject NavigationManager Navigation
|
||||
@inject TimeProvider Clock
|
||||
|
||||
@* The notifications of SPEC §9 (mockup 010): a side panel from the bell with all or only the unread ones, newest
|
||||
first. A click marks one as read and opens its page; "Segna tutte come lette" clears the bell. A notification for
|
||||
everyone is read by each user for themselves. *@
|
||||
<KhDrawer Open="Open" Title="@T["Shell.Notifications.Title"]" Icon="bell" OnClose="CloseAsync">
|
||||
<ChildContent>
|
||||
<div class="kh-seg kh-notif-filter" role="group" aria-label="@T["Shell.Notifications.Filter"]">
|
||||
<button type="button" class="@(_unreadOnly ? null : "on")" aria-pressed="@(_unreadOnly ? "false" : "true")" @onclick="() => _unreadOnly = false">
|
||||
@T.Format("Shell.Notifications.All", _items.Count)
|
||||
</button>
|
||||
<button type="button" class="@(_unreadOnly ? "on" : null)" aria-pressed="@(_unreadOnly ? "true" : "false")" @onclick="() => _unreadOnly = true">
|
||||
@T.Format("Shell.Notifications.Unread", Unread)
|
||||
</button>
|
||||
</div>
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (!Shown.Any())
|
||||
{
|
||||
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T[_unreadOnly ? "Shell.Notifications.NoneUnread" : "Shell.Notifications.None"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="kh-notifs">
|
||||
@foreach (var item in Shown)
|
||||
{
|
||||
<li class="kh-notif @(item.Read ? null : "unread")" @key="item.Id">
|
||||
<span class="ico-box @ToneOf(item.Severity)" aria-hidden="true"><KhIcon Name="@IconOf(item.Severity)" /></span>
|
||||
<button type="button" class="kh-notif-main" @onclick="() => OpenAsync(item)">
|
||||
<span class="t">@item.Title</span>
|
||||
@if (item.Body is not null)
|
||||
{
|
||||
<span class="s">@item.Body</span>
|
||||
}
|
||||
<span class="m">
|
||||
<span class="badge gray">@CategoryOf(item.Category)</span>
|
||||
<span>@When(item.CreatedAt)</span>
|
||||
</span>
|
||||
</button>
|
||||
@if (!item.Read)
|
||||
{
|
||||
<button type="button" class="ib" title="@T["Shell.Notifications.MarkRead"]" aria-label="@T.Format("Shell.Notifications.MarkReadOf", item.Title)"
|
||||
@onclick="() => MarkReadAsync(item)"><KhIcon Name="check" /></button>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn" disabled="@(Unread == 0)" @onclick="MarkAllAsync"><KhIcon Name="check" /> @T["Shell.Notifications.MarkAll"]</button>
|
||||
</Footer>
|
||||
</KhDrawer>
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<InboxItem> _items = [];
|
||||
private bool _unreadOnly;
|
||||
private bool _loaded;
|
||||
private bool _wasOpen;
|
||||
|
||||
/// <summary>Whether the panel is shown.</summary>
|
||||
[Parameter]
|
||||
public bool Open { get; set; }
|
||||
|
||||
/// <summary>Opens or closes it.</summary>
|
||||
[Parameter]
|
||||
public EventCallback<bool> OpenChanged { get; set; }
|
||||
|
||||
/// <summary>Told the unread count after every change.</summary>
|
||||
[Parameter]
|
||||
public EventCallback<int> UnreadChanged { get; set; }
|
||||
|
||||
private int Unread => _items.Count(i => !i.Read);
|
||||
|
||||
private IEnumerable<InboxItem> Shown => _unreadOnly ? _items.Where(i => !i.Read) : _items;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
if (Open && !_wasOpen)
|
||||
{
|
||||
_loaded = false;
|
||||
await LoadAsync();
|
||||
}
|
||||
|
||||
_wasOpen = Open;
|
||||
}
|
||||
|
||||
private async Task LoadAsync()
|
||||
{
|
||||
_items = Session.Actor is { } actor ? await Notifications.InboxAsync(actor) : [];
|
||||
_loaded = true;
|
||||
await UnreadChanged.InvokeAsync(Unread);
|
||||
}
|
||||
|
||||
private Task CloseAsync() => OpenChanged.InvokeAsync(false);
|
||||
|
||||
private async Task MarkReadAsync(InboxItem item)
|
||||
{
|
||||
if (Session.Actor is { } actor && !item.Read)
|
||||
{
|
||||
await Notifications.MarkReadAsync(actor, item.Id);
|
||||
await LoadAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OpenAsync(InboxItem item)
|
||||
{
|
||||
await MarkReadAsync(item);
|
||||
if (UserPreferences.IsLocalPath(item.Link))
|
||||
{
|
||||
await CloseAsync();
|
||||
Navigation.NavigateTo(item.Link!.TrimStart('/'));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task MarkAllAsync()
|
||||
{
|
||||
if (Session.Actor is { } actor)
|
||||
{
|
||||
await Notifications.MarkAllReadAsync(actor);
|
||||
await LoadAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private string CategoryOf(string category) =>
|
||||
T.Contains("Shell.Notifications.Categories." + category) ? T["Shell.Notifications.Categories." + category] : category;
|
||||
|
||||
private string When(DateTime createdAt)
|
||||
{
|
||||
var at = new DateTimeOffset(DateTime.SpecifyKind(createdAt, DateTimeKind.Utc)).ToOffset(Clock.GetLocalNow().Offset);
|
||||
var now = Clock.GetLocalNow();
|
||||
var minutes = (int)(now - at).TotalMinutes;
|
||||
return minutes switch
|
||||
{
|
||||
< 1 => T["Shell.Notifications.Now"],
|
||||
< 60 => T.Format("Shell.Notifications.MinutesAgo", minutes),
|
||||
_ when at.Date == now.Date => at.ToString("HH:mm", T.Culture),
|
||||
_ when at.Date == now.Date.AddDays(-1) => T.Format("Shell.Notifications.Yesterday", at.ToString("HH:mm", T.Culture)),
|
||||
_ => at.ToString("d MMM HH:mm", T.Culture),
|
||||
};
|
||||
}
|
||||
|
||||
private static string IconOf(NotificationSeverity severity) => severity switch
|
||||
{
|
||||
NotificationSeverity.Error => "x-circle",
|
||||
NotificationSeverity.Warning => "alert",
|
||||
NotificationSeverity.Success => "check-circle",
|
||||
_ => "info",
|
||||
};
|
||||
|
||||
private static string? ToneOf(NotificationSeverity severity) => severity switch
|
||||
{
|
||||
NotificationSeverity.Error => "err",
|
||||
NotificationSeverity.Warning => "warn",
|
||||
NotificationSeverity.Success => "ok",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
@@ -54,34 +54,15 @@
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="pop">
|
||||
<button type="button" class="tbtn" aria-haspopup="menu" aria-expanded="@(_open == Popup.Notifications)"
|
||||
aria-label="@T.Format("Shell.TopBar.NotificationsCount", _unread.Count)" @onclick="ToggleNotificationsAsync">
|
||||
<KhIcon Name="bell" />
|
||||
@if (_unread.Count > 0)
|
||||
{
|
||||
<span class="dot"></span>
|
||||
}
|
||||
<span class="tip">@T["Shell.TopBar.Notifications"]</span>
|
||||
</button>
|
||||
@if (_open == Popup.Notifications)
|
||||
<button type="button" class="tbtn" aria-haspopup="dialog" aria-expanded="@(_notifications ? "true" : "false")"
|
||||
aria-label="@T.Format("Shell.TopBar.NotificationsCount", _unread)" @onclick="ToggleNotifications">
|
||||
<KhIcon Name="bell" />
|
||||
@if (_unread > 0)
|
||||
{
|
||||
<div class="popmenu notif" role="menu">
|
||||
<div class="fh">@T["Shell.TopBar.Notifications"]</div>
|
||||
@if (_unread.Count == 0)
|
||||
{
|
||||
<div class="mi muted">@T["Shell.TopBar.NoNotifications"]</div>
|
||||
}
|
||||
@foreach (var n in _unread)
|
||||
{
|
||||
<a class="mi" role="menuitem" href="@(n.Link is { } link && UserPreferences.IsLocalPath(link) ? link.TrimStart('/') : "#")" @onclick="Close">
|
||||
<KhIcon Name="@SeverityIcon(n.Severity)" />
|
||||
<span class="grow"><b>@n.Title</b>@if (n.Body is not null) {<br /><span class="muted small">@n.Body</span>}</span>
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
<span class="dot"></span>
|
||||
}
|
||||
</div>
|
||||
<span class="tip">@T["Shell.TopBar.Notifications"]</span>
|
||||
</button>
|
||||
|
||||
<button type="button" class="tbtn" aria-label="@ThemeLabel" @onclick="Theme.ToggleDarkAsync">
|
||||
<KhIcon Name="@(Session.Preferences.Theme == ThemeMode.Dark ? "sun" : "moon")" /><span class="tip">@ThemeLabel</span>
|
||||
@@ -98,18 +79,20 @@
|
||||
{
|
||||
<div class="scrim" @onclick="Close"></div>
|
||||
}
|
||||
<NotificationPanel Open="_notifications" OpenChanged="open => _notifications = open" UnreadChanged="count => _unread = count" />
|
||||
|
||||
@code {
|
||||
private enum Popup
|
||||
{
|
||||
Company,
|
||||
Recent,
|
||||
Notifications,
|
||||
User,
|
||||
}
|
||||
|
||||
private Popup? _open;
|
||||
private IReadOnlyList<(string Title, string? Body, string? Link, Khaemhat.Core.Instance.NotificationSeverity Severity)> _unread = [];
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private int _unread;
|
||||
private bool _notifications;
|
||||
|
||||
/// <summary>Opens the global search.</summary>
|
||||
[Parameter]
|
||||
@@ -126,7 +109,8 @@
|
||||
{
|
||||
Session.Changed += OnChanged;
|
||||
Tabs.Changed += OnChanged;
|
||||
await LoadNotificationsAsync();
|
||||
await CountUnreadAsync();
|
||||
_ = RefreshAsync(_stop.Token);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -134,6 +118,8 @@
|
||||
{
|
||||
Session.Changed -= OnChanged;
|
||||
Tabs.Changed -= OnChanged;
|
||||
_stop.Cancel();
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
private void OnChanged() => _ = InvokeAsync(StateHasChanged);
|
||||
@@ -142,39 +128,44 @@
|
||||
|
||||
private void Close() => _open = null;
|
||||
|
||||
private async Task ToggleNotificationsAsync()
|
||||
private void ToggleNotifications()
|
||||
{
|
||||
Toggle(Popup.Notifications);
|
||||
if (_open == Popup.Notifications)
|
||||
_open = null;
|
||||
_notifications = !_notifications;
|
||||
}
|
||||
|
||||
private async Task CountUnreadAsync()
|
||||
{
|
||||
if (Session.Actor is { } actor)
|
||||
{
|
||||
await LoadNotificationsAsync();
|
||||
_unread = (await Notifications.InboxAsync(actor, unreadOnly: true)).Count;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoadNotificationsAsync()
|
||||
// The bell lights up for notifications that arrive while the page is open: a look every minute.
|
||||
private async Task RefreshAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (Session.Actor is not { } actor)
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
|
||||
try
|
||||
{
|
||||
return;
|
||||
while (await timer.WaitForNextTickAsync(cancellationToken))
|
||||
{
|
||||
await InvokeAsync(async () =>
|
||||
{
|
||||
await CountUnreadAsync();
|
||||
StateHasChanged();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (actor.SystemUserId is { } systemUser)
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_unread = [.. (await Notifications.UnreadForInstanceAsync(systemUser)).Select(n => (n.Title, n.Body, n.Link, n.Severity))];
|
||||
// The page closed.
|
||||
}
|
||||
else if (actor is { CompanyCode: { } company, CompanyUserId: { } user })
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
_unread = [.. (await Notifications.UnreadForUserAsync(company, user)).Select(n => (n.Title, n.Body, n.Link, n.Severity))];
|
||||
// The circuit went away.
|
||||
}
|
||||
}
|
||||
|
||||
private static string Relative(string url) => url.TrimStart('/');
|
||||
|
||||
private static string SeverityIcon(Khaemhat.Core.Instance.NotificationSeverity severity) => severity switch
|
||||
{
|
||||
Khaemhat.Core.Instance.NotificationSeverity.Error => "x-circle",
|
||||
Khaemhat.Core.Instance.NotificationSeverity.Warning => "alert",
|
||||
Khaemhat.Core.Instance.NotificationSeverity.Success => "check-circle",
|
||||
_ => "info",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Khaemhat.Application.Search;
|
||||
using Khaemhat.Application.Security;
|
||||
|
||||
namespace Khaemhat.Web.Help;
|
||||
|
||||
/// <summary>The help pages in the global search: titles first, then the sections of the pages.</summary>
|
||||
/// <param name="wiki">The wiki shipped with the application.</param>
|
||||
public sealed class HelpSearchProvider(WikiLibrary wiki) : ISearchProvider
|
||||
{
|
||||
/// <summary>The group of the results.</summary>
|
||||
public const string Group = "Shell.Search.Help";
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<SearchScope> Scopes { get; } = [SearchScope.All];
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var pages = wiki.PageNames.Select(wiki.Get).OfType<WikiPage>().ToList();
|
||||
var titles = pages.Where(p => query.Matches(p.Title))
|
||||
.Select(p => new SearchHit(Group, "help", p.Title, null, WikiLibrary.Href(p.Name)));
|
||||
var sections = pages.SelectMany(p => p.Headings.Where(query.Matches)
|
||||
.Select(h => new SearchHit(Group, "help", h, p.Title, WikiLibrary.Href(p.Name) + "#" + WikiMarkdown.Slug(h))));
|
||||
return Task.FromResult<IReadOnlyList<SearchHit>>([.. titles.Concat(sections).Take(GlobalSearchService.PerProvider)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Khaemhat.Web.Help;
|
||||
|
||||
/// <summary>A page of the help.</summary>
|
||||
/// <param name="Name">The page name, as in the wiki (<c>Interfaccia-e-scorciatoie</c>).</param>
|
||||
/// <param name="Title">The first heading.</param>
|
||||
/// <param name="Html">The content as HTML.</param>
|
||||
/// <param name="Headings">The second-level headings, for the search.</param>
|
||||
public sealed record WikiPage(string Name, string Title, string Html, IReadOnlyList<string> Headings);
|
||||
|
||||
/// <summary>A group of the help index, from the wiki sidebar.</summary>
|
||||
/// <param name="Title">The group title.</param>
|
||||
/// <param name="Pages">The pages: name and label.</param>
|
||||
public sealed record WikiSection(string Title, IReadOnlyList<(string Page, string Label)> Pages);
|
||||
|
||||
/// <summary>
|
||||
/// The copy of the wiki shipped with the application (SPEC §17: help also for installations without Internet). The
|
||||
/// build copies <c>docs/wiki/*.md</c> to <c>help/wiki/</c> and the images the pages show (mockups, icons) to
|
||||
/// <c>help/media/</c> next to the program; pages are converted once and kept in memory.
|
||||
/// </summary>
|
||||
public sealed partial class WikiLibrary
|
||||
{
|
||||
/// <summary>The address of the help pages inside the application.</summary>
|
||||
public const string BasePath = "/aiuto";
|
||||
|
||||
/// <summary>The address of the images of the help.</summary>
|
||||
public const string MediaPath = BasePath + "/media";
|
||||
|
||||
private const string RawPrefix = "/raw/branch/main/";
|
||||
|
||||
private readonly string _wiki;
|
||||
private readonly string _media;
|
||||
private readonly Dictionary<string, string> _files;
|
||||
private readonly ConcurrentDictionary<string, WikiPage> _pages = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Lazy<IReadOnlyList<WikiSection>> _sidebar;
|
||||
|
||||
/// <summary>Reads the wiki next to the program.</summary>
|
||||
public WikiLibrary()
|
||||
: this(Path.Combine(AppContext.BaseDirectory, "help"))
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Reads the wiki from a folder.</summary>
|
||||
/// <param name="root">The folder with <c>wiki/</c> and <c>media/</c>.</param>
|
||||
public WikiLibrary(string root)
|
||||
{
|
||||
_wiki = Path.Combine(root, "wiki");
|
||||
_media = Path.GetFullPath(Path.Combine(root, "media"));
|
||||
_files = Directory.Exists(_wiki)
|
||||
? Directory.EnumerateFiles(_wiki, "*.md").ToDictionary(f => Path.GetFileNameWithoutExtension(f), f => f, StringComparer.OrdinalIgnoreCase)
|
||||
: new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
_sidebar = new Lazy<IReadOnlyList<WikiSection>>(ReadSidebar);
|
||||
}
|
||||
|
||||
/// <summary>Whether the copy of the wiki is there (it is missing only in a broken build).</summary>
|
||||
public bool IsAvailable => _files.ContainsKey("Home");
|
||||
|
||||
/// <summary>The page names, without the special ones (<c>_Sidebar</c>, <c>_Footer</c>).</summary>
|
||||
public IEnumerable<string> PageNames => _files.Keys.Where(k => !k.StartsWith('_')).Order(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The index of the help, from the wiki sidebar.</summary>
|
||||
public IReadOnlyList<WikiSection> Sidebar => _sidebar.Value;
|
||||
|
||||
/// <summary>The address of a help page inside the application.</summary>
|
||||
/// <param name="page">The page name, optionally with <c>#anchor</c>.</param>
|
||||
/// <returns>The address.</returns>
|
||||
public static string Href(string page)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(page);
|
||||
return BasePath[1..] + "/" + page;
|
||||
}
|
||||
|
||||
/// <summary>Whether a page exists.</summary>
|
||||
/// <param name="page">The page name.</param>
|
||||
/// <returns><see langword="true"/> if it does.</returns>
|
||||
public bool Exists(string page) => _files.ContainsKey(page) && !page.StartsWith('_');
|
||||
|
||||
/// <summary>A page, converted to HTML.</summary>
|
||||
/// <param name="page">The page name.</param>
|
||||
/// <returns>The page, or <see langword="null"/> if it does not exist.</returns>
|
||||
public WikiPage? Get(string page)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(page);
|
||||
if (!Exists(page))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return _pages.GetOrAdd(page, name =>
|
||||
{
|
||||
var file = _files[name];
|
||||
var markdown = File.ReadAllText(file);
|
||||
var lines = markdown.Split('\n');
|
||||
var title = lines.Select(l => l.Trim()).FirstOrDefault(l => l.StartsWith("# ", StringComparison.Ordinal)) is { } h1
|
||||
? WikiMarkdown.PlainText(h1[2..])
|
||||
: name.Replace('-', ' ');
|
||||
var headings = lines.Select(l => l.Trim()).Where(l => l.StartsWith("## ", StringComparison.Ordinal)).Select(l => WikiMarkdown.PlainText(l[3..])).ToList();
|
||||
return new WikiPage(Path.GetFileNameWithoutExtension(file), title, WikiMarkdown.ToHtml(markdown, Links), headings);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The file of an image of the help, if it is one of the copied ones.</summary>
|
||||
/// <param name="path">The path after <see cref="MediaPath"/>, such as <c>docs/mockups/thumbs/004-dashboard.png</c>.</param>
|
||||
/// <returns>The full file name, or <see langword="null"/>.</returns>
|
||||
public string? MediaFile(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || !MediaName().IsMatch(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var full = Path.GetFullPath(Path.Combine(_media, path));
|
||||
return full.StartsWith(_media + Path.DirectorySeparatorChar, StringComparison.Ordinal) && File.Exists(full) ? full : null;
|
||||
}
|
||||
|
||||
private WikiLinks Links => new(Href, LocalMedia);
|
||||
|
||||
// Images point to the raw files of the repository (".../raw/branch/main/docs/mockups/thumbs/x.png") or to img/
|
||||
// next to the pages; the copied ones are served from the application, the others stay on the web.
|
||||
private string? LocalMedia(string url)
|
||||
{
|
||||
var raw = url.IndexOf(RawPrefix, StringComparison.Ordinal);
|
||||
var path = raw >= 0 ? url[(raw + RawPrefix.Length)..] : url.StartsWith("img/", StringComparison.Ordinal) ? "docs/wiki/" + url : null;
|
||||
return path is not null && MediaFile(path) is not null ? MediaPath[1..] + "/" + path : null;
|
||||
}
|
||||
|
||||
private List<WikiSection> ReadSidebar()
|
||||
{
|
||||
var sections = new List<WikiSection>();
|
||||
if (!_files.TryGetValue("_Sidebar", out var file))
|
||||
{
|
||||
return sections;
|
||||
}
|
||||
|
||||
string? title = null;
|
||||
var pages = new List<(string, string)>();
|
||||
foreach (var raw in File.ReadAllLines(file))
|
||||
{
|
||||
var line = raw.Trim();
|
||||
if (line.StartsWith("**", StringComparison.Ordinal) && !line.StartsWith("**[", StringComparison.Ordinal))
|
||||
{
|
||||
Flush();
|
||||
title = WikiMarkdown.PlainText(line);
|
||||
}
|
||||
else if (SidebarLink().Match(line) is { Success: true } link && Exists(link.Groups[2].Value))
|
||||
{
|
||||
pages.Add((link.Groups[2].Value, link.Groups[1].Value));
|
||||
}
|
||||
}
|
||||
|
||||
Flush();
|
||||
return sections;
|
||||
|
||||
void Flush()
|
||||
{
|
||||
if (title is not null && pages.Count > 0)
|
||||
{
|
||||
sections.Add(new WikiSection(title, [.. pages]));
|
||||
}
|
||||
|
||||
pages.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^-\s*\[([^\]]+)\]\(([A-Za-z0-9-]+)\)")]
|
||||
private static partial Regex SidebarLink();
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9_\-/.]*\.(png|jpg|jpeg|svg|gif|webp)$", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex MediaName();
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Khaemhat.Web.Help;
|
||||
|
||||
/// <summary>Where the links and images of a wiki page point inside the application.</summary>
|
||||
/// <param name="Page">The address of another wiki page (<c>Anagrafiche</c>, <c>Anagrafiche#clienti</c>).</param>
|
||||
/// <param name="Media">The local address of an image, or <see langword="null"/> to keep the original one.</param>
|
||||
public sealed record WikiLinks(Func<string, string> Page, Func<string, string?> Media);
|
||||
|
||||
/// <summary>
|
||||
/// Turns the Markdown of <c>docs/wiki/</c> into HTML for the help (SPEC §17, mockup 011), written in house (no external
|
||||
/// libraries, ADR 0002). It covers what the wiki uses: headings with anchors, paragraphs, bold, italic, code, links,
|
||||
/// images, nested lists, tables, quotes, code blocks and rules. Every piece of text is encoded and only http, https,
|
||||
/// anchors and wiki pages become links, so a page cannot inject markup or scripts.
|
||||
/// </summary>
|
||||
public static partial class WikiMarkdown
|
||||
{
|
||||
/// <summary>Converts a page.</summary>
|
||||
/// <param name="markdown">The Markdown.</param>
|
||||
/// <param name="links">Where links and images go.</param>
|
||||
/// <returns>The HTML.</returns>
|
||||
public static string ToHtml(string markdown, WikiLinks links)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(markdown);
|
||||
ArgumentNullException.ThrowIfNull(links);
|
||||
var lines = markdown.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Split('\n');
|
||||
var html = new StringBuilder();
|
||||
new Parser(lines, links, html).Blocks(0, lines.Length);
|
||||
return html.ToString();
|
||||
}
|
||||
|
||||
/// <summary>The anchor of a heading, as the wiki makes it: lower case, words joined by dashes.</summary>
|
||||
/// <param name="text">The heading text (Markdown).</param>
|
||||
/// <returns>The anchor.</returns>
|
||||
public static string Slug(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
var plain = PlainText(text).ToLower(CultureInfo.InvariantCulture);
|
||||
var slug = new StringBuilder();
|
||||
foreach (var c in plain)
|
||||
{
|
||||
if (char.IsLetterOrDigit(c) || c is '-' or '_')
|
||||
{
|
||||
slug.Append(c);
|
||||
}
|
||||
else if (c == ' ')
|
||||
{
|
||||
slug.Append('-');
|
||||
}
|
||||
}
|
||||
|
||||
return slug.ToString();
|
||||
}
|
||||
|
||||
/// <summary>The text of a line of Markdown without its marks.</summary>
|
||||
/// <param name="text">The Markdown.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string PlainText(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
var plain = LinkPattern().Replace(text, "$1");
|
||||
return plain.Replace("**", string.Empty, StringComparison.Ordinal).Replace("`", string.Empty, StringComparison.Ordinal)
|
||||
.Replace("*", string.Empty, StringComparison.Ordinal).Trim();
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"!?\[([^\]]*)\]\([^)]*\)")]
|
||||
private static partial Regex LinkPattern();
|
||||
|
||||
[GeneratedRegex(@"^(\s*)([-*+]|\d+[.)])\s+(.*)$")]
|
||||
private static partial Regex ListItemPattern();
|
||||
|
||||
[GeneratedRegex(@"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$")]
|
||||
private static partial Regex TableRulePattern();
|
||||
|
||||
[GeneratedRegex(@"^(#{1,6})\s+(.*?)\s*#*\s*$")]
|
||||
private static partial Regex HeadingPattern();
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9-]*(#[A-Za-z0-9_\-\p{L}]*)?$")]
|
||||
private static partial Regex PagePattern();
|
||||
|
||||
private sealed class Parser(string[] lines, WikiLinks links, StringBuilder html)
|
||||
{
|
||||
public void Blocks(int start, int end)
|
||||
{
|
||||
var i = start;
|
||||
while (i < end)
|
||||
{
|
||||
var line = lines[i];
|
||||
var trimmed = line.Trim();
|
||||
if (trimmed.Length == 0)
|
||||
{
|
||||
i++;
|
||||
}
|
||||
else if (trimmed.StartsWith("```", StringComparison.Ordinal))
|
||||
{
|
||||
i = Fence(i, end);
|
||||
}
|
||||
else if (HeadingPattern().Match(trimmed) is { Success: true } heading)
|
||||
{
|
||||
var level = heading.Groups[1].Length;
|
||||
var text = heading.Groups[2].Value;
|
||||
html.Append(CultureInfo.InvariantCulture, $"<h{level} id=\"{Attr(Slug(text))}\">").Append(Inline(text)).Append(CultureInfo.InvariantCulture, $"</h{level}>\n");
|
||||
i++;
|
||||
}
|
||||
else if (trimmed is "---" or "***" or "___")
|
||||
{
|
||||
html.Append("<hr />\n");
|
||||
i++;
|
||||
}
|
||||
else if (trimmed.StartsWith('>'))
|
||||
{
|
||||
i = Quote(i, end);
|
||||
}
|
||||
else if (trimmed.StartsWith('|') && i + 1 < end && TableRulePattern().IsMatch(lines[i + 1]))
|
||||
{
|
||||
i = Table(i, end);
|
||||
}
|
||||
else if (ListItemPattern().Match(line) is { Success: true } item)
|
||||
{
|
||||
i = List(i, end, item.Groups[1].Value.Length);
|
||||
}
|
||||
else
|
||||
{
|
||||
i = Paragraph(i, end);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int Fence(int i, int end)
|
||||
{
|
||||
var body = new List<string>();
|
||||
var j = i + 1;
|
||||
while (j < end && !lines[j].Trim().StartsWith("```", StringComparison.Ordinal))
|
||||
{
|
||||
body.Add(lines[j]);
|
||||
j++;
|
||||
}
|
||||
|
||||
html.Append("<pre><code>").Append(Encode(string.Join('\n', body))).Append("</code></pre>\n");
|
||||
return Math.Min(j + 1, end);
|
||||
}
|
||||
|
||||
private int Quote(int i, int end)
|
||||
{
|
||||
var inner = new List<string>();
|
||||
var j = i;
|
||||
while (j < end && lines[j].TrimStart().StartsWith('>'))
|
||||
{
|
||||
var text = lines[j].TrimStart()[1..];
|
||||
inner.Add(text.StartsWith(' ') ? text[1..] : text);
|
||||
j++;
|
||||
}
|
||||
|
||||
// "> **Stato:** bozza · ..." at the top of every page is the page state, not a note.
|
||||
var meta = inner.Count > 0 && inner[0].StartsWith("**Stato:**", StringComparison.Ordinal);
|
||||
html.Append(meta ? "<div class=\"kh-help-meta\">" : "<div class=\"callout info\"><div>");
|
||||
|
||||
// Each line of the page state is a fact of its own: keep them on separate lines.
|
||||
var nested = new Parser(meta ? [.. inner.Select((l, n) => n < inner.Count - 1 ? l.TrimEnd() + " " : l)] : [.. inner], links, html);
|
||||
nested.Blocks(0, inner.Count);
|
||||
html.Append(meta ? "</div>\n" : "</div></div>\n");
|
||||
return j;
|
||||
}
|
||||
|
||||
private int Table(int i, int end)
|
||||
{
|
||||
var header = Cells(lines[i]);
|
||||
html.Append("<div class=\"kh-help-table\"><table class=\"grid\"><thead><tr>");
|
||||
foreach (var cell in header)
|
||||
{
|
||||
html.Append("<th>").Append(Inline(cell)).Append("</th>");
|
||||
}
|
||||
|
||||
html.Append("</tr></thead><tbody>");
|
||||
var j = i + 2;
|
||||
while (j < end && lines[j].Trim().StartsWith('|'))
|
||||
{
|
||||
html.Append("<tr>");
|
||||
var cells = Cells(lines[j]);
|
||||
for (var c = 0; c < header.Count; c++)
|
||||
{
|
||||
html.Append("<td>").Append(c < cells.Count ? Inline(cells[c]) : string.Empty).Append("</td>");
|
||||
}
|
||||
|
||||
html.Append("</tr>");
|
||||
j++;
|
||||
}
|
||||
|
||||
html.Append("</tbody></table></div>\n");
|
||||
return j;
|
||||
}
|
||||
|
||||
private static List<string> Cells(string line)
|
||||
{
|
||||
var text = line.Trim();
|
||||
if (text.StartsWith('|'))
|
||||
{
|
||||
text = text[1..];
|
||||
}
|
||||
|
||||
if (text.EndsWith('|') && !text.EndsWith("\\|", StringComparison.Ordinal))
|
||||
{
|
||||
text = text[..^1];
|
||||
}
|
||||
|
||||
var cells = new List<string>();
|
||||
var current = new StringBuilder();
|
||||
var inCode = false;
|
||||
for (var k = 0; k < text.Length; k++)
|
||||
{
|
||||
var c = text[k];
|
||||
if (c == '\\' && k + 1 < text.Length && text[k + 1] == '|')
|
||||
{
|
||||
current.Append('|');
|
||||
k++;
|
||||
}
|
||||
else if (c == '`')
|
||||
{
|
||||
inCode = !inCode;
|
||||
current.Append(c);
|
||||
}
|
||||
else if (c == '|' && !inCode)
|
||||
{
|
||||
cells.Add(current.ToString().Trim());
|
||||
current.Clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
current.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
cells.Add(current.ToString().Trim());
|
||||
return cells;
|
||||
}
|
||||
|
||||
private int List(int i, int end, int indent)
|
||||
{
|
||||
var ordered = char.IsDigit(ListItemPattern().Match(lines[i]).Groups[2].Value[0]);
|
||||
html.Append(ordered ? "<ol>" : "<ul>");
|
||||
var j = i;
|
||||
while (j < end)
|
||||
{
|
||||
var match = ListItemPattern().Match(lines[j]);
|
||||
if (!match.Success || match.Groups[1].Value.Length != indent)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var text = new StringBuilder(match.Groups[3].Value);
|
||||
j++;
|
||||
var nested = new StringBuilder();
|
||||
while (j < end)
|
||||
{
|
||||
var line = lines[j];
|
||||
var lead = line.Length - line.TrimStart().Length;
|
||||
if (line.Trim().Length == 0)
|
||||
{
|
||||
// A blank line ends the item unless the list goes on after it.
|
||||
var next = j + 1;
|
||||
if (next < end && lines[next].Trim().Length > 0 && (lines[next].Length - lines[next].TrimStart().Length) > indent)
|
||||
{
|
||||
j++;
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (ListItemPattern().Match(line) is { Success: true } sub)
|
||||
{
|
||||
if (sub.Groups[1].Value.Length > indent)
|
||||
{
|
||||
var inner = new StringBuilder();
|
||||
j = new Parser(lines, links, inner).List(j, end, sub.Groups[1].Value.Length);
|
||||
nested.Append(inner);
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (lead <= indent || IsBlockStart(line))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
text.Append(' ').Append(line.Trim());
|
||||
j++;
|
||||
}
|
||||
|
||||
html.Append("<li>").Append(Inline(text.ToString())).Append(nested).Append("</li>");
|
||||
if (j < end && lines[j].Trim().Length == 0 && j + 1 < end && ListItemPattern().Match(lines[j + 1]) is { Success: true } after
|
||||
&& after.Groups[1].Value.Length == indent)
|
||||
{
|
||||
j++;
|
||||
}
|
||||
}
|
||||
|
||||
html.Append(ordered ? "</ol>\n" : "</ul>\n");
|
||||
return j;
|
||||
}
|
||||
|
||||
private int Paragraph(int i, int end)
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
var j = i;
|
||||
while (j < end && lines[j].Trim().Length > 0 && (j == i || !IsBlockStart(lines[j])))
|
||||
{
|
||||
// Two spaces at the end of a line are a line break, as in the wiki.
|
||||
var line = lines[j];
|
||||
text.Append(Inline(line.Trim())).Append(line.EndsWith(" ", StringComparison.Ordinal) ? "<br />" : " ");
|
||||
j++;
|
||||
}
|
||||
|
||||
html.Append("<p>").Append(text.ToString().TrimEnd()).Append("</p>\n");
|
||||
return j;
|
||||
}
|
||||
|
||||
private static bool IsBlockStart(string line)
|
||||
{
|
||||
var trimmed = line.Trim();
|
||||
return trimmed.StartsWith("```", StringComparison.Ordinal) || trimmed.StartsWith('>') || trimmed.StartsWith('|')
|
||||
|| HeadingPattern().IsMatch(trimmed) || ListItemPattern().IsMatch(line) || trimmed is "---" or "***" or "___";
|
||||
}
|
||||
|
||||
private string Inline(string text)
|
||||
{
|
||||
var output = new StringBuilder();
|
||||
var i = 0;
|
||||
while (i < text.Length)
|
||||
{
|
||||
var c = text[i];
|
||||
if (c == '\\' && i + 1 < text.Length && char.IsPunctuation(text[i + 1]) || c == '\\' && i + 1 < text.Length && char.IsSymbol(text[i + 1]))
|
||||
{
|
||||
output.Append(Encode(text[i + 1].ToString()));
|
||||
i += 2;
|
||||
}
|
||||
else if (c == '`' && text.IndexOf('`', i + 1) is var close && close > i)
|
||||
{
|
||||
output.Append("<code>").Append(Encode(text[(i + 1)..close])).Append("</code>");
|
||||
i = close + 1;
|
||||
}
|
||||
else if (c == '!' && i + 1 < text.Length && text[i + 1] == '[' && TryLink(text, i + 1, out var alt, out var src, out var after))
|
||||
{
|
||||
var local = links.Media(src);
|
||||
var url = local ?? (IsWeb(src) ? src : null);
|
||||
output.Append(url is null
|
||||
? Encode(alt)
|
||||
: $"<img src=\"{Attr(url)}\" alt=\"{Attr(PlainText(alt))}\" loading=\"lazy\" />");
|
||||
i = after;
|
||||
}
|
||||
else if (c == '[' && TryLink(text, i, out var label, out var href, out var next))
|
||||
{
|
||||
output.Append(Anchor(label, href));
|
||||
i = next;
|
||||
}
|
||||
else if (c == '*' && i + 1 < text.Length && text[i + 1] == '*' && text.IndexOf("**", i + 2, StringComparison.Ordinal) is var bold && bold > i + 2)
|
||||
{
|
||||
output.Append("<strong>").Append(Inline(text[(i + 2)..bold])).Append("</strong>");
|
||||
i = bold + 2;
|
||||
}
|
||||
else if (c is '*' or '_' && i + 1 < text.Length && !char.IsWhiteSpace(text[i + 1]) && (c == '*' || i == 0 || !char.IsLetterOrDigit(text[i - 1]))
|
||||
&& Closing(text, i + 1, c) is var em && em > i + 1)
|
||||
{
|
||||
output.Append("<em>").Append(Inline(text[(i + 1)..em])).Append("</em>");
|
||||
i = em + 1;
|
||||
}
|
||||
else if (c == '<' && text.AsSpan(i).StartsWith("<br", StringComparison.OrdinalIgnoreCase) && text.IndexOf('>', i) is var gt && gt > i)
|
||||
{
|
||||
output.Append("<br />");
|
||||
i = gt + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
output.Append(Encode(c.ToString()));
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
return output.ToString();
|
||||
}
|
||||
|
||||
private static int Closing(string text, int from, char mark)
|
||||
{
|
||||
for (var k = from; k < text.Length; k++)
|
||||
{
|
||||
if (text[k] == mark && !char.IsWhiteSpace(text[k - 1]) && (k + 1 >= text.Length || text[k + 1] != mark)
|
||||
&& (mark == '*' || k + 1 >= text.Length || !char.IsLetterOrDigit(text[k + 1])))
|
||||
{
|
||||
return k;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static bool TryLink(string text, int open, out string label, out string href, out int after)
|
||||
{
|
||||
label = href = string.Empty;
|
||||
after = open;
|
||||
var depth = 0;
|
||||
var k = open;
|
||||
for (; k < text.Length; k++)
|
||||
{
|
||||
if (text[k] == '[')
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
else if (text[k] == ']' && --depth == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (k + 1 >= text.Length || text[k + 1] != '(')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var closeParen = text.IndexOf(')', k + 2);
|
||||
if (closeParen < 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
label = text[(open + 1)..k];
|
||||
href = text[(k + 2)..closeParen].Trim();
|
||||
var space = href.IndexOf(' ', StringComparison.Ordinal);
|
||||
if (space > 0)
|
||||
{
|
||||
href = href[..space];
|
||||
}
|
||||
|
||||
after = closeParen + 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
private string Anchor(string label, string href)
|
||||
{
|
||||
var inner = Inline(label);
|
||||
if (IsWeb(href))
|
||||
{
|
||||
return $"<a href=\"{Attr(href)}\" target=\"_blank\" rel=\"noopener\">{inner}</a>";
|
||||
}
|
||||
|
||||
if (href.StartsWith('#'))
|
||||
{
|
||||
return $"<a href=\"{Attr("#" + Slug(href[1..].Replace('-', ' ')))}\">{inner}</a>";
|
||||
}
|
||||
|
||||
return PagePattern().IsMatch(href) ? $"<a href=\"{Attr(links.Page(href))}\">{inner}</a>" : inner;
|
||||
}
|
||||
|
||||
private static bool IsWeb(string url) =>
|
||||
url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("http://", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static string Encode(string text) => WebUtility.HtmlEncode(text);
|
||||
|
||||
private static string Attr(string text) => WebUtility.HtmlEncode(text);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ using Khaemhat.Core.Common;
|
||||
using Khaemhat.Infrastructure.Logging;
|
||||
using Khaemhat.Infrastructure.Security;
|
||||
using Khaemhat.Web.Components;
|
||||
using Khaemhat.Web.Help;
|
||||
using Khaemhat.Web.Security;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
@@ -109,6 +110,7 @@ public static class KhaemhatApp
|
||||
app.MapStaticAssets();
|
||||
app.MapSignOut();
|
||||
app.MapCompanySwitch();
|
||||
app.MapHelp();
|
||||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
|
||||
@@ -130,6 +132,27 @@ public static class KhaemhatApp
|
||||
}
|
||||
}
|
||||
|
||||
// The images of the help pages (mockups, icons) from the copy of the wiki, and /help, the address of SPEC §17, which
|
||||
// leads to the help page inside the application (mockup 011).
|
||||
private static void MapHelp(this IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapGet(WikiLibrary.MediaPath + "/{**path}", (string path, WikiLibrary wiki) =>
|
||||
wiki.MediaFile(path) is { } file
|
||||
? Results.File(file, Path.GetExtension(file).ToLowerInvariant() switch
|
||||
{
|
||||
".svg" => "image/svg+xml",
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
".gif" => "image/gif",
|
||||
".webp" => "image/webp",
|
||||
_ => "image/png",
|
||||
})
|
||||
: Results.NotFound())
|
||||
.AllowAnonymous();
|
||||
endpoints.MapGet("/help/{**page}", (HttpContext context, string? page) =>
|
||||
Results.Redirect(context.Request.PathBase + WikiLibrary.BasePath + (string.IsNullOrEmpty(page) ? string.Empty : "/" + Uri.EscapeDataString(page))));
|
||||
endpoints.MapGet("/help", (HttpContext context) => Results.Redirect(context.Request.PathBase + WikiLibrary.BasePath));
|
||||
}
|
||||
|
||||
// POST /session/company: an instance account chooses the company of its session (top bar, SPEC §10.2). The page
|
||||
// is reloaded, so the new circuit starts in the new company.
|
||||
private static void MapCompanySwitch(this IEndpointRouteBuilder endpoints) =>
|
||||
|
||||
@@ -10,6 +10,7 @@ using Khaemhat.Application.Localization;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Notifications;
|
||||
using Khaemhat.Application.Preferences;
|
||||
using Khaemhat.Application.Search;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Caching;
|
||||
using Khaemhat.Core.Files;
|
||||
@@ -27,6 +28,7 @@ using Khaemhat.Infrastructure.Files;
|
||||
using Khaemhat.Infrastructure.Licensing;
|
||||
using Khaemhat.Infrastructure.Logging;
|
||||
using Khaemhat.Infrastructure.Security;
|
||||
using Khaemhat.Web.Help;
|
||||
using Khaemhat.Web.Security;
|
||||
using Khaemhat.Web.Shell;
|
||||
|
||||
@@ -50,6 +52,9 @@ internal static class KhaemhatServices
|
||||
{
|
||||
var dataAssembly = typeof(CompanyRegistry).Assembly;
|
||||
services.AddSingleton(options);
|
||||
services.AddSingleton(_ => new WikiLibrary());
|
||||
services.AddSingleton<ISearchProvider, HelpSearchProvider>();
|
||||
services.AddSingleton<GlobalSearchService>();
|
||||
services.AddSingleton(logSink);
|
||||
services.AddSingleton(TimeProvider.System);
|
||||
services.AddSingleton<BootstrapState>();
|
||||
|
||||
@@ -23,4 +23,14 @@
|
||||
<Content Remove="Resources/**/*.json" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- The help (SPEC §17, ADR 0023): a copy of the wiki and of the images it shows, next to the program, so F1 works
|
||||
without Internet. Read by WikiLibrary from help/. -->
|
||||
<ItemGroup>
|
||||
<None Include="../../docs/wiki/*.md" Link="help/wiki/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
<None Include="../../docs/wiki/img/**/*" Link="help/media/docs/wiki/img/%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
<None Include="../../docs/mockups/thumbs/*.png" Link="help/media/docs/mockups/thumbs/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
<None Include="../../docs/mockups/png/*.png" Link="help/media/docs/mockups/png/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
<None Include="../../assets/*.png" Link="help/media/assets/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -357,6 +357,17 @@
|
||||
"OpenCard": "Apri la scheda",
|
||||
"Block": "Blocca"
|
||||
}
|
||||
},
|
||||
"Help": {
|
||||
"Title": "Aiuto",
|
||||
"TabTitle": "Aiuto · {0}",
|
||||
"Heading": "Aiuto · {0}",
|
||||
"Crumb": "Aiuto (F1)",
|
||||
"Index": "Indice dell'aiuto",
|
||||
"OpenWiki": "Apri nel wiki",
|
||||
"Report": "Segnala un problema",
|
||||
"Missing": "La copia della wiki non è presente in questa installazione: apri la wiki online.",
|
||||
"NotFound": "La pagina «{0}» non esiste nella wiki: scegline una dall'indice."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,6 @@
|
||||
"NoRecent": "Nessuna pagina aperta di recente",
|
||||
"Notifications": "Notifiche",
|
||||
"NotificationsCount": "Notifiche: {0} non lette",
|
||||
"NoNotifications": "Nessuna notifica da leggere",
|
||||
"ThemeDark": "Passa al tema scuro",
|
||||
"ThemeLight": "Passa al tema chiaro",
|
||||
"Help": "Aiuto della pagina"
|
||||
@@ -167,13 +166,18 @@
|
||||
},
|
||||
"Search": {
|
||||
"Title": "Ricerca globale",
|
||||
"Placeholder": "Cerca una pagina o un comando (> per i comandi)",
|
||||
"Placeholder": "Cerca pagine, aiuto e comandi (> comandi, # documenti, @ persone)",
|
||||
"NoResults": "Nessun risultato",
|
||||
"Pages": "Pagine",
|
||||
"CommandsGroup": "Comandi",
|
||||
"Move": "sposta",
|
||||
"Open": "apri",
|
||||
"Commands": "comandi"
|
||||
"Commands": "comandi",
|
||||
"Help": "Aiuto",
|
||||
"Documents": "documenti",
|
||||
"People": "persone",
|
||||
"DocumentsSoon": "La ricerca dei documenti arriva con i moduli Vendite e Acquisti",
|
||||
"PeopleSoon": "La ricerca delle persone arriva con le anagrafiche e il CRM"
|
||||
},
|
||||
"Commands": {
|
||||
"ToggleTheme": "Cambia tema chiaro/scuro",
|
||||
@@ -214,6 +218,26 @@
|
||||
"Paused": "La sessione è stata sospesa dal server.",
|
||||
"ResumeFailed": "Impossibile riprendere la sessione.",
|
||||
"Resume": "Riprendi"
|
||||
},
|
||||
"Notifications": {
|
||||
"Title": "Notifiche",
|
||||
"Filter": "Quali notifiche",
|
||||
"All": "Tutte ({0})",
|
||||
"Unread": "Non lette ({0})",
|
||||
"None": "Nessuna notifica.",
|
||||
"NoneUnread": "Hai letto tutto.",
|
||||
"MarkRead": "Segna come letta",
|
||||
"MarkReadOf": "Segna come letta: {0}",
|
||||
"MarkAll": "Segna tutte come lette",
|
||||
"Now": "Adesso",
|
||||
"MinutesAgo": "{0} min fa",
|
||||
"Yesterday": "Ieri {0}",
|
||||
"Categories": {
|
||||
"security": "Sicurezza",
|
||||
"jobs": "Attività",
|
||||
"system": "Sistema",
|
||||
"licenses": "Licenza"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,4 +62,24 @@ public static class HelpLinks
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns>The address.</returns>
|
||||
public static string UrlFor(string baseUrl, string path) => baseUrl + PageFor(path);
|
||||
|
||||
/// <summary>The help page of a path inside the application (F1, mockup 011).</summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns>The relative address, such as <c>aiuto/Anagrafiche</c>.</returns>
|
||||
public static string LocalFor(string path) => Khaemhat.Web.Help.WikiLibrary.Href(PageFor(path));
|
||||
|
||||
/// <summary>The online wiki: <c>KHAEMHAT_HELP_URL</c> or the project wiki, always ending with a slash.</summary>
|
||||
/// <param name="configured">The configured address, if any.</param>
|
||||
/// <returns>The address.</returns>
|
||||
public static string BaseUrl(string? configured) =>
|
||||
string.IsNullOrWhiteSpace(configured) ? DefaultBaseUrl : configured.EndsWith('/') ? configured : configured + "/";
|
||||
|
||||
/// <summary>Where to report a problem: the issues of the repository whose wiki it is (Gitea and GitHub alike).</summary>
|
||||
/// <param name="baseUrl">The wiki address.</param>
|
||||
/// <returns>The address of a new issue, or <see langword="null"/> when the wiki is not a repository wiki.</returns>
|
||||
public static string? IssuesUrl(string baseUrl)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(baseUrl);
|
||||
return baseUrl.EndsWith("/wiki/", StringComparison.OrdinalIgnoreCase) ? baseUrl[..^"wiki/".Length] + "issues/new" : null;
|
||||
}
|
||||
}
|
||||
@@ -191,3 +191,53 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
|
||||
@media (max-width: 1279px) { .kh-home.kh-with-drawer { margin-right: 0; } }
|
||||
@media (max-width: 999px) { .kh-wgrid > .widget { grid-column: 1 / -1; } }
|
||||
@media (max-width: 599px) { .kh-wlist .badge { display: none; } }
|
||||
|
||||
/* ---- notifications panel (issue #32, mockup 010) ---- */
|
||||
.kh-notif-filter { margin-bottom: 4px; }
|
||||
.kh-notifs { list-style: none; margin: 0 -16px; padding: 0; }
|
||||
.kh-notif { display: flex; align-items: flex-start; gap: 10px; padding: 10px 16px; border-bottom: 1px solid var(--kh-border); }
|
||||
.kh-notif.unread { background: var(--kh-accent-soft); }
|
||||
.kh-notif .ico-box { width: 28px; height: 28px; flex: none; }
|
||||
.kh-notif-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; border: 0; background: none; padding: 0; text-align: left;
|
||||
font: inherit; color: var(--kh-text); cursor: pointer; }
|
||||
.kh-notif-main .t { font-size: 12.5px; }
|
||||
.kh-notif.unread .kh-notif-main .t { font-weight: 600; }
|
||||
.kh-notif-main .s { font-size: 11.5px; color: var(--kh-text-2); display: -webkit-box; -webkit-line-clamp: 3; line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
.kh-notif-main .m { display: flex; align-items: center; gap: 8px; font-size: 11px; color: var(--kh-text-3); }
|
||||
.kh-notif-main:focus-visible { outline: 2px solid var(--kh-accent); outline-offset: 2px; border-radius: 4px; }
|
||||
|
||||
/* ---- help (issue #32, mockup 011) ---- */
|
||||
.kh-help { display: grid; grid-template-columns: 260px minmax(0, 1fr); gap: var(--kh-gap); align-items: start; margin-top: var(--kh-gap); }
|
||||
.kh-help-index { padding: 8px; display: flex; flex-direction: column; gap: 1px; position: sticky; top: 0; max-height: calc(100vh - 190px); overflow: auto; }
|
||||
.kh-help-group { font-size: 10.5px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--kh-text-3); padding: 10px 8px 4px; }
|
||||
.kh-help-link { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: var(--kh-radius); color: var(--kh-text); text-decoration: none; font-size: 12.5px; }
|
||||
.kh-help-link svg.i { color: var(--kh-text-3); }
|
||||
.kh-help-link:hover { background: var(--kh-row-hover); }
|
||||
.kh-help-link.on { background: var(--kh-accent-soft); color: var(--kh-accent-text); font-weight: 600; }
|
||||
.kh-help-link.on svg.i { color: var(--kh-accent); }
|
||||
.kh-help-body { padding: 22px 26px 28px; font-size: 13.5px; line-height: 1.6; color: var(--kh-text); min-width: 0; }
|
||||
.kh-help-body h1 { font-size: 22px; font-weight: 650; margin: 0 0 10px; }
|
||||
.kh-help-body h2 { font-size: 16px; font-weight: 600; margin: 26px 0 8px; }
|
||||
.kh-help-body h3 { font-size: 14px; font-weight: 600; margin: 18px 0 6px; }
|
||||
.kh-help-body p, .kh-help-body ul, .kh-help-body ol { margin: 0 0 10px; }
|
||||
.kh-help-body ul, .kh-help-body ol { padding-left: 22px; }
|
||||
.kh-help-body li { margin: 2px 0; }
|
||||
.kh-help-body a { color: var(--kh-accent-text); }
|
||||
.kh-help-body code { font-family: var(--kh-font-mono, ui-monospace, Consolas, monospace); font-size: .92em; background: var(--kh-surface-3); border-radius: 4px; padding: 1px 4px; }
|
||||
.kh-help-body pre { background: var(--kh-surface-2); border: 1px solid var(--kh-border); border-radius: var(--kh-radius); padding: 10px 12px; overflow: auto; font-size: 12px; line-height: 1.45; }
|
||||
.kh-help-body pre code { background: none; padding: 0; }
|
||||
.kh-help-body img { max-width: 100%; border: 1px solid var(--kh-border); border-radius: var(--kh-radius); margin: 6px 0; }
|
||||
.kh-help-body hr { border: 0; border-top: 1px solid var(--kh-border); margin: 18px 0; }
|
||||
.kh-help-body .callout { margin: 10px 0; font-size: 13px; }
|
||||
.kh-help-body .callout p:last-child { margin-bottom: 0; }
|
||||
.kh-help-meta { font-size: 12px; color: var(--kh-text-3); margin-bottom: 14px; }
|
||||
.kh-help-meta p { margin: 0; }
|
||||
.kh-help-table { overflow-x: auto; margin: 6px 0 14px; border: 1px solid var(--kh-border); border-radius: var(--kh-radius); }
|
||||
.kh-help-table table.grid { width: 100%; }
|
||||
.kh-help-table table.grid td { white-space: normal; height: auto; padding: 6px 10px; max-width: none; vertical-align: top; }
|
||||
.kh-help-table table.grid th { white-space: normal; text-align: left; }
|
||||
/* Global search (mockup 009): the page a help section belongs to. */
|
||||
.palette .hit .d { color: var(--kh-text-3); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
|
||||
.palette .hit > span:first-of-type { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.palette .hit .d:last-child { margin-left: auto; }
|
||||
@media (max-width: 899px) { .kh-help { grid-template-columns: 1fr; } .kh-help-index { position: static; max-height: 240px; } }
|
||||
@@ -44,7 +44,15 @@
|
||||
document.addEventListener("keydown", function (e) {
|
||||
if (e.key !== "Escape" || e.defaultPrevented) return;
|
||||
const overlays = document.querySelectorAll(".overlay");
|
||||
if (overlays.length === 0 || (e.target.closest && e.target.closest(".overlay"))) return;
|
||||
if (overlays.length === 0) {
|
||||
// No dialog: a side panel closes too, but only when the focus is nowhere (a field keeps its own Escape).
|
||||
const drawers = document.querySelectorAll(".kh-drawer");
|
||||
if (drawers.length === 0 || e.target !== document.body) return;
|
||||
const shut = drawers[drawers.length - 1].querySelector(".kh-close");
|
||||
if (shut) shut.click();
|
||||
return;
|
||||
}
|
||||
if (e.target.closest && e.target.closest(".overlay")) return;
|
||||
const close = overlays[overlays.length - 1].querySelector(".kh-close");
|
||||
if (close) close.click();
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user