Initial Commit.

This commit is contained in:
Cameron Taylor 2022-06-10 17:12:43 -04:00
commit 077da21937
16 changed files with 2459 additions and 0 deletions

63
.gitattributes vendored Normal file
View File

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

363
.gitignore vendored Normal file
View File

@ -0,0 +1,363 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

25
HtmlFactory.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.2.32519.379
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HtmlFactory", "HtmlFactory\HtmlFactory.csproj", "{537C8BD1-E339-4231-BCDC-3B769A6091A2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{537C8BD1-E339-4231-BCDC-3B769A6091A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{537C8BD1-E339-4231-BCDC-3B769A6091A2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{537C8BD1-E339-4231-BCDC-3B769A6091A2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{537C8BD1-E339-4231-BCDC-3B769A6091A2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C712CC4B-2F5D-4E9A-836C-1096F6191379}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,33 @@
using System.Collections.Generic;
using System.Linq;
namespace HtmlFactory
{
internal static class AttributesComparer
{
public static bool Equals(IEnumerable<KeyValuePair<string, string>> leftAttributes,
IEnumerable<KeyValuePair<string, string>> rightAttributes, params string[] keysToExclude)
{
return Equals(leftAttributes, rightAttributes, EqualityComparer<string>.Default, keysToExclude);
}
private static bool Equals(IEnumerable<KeyValuePair<string, string>> leftAttributes,
IEnumerable<KeyValuePair<string, string>> rightAttributes,
IEqualityComparer<string> equalityComparer,
params string[] keysToExclude)
{
var leftDictionary = leftAttributes.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
var rightDictionary = rightAttributes.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
if (leftDictionary.Count != rightDictionary.Count) return false;
keysToExclude = keysToExclude ?? new string[0];
foreach (var keyValuePair in leftDictionary.Where(kvp => !keysToExclude.Contains(kvp.Key)))
{
if (!rightDictionary.TryGetValue(keyValuePair.Key, out var value)) return false;
if (!equalityComparer.Equals(keyValuePair.Value, value)) return false;
}
return true;
}
}
}

25
HtmlFactory/Enums.cs Normal file
View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace HtmlFactory
{
internal class Enums
{
}
}
namespace HtmlFactory.TagRenderCompat
{
public enum TagRenderMode
{
Normal = 0,
StartTag = 1,
EndTag = 2,
SelfClosing = 3
}
}

View File

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="HtmlAgilityPack" Version="1.11.43" />
<PackageReference Include="Microsoft.AspNetCore.Html.Abstractions" Version="2.2.0" />
</ItemGroup>
</Project>

1147
HtmlFactory/HtmlTag.cs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace HtmlFactory
{
/// <summary>
/// Contains a whole series of useful methods to manipulate common HTML attributes of an HtmlTag
/// </summary>
public static partial class HtmlTagExtensions
{
/// <summary>
/// Sets the name property. This is a shorthand for the <see cref="HtmlTag.Attribute" /> method with 'name' as the
/// attribute parameter value.
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="name">The value for the 'name' attribute</param>
/// <param name="replaceExisting">
/// A value indicating whether the existing attribute, if any, should have its value replaced
/// by the <paramref name="name" /> provided.
/// </param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Name(this HtmlTag htmlTag, string name, bool replaceExisting = true)
{
return htmlTag.Attribute("name", name, replaceExisting);
}
/// <summary>
/// Sets the title property. This is a shorthand for the <see cref="HtmlTag.Attribute" /> method with 'title' as the
/// attribute parameter value.
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="title">The value for the 'title' attribute</param>
/// <param name="replaceExisting">
/// A value indicating whether the existing attribute, if any, should have its value replaced
/// by the <paramref name="title" /> provided.
/// </param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Title(this HtmlTag htmlTag, string title, bool replaceExisting = true)
{
return htmlTag.Attribute("title", title, replaceExisting);
}
/// <summary>
/// Sets the id property. This is a shorthand for the <see cref="HtmlTag.Attribute" /> method with 'id' as the attribute
/// parameter value.
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="id">The value for the 'id' attribute</param>
/// <param name="replaceExisting">
/// A value indicating whether the existing attribute, if any, should have its value replaced
/// by the <paramref name="id" /> provided.
/// </param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Id(this HtmlTag htmlTag, string id, bool replaceExisting = true)
{
return htmlTag.Attribute("id", id, replaceExisting);
}
/// <summary>
/// Sets the type property. This is a shorthand for the <see cref="HtmlTag.Attribute" /> method with 'type' as the
/// attribute parameter value.
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="type">The value for the 'type' attribute</param>
/// <param name="replaceExisting">
/// A value indicating whether the existing attribute, if any, should have its value replaced
/// by the <paramref name="type" /> provided.
/// </param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Type(this HtmlTag htmlTag, string type, bool replaceExisting = true)
{
return htmlTag.Attribute("type", type, replaceExisting);
}
/// <summary>
/// Sets the value property. This is a shorthand for the <see cref="HtmlTag.Attribute" /> method with 'value' as the
/// attribute parameter value.
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="value">The value for the 'value' attribute</param>
/// <param name="replaceExisting">
/// A value indicating whether the existing attribute, if any, should have its value replaced
/// by the <paramref name="value" /> provided.
/// </param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Value(this HtmlTag htmlTag, string value, bool replaceExisting = true)
{
return htmlTag.Attribute("value", value, replaceExisting);
}
/// <summary>
/// Sets the href property. This is a shorthand for the <see cref="HtmlTag.Attribute" /> method with 'href' as the
/// attribute parameter value.
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="href">The value for the 'href' attribute</param>
/// <param name="replaceExisting">
/// A value indicating whether the existing attribute, if any, should have its value replaced
/// by the <paramref name="href" /> provided.
/// </param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Href(this HtmlTag htmlTag, string href, bool replaceExisting = true)
{
return htmlTag.Attribute("href", href, replaceExisting);
}
/// <summary>
/// Sets the src property. This is a shorthand for the <see cref="HtmlTag.Attribute" /> method with 'src' as the
/// attribute parameter value.
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="src">The value for the 'src' attribute</param>
/// <param name="replaceExisting">
/// A value indicating whether the existing attribute, if any, should have its value replaced
/// by the <paramref name="src" /> provided.
/// </param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Src(this HtmlTag htmlTag, string src, bool replaceExisting = true)
{
return htmlTag.Attribute("src", src, replaceExisting);
}
}
}

View File

@ -0,0 +1,107 @@
using System;
namespace HtmlFactory
{
public static partial class HtmlTagExtensions
{
/// <summary>
/// Sets the width style. This is a shorthand for calling the <see cref="HtmlTag.Style" /> method with the 'width' key
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="width">The width. This can be any valid css value for 'width'</param>
/// <param name="replaceExisting">A value indicating whether the existing width, if any, should be overriden or not</param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Width(this HtmlTag htmlTag, string width, bool replaceExisting = true)
{
if (width == null)
throw new ArgumentNullException(nameof(width));
return htmlTag.Style("width", width, replaceExisting);
}
/// <summary>
/// Sets the height style. This is a shorthand for calling the <see cref="HtmlTag.Style" /> method with the 'height' key
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="height">The height. This can be any valid css value for 'height'</param>
/// <param name="replaceExisting">A value indicating whether the existing height, if any, should be overriden or not</param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Height(this HtmlTag htmlTag, string height, bool replaceExisting = true)
{
if (height == null)
throw new ArgumentNullException(nameof(height));
return htmlTag.Style("height", height, replaceExisting);
}
/// <summary>
/// Sets the margin style. This is a shorthand for calling the <see cref="HtmlTag.Style" /> method with the 'margin' key
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="margin">The margin. This can be any valid css value for 'margin'</param>
/// <param name="replaceExisting">A value indicating whether the existing margin, if any, should be overriden or not</param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Margin(this HtmlTag htmlTag, string margin, bool replaceExisting = true)
{
if (margin == null)
throw new ArgumentNullException(nameof(margin));
return htmlTag.Style("margin", margin, replaceExisting);
}
/// <summary>
/// Sets the padding style. This is a shorthand for calling the <see cref="HtmlTag.Style" /> method with the 'padding'
/// key
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="padding">The padding. This can be any valid css value for 'padding'</param>
/// <param name="replaceExisting">A value indicating whether the existing padding, if any, should be overriden or not</param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Padding(this HtmlTag htmlTag, string padding, bool replaceExisting = true)
{
if (padding == null)
throw new ArgumentNullException(nameof(padding));
return htmlTag.Style("padding", padding, replaceExisting);
}
/// <summary>
/// Sets the color style. This is a shorthand for calling the <see cref="HtmlTag.Style" /> method with the 'color' key
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="color">The color. This can be any valid css value for 'color'</param>
/// <param name="replaceExisting">A value indicating whether the existing color, if any, should be overriden or not</param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Color(this HtmlTag htmlTag, string color, bool replaceExisting = true)
{
if (color == null)
throw new ArgumentNullException(nameof(color));
return htmlTag.Style("color", color, replaceExisting);
}
/// <summary>
/// Sets the text-align style. This is a shorthand for calling the <see cref="HtmlTag.Style" /> method with the
/// 'text-align' key
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="textAlign">The text alignment. This can be any valid css value for 'text-align'</param>
/// <param name="replaceExisting">A value indicating whether the existing text-align, if any, should be overriden or not</param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag TextAlign(this HtmlTag htmlTag, string textAlign, bool replaceExisting = true)
{
if (textAlign == null)
throw new ArgumentNullException(nameof(textAlign));
return htmlTag.Style("text-align", textAlign, replaceExisting);
}
/// <summary>
/// Sets the border style. This is a shorthand for calling the <see cref="HtmlTag.Style" /> method with the 'border' key
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="border">The border. This can be any valid css value for 'border'</param>
/// <param name="replaceExisting">A value indicating whether the existing border, if any, should be overriden or not</param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Border(this HtmlTag htmlTag, string border, bool replaceExisting = true)
{
if (border == null)
throw new ArgumentNullException(nameof(border));
return htmlTag.Style("border", border, replaceExisting);
}
}
}

View File

@ -0,0 +1,39 @@
using System.IO;
using System.Text.Encodings.Web;
namespace HtmlFactory
{
public static partial class HtmlTagExtensions
{
/// <summary>
/// Gets the HTML stripped content of this <see cref="HtmlTag"/>
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag"/></param>
/// <returns>The HTML stripped contents.</returns>
public static string Text(this HtmlTag htmlTag)
{
if (htmlTag == null)
return string.Empty;
using (var writer = new StringWriter())
{
Write(htmlTag, writer, HtmlEncoder.Default);
return writer.ToString();
}
}
private static void Write(HtmlTag htmlTag, TextWriter writer, HtmlEncoder encoder)
{
foreach (var content in htmlTag.Contents)
{
if (content is HtmlText text)
{
text.WriteTo(writer, encoder);
}
else if (content is HtmlTag tag)
{
Write(tag, writer, encoder);
}
}
}
}
}

View File

@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace HtmlFactory
{
public static partial class HtmlTagExtensions
{
/// <summary>
/// Sets the 'checked' attribute to 'checked' if <paramref name="checked" /> is true or removes the attribute if
/// <paramref name="checked" /> is false
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="checked">
/// A value indicating whether this tag should have the attribute 'checked' with value 'checked' or
/// not.
/// </param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Checked(this HtmlTag htmlTag, bool @checked)
{
return htmlTag.ToggleAttribute("checked", @checked);
}
/// <summary>
/// Sets the 'disabled' attribute to 'disabled' if <paramref name="disabled" /> is true or removes the attribute if
/// <paramref name="disabled" /> is false
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="disabled">
/// A value indicating whether this tag should have the attribute 'disabled' with value 'disabled'
/// or not.
/// </param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Disabled(this HtmlTag htmlTag, bool disabled)
{
return htmlTag.ToggleAttribute("disabled", disabled);
}
/// <summary>
/// Sets the 'selected' attribute to 'selected' if <paramref name="selected" /> is true or removes the attribute if
/// <paramref name="selected" /> is false
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="selected">
/// A value indicating whether this tag should have the attribute 'selected' with value 'selected'
/// or not.
/// </param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Selected(this HtmlTag htmlTag, bool selected)
{
return htmlTag.ToggleAttribute("selected", selected);
}
/// <summary>
/// Sets the 'readonly' attribute to 'readonly' if <paramref name="readonly" /> is true or removes the attribute if
/// <paramref name="readonly" /> is false
/// </summary>
/// <param name="htmlTag">This <see cref="HtmlTag" /></param>
/// <param name="readonly">
/// A value indicating whether this tag should have the attribute 'readonly' with value 'readonly'
/// or not.
/// </param>
/// <returns>This <see cref="HtmlTag" /></returns>
public static HtmlTag Readonly(this HtmlTag htmlTag, bool @readonly)
{
return htmlTag.ToggleAttribute("readonly", @readonly);
}
}
}

281
HtmlFactory/HtmlTags.cs Normal file
View File

@ -0,0 +1,281 @@
using System;
using System.Collections.Generic;
using System.Text;
using HtmlFactory.TagRenderCompat;
namespace HtmlFactory
{
/// <summary>
/// Provides convenience properties to create instances of <see cref="HtmlTag" />
/// </summary>
public static class HtmlTags
{
public static HtmlTag A => new HtmlTag("a");
public static HtmlTag Abbr => new HtmlTag("abbr");
public static HtmlTag Address => new HtmlTag("address");
public static HtmlTag Area => new HtmlTag("area").Render(TagRenderMode.SelfClosing);
public static HtmlTag Article => new HtmlTag("article");
public static HtmlTag Aside => new HtmlTag("aside");
public static HtmlTag Audio => new HtmlTag("audio");
public static HtmlTag B => new HtmlTag("b");
public static HtmlTag Base => new HtmlTag("base").Render(TagRenderMode.SelfClosing);
public static HtmlTag Bdi => new HtmlTag("bdi");
public static HtmlTag Bdo => new HtmlTag("bdo");
public static HtmlTag BlockQuote => new HtmlTag("blockquote");
public static HtmlTag Body => new HtmlTag("body");
public static HtmlTag Br => new HtmlTag("br").Render(TagRenderMode.SelfClosing);
public static HtmlTag Button => new HtmlTag("button");
public static HtmlTag Canvas => new HtmlTag("canvas");
public static HtmlTag Caption => new HtmlTag("caption");
public static HtmlTag Cite => new HtmlTag("cite");
public static HtmlTag Code => new HtmlTag("code");
public static HtmlTag Col => new HtmlTag("col").Render(TagRenderMode.SelfClosing);
public static HtmlTag ColGroup => new HtmlTag("colgroup");
public static HtmlTag Data => new HtmlTag("data");
public static HtmlTag DataList => new HtmlTag("datalist");
public static HtmlTag Dd => new HtmlTag("dd");
public static HtmlTag Del => new HtmlTag("del");
public static HtmlTag Details => new HtmlTag("details");
public static HtmlTag Dfn => new HtmlTag("dfn");
public static HtmlTag Div => new HtmlTag("div");
public static HtmlTag Dl => new HtmlTag("dl");
public static HtmlTag Dt => new HtmlTag("dt");
public static HtmlTag Em => new HtmlTag("em");
public static HtmlTag Embed => new HtmlTag("embed").Render(TagRenderMode.SelfClosing);
public static HtmlTag Fieldset => new HtmlTag("fieldset");
public static HtmlTag FigCaption => new HtmlTag("figcaption");
public static HtmlTag Figure => new HtmlTag("figure");
public static HtmlTag Footer => new HtmlTag("footer");
public static HtmlTag Form => new HtmlTag("form");
public static HtmlTag H1 => new HtmlTag("h1");
public static HtmlTag H2 => new HtmlTag("h2");
public static HtmlTag H3 => new HtmlTag("h3");
public static HtmlTag H4 => new HtmlTag("h4");
public static HtmlTag H5 => new HtmlTag("h5");
public static HtmlTag H6 => new HtmlTag("h6");
public static HtmlTag Head => new HtmlTag("head");
public static HtmlTag Header => new HtmlTag("header");
public static HtmlTag Hr => new HtmlTag("hr").Render(TagRenderMode.SelfClosing);
public static HtmlTag Html => new HtmlTag("html");
public static HtmlTag I => new HtmlTag("i");
public static HtmlTag Iframe => new HtmlTag("iframe");
public static HtmlTag Img => new HtmlTag("img").Render(TagRenderMode.SelfClosing);
public static HtmlTag Ins => new HtmlTag("ins");
public static HtmlTag Kbd => new HtmlTag("kbd");
public static HtmlTag Keygen => new HtmlTag("keygen");
public static HtmlTag Label => new HtmlTag("label");
public static HtmlTag Legend => new HtmlTag("legend");
public static HtmlTag Li => new HtmlTag("li");
public static HtmlTag Link => new HtmlTag("link").Render(TagRenderMode.SelfClosing);
public static HtmlTag Main => new HtmlTag("main");
public static HtmlTag Map => new HtmlTag("map");
public static HtmlTag Mark => new HtmlTag("mark");
public static HtmlTag Menu => new HtmlTag("menu");
public static HtmlTag MenuItem => new HtmlTag("menuitem");
public static HtmlTag Meta => new HtmlTag("meta").Render(TagRenderMode.SelfClosing);
public static HtmlTag Meter => new HtmlTag("meter");
public static HtmlTag Nav => new HtmlTag("nav");
public static HtmlTag NoScript => new HtmlTag("noscript");
public static HtmlTag Object => new HtmlTag("object");
public static HtmlTag Ol => new HtmlTag("ol");
public static HtmlTag OptGroup => new HtmlTag("optgroup");
public static HtmlTag Option => new HtmlTag("option");
public static HtmlTag Output => new HtmlTag("output");
public static HtmlTag P => new HtmlTag("p");
public static HtmlTag Param => new HtmlTag("param").Render(TagRenderMode.SelfClosing);
public static HtmlTag Pre => new HtmlTag("pre");
public static HtmlTag Progress => new HtmlTag("progress");
public static HtmlTag Q => new HtmlTag("q");
public static HtmlTag Rp => new HtmlTag("rp");
public static HtmlTag Rt => new HtmlTag("rt");
public static HtmlTag Ruby => new HtmlTag("ruby");
public static HtmlTag S => new HtmlTag("s");
public static HtmlTag Samp => new HtmlTag("samp");
public static HtmlTag Script => new HtmlTag("script");
public static HtmlTag Section => new HtmlTag("section");
public static HtmlTag Select => new HtmlTag("select");
public static HtmlTag Small => new HtmlTag("small");
public static HtmlTag Source => new HtmlTag("source").Render(TagRenderMode.SelfClosing);
public static HtmlTag Span => new HtmlTag("span");
public static HtmlTag Strong => new HtmlTag("strong");
public static HtmlTag Style => new HtmlTag("style");
public static HtmlTag Sub => new HtmlTag("sub");
public static HtmlTag Summary => new HtmlTag("summary");
public static HtmlTag Sup => new HtmlTag("sup");
public static HtmlTag Table => new HtmlTag("table");
public static HtmlTag Tbody => new HtmlTag("tbody");
public static HtmlTag Td => new HtmlTag("td");
public static HtmlTag Template => new HtmlTag("template");
public static HtmlTag Textarea => new HtmlTag("textarea");
public static HtmlTag Tfoot => new HtmlTag("tfoot");
public static HtmlTag Th => new HtmlTag("th");
public static HtmlTag Thead => new HtmlTag("thead");
public static HtmlTag Time => new HtmlTag("time");
public static HtmlTag Title => new HtmlTag("title");
public static HtmlTag Tr => new HtmlTag("tr");
public static HtmlTag Track => new HtmlTag("track").Render(TagRenderMode.SelfClosing);
public static HtmlTag U => new HtmlTag("u");
public static HtmlTag Ul => new HtmlTag("ul");
public static HtmlTag Var => new HtmlTag("var");
public static HtmlTag Video => new HtmlTag("video");
public static HtmlTag Wbr => new HtmlTag("wbr").Render(TagRenderMode.SelfClosing);
public static class Input
{
public static HtmlTag Button => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("button");
public static HtmlTag CheckBox => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("checkbox");
public static HtmlTag Color => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("color");
public static HtmlTag Date => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("date");
public static HtmlTag DateTime => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("datetime");
public static HtmlTag DateTimeLocal => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("datetime-local");
public static HtmlTag Email => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("email");
public static HtmlTag File => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("file");
public static HtmlTag Hidden => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("hidden");
public static HtmlTag Image => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("image");
public static HtmlTag Month => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("month");
public static HtmlTag Number => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("number");
public static HtmlTag Password => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("password");
public static HtmlTag Radio => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("radio");
public static HtmlTag Range => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("range");
public static HtmlTag Reset => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("reset");
public static HtmlTag Search => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("search");
public static HtmlTag Submit => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("submit");
public static HtmlTag Tel => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("tel");
public static HtmlTag Text => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("text");
public static HtmlTag Time => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("time");
public static HtmlTag Url => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("url");
public static HtmlTag Week => new HtmlTag("input").Render(TagRenderMode.SelfClosing).Type("week");
}
}
}

100
HtmlFactory/HtmlText.cs Normal file
View File

@ -0,0 +1,100 @@
using System.Collections.Generic;
using System.IO;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Html;
namespace HtmlFactory
{
/// <summary>
/// Represents a text node that has an optional parent and some text
/// </summary>
public class HtmlText : IHtmlElement
{
private readonly IHtmlContent _content = null;
private string _rawinput;
private bool IsEncoded = false;
public string Tagname => null;
public Dictionary<string, string> Attributes { get => null; set { } }
public List<IHtmlElement> Contents { get => null; set { } }
/// <summary>
/// Initializes a new instance of <see cref="HtmlText" />
/// </summary>
/// <param name="text">The text that still needs to be encoded</param>
public HtmlText(string text, bool inToBeEncoded = true)
{
_rawinput = text;
IsEncoded = !inToBeEncoded;
}
/// <summary>
/// Initializes a new instance of <see cref="HtmlText" />
/// </summary>
/// <param name="htmlString">The already encoded HTML string</param>
public HtmlText(HtmlString htmlString)
{
_content = htmlString ?? new HtmlString(string.Empty);
}
/// <inheritdoc />
public void WriteTo(TextWriter writer, HtmlEncoder encoder)
{
if (_content == null && !string.IsNullOrEmpty(_rawinput))
{
if (IsEncoded)
{
writer.Write(_rawinput);
}
else
{
encoder.Encode(writer, _rawinput);
}
}
else
{
_content.WriteTo(writer, encoder);
}
}
/// <inheritdoc />
public override string ToString()
{
using (var writer = new StringWriter())
{
WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
private bool Equals(HtmlText other)
{
return string.Equals(ToString(), other.ToString());
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != GetType())
return false;
return Equals((HtmlText)obj);
}
/// <inheritdoc />
public override int GetHashCode()
{
return ToString().GetHashCode();
}
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Html;
namespace HtmlFactory
{
/// <summary>
/// Contains utility methods to convert <see cref="IHtmlContent"/> into other things, such as an <see cref="HtmlTag"/>.
/// </summary>
public static class IHtmlContentExtensions
{
/// <summary>
/// Renders this html content to an HTML string using the default HTML encoder
/// </summary>
/// <param name="htmlContent">The HTML content to render</param>
/// <returns>A string representation of the HTML content</returns>
public static string ToHtmlString(this IHtmlContent htmlContent)
{
using (var writer = new StringWriter())
{
htmlContent.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
/// <summary>
/// Parses the provided HTML content and tries to extract an HTML tag from it.
///
/// </summary>
/// <param name="htmlContent"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public static HtmlTag ToHtmlTag(this IHtmlContent htmlContent)
{
var htmlTags = HtmlTag.ParseAll(htmlContent).OfType<HtmlTag>().ToList();
if (htmlTags.Count > 1) throw new ArgumentException($"Multiple tags parsed from html: {Environment.NewLine}" +
$"{string.Join(Environment.NewLine, htmlTags.Select(t => t.ToString()))}");
return htmlTags.SingleOrDefault();
}
}
}

15
HtmlFactory/Interfaces.cs Normal file
View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Html;
namespace HtmlFactory
{
public interface IHtmlElement : IHtmlContent
{
string Tagname { get; }
Dictionary<string, string> Attributes { get; set; }
List<IHtmlElement> Contents { get; set; }
}
}

View File

@ -0,0 +1,11 @@

Install-Package Microsoft.AspNetCore.Html.Abstractions -Version 2.2.0
Install-Package HtmlAgilityPack -Version 1.11.43