Skip to content

Instantly share code, notes, and snippets.

@James-Byrne
Last active January 14, 2021 21:46
Show Gist options
  • Save James-Byrne/9a99cd8c1cb37759a671c32022e8b592 to your computer and use it in GitHub Desktop.
Save James-Byrne/9a99cd8c1cb37759a671c32022e8b592 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// ui-tabs/tab.ts
const tab = Machine({
initial: 'idle',
context: {
closable: true,
active: false
},
on: {
SELECT: {
target: 'selected',
actions: assign({
active: true
})
},
DESELECT: {
target: 'idle',
actions: assign({
active: false
})
},
CLOSE: {
actions: sendParent(context => ({
type: 'CLOSE',
...context
}))
}
},
states: {
idle: {},
selected: {}
}
});
// ui-tabs.ts
const uiTabs = Machine({
id: 'search-orders',
initial: 'idle',
states: {
idle: {},
}
});
const tabContext = Machine({
initial: 'idle',
context: {
active: true,
tabs: []
},
on: {
WAKE: assign({ active: true }),
ARCHIVE: assign({ active: false }),
CLOSE_TAB: assign({
tabs: (c, e) => {
return c.tabs.reduce((acc, tab) => {
if (tab.id === e.tabId) return acc;
return [...acc, tab];
}, []);
}
}),
REGISTER: assign({
tabs: (c, e) => {
return [
...c.tabs,
spawn(
e.tab ?? tab,
e.tabId ?? 'tabID'
)
];
}
})
},
states: {
idle: {}
}
});
// services/tabs
const tabsService = Machine({
id: 'tabsService',
initial: 'idle',
context: {
tabContexts: [],
},
on: {
ARCHIVE_TAB_CONTEXT: {
actions: send('ARCHIVE', {
to: (c, e) => e.tabContextId
})
},
REGISTER_TAB_CONTEXT: [
{
cond: 'contextIsArchived',
actions: send('WAKE', {
to: (c, e) => e.tabContextId
})
},
{
actions: assign({
tabContexts: (c, e) => {
return [
...c.tabContexts,
spawn(
e.tabContext ?? tabContext,
e.tabContextId ?? 'test'
)
];
}
})
}
]
},
states: {
idle: {}
}
}, {
guards: {
contextIsArchived(context, event) {
// Check if the context is archived
return false;
}
}
});
const ts = interpret(tabsService)
.onTransition((context, event) => {
console.log(event.type, {
context,
event
});
});
ts.start();
ts.send('REGISTER_TAB_CONTEXT', {
tabContext, tabContextId: 'test'
});
ts.send('ARCHIVE_TAB_CONTEXT', {
tabContextId: 'test'
});
console.log('ts', ts);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment