Example #1
0
        public List <IReactComponent> GetMatchingChildren(IReactComponent component, bool pseudoElement = false)
        {
            var list = new List <IReactComponent>();

            GetMatchingChildrenInner(component, pseudoElement, list, component, false, LeafNodes);
            return(list);
        }
Example #2
0
        /// <summary>
        /// This will override the layout in a normal MVC app, since the view isen't invoked.
        /// Makes more sense to use on a Sitecore website
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            try
            {
                HttpResponseBase response = context.HttpContext.Response;
                var sb = new StringBuilder();

                IReactComponent component = Environment.CreateComponent <T>(_componentName, _model, _containerId, _clientOnly, _serverOnly);
                if (!string.IsNullOrEmpty(_tag))
                {
                    component.ContainerTag = _tag;
                }
                if (!string.IsNullOrEmpty(_containerClass))
                {
                    component.ContainerClass = _containerClass;
                }

                var originalResult  = component.RenderHtml(_clientOnly, _serverOnly);
                var serializedModel = JsonConvert.SerializeObject(_model);

                sb.Append($"<div data-react-component=\"{_componentName.ToLower()}\">");
                sb.Append(originalResult);
                sb.Append($"<script>");
                sb.Append(serializedModel);
                sb.Append("</script>");
                sb.Append("</div>");

                response.Write(sb.ToString());
            }
            finally
            {
                Environment.ReturnEngineToPool();
            }
        }
Example #3
0
        public static IHtmlString ReactWithModel <T>(this HtmlHelper htmlHelper, string componentName, T props, string htmlTag = null, string containerId = null, bool clientOnly = false, bool serverOnly = false, string containerClass = null, Action <Exception, string, string> exceptionHandler = null, IRenderFunctions renderFunctions = null)
        {
            try
            {
                var sb = new StringBuilder();
                containerId = componentName.ToLower();

                IReactComponent component = Environment.CreateComponent <T>(componentName, props, containerId, clientOnly, serverOnly);
                if (!string.IsNullOrEmpty(htmlTag))
                {
                    component.ContainerTag = htmlTag;
                }
                if (!string.IsNullOrEmpty(containerClass))
                {
                    component.ContainerClass = containerClass;
                }

                var originalResult  = component.RenderHtml(clientOnly, serverOnly);
                var serializedModel = JsonConvert.SerializeObject(props);

                sb.Append($"<div data-react-component=\"{componentName.ToLower()}\">");
                sb.Append(originalResult);
                sb.Append($"<script>");
                sb.Append($"{serializedModel}");
                sb.Append("</script>");
                sb.Append("</div>");

                return(new HtmlString(sb.ToString()));
            }
            finally
            {
                Environment.ReturnEngineToPool();
            }
        }
Example #4
0
        protected override void DoRender(HtmlTextWriter output)
        {
            IReactComponent reactComponent = Environment.CreateComponent(Name, GetProps());

            output.Write(reactComponent.RenderHtml());
            output.Write("<script>{0}</script>".FormatWith(reactComponent.RenderJavaScript()));
        }
Example #5
0
        protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            var componentName = Path.GetFileNameWithoutExtension(this.ViewPath)?.Replace("-", string.Empty);
            var props         = GetProps(viewContext.ViewData.Model);

            try
            {
                IReactComponent reactComponent = this.Environment.CreateComponent(componentName, props);
                if (ReactSettingsProvider.Current.EnableClientside)
                {
                    writer.WriteLine(reactComponent.RenderHtml());
                    var tagBuilder = new TagBuilder("script")
                    {
                        InnerHtml = reactComponent.RenderJavaScript()
                    };


                    writer.Write(System.Environment.NewLine);
                    writer.Write(tagBuilder.ToString());
                }
                else
                {
                    writer.WriteLine(reactComponent.RenderHtml(renderServerOnly: true));
                }
            }
            catch (React.Exceptions.ReactScriptLoadException ex)
            {
                throw new ReactScriptLoadException("ReactJs.Net script loading exception.", ex);
            }
        }
Example #6
0
        private bool GetMatchingChildrenInner(
            IReactComponent component, bool pseudoElement, List <IReactComponent> list, IReactComponent scope, bool singleItem, List <RuleTreeNode <T> > leafList)
        {
            var matches = leafList.Any(x => x.Matches(component, scope));

            if (matches)
            {
                list.Add(component);
            }
            if (matches && singleItem)
            {
                return(true);
            }

            if (component is ContainerComponent cmp)
            {
                foreach (var child in cmp.Children)
                {
                    var childMatches = GetMatchingChildrenInner(child, pseudoElement, list, scope, singleItem, leafList);
                    if (childMatches && singleItem)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Example #7
0
        public IReactComponent GetMatchingChild(IReactComponent component, bool pseudoElement = false)
        {
            var list = new List <IReactComponent>();

            GetMatchingChildrenInner(component, pseudoElement, list, component, true, LeafNodes);
            return(list.FirstOrDefault());
        }
 public void RemoveListener(IReactComponent listener)
 {
     if (listeners.TryGetValue(listener.ListenerGuid, out var action))
     {
         listeners.Remove(listener.ListenerGuid);
         reactions.Remove(listener.ComponentReact);
     }
 }
Example #9
0
 public void UnregisterChild(IReactComponent child)
 {
     if (child is ReactComponent u)
     {
         u.RectTransform.SetParent(null, false);
         Children.Remove(u);
         Layout.RemoveChild(u.Layout);
     }
 }
Example #10
0
 public void UnregisterChild(IReactComponent child)
 {
     if (child is IEditorComponent <VisualElement> u)
     {
         Element.Remove(u.Element);
         Children.Remove(u);
         Layout.RemoveChild(u.Layout);
     }
 }
        public void AddListener(IReactComponent listener)
        {
            if (listeners.ContainsKey(listener.ListenerGuid))
            {
                return;
            }

            listeners.Add(listener.ListenerGuid, listener.ComponentReact);
            reactions.Add(listener.ComponentReact);
        }
        /// <summary>
        /// Adds the provided <see cref="IReactComponent"/> to the list of components to render client side.
        /// </summary>
        /// <param name="component">Component to add to client side render list</param>
        /// <param name="clientOnly">True if server-side rendering will be bypassed. Defaults to false.</param>
        /// <returns>The component</returns>
        public virtual IReactComponent CreateComponent(IReactComponent component, bool clientOnly = false)
        {
            if (!clientOnly)
            {
                EnsureUserScriptsLoaded();
            }

            _components.Add(component);
            return(component);
        }
Example #13
0
        public override void Visit(IReactComponent component)
        {
            switch (component)
            {
            case TextComponent t:
                Text += t.Text.text;
                break;

            default:
                break;
            }
        }
Example #14
0
        public void RegisterRootView(IReactComponent view)
        {
            var rootTag = _rootViewStartTag ?? 1;

            view.ReactTag = rootTag;

            _rootViewStartTag = view.ReactTag + 10;

            _viewRegistry[rootTag] = view;

            _rootViews.Add(view);
        }
Example #15
0
        public void setEventListener(IReactComponent element, string eventType, JsValue value)
        {
            var hasValue = value != null && !value.IsNull() && !value.IsUndefined() && !value.IsBoolean();
            var callback = value.As <FunctionInstance>();

            if (hasValue && callback == null)
            {
                throw new Exception("The callback for an event must be a function.");
            }

            element.SetEventListener(eventType, new Callback(callback));
        }
Example #16
0
        public void AddAfter()
        {
            if (AfterPseudo != null)
            {
                return;
            }
            var tc = new TextComponent("", Context, "_after");

            AfterPseudo        = tc;
            tc.IsPseudoElement = true;
            tc.GameObject.name = "[After]";
            tc.SetParent(this, Children.LastOrDefault(), true);
        }
Example #17
0
        public bool Matches(IReactComponent component, IReactComponent scope)
        {
            if (!ThisMatches(component, scope))
            {
                return(false);
            }

            // We are at root, all rules matched
            if (Parent == null)
            {
                return(true);
            }

            var relative = component;
            var runOnce  = RelationType == RuleRelationType.DirectSibling || RelationType == RuleRelationType.DirectParent || RelationType == RuleRelationType.Self;

            while (relative != null)
            {
                if (RelationType == RuleRelationType.Parent || RelationType == RuleRelationType.DirectParent)
                {
                    relative = relative.Parent;
                }
                else if (RelationType == RuleRelationType.Sibling || RelationType == RuleRelationType.DirectSibling)
                {
                    if (relative.Parent == null)
                    {
                        return(false);
                    }
                    var ind = relative.Parent.Children.IndexOf(relative);
                    if (ind == 0)
                    {
                        return(false);
                    }
                    relative = relative.Parent.Children[ind - 1];
                }

                if (Parent.Matches(relative, scope))
                {
                    return(true);
                }
                if (runOnce)
                {
                    return(false);
                }
            }

            return(false);
        }
Example #18
0
        private bool ThisMatches(IReactComponent component, IReactComponent scope)
        {
            // We are at root, all rules matched
            if (ParsedSelector == null)
            {
                return(true);
            }

            // We reached the end of component hierarchy and there are still rules to process
            // This means the matching is incomplete
            if (component == null)
            {
                return(false);
            }

            return(ParsedSelector.All(x => x.Negated ^ x.Matches(component, scope)));
        }
Example #19
0
 public void RegisterChild(IReactComponent child, int index = -1)
 {
     if (child is ReactComponent u)
     {
         u.RectTransform.SetParent(Container, false);
         if (index >= 0)
         {
             u.RectTransform.SetSiblingIndex(index);
             Children.Insert(index, u);
             Layout.Insert(index, u.Layout);
         }
         else
         {
             Children.Add(u);
             Layout.AddChild(u.Layout);
         }
     }
 }
Example #20
0
 public void RegisterChild(IReactComponent child, int index = -1)
 {
     if (child is IEditorComponent <VisualElement> u)
     {
         if (index >= 0)
         {
             Element.Insert(index, u.Element);
             Children.Insert(index, u);
             Layout.Insert(index, u.Layout);
         }
         else
         {
             Element.Add(u.Element);
             Children.Add(u);
             Layout.AddChild(u.Layout);
         }
     }
 }
        public void SetPropsForView(IDictionary <string, object> props, IReactComponent view)
        {
            if (view == null || props == null)
            {
                return;
            }

            if (_defaultView == null)
            {
                _defaultView = CreateViewWithTag(-1);
            }

            Execute.OnUIThread(() =>
            {
                props.Keys.Apply(key =>
                {
                    SetPropertyForKey(view, key, props[key]);
                });
            });
        }
        protected override void RenderContents(HtmlTextWriter output)
        {
            //### We are rendering React components to a Literal on ReactComponent.ascx
            //multiple compoents can be rendered from here.

            //render react components
            var             env            = AssemblyRegistration.Container.Resolve <IReactEnvironment>();
            IReactComponent reactComponent = null;

            switch (this.ComponentName)
            {
            case ComponentNameEnum.HelloWorld:
                //set componet properties
                var objectModel = new { user = HelloWorldUserName };
                //Get Hello World Component
                reactComponent = env.CreateComponent("PageContent", objectModel);
                break;

            case ComponentNameEnum.HelloWorld2:
                //set componet properties
                var objectModel_helloWorld2 = new { name = HelloWorldUserName };
                //Get Hello World Component
                reactComponent = env.CreateComponent("HelloWorld2", objectModel_helloWorld2);
                break;

            case ComponentNameEnum.ReactImage:
                //set componet properties
                var objectModel_reactImage = new { imageName = ReactImageName };
                //Get ReactImage Component
                reactComponent = env.CreateComponent("ReactImage", objectModel_reactImage, "imageDiv");
                break;
            }

            if ((env != null) && (reactComponent != null))
            {
                //render
                output.Write(reactComponent.RenderHtml());
            }
        }
Example #23
0
        public void SetParent(IContainerComponent parent, IReactComponent relativeTo = null, bool insertAfter = false)
        {
            if (Parent != null)
            {
                Parent.UnregisterChild(this);
            }

            Parent = parent;

            if (Parent == null)
            {
                return;
            }

            relativeTo = relativeTo ?? (insertAfter ? null : parent.AfterPseudo);

            if (relativeTo == null)
            {
                parent.RegisterChild(this);
            }
            else
            {
                var ind = parent.Children.IndexOf(relativeTo);
                if (insertAfter)
                {
                    ind++;
                }

                parent.RegisterChild(this, ind);
            }

            Style.Parent = parent.Style;
            ResolveStyle(true);

            Parent.ScheduleLayout();
        }
Example #24
0
 public string Get(IReactComponent component)
 {
     Text = "";
     component.Accept(this);
     return(Text);
 }
        public void SetPropsForView(IDictionary<string, object> props, IReactComponent view)
        {
            if (view == null || props == null)
            {
                return;
            }

            if (_defaultView == null)
            {
                _defaultView = CreateViewWithTag(-1);
            }

            Execute.OnUIThread(() =>
            {
                props.Keys.Apply(key =>
                {
                    SetPropertyForKey(view, key, props[key]);
                });
            });
        }
Example #26
0
 public void RemoveGlobalReactComponent(IReactComponent reactComponent)
 {
     componentsService.RemoveListener(reactComponent);
 }
Example #27
0
 public void AddGlobalReactComponent(IReactComponent reactComponent)
 {
     componentsService.AddListener(reactComponent);
 }
 public static bool IsReactRootView(this IReactComponent component)
 {
     return(component != null && component.ReactTag.HasValue && component.ReactTag.Value % 10 == 1);
 }
Example #29
0
        public void RegisterRootView(IReactComponent view)
        {
            var rootTag = _rootViewStartTag ?? 1;
            view.ReactTag = rootTag;

            _rootViewStartTag = view.ReactTag + 10;

            _viewRegistry[rootTag] = view;

            _rootViews.Add(view);
        }
Example #30
0
        public bool Matches(IReactComponent component, IReactComponent scope = null)
        {
            if (component.IsPseudoElement)
            {
                return(Type == RuleSelectorPartType.Tag && Name == component.Tag);
            }

            switch (Type)
            {
            case RuleSelectorPartType.None:
                return(false);

            case RuleSelectorPartType.All:
                return(true);

            case RuleSelectorPartType.Tag:
                if (Name != null && Name.StartsWith("_"))
                {
                    return(component.Name == Name);
                }
                return(Name == component.Tag);

            case RuleSelectorPartType.Id:
                return(Name == component.Name);

            case RuleSelectorPartType.ClassName:
                return(component.ClassList != null && component.ClassList.Contains(Name));

            case RuleSelectorPartType.Attribute:
                return(component.Data.TryGetValue(Name, out var val) && Equals(val, Parameter));

            case RuleSelectorPartType.DirectDescendant:
            case RuleSelectorPartType.AdjacentSibling:
            case RuleSelectorPartType.Sibling:
            case RuleSelectorPartType.Self:
                return(true);

            case RuleSelectorPartType.Not:
                break;

            case RuleSelectorPartType.FirstChild:
                return(component.Parent != null && component.Parent.Children[0] == component);

            case RuleSelectorPartType.LastChild:
                return(component.Parent != null && component.Parent.Children[component.Parent.Children.Count - 1] == component);

            case RuleSelectorPartType.NthChild:
                return(component.Parent != null && ((NthChildParameter)Parameter).Matches(component.Parent.Children.IndexOf(component) + 1));

            case RuleSelectorPartType.NthLastChild:
                return(component.Parent != null && ((NthChildParameter)Parameter).Matches(component.Parent.Children.Count - component.Parent.Children.IndexOf(component)));

            case RuleSelectorPartType.Empty:
                var cmp = component as IContainerComponent;
                return(cmp == null || cmp.Children.Count == 0);

            case RuleSelectorPartType.OnlyChild:
                return(component.Parent != null && component.Parent.Children.Count == 1);

            case RuleSelectorPartType.Root:
                return(component is IHostComponent);

            case RuleSelectorPartType.Scope:
                return(scope != null && component == scope);

            case RuleSelectorPartType.Before:
            case RuleSelectorPartType.After:
                return(true);

            case RuleSelectorPartType.Hover:
            case RuleSelectorPartType.Focus:
            case RuleSelectorPartType.FocusVisible:
            case RuleSelectorPartType.FocusWithin:
            case RuleSelectorPartType.Active:
                return(true);

            case RuleSelectorPartType.Important:
            case RuleSelectorPartType.Special:
                return(true);

            case RuleSelectorPartType.State:
                return(component.StateStyles.GetState(Parameter as string));

            default:
                break;
            }

            return(false);
        }
Example #31
0
 public void RemoveAfter()
 {
     AfterPseudo?.Destroy();
     AfterPseudo = null;
 }
Example #32
0
 public abstract void Visit(IReactComponent component);
 public void RemoveView(IReactComponent child)
 {
     _views.Remove(child);
 }
 public void AddViewAtIndex(IReactComponent view, int index)
 {
     _views.Insert(index, view);
 }
 public void AddView(IReactComponent view)
 {
     _views.Add(view);
 }