Last active
January 22, 2024 10:08
-
-
Save adnanzameer/44234218a09423891571f1ce61281ac8 to your computer and use it in GitHub Desktop.
Improving Alt Text for Images in TinyMCE and Optimizley CMS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Alloy.Models.Media; | |
using EPiServer.Core; | |
using EPiServer.Core.Html.StringParsing; | |
using EPiServer.ServiceLocation; | |
using EPiServer.Web; | |
using HtmlAgilityPack; | |
public static class XhtmlExtensions | |
{ | |
public static XhtmlString AdjustAltText(this XhtmlString xhtmlString) | |
{ | |
if (xhtmlString == null) return new XhtmlString(string.Empty); | |
var contextModeResolver = ServiceLocator.Current.GetInstance<IContextModeResolver>(); | |
if (contextModeResolver.CurrentMode == ContextMode.Edit) | |
{ | |
return xhtmlString; | |
} | |
var htmlString = xhtmlString.ToHtmlString(); | |
var doc = new HtmlDocument(); | |
doc.LoadHtml(htmlString); | |
// find all image tags | |
var images = doc.DocumentNode.SelectNodes("//img"); | |
if (images == null) | |
return xhtmlString; | |
var altTextDictionary = GenerateAltTextDictionary(xhtmlString.Fragments); | |
// Iterate through each image and replace alt="" or alt="name" with alt="alt text" to enhance accessibility. | |
foreach (var image in images) | |
{ | |
var src = image.Attributes["src"].Value; | |
if (string.IsNullOrWhiteSpace(src)) | |
continue; | |
if (src.StartsWith("~")) | |
{ | |
src = src[1..]; | |
} | |
var altText = image.Attributes["alt"].Value; | |
if (!string.IsNullOrWhiteSpace(altText)) | |
continue; | |
// If we have the alt text associated with a key, substitute it with the corresponding value from the dictionary. | |
// Keep in mind that the dictionary stores pairs of <Url, AltText>. | |
if (altTextDictionary.ContainsKey(src)) | |
{ | |
image.SetAttributeValue("alt", altTextDictionary[src]); | |
} | |
} | |
var outerHtml = doc.DocumentNode.OuterHtml; | |
return new XhtmlString(outerHtml); | |
} | |
private static Dictionary<string, string> GenerateAltTextDictionary(StringFragmentCollection htmlFragments) | |
{ | |
var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>(); | |
var altTextDictionary = new Dictionary<string, string>(); | |
foreach (var urlFragment in htmlFragments.Where(x => x is UrlFragment)) | |
{ | |
foreach (var guid in urlFragment.ReferencedPermanentLinkIds) | |
{ | |
if (!contentLoader.TryGet(guid, out ImageFile image) || string.IsNullOrEmpty(image.AltText)) | |
continue; | |
var key = $"/link/{image.ContentGuid:N}.aspx"; | |
if (!altTextDictionary.ContainsKey(key)) | |
{ | |
altTextDictionary.Add(key, image.AltText); | |
} | |
} | |
} | |
return altTextDictionary; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment