Condition Editor

by wio_dude

HTML

<textarea id="condition-result"></textarea>

<div id="condition-editor"></div>

CSS

ul {
  list-style-type: none;
}

JavaScript

const conditionEditor = document.getElementById('condition-editor')
const conditionResult = document.getElementById('condition-result')

const switches = new Set(['a', 'b', 'c', 'd', 'e', 'f', 'g']);

function setFirst(s) {
	return s.values().next().value;
}


class EditListener {
	constructor() {
  	this.handlers = []
  }
  
	onEdit(handler) {
  	this.handlers.push(handler)
  }
  
  dispatchEdit(value) {
  	for (const handler of this.handlers) {
    	handler(value)
    }
  }
  
}

class SwitchEditor extends EditListener {
	constructor(value = setFirst(switches)) {
  	super()
    const dom = document.createElement('select')
    for (const switchName of switches) {
    	const option = document.createElement('option')
      option.value = switchName
      option.innerHTML = switchName
      if (value === switchName) {
      	option.selected = true
      }
      dom.appendChild(option)
    }
    dom.addEventListener('input', (evt) => {
    	this.setValue(this.dom.value)
    })
    this.value = value
    this.dom = dom
  }
  
  setValue(value) {
  	this.value = value
    this.dispatchEdit(value)
  }
  
  getValue() {
  	return this.value
  }
  
  getDOM() {
  	return this.dom
  }
}

class BinaryOpdEditor extends EditListener {
	constructor(op) {
  	super()
  	const dom = document.createElement('span')
    const list = document.createElement('ul')
    const add = document.createElement('input')
    add.type = 'button'
    add.value = 'Add Element'
    add.addEventListener('click', (evt) => {
      const item = document.createElement('li')
      const remove = document.createElement('input')
      remove.value = 'X'
      remove.type = 'button'
      item.appendChild(remove)
      const editor = new ValueEditor()
      editor.onEdit(value => this.dispatchEdit(this.getValue()))
      item.appendChild(editor.getDOM())
      this.list.appendChild(item)
    	this.valueEditors.push(editor)
      this.dispatchEdit(this.getValue())
      remove.addEventListener('click', (evt)...