From 810935a68028ec9f7dc353a1b1fad8cb237a0615 Mon Sep 17 00:00:00 2001 From: dingo Date: Tue, 17 Mar 2026 08:26:57 -0400 Subject: [PATCH] =?UTF-8?q?Feature:=20card=20editor=20Assets=20tab=20?= =?UTF-8?q?=E2=80=94=20CDN=20picker=20+=20inline=20previews=20+=20model=20?= =?UTF-8?q?config?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Move Scale and Tint Colour from Basic tab into Assets tab under a new "3D Model Config" section (defaults: Scale=null→1.0, Tint=null) - Model3D assets: folder icon opens a CDN picker modal that lists all *.glb / *.gltf from the models/ bucket (cached after first load), filterable by filename, with a list-group UI - Art2D assets: same picker pattern but pulls from cardart/ bucket and shows image thumbnails in a responsive grid - Model3D inline 3D preview via appears below the URL when set; "Load animations" button invokes the same JS interop as CdnBrowser and populates an animation dropdown - Art2D inline image preview appears below the URL when set - Changing or uploading a URL clears cached animation state so the Load button reappears for the new file - JS guard (window.sorCdn = window.sorCdn || {}) prevents double- definition when CdnBrowser is also loaded in the same session Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- .../Components/Pages/Cards/CardEditor.razor | 392 ++++++++++++++++-- 1 file changed, 347 insertions(+), 45 deletions(-) diff --git a/Server/src/SOR.Admin/Components/Pages/Cards/CardEditor.razor b/Server/src/SOR.Admin/Components/Pages/Cards/CardEditor.razor index 226d43f..55b5409 100644 --- a/Server/src/SOR.Admin/Components/Pages/Cards/CardEditor.razor +++ b/Server/src/SOR.Admin/Components/Pages/Cards/CardEditor.razor @@ -1,10 +1,15 @@ @page "/cards/new" @page "/cards/{Id:guid}" @attribute [Authorize(Roles = "Admin,SuperAdmin")] +@implements IDisposable @inject CatalogDbContext Db @inject NavigationManager Nav @inject SOR.Cdn.ICdnClient Cdn +@inject Amazon.S3.IAmazonS3 S3 +@inject Microsoft.Extensions.Options.IOptions CdnOptionsAccessor +@inject IJSRuntime JS @using Microsoft.AspNetCore.Components.Forms +@using Amazon.S3.Model @(_isNew ? "New Card" : _card?.Name ?? "Card") – SOR Admin @@ -112,26 +117,6 @@ else - -
3D Model
-
- - -
null = 1.0 (no change)
-
-
- -
- - @if (!string.IsNullOrWhiteSpace(_card.ModelTintColor)) - { - - } -
-
Multiplicative hex tint over the model. Null = white (no tint).
-
} @@ -270,6 +255,29 @@ else else if (_activeTab == "Assets") { + +
+
3D Model Config
+
+ + +
Null = 1.0 (no change)
+
+
+ +
+ + @if (!string.IsNullOrWhiteSpace(_card.ModelTintColor)) + { + + } +
+
Multiplicative hex tint. Null = white (no tint).
+
+
+
Static Assets
@if (_uploadError != null) @@ -281,6 +289,7 @@ else @foreach (var asset in _card.Assets) { var capturedAsset = asset; + var mvId = $"mv_{asset.Id:N}";
@@ -291,9 +300,16 @@ else
+ +
+ @if (!string.IsNullOrEmpty(asset.CdnUrl)) { @@ -303,6 +319,8 @@ else
+ + @if (asset.AssetType == CardAssetType.Model3D) {
@@ -319,7 +337,50 @@ else
+ + @if (!string.IsNullOrEmpty(asset.CdnUrl)) + { + + +
+ @if (_assetAnimations.TryGetValue(asset.Id, out var anims) && anims.Count > 0) + { + + } + else + { + + } +
+ } } + + + @if (asset.AssetType == CardAssetType.Art2D && !string.IsNullOrEmpty(asset.CdnUrl)) + { + Art preview + } +
@@ -424,6 +485,102 @@ else } } + +@if (_pickerOpen) +{ + + +} + + + + @code { [Parameter] public Guid? Id { get; set; } @@ -439,6 +596,152 @@ else private readonly HashSet _uploading = new(); private string? _uploadError; + // ── CDN Picker ─────────────────────────────────────────────────────────── + + private bool _pickerOpen; + private bool _pickerLoading; + private Guid? _pickerAssetId; + private CardAssetType _pickerType; + private string _pickerFilter = ""; + private List _pickerItems = []; + private List _modelsCache = []; + private List _artCache = []; + private bool _modelsLoaded; + private bool _artLoaded; + + private IEnumerable FilteredPickerItems => + string.IsNullOrWhiteSpace(_pickerFilter) + ? _pickerItems + : _pickerItems.Where(i => i.ShortName.Contains(_pickerFilter, StringComparison.OrdinalIgnoreCase)); + + private sealed record CdnPickerItem(string Key, string ShortName, string PublicUrl); + + private async Task OpenPickerAsync(CardAsset asset) + { + _pickerAssetId = asset.Id; + _pickerType = asset.AssetType; + _pickerFilter = ""; + _pickerOpen = true; + _pickerLoading = true; + StateHasChanged(); + await LoadPickerItemsAsync(); + _pickerLoading = false; + } + + private async Task LoadPickerItemsAsync() + { + if (_pickerType == CardAssetType.Model3D) + { + if (!_modelsLoaded) + { + _modelsCache = await FetchCdnItemsAsync("models/", + k => k.EndsWith(".glb", StringComparison.OrdinalIgnoreCase) || + k.EndsWith(".gltf", StringComparison.OrdinalIgnoreCase)); + _modelsLoaded = true; + } + _pickerItems = _modelsCache; + } + else + { + if (!_artLoaded) + { + _artCache = await FetchCdnItemsAsync("cardart/", + k => k.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || + k.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) || + k.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || + k.EndsWith(".webp", StringComparison.OrdinalIgnoreCase)); + _artLoaded = true; + } + _pickerItems = _artCache; + } + } + + private async Task> FetchCdnItemsAsync(string prefix, Func filter) + { + var opts = CdnOptionsAccessor.Value; + var response = await S3.ListObjectsV2Async(new ListObjectsV2Request + { + BucketName = opts.BucketName, + Prefix = prefix, + MaxKeys = 1000, + }); + return response.S3Objects + .Where(o => !o.Key.EndsWith('/') && filter(o.Key)) + .Select(o => + { + var shortName = o.Key.Contains('/') ? o.Key[(o.Key.LastIndexOf('/') + 1)..] : o.Key; + return new CdnPickerItem(o.Key, shortName, BuildCdnUrl(opts, o.Key)); + }) + .OrderBy(i => i.ShortName) + .ToList(); + } + + private void SelectPickerItem(string publicUrl) + { + var asset = _card!.Assets.FirstOrDefault(a => a.Id == _pickerAssetId); + if (asset != null) + { + asset.CdnUrl = publicUrl; + if (string.IsNullOrEmpty(asset.MimeType)) + { + asset.MimeType = _pickerType == CardAssetType.Model3D + ? "model/gltf-binary" + : publicUrl.EndsWith(".webp", StringComparison.OrdinalIgnoreCase) ? "image/webp" : "image/jpeg"; + } + // Clear cached animations so "Load animations" button reappears for the new URL. + _assetAnimations.Remove(asset.Id); + _assetSelectedAnim.Remove(asset.Id); + } + _pickerOpen = false; + } + + private static string BuildCdnUrl(SOR.Cdn.CdnOptions opts, string key) + { + var baseUrl = opts.PublicBaseUrl.TrimEnd('/'); + var bucket = opts.BucketName.Trim('/'); + return baseUrl.EndsWith("/" + bucket, StringComparison.OrdinalIgnoreCase) + ? $"{baseUrl}/{key}" + : $"{baseUrl}/{bucket}/{key}"; + } + + // ── Model-viewer animation interop ─────────────────────────────────────── + + private readonly Dictionary> _assetAnimations = new(); + private readonly Dictionary _assetSelectedAnim = new(); + private Guid? _activePreviewAssetId; + private DotNetObjectReference? _dotnetRef; + + protected override void OnInitialized() + { + _dotnetRef = DotNetObjectReference.Create(this); + } + + [JSInvokable] + public void OnAnimationsLoaded(string[] animations) + { + if (_activePreviewAssetId == null) return; + var id = _activePreviewAssetId.Value; + _assetAnimations[id] = [.. animations]; + _assetSelectedAnim[id] = animations.FirstOrDefault() ?? ""; + InvokeAsync(StateHasChanged); + } + + private async Task InitModelViewerAsync(Guid assetId, string elementId) + { + _activePreviewAssetId = assetId; + await JS.InvokeVoidAsync("sorCdn.initModelViewerAnimations", elementId, _dotnetRef); + } + + private async Task SetModelAnimAsync(Guid assetId, string elementId, string animName) + { + _assetSelectedAnim[assetId] = animName; + await JS.InvokeVoidAsync("sorCdn.setModelAnimation", elementId, animName); + } + + public void Dispose() => _dotnetRef?.Dispose(); + + // ── Lifecycle ───────────────────────────────────────────────────────────── + protected override async Task OnInitializedAsync() { _isNew = Id == null; @@ -472,6 +775,8 @@ else } } + // ── Save / Delete ───────────────────────────────────────────────────────── + private async Task SaveAsync() { if (_card == null) return; @@ -481,12 +786,10 @@ else try { - // Flush genus input to array. _card.Genus = string.IsNullOrWhiteSpace(_genusInput) ? null : _genusInput.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - // Flush abilities JSON to the correct column. if (_card.CardType is CardType.Repentance or CardType.Instinct or CardType.Terramorpha) _card.EffectsJson = string.IsNullOrWhiteSpace(_abilitiesJson) ? null : _abilitiesJson; else @@ -495,9 +798,7 @@ else _card.UpdatedAt = DateTimeOffset.UtcNow; if (_isNew) - { Db.CardDefinitions.Add(_card); - } await Db.SaveChangesAsync(); _saveSuccess = true; @@ -526,6 +827,8 @@ else Nav.NavigateTo("/cards"); } + // ── Asset helpers ───────────────────────────────────────────────────────── + private void AddAsset(CardAssetType type) { var entry = new CardAsset @@ -541,10 +844,8 @@ else private void RemoveAsset(CardAsset asset) { _card!.Assets.Remove(asset); - // EF automatically marks Unchanged assets as Deleted when removed from a required - // relationship collection. For Added (unsaved) assets EF detaches them — calling - // Db.Remove on a detached entity re-attaches it as Deleted and causes a - // 0-rows-affected DbUpdateConcurrencyException on save. + _assetAnimations.Remove(asset.Id); + _assetSelectedAnim.Remove(asset.Id); } private void AddAnimation() @@ -557,10 +858,9 @@ else private void RemoveAnimation(CardAnimationBinding anim) { _card!.AnimationBindings.Remove(anim); - // Same as RemoveAsset: EF handles orphan deletion automatically. } - // ── CDN upload helpers ─────────────────────────────────────────────────── + // ── CDN upload helpers ──────────────────────────────────────────────────── private async Task UploadAssetAsync(CardAsset asset, InputFileChangeEventArgs e) { @@ -569,17 +869,19 @@ else StateHasChanged(); try { - var file = e.File; - var folder = $"cards/{_card!.Id}/assets"; - var stem = Path.GetFileNameWithoutExtension(file.Name); - var ext = Path.GetExtension(file.Name); + var file = e.File; + var folder = $"cards/{_card!.Id}/assets"; + var stem = Path.GetFileNameWithoutExtension(file.Name); + var ext = Path.GetExtension(file.Name); var uniqueName = $"{stem}_{DateTimeOffset.UtcNow:yyyyMMddHHmmss}{ext}"; await using var stream = file.OpenReadStream(maxAllowedSize: 100 * 1024 * 1024); var result = await Cdn.UploadAsync(folder, uniqueName, file.ContentType, stream); if (result.Success) { - asset.CdnUrl = result.PublicUrl ?? string.Empty; + asset.CdnUrl = result.PublicUrl ?? string.Empty; asset.MimeType = file.ContentType; + _assetAnimations.Remove(asset.Id); + _assetSelectedAnim.Remove(asset.Id); } else { @@ -634,7 +936,7 @@ else _ => "*/*", }; - // ── Flag descriptors (avoids 10 identical checkboxes) ─────────────────── + // ── Flag descriptors ────────────────────────────────────────────────────── private sealed record FlagDescriptor( string Label, @@ -643,14 +945,14 @@ else private readonly FlagDescriptor[] _unitFlags = [ - new("Can Attack", c => c.CanAttack ?? false, (c, v) => c.CanAttack = v), - new("Can Defend", c => c.CanDefend ?? false, (c, v) => c.CanDefend = v), - new("Can Be Attacked", c => c.CanBeAttacked ?? false, (c, v) => c.CanBeAttacked = v), - new("Can Be Blocked", c => c.CanBeBlocked ?? false, (c, v) => c.CanBeBlocked = v), - new("Can Move", c => c.CanMove ?? false, (c, v) => c.CanMove = v), - new("Can Be Obstructed",c => c.CanBeObstructed ?? false, (c, v) => c.CanBeObstructed = v), - new("Requires LOS", c => c.RequiresLos ?? false, (c, v) => c.RequiresLos = v), - new("Can Use Ability", c => c.CanUseAbility ?? false, (c, v) => c.CanUseAbility = v), - new("Can Be Sacrificed",c => c.CanBeSacrificed ?? false, (c, v) => c.CanBeSacrificed = v), + new("Can Attack", c => c.CanAttack ?? false, (c, v) => c.CanAttack = v), + new("Can Defend", c => c.CanDefend ?? false, (c, v) => c.CanDefend = v), + new("Can Be Attacked", c => c.CanBeAttacked ?? false, (c, v) => c.CanBeAttacked = v), + new("Can Be Blocked", c => c.CanBeBlocked ?? false, (c, v) => c.CanBeBlocked = v), + new("Can Move", c => c.CanMove ?? false, (c, v) => c.CanMove = v), + new("Can Be Obstructed", c => c.CanBeObstructed ?? false, (c, v) => c.CanBeObstructed = v), + new("Requires LOS", c => c.RequiresLos ?? false, (c, v) => c.RequiresLos = v), + new("Can Use Ability", c => c.CanUseAbility ?? false, (c, v) => c.CanUseAbility = v), + new("Can Be Sacrificed", c => c.CanBeSacrificed ?? false, (c, v) => c.CanBeSacrificed = v), ]; }