7 ms·
UI = f(statesⁿ)
- taeric 3y agoI am growing into the idea that everyone should try and build some games. Just a "simple" card game like solitaire would suffice for a lot of the lessons. Biggest one being that anything you want to be able to do visually has to be represented somewhere as state. Pretty much period. And this state will be far more complicated than the simplified state diagram that you will come up with if you are only modeling the intended actions of a game. If you are lucky with extra computing power, you can layer your code so that the core rules of the game are able to be written independently of how you represent the cards in play. But I assert that you will often be surprised that accomplishing this separation is more code than the alternatives.
- cushpush 3y agoPeople who say the universe is a simulation never consider the graphical overhead required. It'd be so annoying to make, I don't believe even an alien species would have the patience for it.
- ikari_pl 3y agoAI had the patience, Mr Anderson
- serial_dev 3y agoThey (we?) could use AI for that, why would you write it by hand?
- p0w3n3d 3y agoIt's simple. You just create set of rules that will eventually end up in earth being created. Just requires you to be God
- 01HNNWZ0MV43FF 3y ago"Red shift is a feature, not a bug!"
- naasking 3y agoThis is a common misunderstanding. You don't have to simulate the universe, you only have to simulate the minds that believe they are observing the universe. You are then by necessity merely simulating their perceptual facts rather than all of the physical states that eventually produce a perceptual fact. This is considerably simpler.
- solardev 3y agoI would love to try something like that, but I have no idea how to model complex game logic like that in data, especially if it's decoupled from the UI state =/ For example, to make even a "simple" game on something like Boardgamearena, you're supposed to create a state machine: https://www.slideshare.net/boardgamearena/bga-studio-focus-on-bga-game-state-machine https://www.slideshare.net/boardgamearena/bga-studio-focus-o... I don't even know what that is, and it's a lot more complicated than anything I'd ever seen on the frontend in the HTML/JS world. (To be fair, that's probably because I never had proper CS training. I'm just a self-taught web dev.) But it seems to me that even simple games require creating really complex engines that aren't really similar to the businesses needs I've coded for in the past... Not disagreeing with you at all, it all just seems so overwhelming compared to simple stuff like HTML/CSS/JS.
- matthewfcarlson 3y agoEven better, make a simple networked game. Socket.io makes it quite trivial to send messages. What I found works really well is keeping state as a series of mutations. Then a client emits a mutation and its broadcast out, if the mutation can’t apply, then it gets discarded and the server sends its copy of the state to the client that emitted the bad mutation. Makes it really hard to cheat but only requires sending mutations to the clients. https://matthewc.dev/projects/vuex-sync-p1/ https://matthewc.dev/projects/vuex-sync-p1/
- swatcoder 3y agoThat's sort of the point. A lot of people got drawn into the industry in its latest boom and found themselves glueing together remote services using an ever-changing collection of heavy frontend frameworks and never experienced actually modeling an application from top to bottom. It doesn't need to be a game, but doing more of the dirty work that "[you] have no idea how to model" andis "more complicated than anything [you]'ve ever seen" can help induct you into a much richer and more cognizant craft practice.
- solardev 3y agoThis isn't so much the old argument of (say) Next.js v HTML(x), but of the different degrees of state complexity required in a typical business app vs an actual game (at least to my mind). To me, it's a lot clearer how to deal with a traditional ecommerce database setup like Northwind Traders (https://en.wikiversity.org/wiki/Database_Examples/Northwind https://en.wikiversity.org/wiki/Database_Examples/Northwind). I've had to do that many times and know how to model such a thing. I have no idea how to start modeling the state for a game like Wingspan (https://boardgamearena.com/gamepanel?game=wingspan https://boardgamearena.com/gamepanel?game=wingspan), much less something more complicated, like Magic: The Gathering, where any of several tens of thousands of cards can interact with each other in novel ways, maybe even leading to infinite loops and such. In my mind it's like a giant if-then flowchart with a billion flows. I wish I could see the source code for the rules engine of such a thing, but with a step-by-step tutorial...
- TacticalCoder 3y ago> Just a "simple" card game like solitaire would suffice for a lot of the lessons. I've written an actual game, a 2D platformer. If there's a domain where it's easy to demonstrate that the view is purely a function of the state it's precisely in gaming. In many games you can toggle (in dev or even for some during gameplay) between "the real view" and, say, wireframe view of the game (with lots of debug infos added too for example). Or you can toggle between a 3D view of your game or a top-down 2D one. Or you can toggle between different types of rendering (as in Diablo 2 where both a 2D and fake 3D view where available and the modern Diablo 2 ressurected, where you can you can show... The 25 year old view if you want to, at any time). Many games are 100% deterministic and the entire game user(s) played can be recreated from only a record of the user(s) inputs (which is why some save files for long games can be tinier than tiny). And it'll replay the same on different screen configurations / different platforms. The view in a game at time n is literally f(state n).
- taeric 3y agoCertainly! That was indeed my intention here. The big learning I'm intending is just how much state that people take for granted is necessary to track.
- ape_key 3y agorespectfully you haven’t written enough games > real game turn-based and real-time games have different kinds of complexity, so a platformer won’t expose you to all of it. turn-based games are roughly going to give you an easier time separating the game code, but the UI code is going to feel like a debilitating slog. > Many games are 100% deterministic Until you use floating points, networking, or different platforms. This is more likely to be true in turn-based games, and super unlikely in anything real-time and multiplayer. Most games like that periodically sync state instead of relying on applying actions on each client
- amelius 3y agoAre you saying that IEEE 754 floating point (which everybody is using) is not deterministic?
- bjnewman85 3y agoUI=F((irreducibleComplexity + poorDesignChoices + poorArchitectureChoices + techDebt + bad coding + states)^n). The author mixes web and native UI development here to encompass a partial range of possible UIs, there's obviously a lot more complexity in UI development if we expand that list to include AR/VR, CLIs, voice-based interfaces, etc. But also most software UIs we are building today are overly complicated. Because devs forget f() is supposed to narrow the complexity space to match the users needs, by making illegal states unrepresentable.
- wetpaws 3y ago[dead]
- jimberlage 3y agoTBH - I find the opposite is true. Far more complaints have been of the form “this isn’t an illegal state, the dev mistakenly thought so because they’re not a domain expert - why won’t they let me do this?” And some illegal states are useful. Letting a form exist with a field the user can’t fill out, along with disabled logic and a helper message, is often the best way to onboard users to your tool. Lots of proponents of making illegal states unrepresentable take those fields away so they don’t have to muck with validation logic, which takes away your best way to explain how to use your tool to a user.
- bjnewman85 3y agoi would argue that any state that is useful should not be illegal, but i agree with you that people have often used that phrase to mean what you said
- hombre_fatal 3y agoThat's not criticism of syncing possible states with expected ones. e.g. Not having a disabled={condition} on some input field isn't going to change the fact that the client wasn't built to handle that state. Either the client was written to expect it or it was not. All you're saying is just expect the states that make sense which is (A) a trivial claim and (B) something you have to do even if you don't make unexpected states impossible.
- mathgladiator 3y agoSo, I'm in the camp of UI = f(state) because I look at things like stadia/app-streaming as an obviously better way to build software faster. However, there are challenges, so I've got an experiment with a new UI framework called RxHTML that basically treats the browser as a function of a stream JSON document and local view state with a tiny language to manipulate the view state. It works shockingly well, and the goal isn't to be 100% of all use-cases but to make 90% super easy for anyone to do.
- qudat 3y agoI think `view = fn(state)` is mostly right but how it is implemented is wrong. If we look at react, everything is nice and declarative until you register event handlers, at which point you enter imperative land to hand manipulate state. I think what is more accurate is: `view = fn(event-stream)`. Events include but not limited to: - User events - Prop change events - Local state change events - Global state change events When we switch the paradigm to be about event streams, all of a sudden there is no bifurcation between prop, local state, global state, and user events -- it is all treated the exact same.
- hombre_fatal 3y agoThis sounds like `state = reduce(state, event)` and `view = fn(state)` where the view has UI handlers that dispatch events rather than mutating anything. Elm is probably the simplest example of this paradigm top-to-bottom, but you can wire up something pretty simple in vanilla React with just useReducer and useContext.
- esmevane 3y agoI like to think of it as `view, effects = fn(state, events)`, where effects are any subsequent events or instructions that come out of a state change. I think of it very close to how you're outlining it here, though, and when I'm thinking of effects I'm generally also thinking of it as a set of things that can fit into an event stream like you're outlining.
- fleabitdev 3y agoThe purpose of `view = fn(state)` is to protect you from O(n*m) complexity scaling if you handle each event in isolation. For any given part of your UI, you'll have n events to handle ("UI started up for the first time", "x changed", "y changed", "checkbox toggled", "undo", "redo", "file loaded"), and m invariants to uphold ("while the checkbox is checked, the user cannot edit y", "while x is less than y, the UI should display a warning", "this label displays the current value of y as a localised string"). If you try to manually maintain each invariant when handling each event, you'll find it works for simple cases, but it falls apart for larger values of n and m.
- 3y ago
- parhamn 3y agoSomewhat unrelated but, I've been doing a ton of frontend coding past few years (coming from a backend/infra background). I think browser development is an underrated difficult problem. With a lot of crappy half-assed solutions that don't have solutions at depth that the backend ecosystem has. Like if you get to the essence of it you're syncing two local event loops -- the JavaScript and browser renderer, omitting the JS async queue and webworkers. Then you have a distributed system on top connecting to your backend. And sometimes you have a distributed system across the same local instance of the app, e.g. multiple tabs of the same app. All this with neanderthal grade tools. At every layer of this there are half-thought tools with inconsistent data models that try to connect different layers of the problem (component rendering, data fetching, event loops, background jobs, etc) without any great way to do so. Straight glue. Sure most people call some hook with refresh loop or something and call it day, but the problem still hasn't been solved well for building ultra-rich apps.
- n2d4 3y agoThis is the problem that most JavaScript frontend frameworks are trying to solve. Most of them just connect JS and renderer event loops, but some are approaching data fetching and background jobs as well (like React with the experimental `use` hook, or Svelte Query). They do however come with significant complexity for new users, and if you write React code without understanding the underlying event loops, you'll write code with weird edge cases (eg. overreliance on useEffect). But I do think that they solve the problem pretty well once you got past that initial burden of learning them.
- parhamn 3y ago> they solve the problem pretty well once you got past that initial burden of learning them. Please do share how the canary `use` hook solves: remote data syncing, proper data sharing across the UI, real-time remote syncing, incremental updates, optimistic updates, realtime collaboration, offline only, etc These are table stakes for good rich apps now. Now your answer is probably going to be to 'use other tools for this' and the lack of cohesion between those tools is what I'm saying is crappy glue. The atoms aren't good.
- michaelsbradley 3y agoFor help in modeling the states and taming the complexity: https://stately.ai/docs/xstate https://stately.ai/docs/xstate
- davidkpiano 3y ago(Creator here) Thank you for the mention!
- scottcorgan 3y agoSounds like Cycle.js
- LAC-Tech 3y agoShower thought I've had recently: would we not be better off modelling a UI as Actions, rather than states? Each action changes this part of the markup, makes these requests to app state / client DB / remote server. This also maps better to a user centric conception of the app.
- notpachet 3y agoIf you ascribe to the unidirectional data flow philosophy a la Redux, then actions are just transformations between immutable state representations.
- ramesh31 3y agoYou've just described Redux/Flux
- LAC-Tech 3y agoThen my description isn't very good because I'm not imagining redux at all.
- lioeters 3y agoHere's how I model it: the view is a function of state; and actions create a new state, which re-renders the view. state -> view -> actions - | ^----------------------- Actions can be from the user via the view, but it can come from elsewhere, for example, websocket events. I like what another commenter said about a "stream of events", though in my mind an action is more limited than an event. An action has no event handlers, it can only dispatch state changes (or other actions).
- jmount 3y agoIt is getting to the point that I feel we need a rule of the form: your UI is rejected unless you can tell a new user how to succeed with it over the phone. To my mind this means at least: fewer modalities, no hidden menus (hamburger), and, many other things.
- s4i 3y agoThe list is missing URL query params, arguably one of the more common yet underlooked places to store global state in web apps.
- slmjkdbtl 3y agoI think UI = f(state) can only be 100% true in immediate mode UIs? That you can literally have a pure function that takes state and user input and returns a pixel buffer to put on screen. That seems not possible for retained mode UI, which most UI development are?
- tadfisher 3y agoYou can have an immediate-mode frontend to retained-mode state; see React, Compose, SwiftUI, etc. In this case, the retained state is an implementation detail, but the goal of the framework is to render your UI function deterministically whether it's updating or creating fresh state.
- _thisdot 3y ago> Loading - A fetch is happening Loading/Fetching can have multiple states. Some I can think of are: 1. Fetching data when there is no data 2. Fetching data to replace the data, but the data on the screen is not invalid 3. Fetching data to append to the existing data All these warrant different states imo. I have some screenshots on Loading/Fetching here: https://rahulkrrrishna.xyz/notes/2024/01/01/loading-vs-fetching.html https://rahulkrrrishna.xyz/notes/2024/01/01/loading-vs-fetch... I like what `react-query` does. They toggle `isLoading` to true when the data is invalid/nonexistent. All subsequent fetches toggle a different state called `isFetching`
- bsimpson 3y agoAdmittedly I haven't read this article, but the title reminds me of staltz's excellent conceptualization of interactive interfaces: The user sees screens and generates events. The computer sees events and generates screens. It's a mutually observing cycle (hence the name of his framework, Cycle.js).
- bordercases 3y agoThis is the drive behind comonadic UI frameworks in functional programming - streams of mutual recursion.
- grodes 3y agoIt’s just state. A big state, but just state.
- bowsamic 3y agoI was hoping he was actually going to formalise the notion
- pirate3215 3y agoWhenever someone mentions "UI is a function of state", I think about transitions and animations. Is every frame in a transition also a function of state? I tried adding a transition to a dialog box in React sometime back. When the user tries to delete some data, a confirmation dialog shows up. It disappears(with CSS transitions) when the user confirms. Deletion happens before transitions are complete and the user sees a different, unexpected state in the dialog for a flicker of time. This is solved if all the data inside the dialog is actually a deep copy of state. If this was not done via react, we could've prevented the dialog content from being bound to the state Should UI really be a function of states?
- Chris_Newton 3y agoI’d say there are two common patterns for implementing behaviours like transition animations in declarative UIs. The platform and/or the engine that is doing the rendering of your declarative UI might provide facilities to describe animations declaratively as well. In web development, we have some support for animations in CSS. It’s also fairly common, if you use a component-based rendering library like React or Vue, to see some kind of Transition component, which typically wraps the UI components that should change during the animation and specifies the required transition behaviour via its properties. More generally, application states can be part of the “state” that your UI derives from. The linked post gives several examples of this, but a very common one in web apps is having a loading flag when content has been requested from some remote source and isn’t yet available. Whatever code you use to fetch that content also sets the loading flag in the meantime. Then the declarative UI code just needs to check the flag and render whatever spinner or other effect it wants to show during that time. The same idea can be used to implement general transitions/animations. Your state can include something like an “is opening” flag, to indicate that a transition is in progress, and for effects that need to vary over time, also something like a time index or percentage complete. The code responsible for the transition behaviour then sets the flag and starts/updates the timer throughout the transition period. On the rendering side, the declarative UI just needs to check if the flag is set, and if so, render the required effect for the current point in the transition. The key point in this second pattern is that some part of your code that isn’t the main declarative UI is responsible for defining this behaviour via the application state. Then the UI rendering code just takes that extra information into account like any other part of the state. I think the problem in your deletion example is that you had competing representations of what was happening in your system. Apparently you had code that was doing the actual deletion and updating that part of the state immediately, but independently you also had CSS doing the animation, so the visible effects in the UI weren’t synchronised. As you said, you can handle that by making sure the old state you need to render the UI until the animation has finished is preserved somewhere and used for rendering during that time. Maybe that means making a temporary copy and using that for rendering until the animation is done, or for a quick animation, maybe a pragmatic choice is to defer triggering the actual deletion behaviour until the end of the animation.
- midtake 3y agoUnless I missed it, the author doesn't seem to provide an argument as to why the function is exponential. It just seems to be a rant about how much state there is. Sure, there is a lot of state, but much of it is "gated" and you don't need to program an exponential amount of logic to get it all to work. To me it's more like UI is the art of turning f(states^n) into f(n*states). With clever modularity and some intuition about how users think, it's a feasible optimization.