S&box Wiki

Revision Difference


<cat>UI.Razor</cat> <title>Razor Overview</title> ⤶ # What are Razor components?⤶ ⤶ ⤶ # What are Razor components?⤶ Asp.net has this thing called [Razor](https://en.wikipedia.org/wiki/ASP.NET_Razor). Filename is `FriendName.razor` ``` @using Sandbox; @using Sandbox.UI; @namespace Menu <root class="friend-name @FriendClasses()">@Friend.Name</root> @code { public Friend Friend { get; set; } string FriendClasses() { if (Friend.IsMe) return "is-me"; if (Friend.IsFriend) return "is-friend"; return ""; } } ``` As you can see, it's html with c# mixed in. This code creates a new panel class called `FriendName`, which just shows a friend's name. <warning> Due to the fact that Razor components compile and hotload into c#, the entire game has to recompile for a hotload to occur. This causes a massive hit on hotload performance compared to external stylesheets and html templates. Due to the fact that Razor components compile and hotload into c#, the entire game has to recompile for a hotload to occur. This causes a massive hit on hotload performance for the layout, compared to external stylesheet hotloading. </warning> # Switching between code and html If you start something with @, it'll be c#. This is easier to understand in visual studio because you'll get intellisense around it. ⤶ <warning>⤶ Please note that Intellisense in Visual Studio for razor panel types is heavily impeded and will not work properly for most code at the moment.⤶ </warning>⤶ <upload src="1/8dab7803c799870.png" size="26827" name="image.png" /> You'll switch back to html as soon as you do a html element, or close the curly braces. # Changing State The UI will be rebuilt when we think the state has changed (interactions usually). If you change the state and need to force the UI to rebuild, you can call `StateHasChanged()`. This won't rebuild the page instantly, it'll just invalidate so it'll be rebuilt on the next page - so you don't have to worry about calling it multiple times. # Loops Where `Categories` is a list of categories. ``` @foreach ( var category in Categories ) { var c = category.category == CurrentCategory ? "active" : ""; <button @onclick=@( () => ChangeCategory( category.category )) class=@c icon="@category.icon">@category.title</button> } ``` # Panels If an html element starts with a capital letter then we assume it's a panel and will try to create/use that class directly. This gives your code a rigidity - because if that panel type changes, your old code will need to too. You can also set properties on the class directly with attributes. If your attribute starts with a capital letter it will be assumed to be a member of the panel. Here's `LobbyChatEntry` ``` @using Sandbox; @using Sandbox.UI; @namespace Menu.Lobby <root class="card"> <div class="card-image" style="background: url( avatar:@Entry.Friend.Id )"> </div> <div class="card-body"> <row> <FriendName Friend=@Entry.Friend></FriendName> <div class="time">@Entry.Created.ToShortTimeString()</div> </row> <h3>@Entry.Message</h3> </div> </root> @code { public Lobby.ChatEntry Entry { get; set; } } ``` and here's a snippet of `LobbyChat` ``` @foreach (var entry in Lobby.ChatEntries ) { <LobbyChatEntry Entry=@entry></LobbyChatEntry> } ``` You can see how we use LobbyChatEntry directly, and set Entry directly. # Root element If your element starts with a <root> element, it'll represent the root of the panel. ``` // Warning.razor <root class="warning"> </root> ``` The above will end up with a single panel of type `Warning` with the class of `warning`. ``` // Warning.razor <div class="warning"> </div> ``` The above will end up with a panel of type `Warning`, with a child `Panel` with the class `warning` # Events You can hook regular panel events with attributes starting with `@on`. Here are some examples. ``` <button @onclick=@SaveChanges>Save Changes</button> <button @onclick=@( () => Log.Info( "Clicked!" ) )>Save Changes</button> <button @onclick=@( ( PanelEvent e ) => Log.Info( $"Clicked {e.This}!" ) )>Save Changes</button> ``` # Callbacks If you're creating a Panel type and it has an event, you can set that action like any other panel attribute. ``` <Switch value=@Value ValueChanged=@( ( bool b ) => Log.Info( $"Switched to {b}" ) )></Switch> ``` # @ref You can get a reference to a created panel using @ref. ⤶ <warning>⤶ Due to the fact that razor panels are only built on their tick, initialization behavior for C# driven procedual UI is largely impeded due to the layout and references only being initialized on the next tick. Proceed with caution when attempting to design C# driven procedual code for panels with razor layouts.⤶ ⤶ Note that most features can be somewhat replicated with razor contained C# logic, refer to some examples on this page to adjust your logic and design to fit razor's structure.⤶ </warning>⤶ ``` <div @ref=ThePanel>This is my panel</div> @code { public Panel ThePanel { get; set; } } ``` # Early Return You can return early in your component if you don't want to render it for some reason.. ``` @if ( Player == null ) { <div>This player isn't valid</div> return; } <div>All about @Player.Name<div> ``` # @code <warning> While the Embedded `@code` tag is very handy for basic code and declarations, it does have some limitations: - Visual studio code analysis and code cleanup do not run. - C# Codegen is not run on .razor embedded code. This means you cannot put [ClientRpc] within a razor file. For any remotely complex code, a partial `.cs` file should be used instead. </warning> The `@code` block allows you to add code which isn't part of the UI. Here you can override any member that you would usually be able to override on Panel. There are some special Razor specific methods that you can override, which will make things a bit easer. ## OnParametersSetAsync OnParametersSet This is called when any of the Parameters change. This allows you an opportunity to reinitialize any other data. The Async version is useful if you have to query some other data source based on external input. ## virtual void OnAfterTreeRender( bool firstTime ) Called after the UI has been built. At this point all the child panels have been created, so if you have created anything with `@ref` that you need to initialize in some other way, this is the best place for that. ## int BuildHash() We need to know when to rebuild the UI. We only want to do it when the state has changed - because it would be a huge waste of time to do it any other time. By default the UI is updated after any event (mouse over, click etc) or when a parameter changes. If you want to kind of watch some external variables and update when they change, you can use the BuildHash function for that. ``` <div>@DateTime.Now</div> @code{ protected override int BuildHash() { return HashCode.Combine( DateTime.Now.ToString() ); } } ``` In the example above, we're showing the UI in the component so want to update it every time it changes. We do this by providing the hash of the string we're using in the hash. ``` @code{ protected override int BuildHash() { return HashCode.Combine(LobbyFrontPage.IsInLobby, Global.InGame); } } ``` In the example above we rebuild the UI whenever the player's lobby and ingame status changes. # <style> You can embed styles in your component. The styles will only apply to your component (and its children). <warning> The Hotload performance warning from the beginning of this page also applies to embedded stylesheets.The Hotload performance warning from the beginning of this page also applies to embedded stylesheets. Use external stylesheets instead, see: https://wiki.facepunch.com/sbox/ui-razor#stylesheets⤶ </warning> ``` @using Sandbox; @using Sandbox.UI; @namespace Menu.CurrentGame <style> .card { padding: 8px; } .card-image { width: 50px; height: 50px; border-radius: 100px; margin-right: 10px; } .friend-name { font-size: 23px; } </style> <root class="card"> <div class="card-image" style="background-image: url( avatar:@Member.Id )"> </div> <div class="card-body"> <FriendName Friend=@Member Override=@Name></FriendName> </div> </root> @code { public string Name { get; set; } public Friend Member { get; set; } } ``` # Stylesheets You can include stylesheets with `@attribute` ``` @using Sandbox; @using Sandbox.UI; @attribute [StyleSheet( "/UI/Styles.scss" )] ``` # Two Way Binds Sometimes you want to bind a variable to a control, and if it changes it, sync the value back. That's what two way binds are. You create a two way bind using `:bind` after the attribute name. ``` <SliderEntry min="0" max="100" step="1" Value:bind=@IntValue></SliderEntry> @code { public int IntValue{ get; set; } = 32; } ``` In the example above, the value is initially set to 32. If the value changes in the Slider, then it sets our IntValue to that value. If our value changes, it sets the Slider value.