Skip to content

Commit 815ddd9

Browse files
v3.0.3
1 parent daef1ad commit 815ddd9

File tree

8 files changed

+126
-124
lines changed

8 files changed

+126
-124
lines changed

src/Umbraco.Community.Sustainability.UI/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "assets",
33
"private": true,
4-
"version": "3.0.2",
4+
"version": "3.0.3",
55
"type": "module",
66
"scripts": {
77
"dev": "vite",
Lines changed: 31 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,33 @@
11
import { co2, hosting } from 'https://cdn.skypack.dev/@tgwf/[email protected]';
22

3-
window.addEventListener("load", (event) => {
4-
scrollPage();
5-
});
6-
7-
export function scrollPage() {
8-
window.scrollTo({
9-
top: document.body.scrollHeight,
10-
behavior: 'smooth'
11-
});
3+
export async function reportEmissions() {
4+
console.log("reportEmissions called");
125

13-
setTimeout(reportEmissions, 2000);
14-
}
6+
await scrollPage();
7+
await delay(2000); // give lazy-loaded resources time to load
158

16-
export async function reportEmissions() {
9+
console.log("getting emissions data");
1710
const emissionsData = await getEmissionsData();
11+
console.log("received emissions data");
1812

1913
const emissionsDiv = document.createElement("div");
2014
emissionsDiv.setAttribute("data-testid", "sustainabilityData");
21-
emissionsDiv.innerHTML = JSON.stringify(emissionsData);
15+
emissionsDiv.textContent = JSON.stringify(emissionsData);
2216

2317
document.body.appendChild(emissionsDiv);
2418
}
2519

26-
export async function getEmissionsData() {
20+
async function scrollPage() {
21+
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
22+
return delay(2000);
23+
}
24+
25+
function delay(ms) {
26+
return new Promise(resolve => setTimeout(resolve, ms));
27+
}
28+
29+
async function getEmissionsData() {
30+
console.log("calculating...");
2731
const resources = getResources();
2832
const bytesSent = getTransferSize(resources);
2933
const hostCheck = await hosting.check(window.location.hostname);
@@ -39,41 +43,22 @@ export async function getEmissionsData() {
3943
};
4044
}
4145

42-
export function getResources() {
46+
function getResources() {
4347
return window.performance.getEntriesByType("resource");
4448
}
4549

46-
export function filterResourceByType(resources, entryType) {
47-
return resources.filter(
48-
(entry) => entry.initiatorType === entryType,
49-
);
50-
}
51-
52-
export function getTransferSize(resources) {
53-
let bytesSent = 0;
54-
resources.forEach((entry) => {
55-
bytesSent += entry.transferSize;
56-
});
57-
58-
return bytesSent;
50+
function getTransferSize(resources) {
51+
return resources.reduce((total, entry) => total + entry.transferSize, 0);
5952
}
6053

61-
export function calculateGrade(score) {
62-
// grade using swd digital carbon ratings
63-
// https://sustainablewebdesign.org/digital-carbon-ratings/
64-
if (score < 0.095) {
65-
return 'A+';
66-
} else if (score < 0.186) {
67-
return 'A';
68-
} else if (score < 0.341) {
69-
return 'B';
70-
} else if (score < 0.493) {
71-
return 'C';
72-
} else if (score < 0.656) {
73-
return 'D';
74-
} else if (score < 0.846) {
75-
return 'E';
76-
} else {
77-
return 'F';
78-
}
54+
// grade using swd digital carbon ratings
55+
// https://sustainablewebdesign.org/digital-carbon-ratings/
56+
function calculateGrade(score) {
57+
if (score < 0.095) return 'A+';
58+
if (score < 0.186) return 'A';
59+
if (score < 0.341) return 'B';
60+
if (score < 0.493) return 'C';
61+
if (score < 0.656) return 'D';
62+
if (score < 0.846) return 'E';
63+
return 'F';
7964
}

src/Umbraco.Community.Sustainability.UI/public/umbraco-package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"$schema": "../umbraco-package-schema.json",
33
"name": "Umbraco.Community.Sustainability",
44
"id": "Umbraco.Community.Sustainability",
5-
"version": "3.0.2",
5+
"version": "3.0.3",
66
"allowTelemetry": true,
77
"extensions": [
88
{

src/Umbraco.Community.Sustainability/Controllers/SustainabilityWorkspaceController.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
using System.Text.Json;
22
using Asp.Versioning;
33
using Microsoft.AspNetCore.Mvc;
4+
using Microsoft.Extensions.Options;
45
using Umbraco.Cms.Core;
6+
using Umbraco.Cms.Core.Configuration.Models;
57
using Umbraco.Cms.Core.Models;
68
using Umbraco.Cms.Core.Models.PublishedContent;
79
using Umbraco.Community.Sustainability.Models;
@@ -18,15 +20,18 @@ public class SustainabilityWorkspaceController : SustainabilityWorkspaceControll
1820
private readonly IPublishedContentQuery _contentQuery;
1921
private readonly IPageMetricService _pageMetricService;
2022
private readonly ISustainabilityService _sustainabilityService;
23+
private readonly WebRoutingSettings _webRoutingSettings;
2124

2225
public SustainabilityWorkspaceController(
2326
IPublishedContentQuery contentQuery,
2427
IPageMetricService pageMetricService,
25-
ISustainabilityService sustainabilityService)
28+
ISustainabilityService sustainabilityService,
29+
IOptions<WebRoutingSettings> webRoutingSettings)
2630
{
2731
_contentQuery = contentQuery;
2832
_pageMetricService = pageMetricService;
2933
_sustainabilityService = sustainabilityService;
34+
_webRoutingSettings = webRoutingSettings.Value;
3035
}
3136

3237
[HttpGet("getOverviewData")]
@@ -111,8 +116,9 @@ public async Task<IActionResult> CheckPage([FromQuery] Guid pageGuid)
111116
return Ok("Page not found");
112117
}
113118

119+
var applicationUri = HttpContext.Request.GetApplicationUri(_webRoutingSettings);
114120
var url = contentItem.Url(mode: UrlMode.Absolute);
115-
var sustainabilityData = await _sustainabilityService.GetSustainabilityData(url);
121+
var sustainabilityData = await _sustainabilityService.GetSustainabilityData(url, applicationUri.AbsoluteUri);
116122

117123
return Ok(sustainabilityData);
118124
}

src/Umbraco.Community.Sustainability/Services/SustainabilityService.cs

Lines changed: 52 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,30 @@
11
using System.Text.Json;
2+
using Microsoft.Extensions.Options;
23
using Microsoft.Playwright;
4+
using Umbraco.Cms.Core.Configuration.Models;
35
using Umbraco.Community.Sustainability.Models;
46

57
namespace Umbraco.Community.Sustainability.Services
68
{
79
public interface ISustainabilityService
810
{
9-
Task<SustainabilityResponse> GetSustainabilityData(string url);
11+
Task<SustainabilityResponse> GetSustainabilityData(string url, string applicationUrl = "");
1012
}
1113

1214
public class SustainabilityService : ISustainabilityService
1315
{
14-
public async Task<SustainabilityResponse> GetSustainabilityData(string url)
16+
public async Task<SustainabilityResponse> GetSustainabilityData(string url, string applicationUrl = "")
1517
{
1618
using var playwright = await Playwright.CreateAsync();
1719
await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions() { Headless = true });
1820

1921
var baseUri = new Uri(url);
20-
var page = await browser.NewPageAsync();
22+
var context = await browser.NewContextAsync(new()
23+
{
24+
BypassCSP = true
25+
});
26+
27+
var page = await context.NewPageAsync();
2128

2229
var response = await page.GotoAsync(url, new PageGotoOptions()
2330
{
@@ -29,35 +36,54 @@ public async Task<SustainabilityResponse> GetSustainabilityData(string url)
2936
return new SustainabilityResponse();
3037
}
3138

32-
var addedScript = await page.AddScriptTagAsync(new PageAddScriptTagOptions()
39+
try
3340
{
34-
Url = "/App_Plugins/UmbracoCommunitySustainability/js/resource-checker.js",
35-
Type = "module"
36-
});
41+
string scriptUrl = string.Concat(applicationUrl, "App_Plugins/Umbraco.Community.Sustainability/resource-checker.js");
3742

38-
await page.Locator("[data-testid=\"sustainabilityData\"]").WaitForAsync(new LocatorWaitForOptions()
39-
{
40-
Timeout = 60000
41-
});
42-
var data = await page.GetByTestId("sustainabilityData").TextContentAsync();
43-
var sustainabilityData = JsonSerializer.Deserialize<SustainabilityData>(data);
43+
await page.EvaluateAsync($@"() => {{
44+
import('{scriptUrl}')
45+
.then(m => m.reportEmissions?.())
46+
.catch(e => console.error('reportEmissions failed', e));
47+
}}");
4448

45-
var resourceGroups = new List<ExternalResourceGroup>();
46-
foreach (ResourceGroupType resourceGroupType in Enum.GetValues(typeof(ResourceGroupType)))
47-
{
48-
var resources = GetExternalResourceGroup(resourceGroupType, sustainabilityData.resources);
49-
resourceGroups.Add(resources);
50-
}
49+
var locator = page.Locator("[data-testid='sustainabilityData']");
50+
await locator.WaitForAsync(new() { Timeout = 60000, State = WaitForSelectorState.Visible });
51+
52+
var dataJson = await locator.TextContentAsync();
5153

52-
await browser.CloseAsync();
54+
if (string.IsNullOrWhiteSpace(dataJson))
55+
return new SustainabilityResponse();
5356

54-
return new SustainabilityResponse()
57+
var sustainabilityData = JsonSerializer.Deserialize<SustainabilityData>(dataJson);
58+
if (sustainabilityData?.resources == null)
59+
return new SustainabilityResponse();
60+
61+
var resourceGroups = new List<ExternalResourceGroup>();
62+
foreach (ResourceGroupType resourceGroupType in Enum.GetValues(typeof(ResourceGroupType)))
63+
{
64+
var resources = GetExternalResourceGroup(resourceGroupType, sustainabilityData.resources);
65+
resourceGroups.Add(resources);
66+
}
67+
68+
return new SustainabilityResponse()
69+
{
70+
TotalSize = sustainabilityData?.pageWeight.GetValueOrDefault() ?? 0,
71+
TotalEmissions = sustainabilityData?.emissions?.co2.GetValueOrDefault() ?? 0,
72+
CarbonRating = sustainabilityData?.carbonRating,
73+
ResourceGroups = resourceGroups
74+
};
75+
}
76+
catch (Exception ex)
5577
{
56-
TotalSize = sustainabilityData?.pageWeight.GetValueOrDefault() ?? 0,
57-
TotalEmissions = sustainabilityData?.emissions?.co2.GetValueOrDefault() ?? 0,
58-
CarbonRating = sustainabilityData?.carbonRating,
59-
ResourceGroups = resourceGroups
60-
};
78+
_ = ex;
79+
return new SustainabilityResponse();
80+
}
81+
finally
82+
{
83+
await page.CloseAsync();
84+
await browser.CloseAsync();
85+
}
86+
6187
}
6288

6389
private ExternalResourceGroup GetExternalResourceGroup(ResourceGroupType groupType, IList<Resource> resources)

src/Umbraco.Community.Sustainability/Umbraco.Community.Sustainability.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
<RootNamespace>Umbraco.Community.Sustainability</RootNamespace>
1717
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
1818

19-
<VersionPrefix>3.0.2</VersionPrefix>
19+
<VersionPrefix>3.0.3</VersionPrefix>
2020
<VersionSuffix></VersionSuffix>
2121
<Authors>Umbraco Sustainability Community Team</Authors>
2222
<Copyright>$([System.DateTime]::UtcNow.ToString(`yyyy`)) © Umbraco Sustainability Community Team</Copyright>
Lines changed: 31 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,33 @@
11
import { co2, hosting } from 'https://cdn.skypack.dev/@tgwf/[email protected]';
22

3-
window.addEventListener("load", (event) => {
4-
scrollPage();
5-
});
6-
7-
export function scrollPage() {
8-
window.scrollTo({
9-
top: document.body.scrollHeight,
10-
behavior: 'smooth'
11-
});
3+
export async function reportEmissions() {
4+
console.log("reportEmissions called");
125

13-
setTimeout(reportEmissions, 2000);
14-
}
6+
await scrollPage();
7+
await delay(2000); // give lazy-loaded resources time to load
158

16-
export async function reportEmissions() {
9+
console.log("getting emissions data");
1710
const emissionsData = await getEmissionsData();
11+
console.log("received emissions data");
1812

1913
const emissionsDiv = document.createElement("div");
2014
emissionsDiv.setAttribute("data-testid", "sustainabilityData");
21-
emissionsDiv.innerHTML = JSON.stringify(emissionsData);
15+
emissionsDiv.textContent = JSON.stringify(emissionsData);
2216

2317
document.body.appendChild(emissionsDiv);
2418
}
2519

26-
export async function getEmissionsData() {
20+
async function scrollPage() {
21+
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
22+
return delay(2000);
23+
}
24+
25+
function delay(ms) {
26+
return new Promise(resolve => setTimeout(resolve, ms));
27+
}
28+
29+
async function getEmissionsData() {
30+
console.log("calculating...");
2731
const resources = getResources();
2832
const bytesSent = getTransferSize(resources);
2933
const hostCheck = await hosting.check(window.location.hostname);
@@ -39,41 +43,22 @@ export async function getEmissionsData() {
3943
};
4044
}
4145

42-
export function getResources() {
46+
function getResources() {
4347
return window.performance.getEntriesByType("resource");
4448
}
4549

46-
export function filterResourceByType(resources, entryType) {
47-
return resources.filter(
48-
(entry) => entry.initiatorType === entryType,
49-
);
50-
}
51-
52-
export function getTransferSize(resources) {
53-
let bytesSent = 0;
54-
resources.forEach((entry) => {
55-
bytesSent += entry.transferSize;
56-
});
57-
58-
return bytesSent;
50+
function getTransferSize(resources) {
51+
return resources.reduce((total, entry) => total + entry.transferSize, 0);
5952
}
6053

61-
export function calculateGrade(score) {
62-
// grade using swd digital carbon ratings
63-
// https://sustainablewebdesign.org/digital-carbon-ratings/
64-
if (score < 0.095) {
65-
return 'A+';
66-
} else if (score < 0.186) {
67-
return 'A';
68-
} else if (score < 0.341) {
69-
return 'B';
70-
} else if (score < 0.493) {
71-
return 'C';
72-
} else if (score < 0.656) {
73-
return 'D';
74-
} else if (score < 0.846) {
75-
return 'E';
76-
} else {
77-
return 'F';
78-
}
54+
// grade using swd digital carbon ratings
55+
// https://sustainablewebdesign.org/digital-carbon-ratings/
56+
function calculateGrade(score) {
57+
if (score < 0.095) return 'A+';
58+
if (score < 0.186) return 'A';
59+
if (score < 0.341) return 'B';
60+
if (score < 0.493) return 'C';
61+
if (score < 0.656) return 'D';
62+
if (score < 0.846) return 'E';
63+
return 'F';
7964
}

src/Umbraco.Community.Sustainability/wwwroot/App_Plugins/Umbraco.Community.Sustainability/umbraco-package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"$schema": "../umbraco-package-schema.json",
33
"name": "Umbraco.Community.Sustainability",
44
"id": "Umbraco.Community.Sustainability",
5-
"version": "3.0.2",
5+
"version": "3.0.3",
66
"allowTelemetry": true,
77
"extensions": [
88
{

0 commit comments

Comments
 (0)