Neighbourhood.omg.lol/Components/Layout/MainLayout.razor

107 lines
2.9 KiB
Text
Raw Permalink Normal View History

2024-05-30 01:06:08 +00:00
@inherits LayoutComponentBase
@implements IDisposable
@inject NavigatorService NavigatorService
@inject NavigationManager NavigationManager
@inject IJSRuntime JS
@inject State State
<NavMenu />
<main class="responsive max">
@Body
</main>
<script>
class Refresher {
constructor(targetEl) {
this.lastKnownScrollPosition = 0
this.ticking = false
this.atTop = true
this.atBottom = false
this.target = targetEl
this.target.addEventListener("scroll", this.scrollEvent)
}
scrolledTo = (scrollPos) => {
// Do something with the scroll position
if (this.atTop && scrollPos > 0) {
this.atTop = false
CSHARP.invokeMethodAsync("SetAtTop", false)
}
else if (!this.atTop && scrollPos == 0) {
// console.log("AT TOP")
this.atTop = true
CSHARP.invokeMethodAsync("SetAtTop", true)
}
const bottom = this.target.scrollHeight - Math.ceil(this.target.offsetHeight)
if (this.atBottom && scrollPos < bottom) {
this.atBottom = false
CSHARP.invokeMethodAsync("SetAtBottom", false)
}
else if (!this.atBottom && scrollPos >= bottom) {
// console.log("AT BOTTOM")
this.atBottom = true
CSHARP.invokeMethodAsync("SetAtBottom", true)
}
}
scrollEvent = (event) => {
this.lastKnownScrollPosition = Math.ceil(event.target.scrollTop)
if (!this.ticking) {
window.requestAnimationFrame(() => {
this.scrolledTo(this.lastKnownScrollPosition)
this.ticking = false
});
this.ticking = true
}
}
Dispose = () => {
this.target.removeEventListener("scroll", this.scrollEvent)
}
}
new Refresher(document.querySelector('main'))
</script>
@code {
private DotNetObjectReference<State>? DotNetRef { get; set; }
protected override void OnAfterRender(bool firstRender) {
base.OnAfterRender(firstRender);
if (firstRender) {
// See warning about memory above in the article
DotNetRef = DotNetObjectReference.Create(State);
JS.InvokeVoidAsync("injectCSharp", DotNetRef);
}
}
protected override void OnInitialized() {
base.OnInitialized();
NavigatorService.NavigationManager = NavigationManager;
State.IntentReceived += IntentRecieved;
if (!string.IsNullOrEmpty(State.ShareString) || !string.IsNullOrEmpty(State.SharePhoto)) {
IntentRecieved();
}
}
private void IntentRecieved(object? sender = null, EventArgs? e = null) {
if (!string.IsNullOrEmpty(State.ShareString)) {
NavigationManager.NavigateTo($"/sharetext/{State.ShareString}");
State.ShareString = null;
}
else if (!string.IsNullOrEmpty(State.SharePhoto)) {
NavigationManager.NavigateTo($"/sharepic/{State.SharePhoto}");
State.SharePhoto = null;
}
}
void IDisposable.Dispose() {
State.IntentReceived -= IntentRecieved;
DotNetRef?.Dispose();
}
}