Feature: card editor Assets tab — CDN picker + inline previews + model config

- 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 <model-viewer> 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 <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-03-17 08:26:57 -04:00
co-authored by Claude Happy
parent 8ef264fd9b
commit 810935a680
@@ -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<SOR.Cdn.CdnOptions> CdnOptionsAccessor
@inject IJSRuntime JS
@using Microsoft.AspNetCore.Components.Forms
@using Amazon.S3.Model
<PageTitle>@(_isNew ? "New Card" : _card?.Name ?? "Card") – SOR Admin</PageTitle>
@@ -112,26 +117,6 @@ else
<label class="form-check-label" for="chkPublished">Published</label>
</div>
</div>
<div class="col-12"><h6 class="text-muted mt-2">3D Model</h6></div>
<div class="col-md-2">
<label class="form-label">Scale</label>
<input @bind="_card.ModelScale" type="number" step="0.01" min="0.01" class="form-control"
placeholder="1.0" />
<div class="form-text">null = 1.0 (no change)</div>
</div>
<div class="col-md-3">
<label class="form-label">Tint Colour</label>
<div class="input-group">
<input @bind="_card.ModelTintColor" class="form-control" placeholder="#RRGGBB" />
@if (!string.IsNullOrWhiteSpace(_card.ModelTintColor))
{
<span class="input-group-text"
style="background:@_card.ModelTintColor; width:36px; border:1px solid #ced4da;"></span>
}
</div>
<div class="form-text">Multiplicative hex tint over the model. Null = white (no tint).</div>
</div>
</div>
}
@@ -270,6 +255,29 @@ else
<!-- ── Assets ─────────────────────────────────────────────────────────── -->
else if (_activeTab == "Assets")
{
<!-- 3D Model Config (card-level, applies to all Model3D assets) -->
<div class="row g-3 mb-4 pb-3 border-bottom">
<div class="col-12"><h6 class="text-muted">3D Model Config</h6></div>
<div class="col-md-2">
<label class="form-label">Scale</label>
<input @bind="_card.ModelScale" type="number" step="0.01" min="0.01"
class="form-control" placeholder="1.0" />
<div class="form-text">Null = 1.0 (no change)</div>
</div>
<div class="col-md-3">
<label class="form-label">Tint Colour</label>
<div class="input-group">
<input @bind="_card.ModelTintColor" class="form-control" placeholder="#RRGGBB" />
@if (!string.IsNullOrWhiteSpace(_card.ModelTintColor))
{
<span class="input-group-text"
style="background:@_card.ModelTintColor;width:36px;border:1px solid #ced4da;"></span>
}
</div>
<div class="form-text">Multiplicative hex tint. Null = white (no tint).</div>
</div>
</div>
<h6 class="text-muted mb-3">Static Assets</h6>
@if (_uploadError != null)
@@ -281,6 +289,7 @@ else
@foreach (var asset in _card.Assets)
{
var capturedAsset = asset;
var mvId = $"mv_{asset.Id:N}";
<div class="col-md-6">
<div class="card">
<div class="card-body">
@@ -291,9 +300,16 @@ else
<i class="bi bi-trash"></i>
</button>
</div>
<!-- CDN URL + browse button -->
<div class="input-group input-group-sm mb-1">
<input @bind="asset.CdnUrl" class="form-control"
placeholder="https://cdn.sor.gg/…" />
<button class="btn btn-outline-secondary" type="button"
title="Pick from CDN"
@onclick="async () => await OpenPickerAsync(capturedAsset)">
<i class="bi bi-folder2-open"></i>
</button>
@if (!string.IsNullOrEmpty(asset.CdnUrl))
{
<a href="@asset.CdnUrl" target="_blank" class="btn btn-outline-secondary">
@@ -303,6 +319,8 @@ else
</div>
<input @bind="asset.MimeType" class="form-control form-control-sm mb-2"
placeholder="MIME type (e.g. image/webp, model/gltf-binary)" />
<!-- Model3D specific fields + 3D preview -->
@if (asset.AssetType == CardAssetType.Model3D)
{
<div class="row g-1 mb-2">
@@ -319,7 +337,50 @@ else
</div>
<input @bind="asset.ModelTintMaskUrl" class="form-control form-control-sm mb-2"
placeholder="Tint mask URL (CDN, optional)" />
@if (!string.IsNullOrEmpty(asset.CdnUrl))
{
<model-viewer id="@mvId"
src="@asset.CdnUrl"
camera-controls
auto-rotate
auto-rotate-delay="1000"
environment-image="neutral"
shadow-intensity="0.8"
style="width:100%;height:280px;background:#f5f5f5;border-radius:4px;margin-bottom:4px">
</model-viewer>
<div class="d-flex gap-2 mb-2 align-items-center">
@if (_assetAnimations.TryGetValue(asset.Id, out var anims) && anims.Count > 0)
{
<select class="form-select form-select-sm flex-grow-1"
value="@_assetSelectedAnim.GetValueOrDefault(capturedAsset.Id, "")"
@onchange="e => SetModelAnimAsync(capturedAsset.Id, mvId, e.Value?.ToString() ?? string.Empty)">
<option value="">– No animation –</option>
@foreach (var anim in anims)
{
<option value="@anim">@anim</option>
}
</select>
}
else
{
<button class="btn btn-sm btn-outline-secondary"
@onclick="async () => await InitModelViewerAsync(capturedAsset.Id, mvId)">
<i class="bi bi-play me-1"></i>Load animations
</button>
}
</div>
}
}
<!-- Art2D inline preview -->
@if (asset.AssetType == CardAssetType.Art2D && !string.IsNullOrEmpty(asset.CdnUrl))
{
<img src="@asset.CdnUrl" alt="Art preview"
class="img-fluid rounded mb-2"
style="max-height:200px;width:100%;object-fit:contain;background:#f5f5f5" />
}
<div class="form-check mb-2">
<input @bind="asset.IsAiGenerated" type="checkbox"
class="form-check-input" id="ai_asset_@asset.Id" />
@@ -424,6 +485,102 @@ else
}
}
<!-- ── CDN Picker Modal ────────────────────────────────────────────────────── -->
@if (_pickerOpen)
{
<div class="modal-backdrop fade show" style="z-index:1050"></div>
<div class="modal show d-block" tabindex="-1" style="z-index:1055">
<div class="modal-dialog modal-xl modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i class="bi bi-folder2-open me-2"></i>
Pick @(_pickerType == CardAssetType.Model3D ? "3D Model" : "Card Art")
</h5>
<button type="button" class="btn-close" @onclick="() => _pickerOpen = false"></button>
</div>
<div class="modal-body">
<input @bind="_pickerFilter" @bind:event="oninput"
class="form-control mb-3"
placeholder="Filter by filename…"
autofocus />
@if (_pickerLoading)
{
<div class="text-center py-5 text-muted">
<div class="spinner-border me-2"></div>Loading CDN files…
</div>
}
else if (!_pickerItems.Any())
{
<p class="text-center text-muted py-4">No files found.</p>
}
else if (_pickerType == CardAssetType.Art2D)
{
<div class="row g-2">
@foreach (var item in FilteredPickerItems)
{
var capturedItem = item;
<div class="col-6 col-sm-4 col-md-3 col-lg-2">
<div class="card h-100 p-1" style="cursor:pointer"
@onclick="() => SelectPickerItem(capturedItem.PublicUrl)">
<img src="@item.PublicUrl" alt="@item.ShortName"
style="height:100px;object-fit:contain;background:#f8f9fa" />
<div class="card-body p-1">
<small class="text-truncate d-block text-muted"
title="@item.Key">@item.ShortName</small>
</div>
</div>
</div>
}
</div>
}
else
{
<div class="list-group">
@foreach (var item in FilteredPickerItems)
{
var capturedItem = item;
<button class="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
@onclick="() => SelectPickerItem(capturedItem.PublicUrl)">
<span><i class="bi bi-box me-2 text-muted"></i>@item.ShortName</span>
<small class="text-muted ms-3 text-truncate" style="max-width:420px">@item.Key</small>
</button>
}
</div>
}
</div>
<div class="modal-footer">
<small class="text-muted me-auto">
@FilteredPickerItems.Count() of @_pickerItems.Count items
</small>
<button class="btn btn-secondary" @onclick="() => _pickerOpen = false">Cancel</button>
</div>
</div>
</div>
</div>
}
<!-- JS: model-viewer animation interop (guard prevents double-define if CdnBrowser also loaded it) -->
<script>
(function () {
var ns = window.sorCdn = window.sorCdn || {};
ns.initModelViewerAnimations = function (elementId, dotnetRef) {
var el = document.getElementById(elementId);
if (!el) { dotnetRef.invokeMethodAsync('OnAnimationsLoaded', []); return; }
var report = function () {
dotnetRef.invokeMethodAsync('OnAnimationsLoaded', Array.from(el.availableAnimations ?? []));
};
if (el.loaded) { report(); } else { el.addEventListener('load', report, { once: true }); }
};
ns.setModelAnimation = function (elementId, animName) {
var el = document.getElementById(elementId);
if (!el) return;
if (animName) { el.setAttribute('animation-name', animName); el.setAttribute('autoplay', ''); }
else { el.removeAttribute('animation-name'); el.removeAttribute('autoplay'); }
};
})();
</script>
@code {
[Parameter] public Guid? Id { get; set; }
@@ -439,6 +596,152 @@ else
private readonly HashSet<Guid> _uploading = new();
private string? _uploadError;
// ── CDN Picker ───────────────────────────────────────────────────────────
private bool _pickerOpen;
private bool _pickerLoading;
private Guid? _pickerAssetId;
private CardAssetType _pickerType;
private string _pickerFilter = "";
private List<CdnPickerItem> _pickerItems = [];
private List<CdnPickerItem> _modelsCache = [];
private List<CdnPickerItem> _artCache = [];
private bool _modelsLoaded;
private bool _artLoaded;
private IEnumerable<CdnPickerItem> 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<List<CdnPickerItem>> FetchCdnItemsAsync(string prefix, Func<string, bool> 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<Guid, List<string>> _assetAnimations = new();
private readonly Dictionary<Guid, string> _assetSelectedAnim = new();
private Guid? _activePreviewAssetId;
private DotNetObjectReference<CardEditor>? _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),
];
}