Skip to content

Commit

Permalink
Fixes #59 #55
Browse files Browse the repository at this point in the history
  • Loading branch information
Rick Butterfield committed Aug 7, 2024
1 parent bcecce0 commit fd4689d
Show file tree
Hide file tree
Showing 28 changed files with 475 additions and 59 deletions.
9 changes: 9 additions & 0 deletions src/Umbraco.Cms.13.x/Umbraco.Cms.13.x.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@
<Nullable>enable</Nullable>
<RootNamespace>Umbraco.Cms._13.x</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Content Remove="appsettings-schema.blockpreview.json" />
</ItemGroup>
<ItemGroup>
<None Include="appsettings-schema.blockpreview.json">
<PackagePath>\</PackagePath>
<Pack>true</Pack>
</None>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Umbraco.BlockGrid.Example.Website" Version="1.0.2" />
Expand Down
21 changes: 21 additions & 0 deletions src/Umbraco.Community.BlockPreview.SchemaGenerator/AppSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Collections.Generic;

namespace Umbraco.Community.BlockPreview.SchemaGenerator
{
internal class AppSettings
{
public BlockPreviewDefinition BlockPreview { get; set; }

internal class BlockPreviewDefinition
{
public ViewLocations ViewLocations { get; set; }
}
}

public class ViewLocations
{
public List<string> BlockList { get; set; }
public List<string> BlockGrid { get; set; }
public List<string> RichText { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using NJsonSchema.Generation;
using NJsonSchema.NewtonsoftJson.Generation;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Umbraco.Community.BlockPreview.SchemaGenerator
{
internal class BlockPreviewSchemaGenerator
{
private readonly JsonSchemaGenerator _schemaGenerator;

public BlockPreviewSchemaGenerator()
{
_schemaGenerator = new JsonSchemaGenerator(new BlockPreviewSchemaGeneratorSettings());
}

public string Generate()
{
var blockPreviewSchema = GenerateBlockPreviewSchema();
return blockPreviewSchema.ToString();
}

private JObject GenerateBlockPreviewSchema()
{
var schema = _schemaGenerator.Generate(typeof(AppSettings));
return JsonConvert.DeserializeObject<JObject>(schema.ToJson());
}
}

internal class BlockPreviewSchemaGeneratorSettings : NewtonsoftJsonSchemaGeneratorSettings
{
public BlockPreviewSchemaGeneratorSettings()
{
AlwaysAllowAdditionalObjectProperties = true;
SerializerSettings = new JsonSerializerSettings()
{
ContractResolver = new WritablePropertiesOnlyResolver(),
};
DefaultReferenceTypeNullHandling = ReferenceTypeNullHandling.NotNull;
SchemaNameGenerator = new NamespacePrefixedSchemaNameGenerator();
SerializerSettings.Converters.Add(new StringEnumConverter());
IgnoreObsoleteProperties = true;
GenerateExamples = true;
}

private class WritablePropertiesOnlyResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
var result = props.Where(p => p.Writable).ToList();
result.ForEach(x => x.PropertyName = ToPascalCase(x.PropertyName));
return result;
}

/// <summary>
/// we serialize everything camel case inside uSync but the settings are actually PascalCase
/// for appsettings.json, so we need to PascalCase each property.
/// </summary>
private string ToPascalCase(string str)
{
if (!string.IsNullOrEmpty(str))
{
return char.ToUpperInvariant(str[0]) + str.Substring(1);
}

return str;
}
}
}

internal class NamespacePrefixedSchemaNameGenerator : DefaultSchemaNameGenerator
{
public override string Generate(Type type) => type.Namespace.Replace(".", string.Empty) + base.Generate(type);
}
}
12 changes: 12 additions & 0 deletions src/Umbraco.Community.BlockPreview.SchemaGenerator/Options.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using CommandLine;

namespace Umbraco.Community.BlockPreview.SchemaGenerator
{
internal class Options
{
[Option('o', "outputFile", Required = false,
HelpText = "",
Default = "..\\..\\..\\..\\Umbraco.Community.BlockPreview\\appsettings-schema.blockpreview.json")]
public string OutputFile { get; set; } = "..\\..\\..\\..\\Umbraco.Community.BlockPreview\\appsettings-schema.blockpreview.json";
}
}
39 changes: 39 additions & 0 deletions src/Umbraco.Community.BlockPreview.SchemaGenerator/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using CommandLine;
using System;
using System.IO;
using System.Threading.Tasks;

namespace Umbraco.Community.BlockPreview.SchemaGenerator
{
internal class Program
{
public static async Task Main(string[] args)
{
try
{
await Parser.Default.ParseArguments<Options>(args)
.WithParsedAsync(Execute);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}

private static async Task Execute(Options options)
{
var generator = new BlockPreviewSchemaGenerator();

var schema = generator.Generate();

var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, options.OutputFile));
Console.WriteLine("Path to use {0}", path);
Directory.CreateDirectory(Path.GetDirectoryName(path));
Console.WriteLine("Ensured directory exists");
await File.WriteAllTextAsync(path, schema);

Console.WriteLine("File written at {0}", path);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>disable</Nullable>

</PropertyGroup>

<ItemGroup>
<PackageReference Include="NJsonSchema" Version="11.0.2" />
<PackageReference Include="NJsonSchema.NewtonsoftJson" Version="11.0.2" />
<PackageReference Include="CommandLineParser" Version="2.9.1" />
</ItemGroup>

<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<DocumentationFile>bin\Release\$(TargetFramework)\Umbraco.Community.BlockPreview.SchemaGenerator.xml</DocumentationFile>
</PropertyGroup>

<Target Name="CopyPackagesXml" BeforeTargets="Build">
<ItemGroup>
<PackageReferenceFiles Include="$(NugetPackageRoot)%(PackageReference.Identity)\%(PackageReference.Version)%(PackageReference.CopyToOutputDirectory)\lib\**\*.xml" />
</ItemGroup>
<Copy SourceFiles="@(PackageReferenceFiles)" DestinationFolder="$(OutDir)" />
</Target>

</Project>
6 changes: 6 additions & 0 deletions src/Umbraco.Community.BlockPreview.sln
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Umbraco.Cms.11.x", "Umbraco
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Umbraco.Cms.13.x", "Umbraco.Cms.13.x\Umbraco.Cms.13.x.csproj", "{782BE0CF-6D6D-42B3-82F6-8415CAB3B911}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Umbraco.Community.BlockPreview.SchemaGenerator", "Umbraco.Community.BlockPreview.SchemaGenerator\Umbraco.Community.BlockPreview.SchemaGenerator.csproj", "{924CBE49-2AC7-4B8B-8977-967BB3221F36}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -33,6 +35,10 @@ Global
{782BE0CF-6D6D-42B3-82F6-8415CAB3B911}.Debug|Any CPU.Build.0 = Debug|Any CPU
{782BE0CF-6D6D-42B3-82F6-8415CAB3B911}.Release|Any CPU.ActiveCfg = Release|Any CPU
{782BE0CF-6D6D-42B3-82F6-8415CAB3B911}.Release|Any CPU.Build.0 = Release|Any CPU
{924CBE49-2AC7-4B8B-8977-967BB3221F36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{924CBE49-2AC7-4B8B-8977-967BB3221F36}.Debug|Any CPU.Build.0 = Debug|Any CPU
{924CBE49-2AC7-4B8B-8977-967BB3221F36}.Release|Any CPU.ActiveCfg = Release|Any CPU
{924CBE49-2AC7-4B8B-8977-967BB3221F36}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
3 changes: 3 additions & 0 deletions src/Umbraco.Community.BlockPreview/BlockPreviewComposer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ public void Compose(IUmbracoBuilder builder)
builder.Services.AddScoped<IBackOfficePreviewService, BackOfficeListPreviewService>();
builder.Services.AddScoped<IBackOfficeListPreviewService, BackOfficeListPreviewService>();
builder.Services.AddScoped<IBackOfficeGridPreviewService, BackOfficeGridPreviewService>();
#if NET8_0
builder.Services.AddScoped<IBackOfficeRtePreviewService, BackOfficeRtePreviewService>();
#endif
builder.Services.AddScoped<ContextCultureService>();

builder.Services.ConfigureOptions<BlockViewEngineOptionsSetup>();
Expand Down
34 changes: 27 additions & 7 deletions src/Umbraco.Community.BlockPreview/BlockPreviewOptions.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,35 @@
using System.Collections.Generic;
using System.Linq;

namespace Umbraco.Community.BlockPreview
namespace Umbraco.Community.BlockPreview
{
public class BlockPreviewOptions
{
public ViewLocations ViewLocations { get; set; }

public List<string>? GetAllViewLocations()
{
var locations = new List<string>();

if (ViewLocations.BlockGrid?.Any() == true)
locations.AddRange(ViewLocations.BlockGrid);

if (ViewLocations.BlockList?.Any() == true)
locations.AddRange(ViewLocations.BlockList);

if (ViewLocations.RichText?.Any() == true)
locations.AddRange(ViewLocations.RichText);

locations.Add(Constants.DefaultViewLocations.BlockGrid);
locations.Add(Constants.DefaultViewLocations.BlockList);
locations.Add(Constants.DefaultViewLocations.RichText);

locations = locations.Distinct().ToList();

return locations;
}

public BlockPreviewOptions()
{
ViewLocations = new ViewLocations();
}

public ViewLocations ViewLocations { get; set; }
}

public class ViewLocations
Expand All @@ -19,12 +38,13 @@ public ViewLocations()
{
BlockList = new List<string>();
BlockGrid = new List<string>();
RichText = new List<string>();
}

public List<string> BlockList { get; set; }

public List<string> BlockGrid { get; set; }

public IEnumerable<string> GetAll() => BlockList.Concat(BlockGrid);
public List<string> RichText { get; set; }
}
}
1 change: 1 addition & 0 deletions src/Umbraco.Community.BlockPreview/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ public static partial class DefaultViewLocations
{
public static string BlockGrid => "/Views/Partials/blockgrid/Components/{0}.cshtml";
public static string BlockList => "/Views/Partials/blocklist/Components/{0}.cshtml";
public static string RichText => "/Views/Partials/richtext/Components/{0}.cshtml";
}

public static partial class Configuration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public class BlockPreviewApiController : UmbracoAuthorizedJsonController
private readonly ContextCultureService _contextCultureService;
private readonly IBackOfficeListPreviewService _backOfficeListPreviewService;
private readonly IBackOfficeGridPreviewService _backOfficeGridPreviewService;
private readonly IBackOfficeRtePreviewService _backOfficeRtePreviewService;
private readonly ILocalizationService _localizationService;
private readonly ISiteDomainMapper _siteDomainMapper;

Expand All @@ -41,6 +42,7 @@ public BlockPreviewApiController(
ContextCultureService contextCultureSwitcher,
IBackOfficeListPreviewService backOfficeListPreviewService,
IBackOfficeGridPreviewService backOfficeGridPreviewService,
IBackOfficeRtePreviewService backOfficeRtePreviewService,
ILocalizationService localizationService,
ISiteDomainMapper siteDomainMapper)
{
Expand All @@ -50,6 +52,7 @@ public BlockPreviewApiController(
_contextCultureService = contextCultureSwitcher;
_backOfficeListPreviewService = backOfficeListPreviewService;
_backOfficeGridPreviewService = backOfficeGridPreviewService;
_backOfficeRtePreviewService = backOfficeRtePreviewService;
_localizationService = localizationService;
_siteDomainMapper = siteDomainMapper;
}
Expand All @@ -68,6 +71,7 @@ public async Task<IActionResult> PreviewMarkup(
[FromQuery] int pageId = 0,
[FromQuery] string blockEditorAlias = "",
[FromQuery] bool isGrid = false,
[FromQuery] bool isRte = false,
[FromQuery] string culture = "")
{
string markup;
Expand All @@ -91,9 +95,18 @@ public async Task<IActionResult> PreviewMarkup(

await SetupPublishedRequest(page, currentCulture);

markup = isGrid ?
await _backOfficeGridPreviewService.GetMarkupForBlock(page, data, blockEditorAlias, ControllerContext, currentCulture) :
await _backOfficeListPreviewService.GetMarkupForBlock(page, data, blockEditorAlias, ControllerContext, currentCulture);
if (isGrid)
{
markup = await _backOfficeGridPreviewService.GetMarkupForBlock(page, data, blockEditorAlias, ControllerContext, currentCulture);
}
else if (isRte)
{
markup = await _backOfficeRtePreviewService.GetMarkupForBlock(page, data, blockEditorAlias, ControllerContext, currentCulture);
}
else
{
markup = await _backOfficeListPreviewService.GetMarkupForBlock(page, data, blockEditorAlias, ControllerContext, currentCulture);
}
}
catch (Exception ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Umbraco.Community.BlockPreview.Extensions
{
public static class BlockGridPreviewTemplateExtensions
{
private static readonly string AREA_TEMPLATE = "<umb-block-grid-render-area-slots></umb-block-grid-render-area-slots>";
private static readonly string AREA_TEMPLATE = "<umb-block-grid-render-area-slots></umb-block-grid-render-area-slots><button ng-click=\"vm.blockEditorApi.requestShowCreate(vm.parentBlock, vm.areaKey, vm.entries.length, $event)\">Add content</button>";

public static async Task<IHtmlContent> GetPreviewBlockGridItemAreasHtmlAsync(this IHtmlHelper html, BlockGridItem item, string template = BlockGridTemplateExtensions.DefaultItemAreasTemplate)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public static IUmbracoBuilder AddBlockPreviewOptions(this IUmbracoBuilder builde
{
x.ViewLocations.BlockGrid.Add(Constants.DefaultViewLocations.BlockGrid);
x.ViewLocations.BlockList.Add(Constants.DefaultViewLocations.BlockList);
x.ViewLocations.RichText.Add(Constants.DefaultViewLocations.RichText);
})
.ValidateDataAnnotations()
.ValidateOnStart();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Umbraco.Community.BlockPreview.Interfaces
{
public interface IBackOfficeRtePreviewService : IBackOfficePreviewService
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public override async Task<string> GetMarkupForBlock(
Type? contentBlockType = FindBlockType(contentTypeAlias);
Type? settingsBlockType = settingsElement != null ? FindBlockType(settingsTypeAlias) : default;

object? blockInstance = CreateBlockInstance(true, contentBlockType, contentElement, settingsBlockType, settingsElement, contentData.Udi, settingsData?.Udi);
object? blockInstance = CreateBlockInstance(true, false, contentBlockType, contentElement, settingsBlockType, settingsElement, contentData.Udi, settingsData?.Udi);

BlockGridItem? typedBlockInstance = blockInstance as BlockGridItem;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public override async Task<string> GetMarkupForBlock(
Type? contentBlockType = FindBlockType(contentTypeAlias);
Type? settingsBlockType = settingsElement != null ? FindBlockType(settingsTypeAlias) : default;

object? blockInstance = CreateBlockInstance(false, contentBlockType, contentElement, settingsBlockType, settingsElement, contentData.Udi, settingsData?.Udi);
object? blockInstance = CreateBlockInstance(false, false, contentBlockType, contentElement, settingsBlockType, settingsElement, contentData.Udi, settingsData?.Udi);

BlockListItem? typedBlockInstance = blockInstance as BlockListItem;

Expand Down
Loading

0 comments on commit fd4689d

Please sign in to comment.