private void BindContext(object target, TagHelperContext context)
 {
     foreach (var propertyInfo in target.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Where(pi => pi.HasCustomAttribute <BindTagHelperContextAttribute>()))
     {
         var attr = propertyInfo.GetCustomAttribute <BindTagHelperContextAttribute>();
         if (string.IsNullOrEmpty(attr.Key))
         {
             var contextItem = context.GetContextItem(propertyInfo.PropertyType, attr.UseInherited);
             if (contextItem != null)
             {
                 propertyInfo.SetValue(target, contextItem);
             }
             if (attr.RemoveContext)
             {
                 context.RemoveContextItem(propertyInfo.PropertyType, attr.UseInherited);
             }
         }
         else
         {
             propertyInfo.SetValue(target, context.GetContextItem(propertyInfo.PropertyType, attr.Key));
             if (attr.RemoveContext)
             {
                 context.RemoveContextItem(attr.Key);
             }
         }
     }
 }
Example #2
0
 public override void Init(TagHelperContext context)
 {
     base.Init(context);
     if (context.HasContextItem <ButtonGroupTagHelper>())
     {
         var buttonGroupContext = context.GetContextItem <ButtonGroupTagHelper>();
         this.Size = buttonGroupContext.Size;
         if (!this.Context.HasValue)
         {
             this.Context = buttonGroupContext.Context;
         }
         if (buttonGroupContext.Vertical && this.Splitted)
         {
             throw new Exception("Splitted dropdowns are not supported inside vertical button groups");
         }
     }
     else if (context.HasContextItem <ButtonToolbarTagHelper>())
     {
         var buttonToolbarContext = context.GetContextItem <ButtonToolbarTagHelper>();
         if (!this.Context.HasValue)
         {
             this.Context = buttonToolbarContext.Context;
         }
         if (!this.Size.HasValue)
         {
             this.Size = buttonToolbarContext.Size;
         }
     }
 }
 public override void Init(TagHelperContext context)
 {
     base.Init(context);
     if (context.HasContextItem <ButtonGroupTagHelper>())
     {
         var buttonGroupContext = context.GetContextItem <ButtonGroupTagHelper>();
         this.Button = true;
         this.ButtonGroupJustified = buttonGroupContext.Justified;
         this.Size = this.ButtonGroupJustified ? buttonGroupContext.Size : BootstrapTagHelpers.Size.Default;
         if (!this.Context.HasValue)
         {
             this.Context = buttonGroupContext.Context;
         }
     }
     else if (context.HasContextItem <ButtonToolbarTagHelper>())
     {
         var buttonToolbarContext = context.GetContextItem <ButtonToolbarTagHelper>();
         this.Button            = true;
         this.WrapInButtonGroup = true;
         if (!this.Context.HasValue)
         {
             this.Context = buttonToolbarContext.Context;
         }
         if (!this.Size.HasValue)
         {
             this.Size = buttonToolbarContext.Size;
         }
     }
 }
Example #4
0
 public static void SetContexts(object target, TagHelperContext context)
 {
     if (target == null)
     {
         throw new ArgumentNullException(nameof(target));
     }
     if (context == null)
     {
         throw new ArgumentNullException(nameof(context));
     }
     foreach (var propertyInfo in target.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Where(pI => pI.HasCustomAttribute <ContextAttribute>()))
     {
         var attr = propertyInfo.GetCustomAttribute <ContextAttribute>();
         if (string.IsNullOrEmpty(attr.Key))
         {
             var contextItem = context.GetContextItem(propertyInfo.PropertyType, attr.UseInherited);
             if (contextItem != null)
             {
                 propertyInfo.SetValue(target, contextItem);
             }
             if (attr.RemoveContext)
             {
                 context.RemoveContextItem(propertyInfo.PropertyType, attr.UseInherited);
             }
         }
         else
         {
             propertyInfo.SetValue(target, context.GetContextItem(propertyInfo.PropertyType, attr.Key));
             if (attr.RemoveContext)
             {
                 context.RemoveContextItem(attr.Key);
             }
         }
     }
 }
        protected override async Task BootstrapProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "div";
            output.AddCssClass("input-group");
            if ((Size ?? SimpleSize.Default) != SimpleSize.Default)
            {
                output.AddCssClass("input-group-" + Size.Value.GetDescription());
            }
            if (!string.IsNullOrEmpty(PreAddonText))
            {
                output.PreContent.SetHtmlContent(AddonTagHelper.GenerateAddon(PreAddonText));
            }
            if (!string.IsNullOrEmpty(PostAddonText))
            {
                output.PostContent.SetHtmlContent(AddonTagHelper.GenerateAddon(PostAddonText));
            }
            await output.GetChildContentAsync();

            var preElementContent = output.PreElement.GetContent();

            output.PreElement.Clear();
            if (FormGroupContext != null)
            {
                FormGroupContext.WrapInDivForHorizontalForm(output, context.GetContextItem <FormGroupTagHelper>()?.HasLabel ?? false);
            }
            else if (FormContext != null)
            {
                FormContext.WrapInDivForHorizontalForm(output, context.GetContextItem <FormGroupTagHelper>()?.HasLabel ?? false);
            }
            output.PreElement.PrependHtml(preElementContent);
            if (!string.IsNullOrEmpty(HelpContent))
            {
                output.PostElement.PrependHtml(HelpBlockTagHelper.GenerateHelpBlock(HelpContent));
            }
        }
Example #6
0
        public async Task ProcessAsync_AddsFieldsetToContext()
        {
            // Arrange
            var dateInputContext = new DateInputContext(haveExplicitValue: false);

            var context = new TagHelperContext(
                tagName: "govuk-date-input-fieldset",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>()
            {
                { typeof(DateInputContext), dateInputContext }
            },
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-date-input-fieldset",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var fieldsetContext = context.GetContextItem <DateInputFieldsetContext>();
                fieldsetContext.SetLegend(isPageHeading: true, attributes: null, content: new HtmlString("Legend"));

                var tagHelperContent = new DefaultTagHelperContent();
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new DateInputFieldsetTagHelper();

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            Assert.True(dateInputContext.Fieldset?.Legend?.IsPageHeading);
            Assert.Equal("Legend", dateInputContext.Fieldset?.Legend?.Content?.RenderToString());
        }
        public async Task ProcessAsync_MissingLegend_ThrowsInvalidOperationException()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-fieldset",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-fieldset",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var fieldsetContext = context.GetContextItem <FieldsetContext>();

                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.SetContent("Main content");
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new FieldsetTagHelper()
            {
                DescribedBy = "describedby",
                Role        = "therole"
            };

            // Act
            var ex = await Record.ExceptionAsync(() => tagHelper.ProcessAsync(context, output));

            // Assert
            Assert.IsType <InvalidOperationException>(ex);
            Assert.Equal("A <govuk-fieldset-legend> element must be provided.", ex.Message);
        }
Example #8
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var summaryListContext = context.GetContextItem <SummaryListContext>();

            var rowContext = new SummaryListRowContext();

            using (context.SetScopedContextItem(rowContext))
            {
                await output.GetChildContentAsync();
            }

            rowContext.ThrowIfIncomplete();

            summaryListContext.AddRow(new SummaryListRow()
            {
                Actions = new SummaryListRowActions()
                {
                    Items      = rowContext.Actions,
                    Attributes = rowContext.ActionsAttributes
                },
                Attributes = output.Attributes.ToAttributeDictionary(),
                Key        = new SummaryListRowKey()
                {
                    Content    = rowContext.Key !.Value.Content,
                    Attributes = rowContext.Key !.Value.Attributes
                },
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var accordionContext = context.GetContextItem <AccordionContext>();

            var itemContext = new AccordionItemContext();

            TagHelperContent childContent;

            using (context.SetScopedContextItem(itemContext))
            {
                childContent = await output.GetChildContentAsync();
            }

            itemContext.ThrowIfIncomplete();

            accordionContext.AddItem(new AccordionItem()
            {
                Expanded          = Expanded,
                HeadingContent    = itemContext.Heading !.Value.Content,
                HeadingAttributes = itemContext.Heading.Value.Attributes,
                SummaryContent    = itemContext.Summary?.Content,
                SummaryAttributes = itemContext.Summary?.Attributes,
                Content           = childContent.Snapshot(),
                Attributes        = output.Attributes.ToAttributeDictionary()
            });
 public override void Init(TagHelperContext context)
 {
     base.Init(context);
     if (FormContext != null)
     {
         context.SetContextItem(new FormTagHelper {
             LabelWidthLg  = FormContext.LabelWidthLg,
             LabelWidthMd  = FormContext.LabelWidthMd,
             LabelWidthSm  = FormContext.LabelWidthSm,
             LabelWidthXs  = FormContext.LabelWidthXs,
             FormGroupSize = FormContext.FormGroupSize,
             Horizontal    = false,
             Inline        = FormContext.Inline,
             ControlSize   = FormContext.ControlSize,
             LabelsSrOnly  = FormContext.LabelsSrOnly
         });
     }
     if (FormGroupContext != null)
     {
         context.SetContextItem(new FormGroupTagHelper {
             FormContext       = context.GetContextItem <FormTagHelper>(),
             Size              = FormGroupContext.Size,
             ControlSize       = FormGroupContext.ControlSize,
             HasFeedback       = FormGroupContext.HasFeedback,
             HasLabel          = FormGroupContext.HasLabel,
             LabelWidthLg      = FormGroupContext.LabelWidthLg,
             LabelWidthMd      = FormGroupContext.LabelWidthMd,
             LabelWidthXs      = FormGroupContext.LabelWidthXs,
             LabelWidthSm      = FormGroupContext.LabelWidthSm,
             ValidationContext = FormGroupContext.ValidationContext
         });
     }
 }
Example #11
0
        private protected override IHtmlContent GenerateFormGroupContent(
            TagHelperContext tagHelperContext,
            FormGroupContext formGroupContext,
            TagHelperOutput tagHelperOutput,
            IHtmlContent childContent,
            out bool haveError)
        {
            var radiosContext = tagHelperContext.GetContextItem <RadiosContext>();

            var contentBuilder = new HtmlContentBuilder();

            var hint = GenerateHint(tagHelperContext, formGroupContext);

            if (hint != null)
            {
                contentBuilder.AppendHtml(hint);
            }

            var errorMessage = GenerateErrorMessage(tagHelperContext, formGroupContext);

            if (errorMessage != null)
            {
                contentBuilder.AppendHtml(errorMessage);
            }

            haveError = errorMessage != null;
            var haveFieldset = radiosContext.Fieldset != null;

            var radiosTagBuilder = GenerateRadios();

            contentBuilder.AppendHtml(radiosTagBuilder);

            if (haveFieldset)
            {
                return(Generator.GenerateFieldset(
                           DescribedBy,
                           role: null,
                           radiosContext.Fieldset !.Legend?.IsPageHeading,
                           radiosContext.Fieldset.Legend?.Content,
                           radiosContext.Fieldset.Legend?.Attributes,
                           content: contentBuilder,
                           radiosContext.Fieldset.Attributes));
            }

            return(contentBuilder);

            TagBuilder GenerateRadios()
            {
                var resolvedIdPrefix = ResolveIdPrefix();

                TryResolveName(out var resolvedName);

                return(Generator.GenerateRadios(
                           resolvedIdPrefix,
                           resolvedName,
                           items: radiosContext.Items,
                           attributes: RadiosAttributes.ToAttributeDictionary()));
            }
        }
Example #12
0
        public async Task ProcessAsync_WithValueAndAspFor_RendersTextAreaWithValue()
        {
            // Arrange
            var modelValue = "Foo value";
            var model      = new Model()
            {
                Foo = modelValue
            };

            var modelExplorer = new EmptyModelMetadataProvider().GetModelExplorerForType(typeof(Model), model)
                                .GetExplorerForProperty(nameof(Model.Foo));
            var viewContext     = new ViewContext();
            var modelExpression = nameof(Model.Foo);

            var modelHelper = new Mock <IModelHelper>();

            modelHelper.Setup(mock => mock.GetModelValue(viewContext, modelExplorer, modelExpression)).Returns(modelValue);

            var context = new TagHelperContext(
                tagName: "govuk-character-count",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-character-count",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var characterCountContext = context.GetContextItem <CharacterCountContext>();

                characterCountContext.SetLabel(
                    isPageHeading: false,
                    attributes: null,
                    content: new HtmlString("The label"));

                characterCountContext.SetValue(new HtmlString("Value"));

                var tagHelperContent = new DefaultTagHelperContent();
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new CharacterCountTagHelper(modelHelper: modelHelper.Object)
            {
                AspFor      = new ModelExpression(modelExpression, modelExplorer),
                Name        = "my-name",
                MaxWords    = 10,
                ViewContext = viewContext
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            var element  = output.RenderToElement();
            var textarea = element.GetElementsByTagName("textarea")[0];

            Assert.Equal("Value", textarea.InnerHtml);
        }
        public async Task ProcessAsync_WithError_GeneratesExpectedOutput()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-textarea",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-textarea",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var textAreaContext = context.GetContextItem <TextAreaContext>();

                textAreaContext.SetLabel(
                    isPageHeading: false,
                    attributes: null,
                    content: new HtmlString("The label"));

                textAreaContext.SetHint(
                    attributes: null,
                    content: new HtmlString("The hint"));

                textAreaContext.SetErrorMessage(
                    visuallyHiddenText: null,
                    attributes: null,
                    content: new HtmlString("The error"));

                var tagHelperContent = new DefaultTagHelperContent();
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new TextAreaTagHelper()
            {
                Id   = "my-id",
                Name = "my-name"
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            var expectedHtml = @"
<div class=""govuk-form-group govuk-form-group--error"">
    <label class=""govuk-label"" for=""my-id"">The label</label>
    <div class=""govuk-hint"" id=""my-id-hint"">The hint</div>
    <p id=""my-id-error"" class=""govuk-error-message"">
        <span class=""govuk-visually-hidden"">Error:</span>
        The error
    </p>
    <textarea class=""govuk-textarea govuk-js-textarea govuk-textarea--error"" id=""my-id"" name=""my-name"" rows=""5"" aria-describedby=""my-id-hint my-id-error""></textarea>
</div>";

            AssertEx.HtmlEqual(expectedHtml, output.RenderToString());
        }
        private protected virtual void SetErrorMessage(TagHelperContent?childContent, TagHelperContext context, TagHelperOutput output)
        {
            var formGroupContext = context.GetContextItem <FormGroupContext>();

            formGroupContext.SetErrorMessage(
                VisuallyHiddenText,
                output.Attributes.ToAttributeDictionary(),
                childContent?.Snapshot());
        }
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var dateInputItemContext = context.GetContextItem <DateInputItemContext>();

            var childContent = await output.GetChildContentAsync();

            dateInputItemContext.SetLabel(childContent.Snapshot(), output.Attributes.ToAttributeDictionary());

            output.SuppressOutput();
        }
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var summaryListRowContext = context.GetContextItem <SummaryListRowContext>();

            var content = await output.GetChildContentAsync();

            summaryListRowContext.SetValue(output.Attributes.ToAttributeDictionary(), content.Snapshot());

            output.SuppressOutput();
        }
Example #17
0
        private protected override void SetErrorMessage(TagHelperContent?childContent, TagHelperContext context, TagHelperOutput output)
        {
            var dateInputContext = context.GetContextItem <DateInputContext>();

            dateInputContext.SetErrorMessage(
                ErrorItems,
                VisuallyHiddenText,
                output.Attributes.ToAttributeDictionary(),
                childContent?.Snapshot());
        }
Example #18
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var inputContext = context.GetContextItem <TextInputContext>();

            var content = await output.GetChildContentAsync();

            inputContext.SetSuffix(output.Attributes.ToAttributeDictionary(), content.Snapshot());

            output.SuppressOutput();
        }
Example #19
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var rowContext = context.GetContextItem <SummaryListRowContext>();

            rowContext.SetActionsAttributes(output.Attributes.ToAttributeDictionary());

            await output.GetChildContentAsync();

            output.SuppressOutput();
        }
Example #20
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var childContent = await output.GetChildContentAsync();

            var detailsContext = context.GetContextItem <DetailsContext>();

            detailsContext.SetSummary(output.Attributes.ToAttributeDictionary(), childContent.Snapshot());

            output.SuppressOutput();
        }
Example #21
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var fieldsetContext = context.GetContextItem <CheckboxesFieldsetContext>();

            var content = await output.GetChildContentAsync();

            fieldsetContext.SetLegend(IsPageHeading, output.Attributes.ToAttributeDictionary(), content: content.Snapshot());

            output.SuppressOutput();
        }
Example #22
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var childContent = await output.GetChildContentAsync();

            var characterCountContext = context.GetContextItem <CharacterCountContext>();

            characterCountContext.SetValue(childContent.Snapshot());

            output.SuppressOutput();
        }
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var itemContext = context.GetContextItem <AccordionItemContext>();

            var childContent = await output.GetChildContentAsync();

            itemContext.SetHeading(output.Attributes.ToAttributeDictionary(), childContent.Snapshot());

            output.SuppressOutput();
        }
Example #24
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var panelContext = context.GetContextItem <PanelContext>();

            var childContent = await output.GetChildContentAsync();

            panelContext.SetTitle(childContent.Snapshot());

            output.SuppressOutput();
        }
Example #25
0
        public async Task ProcessAsync_WithMaxLength_GeneratesExpectedOutput()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-character-count",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-character-count",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var characterCountContext = context.GetContextItem <CharacterCountContext>();

                characterCountContext.SetLabel(
                    isPageHeading: false,
                    attributes: null,
                    content: new HtmlString("The label"));

                characterCountContext.SetHint(
                    attributes: null,
                    content: new HtmlString("The hint"));

                var tagHelperContent = new DefaultTagHelperContent();
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new CharacterCountTagHelper()
            {
                Id        = "my-id",
                Name      = "my-name",
                MaxLength = 200,
                Threshold = 90
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            var expectedHtml = @"
<div class=""govuk-character-count"" data-module=""govuk-character-count"" data-maxlength=""200"" data-threshold=""90"">
    <div class=""govuk-form-group"">
        <label class=""govuk-label"" for=""my-id"">The label</label>
        <div class=""govuk-hint"" id=""my-id-hint"">The hint</div>
        <textarea class=""govuk-textarea govuk-js-character-count"" id=""my-id"" name=""my-name"" rows=""5"" aria-describedby=""my-id-hint""></textarea>
    </div>
    <div id=""my-id-info"" class=""govuk-hint govuk-character-count__message"">
        You can enter up to 200 characters
    </div>
</div>";

            AssertEx.HtmlEqual(expectedHtml, output.RenderToString());
        }
        public async Task ProcessAsync_WithPrefixAndSuffix_GeneratesExpectedOutput()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-input",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-input",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var inputContext = context.GetContextItem <TextInputContext>();

                inputContext.SetLabel(
                    isPageHeading: false,
                    attributes: null,
                    content: new HtmlString("The label"));

                inputContext.SetPrefix(attributes: null, content: new HtmlString("Prefix"));

                inputContext.SetSuffix(attributes: null, content: new HtmlString("Suffix"));

                var tagHelperContent = new DefaultTagHelperContent();
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new TextInputTagHelper()
            {
                Id   = "my-id",
                Name = "my-name"
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            var expectedHtml = @"
<div class=""govuk-form-group"">
    <label for=""my-id"" class=""govuk-label"">The label</label>
    <div class=""govuk-input__wrapper"">
        <div aria-hidden=""true"" class=""govuk-input__prefix"">Prefix</div>
        <input
            class=""govuk-input""
            id=""my-id""
            name=""my-name""
            type=""text"">
        <div aria-hidden=""true"" class=""govuk-input__suffix"">Suffix</div>
    </div>
</div>";

            AssertEx.HtmlEqual(expectedHtml, output.RenderToString());
        }
        public async Task ProcessAsync_WithCheckedItemConditional_GeneratesExpectedOutput()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-radios",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-radios",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var radiosContext = context.GetContextItem <RadiosContext>();

                radiosContext.AddItem(new RadiosItem()
                {
                    Checked      = true,
                    LabelContent = new HtmlString("First"),
                    Conditional  = new RadiosItemConditional()
                    {
                        Content = new HtmlString("Item 1 conditional")
                    },
                    Id    = "first",
                    Value = "first"
                });

                var tagHelperContent = new DefaultTagHelperContent();
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new RadiosTagHelper(new ComponentGenerator(), new DefaultModelHelper())
            {
                IdPrefix = "my-id",
                Name     = "testradios"
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            var expectedHtml = @"
<div class=""govuk-form-group"">
    <div class=""govuk-radios"" data-module=""govuk-radios"">
        <div class=""govuk-radios__item"">
            <input class=""govuk-radios__input"" id=""first"" name=""testradios"" type=""radio"" value=""first"" checked=""checked"" data-aria-controls=""conditional-first"" />
            <label class=""govuk-radios__label govuk-label"" for=""first"">First</label>
        </div>
        <div class=""govuk-radios__conditional"" id=""conditional-first"">Item 1 conditional</div>
    </div>
</div>";

            AssertEx.HtmlEqual(expectedHtml, output.RenderToString());
        }
        public async Task ProcessAsync_AddItemToContext()
        {
            // Arrange
            var dateInputContext = new DateInputContext(haveExplicitValue: false);

            var context = new TagHelperContext(
                tagName: "govuk-date-input-day",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>()
            {
                { typeof(DateInputContext), dateInputContext }
            },
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-date-input-day",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var itemContext = context.GetContextItem <DateInputItemContext>();
                itemContext.SetLabel(new HtmlString("Label"), attributes: new AttributeDictionary());

                var tagHelperContent = new DefaultTagHelperContent();
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new DateInputItemTagHelper()
            {
                Autocomplete = "off",
                Id           = "my-day",
                InputMode    = "im",
                Name         = "my_day",
                Pattern      = "*",
                Value        = 2
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            Assert.Collection(
                dateInputContext.Items.Values,
                item =>
            {
                Assert.Equal("off", item.Autocomplete);
                Assert.Equal("my-day", item.Id);
                Assert.Equal("im", item.InputMode);
                Assert.Equal("Label", item.LabelContent?.RenderToString());
                Assert.Equal("my_day", item.Name);
                Assert.Equal("*", item.Pattern);
                Assert.Equal(2, item.Value);
                Assert.True(item.ValueSpecified);
            });
        }
Example #29
0
        public async Task ProcessAsync_WithItemHint_GeneratesExpectedOutput()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-checkboxes",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-checkboxes",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var checkboxesContext = context.GetContextItem <CheckboxesContext>();

                checkboxesContext.AddItem(new CheckboxesItem()
                {
                    LabelContent = new HtmlString("First"),
                    Hint         = new CheckboxesItemHint()
                    {
                        Content = new HtmlString("First item hint")
                    },
                    Id    = "first",
                    Value = "first"
                });

                var tagHelperContent = new DefaultTagHelperContent();
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new CheckboxesTagHelper(new ComponentGenerator(), new DefaultModelHelper())
            {
                IdPrefix = "my-id",
                Name     = "testcheckboxes"
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            var expectedHtml = @"
<div class=""govuk-form-group"">
    <div class=""govuk-checkboxes"" data-module=""govuk-checkboxes"">
        <div class=""govuk-checkboxes__item"">
            <input class=""govuk-checkboxes__input"" id=""first"" name=""testcheckboxes"" type=""checkbox"" value=""first"" aria-describedby=""first-item-hint"" />
            <label class=""govuk-checkboxes__label govuk-label"" for=""first"">First</label>
            <div class=""govuk-checkboxes__hint govuk-hint"" id=""first-item-hint"">First item hint</div>
        </div>
    </div>
</div>";

            AssertEx.HtmlEqual(expectedHtml, output.RenderToString());
        }
        public async Task ProcessAsync_GeneratesExpectedOutput()
        {
            // Arrange
            var context = new TagHelperContext(
                tagName: "govuk-breadcrumbs",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-breadcrumbs",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var breadcrumbsContext = context.GetContextItem <BreadcrumbsContext>();

                breadcrumbsContext.AddItem(new BreadcrumbsItem()
                {
                    Href    = "first",
                    Content = new HtmlString("First")
                });

                breadcrumbsContext.AddItem(new BreadcrumbsItem()
                {
                    Href    = "second",
                    Content = new HtmlString("Second")
                });

                breadcrumbsContext.AddItem(new BreadcrumbsItem()
                {
                    Content = new HtmlString("Last")
                });

                var tagHelperContent = new DefaultTagHelperContent();
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new BreadcrumbsTagHelper();

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            var expectedHtml = @"
<div class=""govuk-breadcrumbs"">
    <ol class=""govuk-breadcrumbs__list"">
        <li class=""govuk-breadcrumbs__list-item""><a class=""govuk-breadcrumbs__link"" href=""first"">First</a></li>
        <li class=""govuk-breadcrumbs__list-item""><a class=""govuk-breadcrumbs__link"" href=""second"">Second</a></li>
        <li aria-current=""page"" class=""govuk-breadcrumbs__list-item"">Last</li>
    </ol>
</div>";

            AssertEx.HtmlEqual(@expectedHtml, output.RenderToString());
        }