Skip to content

Commit

Permalink
Merge pull request #55 from the-urlist/eliminate-form
Browse files Browse the repository at this point in the history
Remove EditForm and Regular Expressions to cut dependencies.
  • Loading branch information
jongalloway authored Feb 23, 2024
2 parents 0eb4712 + d58a9e1 commit 740602f
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 52 deletions.
17 changes: 6 additions & 11 deletions Client/Shared/LinkBundleDetails.razor
Original file line number Diff line number Diff line change
Expand Up @@ -72,17 +72,12 @@

if (String.IsNullOrEmpty(vanityUrl)) return;

// Create a ValidationContext based on the LinkBundle object
var context = new ValidationContext(StateContainer.LinkBundle, null, null);
// This list will hold the results of the validation
var results = new List<ValidationResult>();
// Perform the data annotations validation
listIsValid = Validator.TryValidateObject(StateContainer.LinkBundle, context, results, true);

// if the data annotations validation fails, no need to check if the vanity url is taken
if (!listIsValid)
// Ensure the vanity url contains only letters, numbers, and dashes without using regex
if (vanityUrl.Any(c => !char.IsLetterOrDigit(c) && c != '-'))
{
validationErrorMessage = results.FirstOrDefault()?.ErrorMessage ?? "";
// if the data annotations validation fails, no need to check if the vanity url is taken
listIsValid = false;
validationErrorMessage = "Vanity URLs can only contain letters, numbers, and dashes.";
return;
}

Expand Down Expand Up @@ -113,7 +108,6 @@
private async Task PublishLinkBundle()
{
HttpResponseMessage response;

if (IsPublished)
{
response = await Http.PutAsJsonAsync<LinkBundle>($"api/links/{StateContainer.LinkBundle.VanityUrl}", StateContainer.LinkBundle);
Expand All @@ -122,6 +116,7 @@
{
response = await Http.PostAsJsonAsync<LinkBundle>("api/links", StateContainer.LinkBundle);
}

var linkBundle = await response.Content.ReadFromJsonAsync<LinkBundle>();

if (linkBundle != null)
Expand Down
90 changes: 56 additions & 34 deletions Client/Shared/NewLink.razor
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,59 @@
@inject HttpClient Http
@inject StateContainer StateContainer

<EditForm Model="@Model" OnValidSubmit="@OnValidSubmit" class="mb-6">
<DataAnnotationsValidator />
<p>Enter a link and press enter</p>
<InputText @ref="newLinkInput" class="input is-large is-size-2" @bind-Value="Model!.Url" id="newLink"
placeholder="http://example.com" ParsingErrorMessage="That doesn't look like a valid URL" />
<ValidationMessage class="has-text-danger is-font-weight-medium mt-2" For="() => Model.Url" />
</EditForm>
<form method="post" @formname="newlinkform" @onsubmit="OnSubmit" class="mb-6">
<p>Enter a link and press enter</p>
<input @ref="newLinkInput" id="newLink" @bind-value="linkurl" placeholder="http://example.com" class="input is-large is-size-2 modified">
<div class="is-font-weight-medium mt-2 @((invalid ? "has-text-danger" : "is-hidden"))">That doesn't look like a valid URL</div>
</form>

@code {
private InputText? newLinkInput;

public Link? Model { get; set; }

protected override void OnInitialized() => Model ??= new();
private string? linkurl;
private bool invalid = false;
private ElementReference newLinkInput;

[Parameter]
public EventCallback<Link> OnNewLinkAdded { get; set; }

private async Task OnValidSubmit()
private async Task OnSubmit()
{
if (!ValidateUrl(linkurl))
{
invalid = true;
StateHasChanged();
return;
}

invalid = false;

var link = new Link
{
Url = Model!.Url!
};
{
Url = linkurl
};

await OnNewLinkAdded.InvokeAsync(link);
Model.Url = null;
await newLinkInput!.Element!.Value.FocusAsync();
linkurl = null;
await newLinkInput.FocusAsync();
await GetOpenGraphInfoForLink(link);
}

private bool ValidateUrl(string? url)
{
if (string.IsNullOrWhiteSpace(url))
{
return false;
}

if (!url.StartsWith("http://") && !url.StartsWith("https://"))
{
url = "http://" + url;
}

return Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp
|| uriResult.Scheme == Uri.UriSchemeHttps) && uriResult.Host.Replace("www.", "").Split('.').Count() > 1 && uriResult.HostNameType == UriHostNameType.Dns && uriResult.Host.Length > uriResult.Host.LastIndexOf(".") + 1;
}

private async Task GetOpenGraphInfoForLink(Link link)
{
try
Expand All @@ -45,21 +67,21 @@
var response = await Http.PostAsJsonAsync<Link>("api/oginfo", link, cts.Token);
var updatedLink = await response.Content.ReadFromJsonAsync<Link>();

if (updatedLink != null)
{
// call statecontainer updatelink
StateContainer.UpdateLinkInBundle(link, updatedLink);
}
}
catch (Exception e)
{
// the request to get opengraph info failed, so log and swallow
Console.WriteLine(e);
StateContainer.RemoveLinkFromUpdatePool(link);
}
finally
{
StateContainer.RemoveLinkFromUpdatePool(link);
if (updatedLink != null)
{
// call statecontainer updatelink
StateContainer.UpdateLinkInBundle(link, updatedLink);
}
}
catch (Exception e)
{
// the request to get opengraph info failed, so log and swallow
Console.WriteLine(e);
StateContainer.RemoveLinkFromUpdatePool(link);
}
finally
{
StateContainer.RemoveLinkFromUpdatePool(link);
}
}
}
}
5 changes: 0 additions & 5 deletions Shared/Link.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;

namespace BlazorApp.Shared
{
public class Link
{
public string Id { get; set; } = Guid.NewGuid().ToString();

[RegularExpression(@"^(https?://)?([\w-]+\.)+[\w-]+(/[\w- ./:?%&=#]*)?$", ErrorMessage = "That doesn't look like a valid URL"), Required]
public string Url { get; set; }

public string Title { get; set; }
public string Description { get; set; }
public string Image { get; set; }
Expand Down
3 changes: 1 addition & 2 deletions Shared/LinkBundle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@ public class LinkBundle
{
[JsonPropertyName("id")]
public string Id { get; set; } = Guid.NewGuid().ToString();
[JsonPropertyName("vanityUrl"), RegularExpression(@"^(^$|[a-zA-Z0-9_\-])+$", ErrorMessage = "Only letters, numbers and dashes")]
[JsonPropertyName("vanityUrl")]
public string VanityUrl { get; set; }
[JsonPropertyName("description")]
public string Description { get; set; }
[JsonPropertyName("userId")]
public string UserId { get; set; }
[JsonPropertyName("provider")]
public string Provider { get; set; }

[JsonPropertyName("links")]
public List<Link> Links { get; set; } = new List<Link>();
}
Expand Down

0 comments on commit 740602f

Please sign in to comment.