Builder Events

by brendanbond

HTML

<link
  href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
  rel="stylesheet"
  integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB"
  crossorigin="anonymous"
/>
<link rel="stylesheet" href="https://cdn.form.io/js/formio.full.min.css" />

<div class="container">
  <div id="formio"></div>
</div>
<script src=" https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js "></script>
<script src="https://cdn.form.io/js/formio.full.js"></script>

CSS

.radio-block label {
  background: #228b22;
  border: 3px solid transparent;
  cursor: pointer;
}
.radio-block.radio-selected label {
  border-color: black;
}

@keyframes slideInFromRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
@keyframes slideInFromLeft {
  from {
    transform: translateX(-100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
.wizard-page.slide-left {
  animation: slideInFromRight 0.4s ease-out;
}
.wizard-page.slide-right {
  animation: slideInFromLeft 0.4s ease-out;
}

JavaScript

function getInstanceFromParent({builder, parent, path, toIndex}) {
  const schema = _.get(parent.schema, path)[toIndex];
  const paths = Formio.Utils.getComponentPaths(schema, parent.component, {
    ...parent.paths,
  });
  return builder.webform.getComponent(paths.fullPath);
}

Formio.builder(
  document.getElementById("formio"),
  "https://examples.form.io/builderevents",
).then((builder) => {
  builder.on('moveComponent', ({ parent, path, toIndex }) => {
    const schema = _.get(parent.schema, path)[toIndex];
    const movedToRoot = parent === builder.webform;
    console.log(movedToRoot);

    if (movedToRoot) {
      const instance = builder.webform.getComponent(schema.key);
      console.log("Moved to root!");
    } else {
        const instance = getInstanceFromParent({builder, parent, path, toIndex});
        console.log("Moved to non-root!");
    }
  });
});