export default function (editor) {
  const textTrait = editor.TraitManager.getType('text')
  editor.TraitManager.addType('sp-component-name', {
    ...textTrait,

    label: '组件名称',

    getInitValue() {
      return this.value;
    },

    createInput({component, trait}) {
      const {name = ''} = component.getAttributes();

      const traitEl = document.createElement('div');
      traitEl.innerHTML = `<input type="text" name="sp-component-name" class="sp-component-name" value="${name}" />`;
      return traitEl;
    },

    onUpdate({elInput, component}) {
      const {name = ''} = component.getAttributes();
      elInput.querySelector('input').value = name;
    },

    onEvent({elInput, component}) {
      const name = elInput.querySelector('.sp-component-name').value;
      const {sp} = component.getAttributes();

      if (sp && sp.metadata.label !== name) {
        sp.metadata.label = name;
        editor.trigger('component:update:name', component, sp);
      }
      component.addAttributes({name});
    },
  });
}
