Skip to content

Instantly share code, notes, and snippets.

@BillClinton
Created March 1, 2023 19:06
Show Gist options
  • Save BillClinton/3f14cd7ed841a0f7bdf5ca1bde7b1d70 to your computer and use it in GitHub Desktop.
Save BillClinton/3f14cd7ed841a0f7bdf5ca1bde7b1d70 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const attachmentFieldMachine = Machine({
id: "AttachmentFieldMachine",
initial: "idle",
predictableActionArguments: true,
context: {
value: [],
fields: {
Title: null,
URL: null,
Status: "normal",
},
},
states: {
idle: {
on: {
INIT: {
target: "ready",
actions: "initialize",
},
},
},
ready: {
on: {
EDIT: {
target: "editing",
actions: "editItem",
},
ADD: {
target: "adding",
actions: "addItem",
},
REMOVE: {
target: "ready",
actions: "removeItem",
},
RESTORE: {
target: "ready",
actions: "restoreItem",
},
RESET: {
target: "idle",
actions: "resetContext",
},
},
},
editing: {
on: {
UPDATE: {
target: "ready",
actions: "updateItem",
},
CANCEL: "ready",
},
},
adding: {
on: {
CREATE: {
target: "ready",
actions: "createItem",
},
CANCEL: "ready",
},
},
},
},
{
actions: {
initialize: assign((context, event) => ({ value: event.value })),
addItem: assign(() => ({ fields: { Title: null, URL: null } })),
editItem: assign((context, event) => ({
fields: {
Title: context.value[event.idx].Title,
URL: context.value[event.idx].URL,
},
key: event.idx,
})),
removeItem: (context, event) => {
const attachment = context.value[event.idx];
Object.assign(attachment, { Status: "removed" });
},
restoreItem: (context, event) => {
const attachment = context.value[event.idx];
Object.assign(attachment, { Status: "normal" });
},
updateItem: (context) => {
const attachment = context.value[context.key];
Object.assign(attachment, context.fields);
},
createItem: assign((context) => ({
value: context.value.concat([
Object.assign(
{
Class: "Slate\\CBL\\Tasks\\Attachments\\Link",
Status: "normal",
},
context.fields
),
]),
})),
resetContext: assign(() => ({
value: [],
fields: {
Title: null,
URL: null,
Status: "normal",
},
})),
},
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment