SlideShare a Scribd company logo
Managing Complex UI with xState
Xavier “X” Lozinguez
Staff Software Engineer @ Jet
Customer Experience Team (Batman)
• French
• PADI Certified Scuba Diver
• BJJ student
Contact
• xavier.lozinguez@jet.com
• @xlozinguez (Github, Twitter)
• http://xavier.lozinguez.com
Agenda
• State Machine? State Charts?
• Example of a “complex” UI
• xState overview
• xState + React
• Q&A
State Machine?
State Charts?
Finite State Machine – ex: traffic light
• Finite amount of states
• Predetermined sequenced transitions
Green Red
Yellow
TIME
R
TIME
R
TIME
R
• Events triggers transitions
State Chart
created by David Harel in 1987
A state chart is a state machine
composed of other state
machines called sub-states.
Sub-states can be state charts
themselves (compound states)
or remain atomic.
Allow for advanced state
composition using hierarchical,
historic and parallel states.
State Chart – ex: traffic light
Green
Yellow
TIME
R
TIME
R
TIME
R
Red
State Chart – ex: traffic light
Green
Yellow
TIME
R
TIME
R
TIME
R
Wal
k
Wai
t
Sto
p
PED_TIM
ER
PED_TIM
ER
Red
Okay… but why? 9
• Tried-and-true methodology for modeling
applications
• Makes the impossible impossible
• Allow for application logic visualization
Complex UI example
Complex UI example
Source: https://material.io/design/interaction/selection.html#item-
Browsing State
CREATE_NEW_ITEM
BROWSE_FOLDERS
SELECT_ITEM
VIEW_ITEM
SEARCH
TOGGLE_VIEW
DISPLAY_INFO
Selecting State
DESELECT_ITEM
RESET_SELECTION
SHARE_SELECTION
DELETE_SELECTION
MOVE_SELECTION_TO_FOLD
SELECT_ITEM
Global State Chart – Browsing & Selecting
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
SELECT_ITEM
RESET_SELECTION
What about
DELETE_SELECTION?
DESELECT_ITEM
(if selectedItems.length >
0)
Global State Chart – Deleting & Prompting
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
xState
xState by David Khourshid (davidkpiano)
Global State Chart – Events
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
Global State Chart – Events
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
xState – Events 20
Composed of a type and an
optional payload
Payload is then handed over to
actions for side-effect purpose
Events cause a state machine to transition from its current state to
the next
type IAppEvent =
| { type: 'SELECT_ITEM', item }
| { type: 'SELECT_ALL_ITEMS’ }
| { type: 'DESELECT_ITEM', item }
| { type: 'DELETE_SELECTION’ }
| { type: 'SELECTION_DELETED’ }
| { type: 'RESET_SELECTION’ }
| { type: 'DISMISS_PROMPT' };
xState: Machine Configuration 21
State machine configuration:
• key (useful to reference
parent/children state)
• context
• state chart: state nodes &
transitions
• Entry state
const appMachineConfig = {
key: 'app’,
context: initialAppContext,
states: {
browsing: {
...
},
selecting: {
...
},
deleting: {
...
},
prompting: {
...
}
},
initial: 'deleting’,
}
Global State Chart - State Transitions
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
Global State Chart - State Transitions
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
Global State Chart - State Transitions
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
xState – State Transitions 25
selecting: {
on: {
SELECT_ITEM: {
// implicit transition (no target)
actions: 'addItemToSelection’
},
DESELECT_ITEM: [{
target: 'browsing’,
cond: (ctx: IAppContext) =>( ctx.selectedItems.length === 1)
// condition: last item in selection
actions: 'removeItemFromSelection’,
}, {
// implicit transition (no target)
cond: (ctx: IAppContext) =>( ctx.selectedItems.length > 1)
// condition: still more items selected
actions: 'removeItemFromSelection’,
}],
RESET_SELECTION: {
target: 'browsing’,
actions: 'resetSelection’
},
DELETE_SELECTION: {
target: 'deleting’,
}
}
},
Selecting
DESELECT_ITEM
(if selectedItems.length <=
0)
RESET_SELECTION
DESELECT_ITEM
(if selectedItems.length > 0)
SELECT_ITEM
DELETE_SELECTION
xState – Actions 26
Actions are fire and forget
side effects triggered upon
state machine transitions
• Three types of actions:
• Entry: executed upon
entering a state
• Exit: executed upon
exiting a state
• Transition: executed
when a transition is
triggered by an event
states: {
browsing: {
onEntry: ['loadItems', 'triggerAnalytics’],
onExit: 'triggerAnalytics’,
on: {
SELECT_ITEM: {
target: 'selecting’,
actions: 'addItemToSelection’
},
SELECT_ALL_ITEMS: {
target: 'selecting’,
actions: 'addAllItemsToSelection’
}
}
},
selecting: {...},
deleting: {...},
prompting: {...}
}
xState – Context 27
• Contains quantitative
data (strings, numbers,
objects, etc.)
• Represents the
“extended state”
managed by the
machine
• Used to hydrate the
application components
• Updated using actions
const initialAppContext: IAppContext = {
items: initialAppContextItems,
selectedItems: []
}
const initialAppContextItems = [{
id: 0,
title: 'Summer Photos’,
owner: 'Anthony Stevens’,
updatedAt: new Date(Date.UTC(2017,6,12))
},
...
]
xState – Updating the context 28
const appMachineOptions = {
actions: {
addItemToSelection: assign((ctx, event) => ({
selectedItems: ctx.selectedItems.concat(event.item)
})),
removeItemFromSelection: assign((ctx, event) => ({
selectedItems: ctx.selectedItems.filter(item => item.id !== event.item.id)
})),
resetSelection: assign((_) => ({
selectedItems: []
})),
deleteSelection: assign(ctx => ({
items: ctx.items.filter(item =>
ctx.selectedItems.findIndex(selectedItem =>
selectedItem.id === item.id) < 0
),
selectedItems: []
})),
}
};
Async Pattern
Global State Chart – Asynchronous Calls
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
Global State Chart - Asynchronous Calls
Browsing Selecting
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length <= 0)
RESET_SELECTION
SELECT_ITEM
DESELECT_ITEM
(if selectedItems.length > 0)
Deleting
DELETE_SELECTION
DELETE_SELECTION_FAILURE
DELETE_SELECTION_SUCCESS
Promptin
g
DISMISS_PROMPT
xState – Asynchronous calls (invoke) 32
For asynchronous calls, xState relies on Promises
• onDone transition is invoked when
the promise resolve()
• onError transition is invoked if the
promise reject()
xState + React
https://codesandbox.io/s/k06kloqzyo
https://github.com/xlozinguez/xstate-demo
Hook xState machine to React
Using the official useMachine hook from @xstate/react
https://github.com/davidkpiano/xstate/tree/master/packages/xstate-
react#readme
xState – Matching state 35
xState – Matching state 36
current.matches(’…’) provides the
ability to set conditional statement
against the machine state.
xState – Matching state 37
=> current.matches(’browsing’) => current.matches(’selecting’)
xState – Triggering State Transitions 38
Transitions are triggered by sending an event to the machine using send({…})
Transitions can also be
triggered using the
Machine.transition({…})
method which requires the
state to transition.
Conclusion
A few take away
Pros Cons
• Self documented and captures the
complete picture
• Explicit and easy to understand
thanks to state charts
• Behavior can be tested independently
from presentation layer
• State charts scale very well due to
their inherent composability
• Can accommodate complex use
cases (services, compound vs
parallel, etc.)
• New paradigm to consider
• Requires a complete picture of the
system so it can be transcribed into
state charts
• Uncovers a different set of problem to
solve around state composition (state vs
context, sub-states)
Thank you!
Questions?
References
• https://github.com/davidkpiano/xstate
• https://xstate.js.org
• https://statecharts.github.io
• https://spectrum.chat/statecharts
• https://medium.com/@DavidKPiano/the-facetime-bug-and-the-dangers-of-
implicit-state-machines-a5f0f61bdaa2
• https://www.slideshare.net/lmatteis/statecharts-controlling-the-behavior-of-
complex-systems
• David Khourshid - Infinitely Better UIs with Finite Automata - Slides
Stay in touch:
• xavier.lozinguez@jet.com
• @xlozinguez (Github, Twitter)
• http://xavier.lozinguez.com
Example Code:
• https://codesandbox.io/s/k06kloqzyo
• https://github.com/xlozinguez/xstate-demo
Ad

More Related Content

What's hot (20)

An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
weili_at_slideshare
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
Nir Elbaz
 
Java web application development
Java web application developmentJava web application development
Java web application development
RitikRathaur
 
Android animation
Android animationAndroid animation
Android animation
Krazy Koder
 
Web engineering - MVC
Web engineering - MVCWeb engineering - MVC
Web engineering - MVC
Nosheen Qamar
 
Servlets
ServletsServlets
Servlets
Sasidhar Kothuru
 
Ef code first
Ef code firstEf code first
Ef code first
ZealousysDev
 
Qt Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1Qt Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1
Emertxe Information Technologies Pvt Ltd
 
Devoxx 2012 hibernate envers
Devoxx 2012   hibernate enversDevoxx 2012   hibernate envers
Devoxx 2012 hibernate envers
Romain Linsolas
 
Html5 Interview Questions & Answers
Html5 Interview Questions & AnswersHtml5 Interview Questions & Answers
Html5 Interview Questions & Answers
Ratnala Charan kumar
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
Young-Ho Cho
 
Domain Driven Design: Zero to Hero
Domain Driven Design: Zero to HeroDomain Driven Design: Zero to Hero
Domain Driven Design: Zero to Hero
Fabrício Rissetto
 
React and redux
React and reduxReact and redux
React and redux
Mystic Coders, LLC
 
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopArchitecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Sudhir Tonse
 
Domain Driven Design 101
Domain Driven Design 101Domain Driven Design 101
Domain Driven Design 101
Richard Dingwall
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
Ramon Ribeiro Rabello
 
Jetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidJetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on Android
Nelson Glauber Leal
 
Linq
LinqLinq
Linq
Vishwa Mohan
 
Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Domain Driven Design Demonstrated
Domain Driven Design Demonstrated
Alan Christensen
 
A Framework Driven Development
A Framework Driven DevelopmentA Framework Driven Development
A Framework Driven Development
정민 안
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
weili_at_slideshare
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
Nir Elbaz
 
Java web application development
Java web application developmentJava web application development
Java web application development
RitikRathaur
 
Android animation
Android animationAndroid animation
Android animation
Krazy Koder
 
Web engineering - MVC
Web engineering - MVCWeb engineering - MVC
Web engineering - MVC
Nosheen Qamar
 
Devoxx 2012 hibernate envers
Devoxx 2012   hibernate enversDevoxx 2012   hibernate envers
Devoxx 2012 hibernate envers
Romain Linsolas
 
Html5 Interview Questions & Answers
Html5 Interview Questions & AnswersHtml5 Interview Questions & Answers
Html5 Interview Questions & Answers
Ratnala Charan kumar
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
Young-Ho Cho
 
Domain Driven Design: Zero to Hero
Domain Driven Design: Zero to HeroDomain Driven Design: Zero to Hero
Domain Driven Design: Zero to Hero
Fabrício Rissetto
 
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopArchitecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Sudhir Tonse
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
Ramon Ribeiro Rabello
 
Jetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidJetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on Android
Nelson Glauber Leal
 
Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Domain Driven Design Demonstrated
Domain Driven Design Demonstrated
Alan Christensen
 
A Framework Driven Development
A Framework Driven DevelopmentA Framework Driven Development
A Framework Driven Development
정민 안
 

Similar to Managing Complex UI using xState (20)

Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov
 
Designing a database like an archaeologist
Designing a database like an archaeologistDesigning a database like an archaeologist
Designing a database like an archaeologist
yoavrubin
 
Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016
Evan Schultz
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
Ignacio Martín
 
Data in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data EfficientlyData in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data Efficiently
Martin Zapletal
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018
Tracy Lee
 
Flutter
FlutterFlutter
Flutter
Dave Chao
 
Behavioral Design Patterns
Behavioral Design PatternsBehavioral Design Patterns
Behavioral Design Patterns
Lidan Hifi
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011
Chris Alfano
 
Simplified Android Development with Simple-Stack
Simplified Android Development with Simple-StackSimplified Android Development with Simple-Stack
Simplified Android Development with Simple-Stack
Gabor Varadi
 
Size Classes
Size ClassesSize Classes
Size Classes
Marat S
 
Gabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi - Reactive State Management with Jetpack ComponentsGabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi
 
Reactive state management with Jetpack Components
Reactive state management with Jetpack ComponentsReactive state management with Jetpack Components
Reactive state management with Jetpack Components
Gabor Varadi
 
Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
Younes (omar) Meliani
 
Om nom nom nom
Om nom nom nomOm nom nom nom
Om nom nom nom
Anna Pawlicka
 
Immutable Libraries for React
Immutable Libraries for ReactImmutable Libraries for React
Immutable Libraries for React
stbaechler
 
Event Sourcing - what could go wrong - Devoxx BE
Event Sourcing - what could go wrong - Devoxx BEEvent Sourcing - what could go wrong - Devoxx BE
Event Sourcing - what could go wrong - Devoxx BE
Andrzej Ludwikowski
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr Tolstykh
CodeFest
 
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Chris Adamson
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoo
felixtrepanier
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov
 
Designing a database like an archaeologist
Designing a database like an archaeologistDesigning a database like an archaeologist
Designing a database like an archaeologist
yoavrubin
 
Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016
Evan Schultz
 
Data in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data EfficientlyData in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data Efficiently
Martin Zapletal
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018
Tracy Lee
 
Behavioral Design Patterns
Behavioral Design PatternsBehavioral Design Patterns
Behavioral Design Patterns
Lidan Hifi
 
Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011Jarv.us Showcase — SenchaCon 2011
Jarv.us Showcase — SenchaCon 2011
Chris Alfano
 
Simplified Android Development with Simple-Stack
Simplified Android Development with Simple-StackSimplified Android Development with Simple-Stack
Simplified Android Development with Simple-Stack
Gabor Varadi
 
Size Classes
Size ClassesSize Classes
Size Classes
Marat S
 
Gabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi - Reactive State Management with Jetpack ComponentsGabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi
 
Reactive state management with Jetpack Components
Reactive state management with Jetpack ComponentsReactive state management with Jetpack Components
Reactive state management with Jetpack Components
Gabor Varadi
 
Immutable Libraries for React
Immutable Libraries for ReactImmutable Libraries for React
Immutable Libraries for React
stbaechler
 
Event Sourcing - what could go wrong - Devoxx BE
Event Sourcing - what could go wrong - Devoxx BEEvent Sourcing - what could go wrong - Devoxx BE
Event Sourcing - what could go wrong - Devoxx BE
Andrzej Ludwikowski
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr Tolstykh
CodeFest
 
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Chris Adamson
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoo
felixtrepanier
 
Ad

Recently uploaded (20)

Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Ad

Managing Complex UI using xState

  • 1. Managing Complex UI with xState
  • 2. Xavier “X” Lozinguez Staff Software Engineer @ Jet Customer Experience Team (Batman) • French • PADI Certified Scuba Diver • BJJ student Contact • [email protected] • @xlozinguez (Github, Twitter) • http://xavier.lozinguez.com
  • 3. Agenda • State Machine? State Charts? • Example of a “complex” UI • xState overview • xState + React • Q&A
  • 5. Finite State Machine – ex: traffic light • Finite amount of states • Predetermined sequenced transitions Green Red Yellow TIME R TIME R TIME R • Events triggers transitions
  • 6. State Chart created by David Harel in 1987 A state chart is a state machine composed of other state machines called sub-states. Sub-states can be state charts themselves (compound states) or remain atomic. Allow for advanced state composition using hierarchical, historic and parallel states.
  • 7. State Chart – ex: traffic light Green Yellow TIME R TIME R TIME R Red
  • 8. State Chart – ex: traffic light Green Yellow TIME R TIME R TIME R Wal k Wai t Sto p PED_TIM ER PED_TIM ER Red
  • 9. Okay… but why? 9 • Tried-and-true methodology for modeling applications • Makes the impossible impossible • Allow for application logic visualization
  • 11. Complex UI example Source: https://material.io/design/interaction/selection.html#item-
  • 14. Global State Chart – Browsing & Selecting Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) SELECT_ITEM RESET_SELECTION What about DELETE_SELECTION? DESELECT_ITEM (if selectedItems.length > 0)
  • 15. Global State Chart – Deleting & Prompting Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 17. xState by David Khourshid (davidkpiano)
  • 18. Global State Chart – Events Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 19. Global State Chart – Events Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 20. xState – Events 20 Composed of a type and an optional payload Payload is then handed over to actions for side-effect purpose Events cause a state machine to transition from its current state to the next type IAppEvent = | { type: 'SELECT_ITEM', item } | { type: 'SELECT_ALL_ITEMS’ } | { type: 'DESELECT_ITEM', item } | { type: 'DELETE_SELECTION’ } | { type: 'SELECTION_DELETED’ } | { type: 'RESET_SELECTION’ } | { type: 'DISMISS_PROMPT' };
  • 21. xState: Machine Configuration 21 State machine configuration: • key (useful to reference parent/children state) • context • state chart: state nodes & transitions • Entry state const appMachineConfig = { key: 'app’, context: initialAppContext, states: { browsing: { ... }, selecting: { ... }, deleting: { ... }, prompting: { ... } }, initial: 'deleting’, }
  • 22. Global State Chart - State Transitions Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 23. Global State Chart - State Transitions Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 24. Global State Chart - State Transitions Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 25. xState – State Transitions 25 selecting: { on: { SELECT_ITEM: { // implicit transition (no target) actions: 'addItemToSelection’ }, DESELECT_ITEM: [{ target: 'browsing’, cond: (ctx: IAppContext) =>( ctx.selectedItems.length === 1) // condition: last item in selection actions: 'removeItemFromSelection’, }, { // implicit transition (no target) cond: (ctx: IAppContext) =>( ctx.selectedItems.length > 1) // condition: still more items selected actions: 'removeItemFromSelection’, }], RESET_SELECTION: { target: 'browsing’, actions: 'resetSelection’ }, DELETE_SELECTION: { target: 'deleting’, } } }, Selecting DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION DESELECT_ITEM (if selectedItems.length > 0) SELECT_ITEM DELETE_SELECTION
  • 26. xState – Actions 26 Actions are fire and forget side effects triggered upon state machine transitions • Three types of actions: • Entry: executed upon entering a state • Exit: executed upon exiting a state • Transition: executed when a transition is triggered by an event states: { browsing: { onEntry: ['loadItems', 'triggerAnalytics’], onExit: 'triggerAnalytics’, on: { SELECT_ITEM: { target: 'selecting’, actions: 'addItemToSelection’ }, SELECT_ALL_ITEMS: { target: 'selecting’, actions: 'addAllItemsToSelection’ } } }, selecting: {...}, deleting: {...}, prompting: {...} }
  • 27. xState – Context 27 • Contains quantitative data (strings, numbers, objects, etc.) • Represents the “extended state” managed by the machine • Used to hydrate the application components • Updated using actions const initialAppContext: IAppContext = { items: initialAppContextItems, selectedItems: [] } const initialAppContextItems = [{ id: 0, title: 'Summer Photos’, owner: 'Anthony Stevens’, updatedAt: new Date(Date.UTC(2017,6,12)) }, ... ]
  • 28. xState – Updating the context 28 const appMachineOptions = { actions: { addItemToSelection: assign((ctx, event) => ({ selectedItems: ctx.selectedItems.concat(event.item) })), removeItemFromSelection: assign((ctx, event) => ({ selectedItems: ctx.selectedItems.filter(item => item.id !== event.item.id) })), resetSelection: assign((_) => ({ selectedItems: [] })), deleteSelection: assign(ctx => ({ items: ctx.items.filter(item => ctx.selectedItems.findIndex(selectedItem => selectedItem.id === item.id) < 0 ), selectedItems: [] })), } };
  • 30. Global State Chart – Asynchronous Calls Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 31. Global State Chart - Asynchronous Calls Browsing Selecting SELECT_ITEM DESELECT_ITEM (if selectedItems.length <= 0) RESET_SELECTION SELECT_ITEM DESELECT_ITEM (if selectedItems.length > 0) Deleting DELETE_SELECTION DELETE_SELECTION_FAILURE DELETE_SELECTION_SUCCESS Promptin g DISMISS_PROMPT
  • 32. xState – Asynchronous calls (invoke) 32 For asynchronous calls, xState relies on Promises • onDone transition is invoked when the promise resolve() • onError transition is invoked if the promise reject()
  • 34. Hook xState machine to React Using the official useMachine hook from @xstate/react https://github.com/davidkpiano/xstate/tree/master/packages/xstate- react#readme
  • 36. xState – Matching state 36 current.matches(’…’) provides the ability to set conditional statement against the machine state.
  • 37. xState – Matching state 37 => current.matches(’browsing’) => current.matches(’selecting’)
  • 38. xState – Triggering State Transitions 38 Transitions are triggered by sending an event to the machine using send({…}) Transitions can also be triggered using the Machine.transition({…}) method which requires the state to transition.
  • 40. A few take away Pros Cons • Self documented and captures the complete picture • Explicit and easy to understand thanks to state charts • Behavior can be tested independently from presentation layer • State charts scale very well due to their inherent composability • Can accommodate complex use cases (services, compound vs parallel, etc.) • New paradigm to consider • Requires a complete picture of the system so it can be transcribed into state charts • Uncovers a different set of problem to solve around state composition (state vs context, sub-states)
  • 42. References • https://github.com/davidkpiano/xstate • https://xstate.js.org • https://statecharts.github.io • https://spectrum.chat/statecharts • https://medium.com/@DavidKPiano/the-facetime-bug-and-the-dangers-of- implicit-state-machines-a5f0f61bdaa2 • https://www.slideshare.net/lmatteis/statecharts-controlling-the-behavior-of- complex-systems • David Khourshid - Infinitely Better UIs with Finite Automata - Slides
  • 43. Stay in touch: • [email protected] • @xlozinguez (Github, Twitter) • http://xavier.lozinguez.com Example Code: • https://codesandbox.io/s/k06kloqzyo • https://github.com/xlozinguez/xstate-demo

Editor's Notes

  • #6: A state machine is a finite set of states that can transition to each other deterministically due to events - The term state used within the statechart formalism simply describes a textual label which drives our program in understanding what needs to happen. - To the contrary, in the React world the term state usually describes some data that we use to render our components. ------ Finite amount of states between which the machine transition in a predetermined sequence using events.
  • #8: A state machine is a finite set of states that can transition to each other deterministically due to events - The term state used within the statechart formalism simply describes a textual label which drives our program in understanding what needs to happen. - To the contrary, in the React world the term state usually describes some data that we use to render our components.
  • #9: A state machine is a finite set of states that can transition to each other deterministically due to events - The term state used within the statechart formalism simply describes a textual label which drives our program in understanding what needs to happen. - To the contrary, in the React world the term state usually describes some data that we use to render our components.
  • #28: While finite states are well-defined in finite state machines and statecharts, state that represents quantitative data (e.g., arbitrary strings, numbers, objects, etc.) that can be potentially infinite is represented as extended state instead
  • #29: Recommended rules: Never mutate the context, use assign({ … }) to preserve state history Never mutate the context externally Unit Test your actions!
  • #33: Machines can talk to each other using the `invoke` method https://xstate.js.org/docs/guides/communication.html
  • #41: By modeling the UI logic as a statechart, not only do you have full visibility into all edge cases, but adding/removing/modifying features becomes much easier and less bug-prone, since you instantly know all parts of your UI logic that feature will affect.