Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Placements module v2 #7483

Merged
merged 14 commits into from
Dec 5, 2020
7 changes: 7 additions & 0 deletions OrchardCore.sln
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrchardCore.ContentPreview.
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrchardCore.Tests.Functional", "test\Functional\OrchardCore.Tests.Functional.csproj", "{2CA507BD-5517-4CD2-8F30-093AC5D11EBA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrchardCore.Placements", "src\OrchardCore.Modules\OrchardCore.Placements\OrchardCore.Placements.csproj", "{5F94223B-CD69-47E1-B4AE-DEA03CBC4D3D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -1033,6 +1035,10 @@ Global
{2CA507BD-5517-4CD2-8F30-093AC5D11EBA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2CA507BD-5517-4CD2-8F30-093AC5D11EBA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2CA507BD-5517-4CD2-8F30-093AC5D11EBA}.Release|Any CPU.Build.0 = Release|Any CPU
{5F94223B-CD69-47E1-B4AE-DEA03CBC4D3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5F94223B-CD69-47E1-B4AE-DEA03CBC4D3D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5F94223B-CD69-47E1-B4AE-DEA03CBC4D3D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5F94223B-CD69-47E1-B4AE-DEA03CBC4D3D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -1213,6 +1219,7 @@ Global
{1286E568-BAFE-45E2-BF60-4350DB99FF83} = {F23AC6C2-DE44-4699-999D-3C478EF3D691}
{57EA05E8-0275-4163-8FD1-2B244E396F91} = {F23AC6C2-DE44-4699-999D-3C478EF3D691}
{2CA507BD-5517-4CD2-8F30-093AC5D11EBA} = {B8D16C60-99B4-43D5-A3AD-4CD89AF39B25}
{5F94223B-CD69-47E1-B4AE-DEA03CBC4D3D} = {90030E85-0C4F-456F-B879-443E8A3F220D}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {46A1D25A-78D1-4476-9CBF-25B75E296341}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@

<input type="hidden" asp-for="Name" />

@if (Model.Editor.Shortcuts != null)
{
<div class="form-group">
@await DisplayAsync(Model.Editor.Shortcuts)
</div>
}

@await DisplayAsync(Model.Editor)

<div class="form-group">
Expand All @@ -39,11 +46,11 @@
{
@foreach (var field in orderedFields)
{
<li class="list-group-item" style="cursor: move;">
<li class="list-group-item" style="cursor: move;">
<div class="properties">
<div class="related">
<a asp-route-action="EditField" asp-route-id="@Model.TypeDefinition.Name" asp-route-name="@field.Name" asp-route-returnUrl="@FullRequestPath" class="btn btn-primary btn-sm" role="button">@T["Edit"]</a>
<a asp-route-action="RemoveFieldFrom" asp-route-id="@Model.TypeDefinition.Name" asp-route-name="@field.Name" class="btn btn-danger btn-sm" role="button" itemprop="UnsafeUrl RemoveUrl">@T["Remove"]</a>
<a asp-route-action="RemoveFieldFrom" asp-route-id="@Model.TypeDefinition.Name" asp-route-name="@field.Name" class="btn btn-danger btn-sm" role="button" itemprop="UnsafeUrl RemoveUrl">@T["Remove"]</a>
</div>
@field.DisplayName() <span class="hint dashed">@field.FieldDefinition.Name.CamelFriendly()</span>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@
<span class="hint">@T["Technical name of the field."]</span>
</div>

@if (Model.Shape.Shortcuts != null)
{
<div class="form-group">
@await DisplayAsync(Model.Shape.Shortcuts)
</div>
}

@if (Model.Shape.Content != null)
{
<div class="form-group">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@
<span class="hint">@T["Technical name of the part."]</span>
</div>

@if (Model.Editor.Shortcuts != null)
{
<div class="form-group">
@await DisplayAsync(Model.Editor.Shortcuts)
</div>
}

@await DisplayAsync(Model.Editor)

<div class="form-group">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@

@if (Model.Shape.Content != null)
{
@if (Model.Shape.Shortcuts != null)
{
<div class="form-group">
@await DisplayAsync(Model.Shape.Shortcuts)
deanmarcussen marked this conversation as resolved.
Show resolved Hide resolved
</div>
}

<div class="form-group">
@await DisplayAsync(Model.Shape.Content)
</div>
Expand Down
36 changes: 36 additions & 0 deletions src/OrchardCore.Modules/OrchardCore.Placements/AdminMenu.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization;
using OrchardCore.Navigation;

namespace OrchardCore.Placements
{
public class AdminMenu : INavigationProvider
{
private readonly IStringLocalizer S;

public AdminMenu(IStringLocalizer<AdminMenu> localizer)
{
S = localizer;
}

public Task BuildNavigationAsync(string name, NavigationBuilder builder)
{
if (!String.Equals(name, "admin", StringComparison.OrdinalIgnoreCase))
{
return Task.CompletedTask;
}

builder
.Add(S["Design"], design => design
.Add(S["Placements"], "Placements", import => import
.Action("Index", "Admin", new { area = "OrchardCore.Placements" })
.Permission(Permissions.ManagePlacements)
.LocalNav()
)
);

return Task.CompletedTask;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OrchardCore.DisplayManagement.Descriptors.ShapePlacementStrategy;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Placements.Services;
using OrchardCore.Placements.ViewModels;

namespace OrchardCore.Placements.Controllers
{
public class AdminController : Controller
{
private readonly ILogger _logger;
private readonly IAuthorizationService _authorizationService;
private readonly PlacementsManager _placementsManager;
private readonly IHtmlLocalizer H;
private readonly IStringLocalizer S;
private readonly INotifier _notifier;

public AdminController(
ILogger<AdminController> logger,
IAuthorizationService authorizationService,
PlacementsManager placementsManager,
IHtmlLocalizer<AdminController> htmlLocalizer,
IStringLocalizer<AdminController> stringLocalizer,
INotifier notifier)
{
_logger = logger;
_authorizationService = authorizationService;
_placementsManager = placementsManager;
_notifier = notifier;

H = htmlLocalizer;
S = stringLocalizer;
}

public async Task<IActionResult> Index()
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
{
return Forbid();
}

var shapeTypes = await _placementsManager.ListShapePlacementsAsync();

return View(new ListShapePlacementsViewModel
{
ShapePlacements = shapeTypes.Select(entry => new ShapePlacementViewModel
{
ShapeType = entry.Key
})
});
}

public async Task<IActionResult> Create(string suggestion, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
{
return Forbid();
}

var template = new PlacementNode[] { new PlacementNode() };

var viewModel = new EditShapePlacementViewModel
{
Creating = true,
ShapeType = suggestion,
Nodes = JsonConvert.SerializeObject(template, Formatting.Indented)
};

ViewData["ReturnUrl"] = returnUrl;
return View("Edit", viewModel);
}

public async Task<IActionResult> Edit(string shapeType, string displayType = null, string contentType = null, string contentPart = null, string differentiator = null, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
{
return Forbid();
}

var placementNodes = (await _placementsManager.GetShapePlacementsAsync(shapeType))?.ToList() ?? new List<PlacementNode>();

if (!placementNodes.Any() || ShouldCreateNode(placementNodes, displayType, contentType, contentPart, differentiator))
{
var generatedNode = new PlacementNode
{
DisplayType = displayType,
Differentiator = differentiator
};
if (!string.IsNullOrEmpty(contentType))
{
generatedNode.Filters.Add("contentType", new JArray(contentType));
}
if (!string.IsNullOrEmpty(contentPart))
{
generatedNode.Filters.Add("contentPart", new JArray(contentPart));
}

placementNodes.Add(generatedNode);
}

var viewModel = new EditShapePlacementViewModel
{
ShapeType = shapeType,
Nodes = JsonConvert.SerializeObject(placementNodes, Formatting.Indented)
};

ViewData["ReturnUrl"] = returnUrl;
return View(viewModel);
}

[HttpPost, ActionName("Edit")]
public async Task<IActionResult> Edit(EditShapePlacementViewModel viewModel, string submit, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
{
return Forbid();
}

ViewData["ReturnUrl"] = returnUrl;

if (viewModel.Creating && await _placementsManager.GetShapePlacementsAsync(viewModel.ShapeType) != null)
{
// Prevent overriding existing rules on creation
_notifier.Warning(H["Placement rules for \"{0}\" already exists. Please edit existing rule.", viewModel.ShapeType]);
return View(viewModel);
}

try
{
IEnumerable<PlacementNode> placementNodes = JsonConvert.DeserializeObject<PlacementNode[]>(viewModel.Nodes) ?? new PlacementNode[0];

// Remove empty nodes
placementNodes = placementNodes.Where(node => !IsEmpty(node));

if (placementNodes.Any())
{
// Save
await _placementsManager.UpdateShapePlacementsAsync(viewModel.ShapeType, placementNodes);
viewModel.Creating = false;

_notifier.Success(H["The \"{0}\" placement have been saved.", viewModel.ShapeType]);
}
else if (viewModel.Creating)
{
_notifier.Warning(H["The \"{0}\" placement is empty.", viewModel.ShapeType]);
return View(viewModel);
}
else
{
// Remove if empty
await _placementsManager.RemoveShapePlacementsAsync(viewModel.ShapeType);
_notifier.Success(H["The \"{0}\" placement has been deleted.", viewModel.ShapeType]);
}
}
catch(JsonReaderException jsonException)
{
_notifier.Error(H["An error occurred while parsing the placement<br/>{0}", jsonException.Message]);
return View(viewModel);
}
catch (Exception e)
{
_notifier.Error(H["An error occurred while saving the placement"]);
_logger.LogError(e, "An error occurred while saving the placement");
return View(viewModel);
}

if (submit != "SaveAndContinue")
{
return RedirectToReturnUrlOrIndex(returnUrl);
}

return View(viewModel);
}

[HttpPost, ActionName("Delete")]
public async Task<IActionResult> Delete(string shapeType, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
{
return Forbid();
}

await _placementsManager.RemoveShapePlacementsAsync(shapeType);
_notifier.Success(H["The \"{0}\" placement has been deleted.", shapeType]);

return RedirectToReturnUrlOrIndex(returnUrl);
}

private IActionResult RedirectToReturnUrlOrIndex(string returnUrl)
{
if ((String.IsNullOrEmpty(returnUrl) == false) && (Url.IsLocalUrl(returnUrl)))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(Index));
}
}

private static bool ShouldCreateNode(IEnumerable<PlacementNode> nodes, string displayType, string contentType, string contentPart, string differentiator)
{
if (string.IsNullOrEmpty(displayType) && string.IsNullOrEmpty(differentiator))
{
return false;
}
else
{
return !nodes.Any(node =>
(string.IsNullOrEmpty(displayType) || node.DisplayType == displayType) &&
(string.IsNullOrEmpty(contentType) || (node.Filters.ContainsKey("contentType") && FilterEquals(node.Filters["contentType"], contentType))) &&
(string.IsNullOrEmpty(contentPart) || (node.Filters.ContainsKey("contentPart") && FilterEquals(node.Filters["contentPart"], contentPart))) &&
(string.IsNullOrEmpty(differentiator) || node.Differentiator == differentiator));
}
}

private static bool IsEmpty(PlacementNode node)
{
return string.IsNullOrEmpty(node.Location)
&& string.IsNullOrEmpty(node.ShapeType)
&& (node.Alternates == null || node.Alternates.Length == 0)
&& (node.Wrappers == null || node.Wrappers.Length == 0);
}

private static bool FilterEquals(JToken token, string value)
{
if (token is JArray)
{
var tokenValues = token.Values<string>();
return tokenValues.Count() == 1 && tokenValues.First() == value;
}
else
{
return token.Value<string>() == value;
}
}
}
}
Loading