<commit_before>import colors from '../../lib/colors'
import Vue from 'vue'

export const entityListMixin = {

  created () {
    this.initHiddenColumns(this.validationColumns, this.hiddenColumns)
  },

  mounted () {
    this.resizeHeaders()
    window.addEventListener('keydown', this.onKeyDown, false)
  },

  beforeDestroy () {
    window.removeEventListener('keydown', this.onKeyDown)
  },

  computed: {
    sortedValidationColumns () {
      let columns = [...this.validationColumns]
      if (this.assetFilledColumns) {
        columns = columns.filter(c => this.assetFilledColumns[c])
      } else if (this.shotFilledColumns) {
        columns = columns.filter(c => this.shotFilledColumns[c])
      }

      return columns.sort((a, b) => {
        const taskTypeA = this.taskTypeMap[a]
        const taskTypeB = this.taskTypeMap[b]
        if (taskTypeA.priority === taskTypeB.priority) {
          return taskTypeA.name.localeCompare(taskTypeB)
        } else if (taskTypeA.priority > taskTypeB.priority) {
          return 1
        } else {
          return -1
        }
      })
    }
  },

  methods: {
    getBackground (color) {
      return colors.hexToRGBa(color, 0.08)
    },

    buildHideKey (columnId) {
      return `column-${this.currentProduction.id}-${columnId}`
    },

    initHiddenColumns (validationColumns, hiddenColumns) {
      validationColumns.forEach((columnId) => {
        const key = this.buildHideKey(columnId)
        Vue.set(
          hiddenColumns,
          columnId,
          localStorage.getItem(key) === 'true'
        )
      })
    },

    hideColumn (columnId) {
      const key = this.buildHideKey(columnId)
      let isColumnHidden = true
      if (localStorage.getItem(key) === 'true') {
        isColumnHidden = false
      }
      localStorage.setItem(key, isColumnHidden)
      Vue.set(this.hiddenColumns, columnId, isColumnHidden)
      this.hiddenColumns[columnId] = isColumnHidden
      return isColumnHidden
    },

    setScrollPosition (scrollPosition) {
      if (this.$refs.body) {
        this.$refs.body.scrollTop = scrollPosition
      }
    },

    setScrollLeftPosition (scrollPosition) {
      if (this.$refs.body) {
        this.$refs.body.scrollLeft = scrollPosition
      }
    },

    getValidationStyle (columnId) {
      const taskType = this.taskTypeMap[columnId]
      return {
        'border-left': `1px solid ${taskType.color}`,
        'background': this.getBackground(taskType.color)
      }
    },

    onTaskSelected (validationInfo) {
      const selection = []
      if (validationInfo.isShiftKey) {
        if (this.lastSelection) {
          let startX = this.lastSelection.x
          let endX = validationInfo.x
          let startY = this.lastSelection.y
          let endY = validationInfo.y
          let grid = this.assetSelectionGrid
          if (!grid) grid = this.shotSelectionGrid

          if (validationInfo.x < this.lastSelection.x) {
            startX = validationInfo.x
            endX = this.lastSelection.x
          }
          if (validationInfo.y < this.lastSelection.y) {
            startY = validationInfo.y
            endY = this.lastSelection.y
          }

          for (let i = startX; i <= endX; i++) {
            for (let j = startY; j <= endY; j++) {
              const ref = 'validation-' + i + '-' + j
              const validationCell = this.$refs[ref][0]
              if (!grid[i][j]) {
                selection.push({
                  entity: validationCell.entity,
                  column: validationCell.column,
                  task: validationCell.task,
                  x: validationCell.rowX,
                  y: validationCell.columnY
                })
              }
            }
          }
          this.$store.commit('ADD_SELECTED_TASK', validationInfo)
        }
      } else if (!validationInfo.isCtrlKey) {
        this.$store.commit('CLEAR_SELECTED_TASKS')
      }
      if (selection.length === 0) {
        this.$store.commit('ADD_SELECTED_TASK', validationInfo)
      } else {
        this.$store.commit('ADD_SELECTED_TASKS', selection)
      }

      if (!validationInfo.isShiftKey && validationInfo.isUserClick) {
        const x = validationInfo.x
        const y = validationInfo.y
        this.lastSelection = { x, y }
        const ref = 'validation-' + x + '-' + y
        const validationCell = this.$refs[ref][0]
        this.$nextTick(() => {
          this.scrollToValidationCell(validationCell)
        })
      }
    },

    onTaskUnselected (validationInfo) {
      if (!validationInfo.isCtrlKey) {
        if (this.nbSelectedTasks === 1) {
          this.$store.commit('REMOVE_SELECTED_TASK', validationInfo)
        } else {
          this.$store.commit('CLEAR_SELECTED_TASKS')
          this.$store.commit('ADD_SELECTED_TASK', validationInfo)
        }
      } else {
        this.$store.commit('REMOVE_SELECTED_TASK', validationInfo)
      }
    },

    showHeaderMenu (columnId, event) {
      const headerMenuEl = this.$refs.headerMenu.$el
      if (headerMenuEl.className === 'header-menu') {
        headerMenuEl.className = 'header-menu hidden'
      } else {
        headerMenuEl.className = 'header-menu'
        let headerElement = event.srcElement.parentNode.parentNode
        if (headerElement.tagName !== 'TH') {
          headerElement = headerElement.parentNode
        }
        const headerBox = headerElement.getBoundingClientRect()
        const left = headerBox.left + 11
        const top = headerBox.bottom + 10
        const width = Math.max(100, headerBox.width - 1)
        headerMenuEl.style.left = left + 'px'
        headerMenuEl.style.top = top + 'px'
        headerMenuEl.style.width = width + 'px'
      }
      this.lastHeaderMenuDisplayed = columnId
    },

    showMetadataHeaderMenu (columnId, event) {
      const headerMenuEl = this.$refs.headerMetadataMenu.$el
      if (headerMenuEl.className === 'header-menu') {
        headerMenuEl.className = 'header-menu hidden'
      } else {
        headerMenuEl.className = 'header-menu'
        let headerElement = event.srcElement.parentNode.parentNode
        const headerBox = headerElement.getBoundingClientRect()
        const left = headerBox.left + 11
        const top = headerBox.bottom + 10
        const width = Math.max(100, headerBox.width - 1)
        headerMenuEl.style.left = left + 'px'
        headerMenuEl.style.top = top + 'px'
        headerMenuEl.style.width = width + 'px'
      }
      this.lastMetadaDataHeaderMenuDisplayed = columnId
    },

    onMinimizeColumnToggled () {
      this.hideColumn(this.lastHeaderMenuDisplayed)
      this.showHeaderMenu()
    },

    onDeleteAllTasksClicked () {
      this.$emit('delete-all-tasks', this.lastHeaderMenuDisplayed)
      this.showHeaderMenu()
    },

    onAddMetadataClicked () {
      this.$emit('add-metadata')
    },

    onEditMetadataClicked () {
      this.$emit('edit-metadata', this.lastMetadaDataHeaderMenuDisplayed)
      this.showMetadataHeaderMenu()
    },

    onDeleteMetadataClicked () {
      this.$emit('delete-metadata', this.lastMetadaDataHeaderMenuDisplayed)
      this.showMetadataHeaderMenu()
    },

    resizeSplittedTableHeaders (columnDescriptors) {
      if (
        this.$refs['body-tbody'] &&
        this.$refs['body-tbody'].length > 0 &&
        this.$refs['body-tbody'][0].children.length > 1
      ) {
        const bodyElement = this.$refs['body-tbody'][0].children[1]
        columnDescriptors.forEach(desc => {
          const width = bodyElement.children[desc.index].offsetWidth
          this.$refs['th-' + desc.name].style['min-width'] = `${width}px`
        })
      }
    }
  }
}
<commit_msg>Fix edge case when dealing with hidden columns<commit_after>import colors from '../../lib/colors'
import Vue from 'vue'

export const entityListMixin = {

  created () {
    this.initHiddenColumns(this.validationColumns, this.hiddenColumns)
  },

  mounted () {
    this.resizeHeaders()
    window.addEventListener('keydown', this.onKeyDown, false)
  },

  beforeDestroy () {
    window.removeEventListener('keydown', this.onKeyDown)
  },

  computed: {
    sortedValidationColumns () {
      let columns = [...this.validationColumns]
      if (this.assetFilledColumns) {
        columns = columns.filter(c => this.assetFilledColumns[c])
      } else if (this.shotFilledColumns) {
        columns = columns.filter(c => this.shotFilledColumns[c])
      }

      return columns.sort((a, b) => {
        const taskTypeA = this.taskTypeMap[a]
        const taskTypeB = this.taskTypeMap[b]
        if (taskTypeA.priority === taskTypeB.priority) {
          return taskTypeA.name.localeCompare(taskTypeB)
        } else if (taskTypeA.priority > taskTypeB.priority) {
          return 1
        } else {
          return -1
        }
      })
    }
  },

  methods: {
    getBackground (color) {
      return colors.hexToRGBa(color, 0.08)
    },

    buildHideKey (columnId) {
      return `column-${this.currentProduction.id}-${columnId}`
    },

    initHiddenColumns (validationColumns, hiddenColumns) {
      if (validationColumns && hiddenColumns) {
        validationColumns.forEach((columnId) => {
          const key = this.buildHideKey(columnId)
          Vue.set(
            hiddenColumns,
            columnId,
            localStorage.getItem(key) === 'true'
          )
        })
      }
    },

    hideColumn (columnId) {
      const key = this.buildHideKey(columnId)
      let isColumnHidden = true
      if (localStorage.getItem(key) === 'true') {
        isColumnHidden = false
      }
      localStorage.setItem(key, isColumnHidden)
      Vue.set(this.hiddenColumns, columnId, isColumnHidden)
      this.hiddenColumns[columnId] = isColumnHidden
      return isColumnHidden
    },

    setScrollPosition (scrollPosition) {
      if (this.$refs.body) {
        this.$refs.body.scrollTop = scrollPosition
      }
    },

    setScrollLeftPosition (scrollPosition) {
      if (this.$refs.body) {
        this.$refs.body.scrollLeft = scrollPosition
      }
    },

    getValidationStyle (columnId) {
      const taskType = this.taskTypeMap[columnId]
      return {
        'border-left': `1px solid ${taskType.color}`,
        'background': this.getBackground(taskType.color)
      }
    },

    onTaskSelected (validationInfo) {
      const selection = []
      if (validationInfo.isShiftKey) {
        if (this.lastSelection) {
          let startX = this.lastSelection.x
          let endX = validationInfo.x
          let startY = this.lastSelection.y
          let endY = validationInfo.y
          let grid = this.assetSelectionGrid
          if (!grid) grid = this.shotSelectionGrid

          if (validationInfo.x < this.lastSelection.x) {
            startX = validationInfo.x
            endX = this.lastSelection.x
          }
          if (validationInfo.y < this.lastSelection.y) {
            startY = validationInfo.y
            endY = this.lastSelection.y
          }

          for (let i = startX; i <= endX; i++) {
            for (let j = startY; j <= endY; j++) {
              const ref = 'validation-' + i + '-' + j
              const validationCell = this.$refs[ref][0]
              if (!grid[i][j]) {
                selection.push({
                  entity: validationCell.entity,
                  column: validationCell.column,
                  task: validationCell.task,
                  x: validationCell.rowX,
                  y: validationCell.columnY
                })
              }
            }
          }
          this.$store.commit('ADD_SELECTED_TASK', validationInfo)
        }
      } else if (!validationInfo.isCtrlKey) {
        this.$store.commit('CLEAR_SELECTED_TASKS')
      }
      if (selection.length === 0) {
        this.$store.commit('ADD_SELECTED_TASK', validationInfo)
      } else {
        this.$store.commit('ADD_SELECTED_TASKS', selection)
      }

      if (!validationInfo.isShiftKey && validationInfo.isUserClick) {
        const x = validationInfo.x
        const y = validationInfo.y
        this.lastSelection = { x, y }
        const ref = 'validation-' + x + '-' + y
        const validationCell = this.$refs[ref][0]
        this.$nextTick(() => {
          this.scrollToValidationCell(validationCell)
        })
      }
    },

    onTaskUnselected (validationInfo) {
      if (!validationInfo.isCtrlKey) {
        if (this.nbSelectedTasks === 1) {
          this.$store.commit('REMOVE_SELECTED_TASK', validationInfo)
        } else {
          this.$store.commit('CLEAR_SELECTED_TASKS')
          this.$store.commit('ADD_SELECTED_TASK', validationInfo)
        }
      } else {
        this.$store.commit('REMOVE_SELECTED_TASK', validationInfo)
      }
    },

    showHeaderMenu (columnId, event) {
      const headerMenuEl = this.$refs.headerMenu.$el
      if (headerMenuEl.className === 'header-menu') {
        headerMenuEl.className = 'header-menu hidden'
      } else {
        headerMenuEl.className = 'header-menu'
        let headerElement = event.srcElement.parentNode.parentNode
        if (headerElement.tagName !== 'TH') {
          headerElement = headerElement.parentNode
        }
        const headerBox = headerElement.getBoundingClientRect()
        const left = headerBox.left + 11
        const top = headerBox.bottom + 10
        const width = Math.max(100, headerBox.width - 1)
        headerMenuEl.style.left = left + 'px'
        headerMenuEl.style.top = top + 'px'
        headerMenuEl.style.width = width + 'px'
      }
      this.lastHeaderMenuDisplayed = columnId
    },

    showMetadataHeaderMenu (columnId, event) {
      const headerMenuEl = this.$refs.headerMetadataMenu.$el
      if (headerMenuEl.className === 'header-menu') {
        headerMenuEl.className = 'header-menu hidden'
      } else {
        headerMenuEl.className = 'header-menu'
        let headerElement = event.srcElement.parentNode.parentNode
        const headerBox = headerElement.getBoundingClientRect()
        const left = headerBox.left + 11
        const top = headerBox.bottom + 10
        const width = Math.max(100, headerBox.width - 1)
        headerMenuEl.style.left = left + 'px'
        headerMenuEl.style.top = top + 'px'
        headerMenuEl.style.width = width + 'px'
      }
      this.lastMetadaDataHeaderMenuDisplayed = columnId
    },

    onMinimizeColumnToggled () {
      this.hideColumn(this.lastHeaderMenuDisplayed)
      this.showHeaderMenu()
    },

    onDeleteAllTasksClicked () {
      this.$emit('delete-all-tasks', this.lastHeaderMenuDisplayed)
      this.showHeaderMenu()
    },

    onAddMetadataClicked () {
      this.$emit('add-metadata')
    },

    onEditMetadataClicked () {
      this.$emit('edit-metadata', this.lastMetadaDataHeaderMenuDisplayed)
      this.showMetadataHeaderMenu()
    },

    onDeleteMetadataClicked () {
      this.$emit('delete-metadata', this.lastMetadaDataHeaderMenuDisplayed)
      this.showMetadataHeaderMenu()
    },

    resizeSplittedTableHeaders (columnDescriptors) {
      if (
        this.$refs['body-tbody'] &&
        this.$refs['body-tbody'].length > 0 &&
        this.$refs['body-tbody'][0].children.length > 1
      ) {
        const bodyElement = this.$refs['body-tbody'][0].children[1]
        columnDescriptors.forEach(desc => {
          const width = bodyElement.children[desc.index].offsetWidth
          this.$refs['th-' + desc.name].style['min-width'] = `${width}px`
        })
      }
    }
  }
}
<|endoftext|>


<commit_before>import colors from '../../lib/colors'
import Vue from 'vue'

export const entityListMixin = {

  created () {
    this.initHiddenColumns(this.validationColumns, this.hiddenColumns)
  },

  mounted () {
    this.resizeHeaders()
    window.addEventListener('keydown', this.onKeyDown, false)
  },

  beforeDestroy () {
    window.removeEventListener('keydown', this.onKeyDown)
  },

  computed: {
    sortedValidationColumns () {
      let columns = [...this.validationColumns]
      if (this.assetFilledColumns) {
        columns = columns.filter(c => this.assetFilledColumns[c])
      } else if (this.shotFilledColumns) {
        columns = columns.filter(c => this.shotFilledColumns[c])
      }

      return columns.sort((a, b) => {
        const taskTypeA = this.taskTypeMap[a]
        const taskTypeB = this.taskTypeMap[b]
        if (taskTypeA.priority === taskTypeB.priority) {
          return taskTypeA.name.localeCompare(taskTypeB)
        } else if (taskTypeA.priority > taskTypeB.priority) {
          return 1
        } else {
          return -1
        }
      })
    }
  },

  methods: {
    getBackground (color) {
      return colors.hexToRGBa(color, 0.08)
    },

    buildHideKey (columnId) {
      return `column-${this.currentProduction.id}-${columnId}`
    },

    initHiddenColumns (validationColumns, hiddenColumns) {
      if (validationColumns && hiddenColumns) {
        validationColumns.forEach((columnId) => {
          const key = this.buildHideKey(columnId)
          Vue.set(
            hiddenColumns,
            columnId,
            localStorage.getItem(key) === 'true'
          )
        })
      }
    },

    hideColumn (columnId) {
      const key = this.buildHideKey(columnId)
      let isColumnHidden = true
      if (localStorage.getItem(key) === 'true') {
        isColumnHidden = false
      }
      localStorage.setItem(key, isColumnHidden)
      Vue.set(this.hiddenColumns, columnId, isColumnHidden)
      this.hiddenColumns[columnId] = isColumnHidden
      return isColumnHidden
    },

    setScrollPosition (scrollPosition) {
      if (this.$refs.body) {
        this.$refs.body.scrollTop = scrollPosition
      }
    },

    setScrollLeftPosition (scrollPosition) {
      if (this.$refs.body) {
        this.$refs.body.scrollLeft = scrollPosition
      }
    },

    getValidationStyle (columnId) {
      const taskType = this.taskTypeMap[columnId]
      return {
        'border-left': `1px solid ${taskType.color}`,
        'background': this.getBackground(taskType.color)
      }
    },

    onTaskSelected (validationInfo) {
      const selection = []
      if (validationInfo.isShiftKey) {
        if (this.lastSelection) {
          let startX = this.lastSelection.x
          let endX = validationInfo.x
          let startY = this.lastSelection.y
          let endY = validationInfo.y
          let grid = this.assetSelectionGrid
          if (!grid) grid = this.shotSelectionGrid

          if (validationInfo.x < this.lastSelection.x) {
            startX = validationInfo.x
            endX = this.lastSelection.x
          }
          if (validationInfo.y < this.lastSelection.y) {
            startY = validationInfo.y
            endY = this.lastSelection.y
          }

          for (let i = startX; i <= endX; i++) {
            for (let j = startY; j <= endY; j++) {
              const ref = 'validation-' + i + '-' + j
              const validationCell = this.$refs[ref][0]
              if (!grid[i][j]) {
                selection.push({
                  entity: validationCell.entity,
                  column: validationCell.column,
                  task: validationCell.task,
                  x: validationCell.rowX,
                  y: validationCell.columnY
                })
              }
            }
          }
          this.$store.commit('ADD_SELECTED_TASK', validationInfo)
        }
      } else if (!validationInfo.isCtrlKey) {
        this.$store.commit('CLEAR_SELECTED_TASKS')
      }
      if (selection.length === 0) {
        this.$store.commit('ADD_SELECTED_TASK', validationInfo)
      } else {
        this.$store.commit('ADD_SELECTED_TASKS', selection)
      }

      if (!validationInfo.isShiftKey && validationInfo.isUserClick) {
        const x = validationInfo.x
        const y = validationInfo.y
        this.lastSelection = { x, y }
        const ref = 'validation-' + x + '-' + y
        const validationCell = this.$refs[ref][0]
        this.$nextTick(() => {
          this.scrollToValidationCell(validationCell)
        })
      }
    },

    onTaskUnselected (validationInfo) {
      if (!validationInfo.isCtrlKey) {
        if (this.nbSelectedTasks === 1) {
          this.$store.commit('REMOVE_SELECTED_TASK', validationInfo)
        } else {
          this.$store.commit('CLEAR_SELECTED_TASKS')
          this.$store.commit('ADD_SELECTED_TASK', validationInfo)
        }
      } else {
        this.$store.commit('REMOVE_SELECTED_TASK', validationInfo)
      }
    },

    showHeaderMenu (columnId, event) {
      const headerMenuEl = this.$refs.headerMenu.$el
      if (headerMenuEl.className === 'header-menu') {
        headerMenuEl.className = 'header-menu hidden'
      } else {
        headerMenuEl.className = 'header-menu'
        let headerElement = event.srcElement.parentNode.parentNode
        if (headerElement.tagName !== 'TH') {
          headerElement = headerElement.parentNode
        }
        const headerBox = headerElement.getBoundingClientRect()
        const left = headerBox.left + 11
        const top = headerBox.bottom + 10
        const width = Math.max(100, headerBox.width - 1)
        headerMenuEl.style.left = left + 'px'
        headerMenuEl.style.top = top + 'px'
        headerMenuEl.style.width = width + 'px'
      }
      this.lastHeaderMenuDisplayed = columnId
    },

    showMetadataHeaderMenu (columnId, event) {
      const headerMenuEl = this.$refs.headerMetadataMenu.$el
      if (headerMenuEl.className === 'header-menu') {
        headerMenuEl.className = 'header-menu hidden'
      } else {
        headerMenuEl.className = 'header-menu'
        let headerElement = event.srcElement.parentNode.parentNode
        const headerBox = headerElement.getBoundingClientRect()
        const left = headerBox.left + 11
        const top = headerBox.bottom + 10
        const width = Math.max(100, headerBox.width - 1)
        headerMenuEl.style.left = left + 'px'
        headerMenuEl.style.top = top + 'px'
        headerMenuEl.style.width = width + 'px'
      }
      this.lastMetadaDataHeaderMenuDisplayed = columnId
    },

    onMinimizeColumnToggled () {
      this.hideColumn(this.lastHeaderMenuDisplayed)
      this.showHeaderMenu()
    },

    onDeleteAllTasksClicked () {
      this.$emit('delete-all-tasks', this.lastHeaderMenuDisplayed)
      this.showHeaderMenu()
    },

    onAddMetadataClicked () {
      this.$emit('add-metadata')
    },

    onEditMetadataClicked () {
      this.$emit('edit-metadata', this.lastMetadaDataHeaderMenuDisplayed)
      this.showMetadataHeaderMenu()
    },

    onDeleteMetadataClicked () {
      this.$emit('delete-metadata', this.lastMetadaDataHeaderMenuDisplayed)
      this.showMetadataHeaderMenu()
    },

    resizeSplittedTableHeaders (columnDescriptors) {
      if (
        this.$refs['body-tbody'] &&
        this.$refs['body-tbody'].length > 0 &&
        this.$refs['body-tbody'][0].children.length > 1
      ) {
        const bodyElement = this.$refs['body-tbody'][0].children[1]
        columnDescriptors.forEach(desc => {
          const width = bodyElement.children[desc.index].offsetWidth
          if (this.$refs['th-' + desc.name]) {
            this.$refs['th-' + desc.name].style['min-width'] = `${width}px`
          }
        })
      }
    }
  }
}
<commit_msg>Fix validation columns sorting in case of equal priorities<commit_after>import colors from '../../lib/colors'
import Vue from 'vue'

export const entityListMixin = {

  created () {
    this.initHiddenColumns(this.validationColumns, this.hiddenColumns)
  },

  mounted () {
    this.resizeHeaders()
    window.addEventListener('keydown', this.onKeyDown, false)
  },

  beforeDestroy () {
    window.removeEventListener('keydown', this.onKeyDown)
  },

  computed: {
    sortedValidationColumns () {
      let columns = [...this.validationColumns]
      if (this.assetFilledColumns) {
        columns = columns.filter(c => this.assetFilledColumns[c])
      } else if (this.shotFilledColumns) {
        columns = columns.filter(c => this.shotFilledColumns[c])
      }

      return columns.sort((a, b) => {
        const taskTypeA = this.taskTypeMap[a]
        const taskTypeB = this.taskTypeMap[b]
        if (taskTypeA.priority === taskTypeB.priority) {
          return taskTypeA.name.localeCompare(taskTypeB.name)
        } else if (taskTypeA.priority > taskTypeB.priority) {
          return 1
        } else {
          return -1
        }
      })
    }
  },

  methods: {
    getBackground (color) {
      return colors.hexToRGBa(color, 0.08)
    },

    buildHideKey (columnId) {
      return `column-${this.currentProduction.id}-${columnId}`
    },

    initHiddenColumns (validationColumns, hiddenColumns) {
      if (validationColumns && hiddenColumns) {
        validationColumns.forEach((columnId) => {
          const key = this.buildHideKey(columnId)
          Vue.set(
            hiddenColumns,
            columnId,
            localStorage.getItem(key) === 'true'
          )
        })
      }
    },

    hideColumn (columnId) {
      const key = this.buildHideKey(columnId)
      let isColumnHidden = true
      if (localStorage.getItem(key) === 'true') {
        isColumnHidden = false
      }
      localStorage.setItem(key, isColumnHidden)
      Vue.set(this.hiddenColumns, columnId, isColumnHidden)
      this.hiddenColumns[columnId] = isColumnHidden
      return isColumnHidden
    },

    setScrollPosition (scrollPosition) {
      if (this.$refs.body) {
        this.$refs.body.scrollTop = scrollPosition
      }
    },

    setScrollLeftPosition (scrollPosition) {
      if (this.$refs.body) {
        this.$refs.body.scrollLeft = scrollPosition
      }
    },

    getValidationStyle (columnId) {
      const taskType = this.taskTypeMap[columnId]
      return {
        'border-left': `1px solid ${taskType.color}`,
        'background': this.getBackground(taskType.color)
      }
    },

    onTaskSelected (validationInfo) {
      const selection = []
      if (validationInfo.isShiftKey) {
        if (this.lastSelection) {
          let startX = this.lastSelection.x
          let endX = validationInfo.x
          let startY = this.lastSelection.y
          let endY = validationInfo.y
          let grid = this.assetSelectionGrid
          if (!grid) grid = this.shotSelectionGrid

          if (validationInfo.x < this.lastSelection.x) {
            startX = validationInfo.x
            endX = this.lastSelection.x
          }
          if (validationInfo.y < this.lastSelection.y) {
            startY = validationInfo.y
            endY = this.lastSelection.y
          }

          for (let i = startX; i <= endX; i++) {
            for (let j = startY; j <= endY; j++) {
              const ref = 'validation-' + i + '-' + j
              const validationCell = this.$refs[ref][0]
              if (!grid[i][j]) {
                selection.push({
                  entity: validationCell.entity,
                  column: validationCell.column,
                  task: validationCell.task,
                  x: validationCell.rowX,
                  y: validationCell.columnY
                })
              }
            }
          }
          this.$store.commit('ADD_SELECTED_TASK', validationInfo)
        }
      } else if (!validationInfo.isCtrlKey) {
        this.$store.commit('CLEAR_SELECTED_TASKS')
      }
      if (selection.length === 0) {
        this.$store.commit('ADD_SELECTED_TASK', validationInfo)
      } else {
        this.$store.commit('ADD_SELECTED_TASKS', selection)
      }

      if (!validationInfo.isShiftKey && validationInfo.isUserClick) {
        const x = validationInfo.x
        const y = validationInfo.y
        this.lastSelection = { x, y }
        const ref = 'validation-' + x + '-' + y
        const validationCell = this.$refs[ref][0]
        this.$nextTick(() => {
          this.scrollToValidationCell(validationCell)
        })
      }
    },

    onTaskUnselected (validationInfo) {
      if (!validationInfo.isCtrlKey) {
        if (this.nbSelectedTasks === 1) {
          this.$store.commit('REMOVE_SELECTED_TASK', validationInfo)
        } else {
          this.$store.commit('CLEAR_SELECTED_TASKS')
          this.$store.commit('ADD_SELECTED_TASK', validationInfo)
        }
      } else {
        this.$store.commit('REMOVE_SELECTED_TASK', validationInfo)
      }
    },

    showHeaderMenu (columnId, event) {
      const headerMenuEl = this.$refs.headerMenu.$el
      if (headerMenuEl.className === 'header-menu') {
        headerMenuEl.className = 'header-menu hidden'
      } else {
        headerMenuEl.className = 'header-menu'
        let headerElement = event.srcElement.parentNode.parentNode
        if (headerElement.tagName !== 'TH') {
          headerElement = headerElement.parentNode
        }
        const headerBox = headerElement.getBoundingClientRect()
        const left = headerBox.left + 11
        const top = headerBox.bottom + 10
        const width = Math.max(100, headerBox.width - 1)
        headerMenuEl.style.left = left + 'px'
        headerMenuEl.style.top = top + 'px'
        headerMenuEl.style.width = width + 'px'
      }
      this.lastHeaderMenuDisplayed = columnId
    },

    showMetadataHeaderMenu (columnId, event) {
      const headerMenuEl = this.$refs.headerMetadataMenu.$el
      if (headerMenuEl.className === 'header-menu') {
        headerMenuEl.className = 'header-menu hidden'
      } else {
        headerMenuEl.className = 'header-menu'
        let headerElement = event.srcElement.parentNode.parentNode
        const headerBox = headerElement.getBoundingClientRect()
        const left = headerBox.left + 11
        const top = headerBox.bottom + 10
        const width = Math.max(100, headerBox.width - 1)
        headerMenuEl.style.left = left + 'px'
        headerMenuEl.style.top = top + 'px'
        headerMenuEl.style.width = width + 'px'
      }
      this.lastMetadaDataHeaderMenuDisplayed = columnId
    },

    onMinimizeColumnToggled () {
      this.hideColumn(this.lastHeaderMenuDisplayed)
      this.showHeaderMenu()
    },

    onDeleteAllTasksClicked () {
      this.$emit('delete-all-tasks', this.lastHeaderMenuDisplayed)
      this.showHeaderMenu()
    },

    onAddMetadataClicked () {
      this.$emit('add-metadata')
    },

    onEditMetadataClicked () {
      this.$emit('edit-metadata', this.lastMetadaDataHeaderMenuDisplayed)
      this.showMetadataHeaderMenu()
    },

    onDeleteMetadataClicked () {
      this.$emit('delete-metadata', this.lastMetadaDataHeaderMenuDisplayed)
      this.showMetadataHeaderMenu()
    },

    resizeSplittedTableHeaders (columnDescriptors) {
      if (
        this.$refs['body-tbody'] &&
        this.$refs['body-tbody'].length > 0 &&
        this.$refs['body-tbody'][0].children.length > 1
      ) {
        const bodyElement = this.$refs['body-tbody'][0].children[1]
        columnDescriptors.forEach(desc => {
          const width = bodyElement.children[desc.index].offsetWidth
          if (this.$refs['th-' + desc.name]) {
            this.$refs['th-' + desc.name].style['min-width'] = `${width}px`
          }
        })
      }
    }
  }
}
<|endoftext|>


<commit_before>/*global window, console, navigator*/

var Erizo = Erizo || {};

Erizo.sessionId = 103;

Erizo.Connection = function (spec) {
    "use strict";
    var that = {};

    spec.session_id = (Erizo.sessionId += 1);

    // Check which WebRTC Stack is installed.
    that.browser = "";

    if (typeof module !== 'undefined' && module.exports) {
        L.Logger.error('Publish/subscribe video/audio streams not supported in erizofc yet');
        that = Erizo.FcStack(spec);
    } else if (window.navigator.userAgent.match("Firefox") !== null) {
        // Firefox
        that.browser = "mozilla";
        that = Erizo.FirefoxStack(spec);
    } else if (window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1] <= 30) {
        // Google Chrome Stable.
        L.Logger.debug("Stable!");
        that = Erizo.ChromeStableStack(spec);
        that.browser = "chrome-stable";
    } else if (window.navigator.userAgent.toLowerCase().indexOf("chrome")>=0) {
        // Google Chrome Canary.
        L.Logger.debug("Canary!");
        that = Erizo.ChromeCanaryStack(spec);
        that.browser = "chrome-canary";
    }  else if (window.navigator.appVersion.match(/Bowser\/([\w\W]*?)\./)[1] === "25") {
        // Bowser
        that.browser = "bowser";
    } else {
        // None.
        that.browser = "none";
        throw "WebRTC stack not available";
    }

    return that;
};

Erizo.GetUserMedia = function (config, callback, error) {
    "use strict";

    navigator.getMedia = ( navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

    if (typeof module !== 'undefined' && module.exports) {
        L.Logger.error('Video/audio streams not supported in erizofc yet');
    } else {
        navigator.getMedia(config, callback, error);
    }
};
<commit_msg>We support now Chrome 31<commit_after>/*global window, console, navigator*/

var Erizo = Erizo || {};

Erizo.sessionId = 103;

Erizo.Connection = function (spec) {
    "use strict";
    var that = {};

    spec.session_id = (Erizo.sessionId += 1);

    // Check which WebRTC Stack is installed.
    that.browser = "";

    if (typeof module !== 'undefined' && module.exports) {
        L.Logger.error('Publish/subscribe video/audio streams not supported in erizofc yet');
        that = Erizo.FcStack(spec);
    } else if (window.navigator.userAgent.match("Firefox") !== null) {
        // Firefox
        that.browser = "mozilla";
        that = Erizo.FirefoxStack(spec);
    } else if (window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1] <= 31) {
        // Google Chrome Stable.
        L.Logger.debug("Stable!");
        that = Erizo.ChromeStableStack(spec);
        that.browser = "chrome-stable";
    } else if (window.navigator.userAgent.toLowerCase().indexOf("chrome")>=0) {
        // Google Chrome Canary.
        L.Logger.debug("Canary!");
        that = Erizo.ChromeCanaryStack(spec);
        that.browser = "chrome-canary";
    }  else if (window.navigator.appVersion.match(/Bowser\/([\w\W]*?)\./)[1] === "25") {
        // Bowser
        that.browser = "bowser";
    } else {
        // None.
        that.browser = "none";
        throw "WebRTC stack not available";
    }

    return that;
};

Erizo.GetUserMedia = function (config, callback, error) {
    "use strict";

    navigator.getMedia = ( navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

    if (typeof module !== 'undefined' && module.exports) {
        L.Logger.error('Video/audio streams not supported in erizofc yet');
    } else {
        navigator.getMedia(config, callback, error);
    }
};
<|endoftext|>


<commit_before>import React from 'react';
import {Entity} from "aframe-react";
import {deselectCurrentMode, getCurrentlySelectedTexture, selectCurrentModel} from "./redux/game_state";
import {connectExit, disconnectExits} from "./redux/neon_state";

export const ROCKS = {
    "#sun": {
        texture: '#sunTexture',
        position: {x: 0, y: 0, z: 0},
        visible: true,
        selectable: true
    },
    "#sticks": {
        texture: '#sticksTexture',
        position: {x: 0.55, y: 0, z: 0},
        visible: true,
        selectable: true
    },
    "fog": {
        texture: '#fogTexture',
        position: {x: 1.1, y: 0, z: 0},
        visible: true,
        selectable: true
    },
    "fence": {
        texture: '#fenceTexture',
        position: {x: 0, y: 0, z: 0.6},
        visible: true,
        selectable: true
    },
    "eye": {
        texture: '#eyeTexture',
        position: {x: 0.55, y: 0, z: 0.6},
        visible: true,
        selectable: true
    },
    "birds": {
        texture: '#birdsTexture',
        position: {x: 1.1, y: 0, z: 0.6},
        visible: true,
        selectable: true
    }
};

export default class Playground extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            fields: ROCKS
        };

        this.onDiskChange = this.onDiskChange.bind(this);
    }

    createAllRocks(callback) {
        return Object.entries(this.state.fields).map((field) => {
            return this.createRock(field[0], field[1], callback);
        })
    }

    createRock(name, data, callback) {
        return <Rock
            key={name}
            name={name}
            src={data.texture}
            hovered_field={
                {
                    position_down: {x: data.position.x, y: data.position.y - 0.15, z: data.position.z},
                    position_up: {x: data.position.x, y: data.position.y, z: data.position.z}
                }
            }
            visible={data.visible}
            onFieldClicked={callback}
            position={data.position}
        />
    }

    onDiskChange(el, name) {
        let fields = this.state.fields;
        var fieldModel = fields[name];
        //Check if model is selected in game state
        let selectedModel = getCurrentlySelectedTexture(el);
        let isDirty = false;
        if (fieldModel.selectable) {
            if (selectedModel) {
                console.log("Placing: " + selectedModel);
                fieldModel.model = selectedModel;
                fieldModel.visible = true;
                deselectCurrentMode(el);
                isDirty = true;
            } else if (fieldModel.model) {
                let model = fieldModel.model;
                //Pickup model
                console.log("Picking up: " + model);
                fieldModel.model = "";
                fieldModel.visible = false;
                selectCurrentModel(el, model);
                isDirty = true;
            }

            if (isDirty) {
                fields[name] = fieldModel;
                this.setState({
                    fields: fields
                });

                this.checkExitsConnect(el);
            }
        }
    }

    checkExitsConnect(el) {
        disconnectExits(el);
        return this.checkConnection(el, 1, 0) || this.checkConnection(el, 0, 1);
    }

    checkConnection(el, startIdx, startIdy) {
        let exitIndex = this.props.dim - 1;
        if (startIdy === exitIndex) {
            console.log(`Connected ${startIdx}, ${startIdy}`);
            if (startIdx === 0) {
                connectExit(el, "exit1");
            } else if (startIdx === exitIndex) {
                connectExit(el, "exit2");
            }
            return true;
        } else {
            let fields = this.state.fields;
            console.log(`${startIdx}, ${startIdy}`);
            let currentField = fields[startIdx][startIdy];
            let connected = false;
            console.log(currentField.model);
            if (currentField.model) {
                if (ROCKS[currentField.model].exit_up) {
                    let nextField = fields[startIdx][startIdy + 1];
                    if (nextField.model) {
                        if (ROCKS[nextField.model].start_down) {
                            connected = this.checkConnection(el, startIdx, startIdy + 1);
                        }
                    }
                }
                if (ROCKS[currentField.model].exit_right) {
                    let nextField = fields[startIdx + 1][startIdy];
                    if (nextField.model) {
                        if (ROCKS[nextField.model].start_left) {
                            connected = connected || this.checkConnection(el, startIdx + 1, startIdy);
                        }
                    }
                }
            }

            return connected;
        }
    }

    render() {
        return (
            <Entity {...this.props}
                    className="fields"
                    shadow="receive: false">
                <Desktop/>
                <Entity position={{x: -0.55, y: 0.5, z: -0.2}}>
                    {
                        this.createAllRocks(this.onDiskChange)
                    }
                </Entity>
            </Entity>
        )
    }
}

class Rock extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            name: this.props.name,
        }
    }

    render() {
        return (
            <Entity
                {...this.props}

                id={this.props.src}
                hoverable
                sound="src: #rockSound; on: fusing"
                className="field intersectable"
                shadow="receive: false"
                events={{
                    click: (evt) => {
                        let el = evt.target;
                        this.props.onFieldClicked(el, this.state.name);
                    }
                }}
            >

                <Entity
                    id={this.props.src}
                    collada-model="#rockButton"
                />
                <a-image
                    position="0 0.15 0"
                    rotation="90 0 0"
                    scale="0.4 0.4 1"
                    src={this.props.src}/>
            </Entity>
        )
    }

}

class Desktop extends React.Component {
    render() {
        return <Entity
            {...this.props}
            id="Desktop"
            collada-model="#rockDesktop"/>
    }
}<commit_msg>Working placing disks<commit_after>import React from 'react';
import {Entity} from "aframe-react";
import {deselectCurrentMode, getCurrentlySelectedTexture, getCurrentlySelectedModel, selectCurrentModel} from "./redux/game_state";
import {connectExit, disconnectExits} from "./redux/neon_state";

export const ROCKS = {
    "#sun": {
        texture: '#sunTexture',
        position: {x: 0, y: 0, z: 0},
        visible: false,
        selectable: true,
        model: "",
    },
    "#sticks": {
        texture: '#sticksTexture',
        position: {x: 0.55, y: 0, z: 0},
        visible: false,
        selectable: true,
        model: "",
    },
    "fog": {
        texture: '#fogTexture',
        position: {x: 1.1, y: 0, z: 0},
        visible: false,
        selectable: true,
        model: "",
    },
    "fence": {
        texture: '#fenceTexture',
        position: {x: 0, y: 0, z: 0.6},
        visible: false,
        selectable: true,
        model: "",
    },
    "eye": {
        texture: '#eyeTexture',
        position: {x: 0.55, y: 0, z: 0.6},
        visible: false,
        selectable: true,
        model: "",
    },
    "birds": {
        texture: '#birdsTexture',
        position: {x: 1.1, y: 0, z: 0.6},
        visible: false,
        selectable: true,
        model: "",
    }
};

export default class Playground extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            fields: ROCKS
        };

        this.onDiskChange = this.onDiskChange.bind(this);
    }

    createAllRocks(callback) {
        return Object.entries(this.state.fields).map((field) => {
            return this.createRock(field[0], field[1], callback);
        })
    }

    createRock(name, data, callback) {
        return <Rock
            key={name}
            name={name}
            src={data.texture}
            hovered_field={
                {
                    position_down: {x: data.position.x, y: data.position.y - 0.15, z: data.position.z},
                    position_up: {x: data.position.x, y: data.position.y, z: data.position.z}
                }
            }
            visible={data.visible}
            onFieldClicked={callback}
            position={data.position}
        />
    }

    onDiskChange(el, name) {
        let fields = this.state.fields;
        var fieldModel = fields[name];
        //Check if model is selected in game state
        let selectedTexture = getCurrentlySelectedTexture(el);
        let isDirty = false;
        if (fieldModel.selectable) {
            if (selectedTexture) {
                console.log("Placing: " + selectedTexture);
                fieldModel.modelSrc = selectedTexture;
                fieldModel.visible = true;
                deselectCurrentMode(el);
                isDirty = true;
            } else if (fieldModel.model) {
                let model = fieldModel.model;
                //Pickup model
                console.log("Picking up: " + model);
                fieldModel.modelSrc = "";
                fieldModel.visible = false;
                selectCurrentModel(el, model);
                isDirty = true;
            }

            if (isDirty) {
                fields[name] = fieldModel;
                this.setState({
                    fields: fields
                });

               // this.checkExitsConnect(el);
            }
        }
    }

    checkExitsConnect(el) {
        disconnectExits(el);
        return this.checkConnection(el, 1, 0) || this.checkConnection(el, 0, 1);
    }

    checkConnection(el, startIdx, startIdy) {
        let exitIndex = this.props.dim - 1;
        if (startIdy === exitIndex) {
            console.log(`Connected ${startIdx}, ${startIdy}`);
            if (startIdx === 0) {
                connectExit(el, "exit1");
            } else if (startIdx === exitIndex) {
                connectExit(el, "exit2");
            }
            return true;
        } else {
            let fields = this.state.fields;
            console.log(`${startIdx}, ${startIdy}`);
            let currentField = fields[startIdx][startIdy];
            let connected = false;
            console.log(currentField.model);
            if (currentField.model) {
                if (ROCKS[currentField.model].exit_up) {
                    let nextField = fields[startIdx][startIdy + 1];
                    if (nextField.model) {
                        if (ROCKS[nextField.model].start_down) {
                            connected = this.checkConnection(el, startIdx, startIdy + 1);
                        }
                    }
                }
                if (ROCKS[currentField.model].exit_right) {
                    let nextField = fields[startIdx + 1][startIdy];
                    if (nextField.model) {
                        if (ROCKS[nextField.model].start_left) {
                            connected = connected || this.checkConnection(el, startIdx + 1, startIdy);
                        }
                    }
                }
            }

            return connected;
        }
    }

    render() {
        return (
            <Entity {...this.props}
                    className="fields"
                    shadow="receive: false">
                <Desktop/>
                <Entity position={{x: -0.55, y: 0.5, z: -0.2}}>
                    {
                        this.createAllRocks(this.onDiskChange)
                    }
                </Entity>
            </Entity>
        )
    }
}
const scaleFactor = 0.04;

class Rock extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            name: this.props.name,
        }
    }

    render() {
        let {visible, ...other} = this.props;
        return (
            <Entity
                {...other}

                id={this.props.src}
                hoverable
                sound="src: #rockSound; on: fusing"
                className="field intersectable"
                shadow="receive: false"
                events={{
                    click: (evt) => {
                        let el = evt.target;
                        this.props.onFieldClicked(el, this.state.name);
                    }
                }}
            >

                <Entity
                    id={this.props.src}
                    collada-model="#rockButton"
                />
                <a-image
                    position="0 0.15 0"
                    rotation="90 0 0"
                    scale="0.4 0.4 1"
                    src={this.props.src}/>

                {<Entity
                    visible={visible}>
                    <Entity id="model"
                        scale={{x: scaleFactor, y: scaleFactor, z: scaleFactor}}
                        rotation={{x: 0.0, y: 0.0, z: -90.0}}
                        position={{x: 0.0, y: 0.0, z: -0.25}}
                        collada-model="#rockDisk"
                        />
                    <a-image
                        position="0 0.15 0"
                        rotation="90 0 0"
                        scale="0.4 0.4 1"
                        src={this.props.modelSrc}/>
                    </Entity>
                }
            </Entity>
        )
    }

}

class Desktop extends React.Component {
    render() {
        return <Entity
            {...this.props}
            id="Desktop"
            collada-model="#rockDesktop"/>
    }
}<|endoftext|>


<commit_before>// code editor things

Template.code.helpers({

  nulldoc: function() {
    return Session.equals('document', null);
  }

});

Template.editor.helpers({

  docid: function() {
    return Session.get('document');
  },

  config: function() {
    return function(editor) { // set default theme
      editor.setTheme('ace/theme/monokai');
      editor.setShowPrintMargin(false);
      editor.getSession().setUseWrapMode(true);
    };
  },

  setMode: function() {
    return function(editor) { // different style on filetype
      var fileId = Session.get('document');
      var fileName = Files.findOne( fileId ).title;
      var modelist = ace.require('ace/ext/modelist');
      var filemode = modelist.getModeForPath( fileName ).mode;
      editor.getSession().setMode( filemode );
    }
  }

});

Template.filename.helpers({

  rename: function() {
    return Session.equals('renaming', true);
  },

  title: function() {
    var ref;
    return (ref = Files.findOne(this + '')) != null ? ref.title : void 0;
  }

});

Template.filename.events({

  // rename the current file
  'submit .rename': function(e) {
    e.preventDefault();
    $(e.target).blur();
    var txt = $('#filetitle')[0].value;
    if (txt == null || txt == '') return false;
    var id = Session.get('document');
    Session.set('renaming', false);
    Files.update(id, {$set:{title:txt}} );
  },

  // enable changing of filename
  'click button.edit': function (e) {
    e.preventDefault();
    Session.set('renaming', true);
    focusForm('#filetitle');
  },

  // delete the current file
  'click button.del': function(e) {
    e.preventDefault();
    var id = Session.get('document');
    Meteor.call('deleteFile', id);
    Session.set('renaming', false);
    Session.set('document', null);
  }

});
<commit_msg>pimp out ace editor<commit_after>// code editor things

Template.code.helpers({

  nulldoc: function() {
    return Session.equals('document', null);
  }

});

Template.editor.helpers({

  docid: function() {
    return Session.get('document');
  },

  config: function() {
    return function(editor) { // set default theme
      editor.setTheme('ace/theme/monokai');
      editor.setShowPrintMargin(false);
      editor.getSession().setUseWrapMode(true);
      var beautify = ace.require('ace/ext/beautify');
      editor.commands.addCommands(beautify.commands);
      editor.setOptions({
        enableBasicAutocompletion: true,
        enableLiveAutocompletion: true,
        enableSnippets: true
      });
    };
  },

  setMode: function() {
    return function(editor) { // different style on filetype
      var fileId = Session.get('document');
      var fileName = Files.findOne( fileId ).title;
      var modelist = ace.require('ace/ext/modelist');
      var filemode = modelist.getModeForPath( fileName ).mode;
      editor.getSession().setMode( filemode );
    }
  }

});

Template.filename.helpers({

  rename: function() {
    return Session.equals('renaming', true);
  },

  title: function() {
    var ref;
    return (ref = Files.findOne(this + '')) != null ? ref.title : void 0;
  }

});

Template.filename.events({

  // rename the current file
  'submit .rename': function(e) {
    e.preventDefault();
    $(e.target).blur();
    var txt = $('#filetitle')[0].value;
    if (txt == null || txt == '') return false;
    var id = Session.get('document');
    Session.set('renaming', false);
    Files.update(id, {$set:{title:txt}} );
  },

  // enable changing of filename
  'click button.edit': function (e) {
    e.preventDefault();
    Session.set('renaming', true);
    focusForm('#filetitle');
  },

  // delete the current file
  'click button.del': function(e) {
    e.preventDefault();
    var id = Session.get('document');
    Meteor.call('deleteFile', id);
    Session.set('renaming', false);
    Session.set('document', null);
  }

});
<|endoftext|>


<commit_before>var React = require('react');
var actions = require('../actions');
var { Navigation } = require('react-router');
var QueryStore = require('../stores/query_store.js');

var QueryList = React.createClass({
    mixins: [QueryStore.listenTo, Navigation],
    getInitialState() {
        return { queries: [] };
    },
    _onChange() {
        this.setState({ queries: QueryStore.all() });
    },
    chooseQuery(q) {
        this.props.chooseQuery(q);
    },
    deleteQuery(q) {
        actions.deleteQuery(q.path);
    },
    render() {
        return

          {this.state.queries.map(q =>

                  {q.data.name}

{q.data.query}

                  {false ?  : ''}

)}

;
    }
});

module.exports = QueryList;
<commit_msg>Add keys to query list<commit_after>var React = require('react');
var actions = require('../actions');
var { Navigation } = require('react-router');
var QueryStore = require('../stores/query_store.js');

var QueryList = React.createClass({
    mixins: [QueryStore.listenTo, Navigation],
    getInitialState() {
        return { queries: [] };
    },
    _onChange() {
        this.setState({ queries: QueryStore.all() });
    },
    chooseQuery(q) {
        this.props.chooseQuery(q);
    },
    deleteQuery(q) {
        actions.deleteQuery(q.path);
    },
    render() {
        return

          {this.state.queries.map((q, i) =>

                  {q.data.name}

{q.data.query}

                  {false ?  : ''}

)}

;
    }
});

module.exports = QueryList;
<|endoftext|>


<commit_before>import execSync from "../services/exec-sync";
import log from "../services/logger";

export default function build ({sourceDir}) {
    log.info("Building lambda");
    execSync(`/bin/sh ${sourceDir}/Lambdafile`);
}
<commit_msg>Run build script in sourceDir<commit_after>import execSync from "../services/exec-sync";
import log from "../services/logger";

export default function build ({sourceDir}) {
    log.info("Building lambda");
    execSync(`/bin/sh ${sourceDir}/Lambdafile`, {
        cwd: sourceDir
    });
}
<|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Docker control")
description("This will return the docker control")
base_component_id("docker_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "text",
            name:       "Dev text",
            default:    "Docker connecter",
            type:       "String"
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    200,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    50,
            type:       "Number"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:     "container_list",
            name:   "Container list",
            type:   "List"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
    ]
)//properties
logo_url("/driver_icons/ducker.png")
*/

    Vue.component("docker_control",{
      props: ["args","design_mode"]
      ,
      template: `

                                        {{args.text}}

`
      ,
      data: function() {
       return {
         msg: "..."
     }
      },

      mounted: async function() {
        if (!this.design_mode) {
            var result = await callFunction(
                                {
                                    driver_name: "serverDockerStuff",
                                    method_name: "serverDockerStuff"  }
                                    ,{ })

           if (result.value) {
                this.args.container_list = result.value.containerList

           }

           }
       }

    })
}
<commit_msg>Trying to show table control in the docker container control<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Docker control")
description("This will return the docker control")
base_component_id("docker_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "text",
            name:       "Dev text",
            default:    "Docker connecter",
            type:       "String"
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    200,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    50,
            type:       "Number"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:     "container_list",
            name:   "Container list",
            type:   "List"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
    ]
)//properties
logo_url("/driver_icons/ducker.png")
*/

    Vue.component("docker_control",{
      props: ["args","design_mode","refresh", "children"]
      ,
      template: `

                                        {{args.text}}

                                             <slot v-bind:refresh='refresh'>
                                             </slot>

`
      ,
      data: function() {
       return {
         msg: "..."
     }
      },

      mounted: async function() {
        if (!this.design_mode) {
            var result = await callFunction(
                                {
                                    driver_name: "serverDockerStuff",
                                    method_name: "serverDockerStuff"  }
                                    ,{ })

           if (result.value) {
                this.args.container_list = result.value.containerList

           }

           }
       }

    })
}
<|endoftext|>


<commit_before>import _ from 'lodash'
import Promise from 'bluebird'
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
// import Mousetrap from 'mousetrap'
var fs = require('fs')
var writeFile = Promise.promisify(fs.writeFile)
var appendFile = Promise.promisify(fs.appendFile)
var readFile = Promise.promisify(fs.readFile)
var fileAccess = Promise.promisify(fs.access)

const storage = require('electron-json-storage');
const getFromStorage = Promise.promisify(storage.get)
const setToStorage = Promise.promisify(storage.set)

// utils
import { saveFile, openFile } from '../utils/fileops.js'

import styles from './AppStyles.css'
// our components
import Settings from './Settings/index.js'
import Toolbar from './Toolbar/index.js'
import MainWindow from './MainWindow/index.js'
import Footer from './Footer/index.js'
import { compiler as elmCompiler } from '../compilers/elm/elm.js'

const {
    compile: compileElm,
    cleanUp: cleanUpElm,
    onNewFileLoad: onNewFileLoadElm,
    formatCode: formatCodeElm,
    generateTests: generateTestsElm } = elmCompiler()

import { compiler as purescriptCompiler } from '../compilers/purescript/purescript.js'
const { compile: compilePurescript, cleanUp: cleanUpPurescript } = purescriptCompiler()

import {ipcRenderer} from 'electron'

const compilers = {
    elm: {
        compile: compileElm,
        cleanUp: cleanUpElm,
        formatCode: formatCodeElm,
        onNewFileLoad: onNewFileLoadElm,
        editorMode: 'elm',
        generateTests: generateTestsElm,
    },
    purescript: {
        compile: compilePurescript,
        cleanUp: cleanUpPurescript,
        editorMode: 'haskell',
    }
}

function getFileNameWithoutExtension(fileName) {
    if(fileName.indexOf('.') >= 0) {
        return _.initial(fileName.split('.')).join('.')
    } else {
        return fileName // no extension in the file name
    }
}

function getPlaygroundFilePath(codeFilePath, playgroundFilePath) {
    if(playgroundFilePath) {
        return playgroundFilePath
    }

    if(!codeFilePath) {
        return null
    }

    const codeFileName = _.last(codeFilePath.split('/'))
    const codeFileFolderPath = _.initial(codeFilePath.split('/')).join('/')
    return codeFileFolderPath + '/' + getFileNameWithoutExtension(codeFileName) + '.frolic'
}

export default class App extends Component {
    constructor(props) {
        super(props)

        this.handleCodeChange = this.handleCodeChange.bind(this)
        this.handlePlaygroundCodeChange = this.handlePlaygroundCodeChange.bind(this)
        this.compile = _.debounce(this.compile.bind(this), 1000)

        this.handleLanguageChange = this.handleLanguageChange.bind(this)
        this.handleEditorThemeChange = this.handleEditorThemeChange.bind(this)
        this.handleFontSizeChange = this.handleFontSizeChange.bind(this)
        this.handleTabSizeChange = this.handleTabSizeChange.bind(this)
        this.handleAutoCompileFlagChange = this.handleAutoCompileFlagChange.bind(this)
        this.handleFileOpenClick = _.debounce(this.handleFileOpenClick.bind(this), 500)
        this.handleFileSaveClick = _.debounce(this.handleFileSaveClick.bind(this), 500)
        this.handleNewFileClick = _.debounce(this.handleNewFileClick.bind(this), 500)
        this.handleSavePlaygroundClick = _.debounce(this.handleSavePlaygroundClick.bind(this), 500)
        this.toggleCodePanelVisibility = this.toggleCodePanelVisibility.bind(this)
        this.togglePlaygroundPanelVisibility = this.togglePlaygroundPanelVisibility.bind(this)
        this.toggleOutputPanelVisibility = this.toggleOutputPanelVisibility.bind(this)
        this.loadFileFromHistory = this.loadFileFromHistory.bind(this)
        this.handleWindowResize = _.debounce(this.handleWindowResize.bind(this), 300)
        this.loadPlaygroundFile = this.loadPlaygroundFile.bind(this)
        this.openPlaygroundFile = this.openPlaygroundFile.bind(this)
        this.handleGenerateTestClick = this.handleGenerateTestClick.bind(this)
        this.handleSettingsClose = this.handleSettingsClose.bind(this)
        this.handleKeyboardHandlerChange = this.handleKeyboardHandlerChange.bind(this)

        this.state = {
            code: 'add x y = x + y',
            playgroundCode: 'add 2 3',
            output: '',
            compiling: false,
            language: 'elm',
            autoCompile: true,
            openFilePath: null,
            showCodePanel: true,
            showPlaygroundPanel: true,
            showOutputPanel: true,
            editorTheme: 'terminal',
            autoCompile: true,
            editorHeight: 1000,
            fontSize: 14,
            tabSize: 4,
            keyboardHandler: 'ace',
            showSettings: false
        }
    }

    componentWillMount() {
        ipcRenderer.on('menuActions', (event, message) => {
            if(!message || !message.action) {
                return
            }

            switch(message.action) {
                case 'newFile':
                    this.handleNewFileClick()
                    break;
                case 'openFile':
                    this.handleFileOpenClick()
                    break;
                case 'openPlaygroundFile':
                    this.openPlaygroundFile()
                    break;
                case 'saveFile':
                    this.handleFileSaveClick()
                    break;
                case 'savePlaygroundFile':
                    this.handleSavePlaygroundClick()
                    break;
                case 'generateTests':
                    this.handleGenerateTestClick()
                    break;
                case 'showPreferences':
                    this.handleShowPreferences()
                    break;
                default:
                    console.log('don\'t understand the menu action', message.action)
            }
        })
    }

    componentDidMount() {
        window.onresize = this.handleWindowResize
        this.handleWindowResize()

        if(this.state.autoCompile) {
            this.compile()
        }
    }

    componentWillUnmount() {
        this.storeFilePathInDb()

        Object.keys(compilers).map((compilerKey) => {
            compilers[compilerKey].cleanUp()
        })
    }

    handleWindowResize() {
        this.setState({
            editorHeight: this.mainWindow.clientHeight
        })
    }

    loadFileFromHistory() {
        getFromStorage('fileData')
                .then((file) => {
                    if(file.filePath) {
                        readFile(file.filePath)
                            .then((content) => this.setState({code: content.toString()}))
                    }
                })
    }

    storeFilePathInDb() {
        return setToStorage('fileData', {filePath: this.state.openFilePath})
                .then(() => console.log('file path stored ', this.state.openFilePath))
                .catch((err) => {
                    console.log('error setting filePath', err)
                })
    }

    compile() {
        this.setState({
            compiling: true,
        }, () => {
            compilers[this.state.language]
                .compile(this.state.code, this.state.playgroundCode, this.state.openFilePath)
                .then((output) => this.setState({output, compiling: false}))
                .catch((output) => this.setState({output, compiling: false}))
        })
    }

    handleCodeChange(newCode) {
        this.setState({
            code: newCode,
            fileSaved: false
        }, () => {
            if(this.state.autoCompile) {
                this.compile()
            }
        })
    }

    handlePlaygroundCodeChange(newCode) {
        this.setState({
            playgroundCode: newCode
        }, () => {
            if(this.state.autoCompile) {
                this.compile()
            }
        })
    }

    handleLanguageChange(e) {
        compilers[this.state.language].cleanUp()
        this.setState({language: e.target.value})
    }

    handleNewFileClick() {
        this.setState({
            openFilePath: null,
            playgroundFilePath: null,
            fileSaved: false,
            code: '',
            playgroundCode: ''
        })
    }

    handleFileSaveClick() {
        return saveFile(this.state.code, this.state.openFilePath, ['elm'])
                .then((filePath) => {
                    compilers[this.state.language]
                        .formatCode(this.state.code)
                        .then((formattedCode) => {
                            this.setState({
                                code: formattedCode,
                                openFilePath: filePath,
                                fileSaved: true
                            })
                        })
                })
                .catch((err) => console.log('error saving file ', err.message))
    }

    handleGenerateTestClick() {
        if(compilers[this.state.language].generateTests) {
            compilers[this.state.language].generateTests(this.state.code, this.state.playgroundCode, this.state.openFilePath)
                .then((tests) => console.log('generated tests', tests))
        } else {
            alert('This compiler, ' + this.state.language + ', does not support test generation')
        }
    }

    handleSettingsClose() {
        this.setState({showSettings: false})
    }

    handleShowPreferences() {
        this.setState({showSettings: true})
    }

    openPlaygroundFile() {
        openFile(['frolic'])
            .then(({filePath, content}) => {
                this.setState({
                    playgroundCode: content.toString(),
                    playgroundFilePath: filePath,
                }, () => {
                    if(this.state.autoCompile) {
                        this.compile()
                    }
                })
            })
            .catch((err) => console.log('error opening playground file', err.message))
    }

    loadPlaygroundFile(codeFile, playgroundFilePath) {
        return fileAccess(getPlaygroundFilePath(codeFile.filePath, playgroundFilePath))
                .then((content) => {
                    return readFile(getPlaygroundFilePath(codeFile.filePath, playgroundFilePath))
                            .then((content) => {
                                return {
                                    codeFile,
                                    playgroundFile: {content: content.toString(), filePath: getPlaygroundFilePath(codeFile.filePath, playgroundFilePath)},
                                }
                            })
                })
                .catch((err) => {
                    console.log('error reading playground file', err.message)
                    return {codeFile, playgroundFile: {content: '', filePath: null}}
                })
    }

    handleSavePlaygroundClick() {
        saveFile(
            this.state.playgroundCode,
            getPlaygroundFilePath(this.state.openFilePath, this.state.playgroundFilePath),
            ['frolic'],
            'Save Playground')
            .then((filePath) => {
                console.log('playground code saved to', filePath)
            })
            .catch((err) => console.log('error saving file ', err.message))
    }

    handleFileOpenClick() {
        openFile(['elm'])
            .then((codeFile) => this.loadPlaygroundFile(codeFile, null))
            .then(({codeFile, playgroundFile}) => {
                this.setState({
                    openFilePath: codeFile.filePath,
                    code: codeFile.content,
                    playgroundCode: playgroundFile.content,
                    playgroundFilePath: playgroundFile.filePath,
                    fileSaved: true
                }, () => {
                    this.storeFilePathInDb()
                    compilers[this.state.language].onNewFileLoad(this.state.openFilePath)
                    if(this.state.autoCompile) {
                        this.compile()
                    }
                })
            })
            .catch((err) => {
                console.log('error opening file ', err.toString())
            })
    }

    handleAutoCompileFlagChange(e) {
        this.setState({autoCompile: e.target.checked})
    }

    handleEditorThemeChange(e) {
        this.setState({editorTheme: e.target.value})
    }

    handleFontSizeChange(e) {
        this.setState({fontSize: parseInt(e.target.value)})
    }

    handleTabSizeChange(e) {
        this.setState({tabSize: parseInt(e.target.value)})
    }

    handleKeyboardHandlerChange(e) {
        this.setState({keyboardHandler: e.target.value})
    }

    toggleCodePanelVisibility(showCodePanel) {
        this.setState({showCodePanel})
    }

    togglePlaygroundPanelVisibility(showPlaygroundPanel) {
        this.setState({showPlaygroundPanel})
    }

    toggleOutputPanelVisibility(showOutputPanel) {
        this.setState({showOutputPanel})
    }

    render() {
        return (
            <div className={styles['root-container']}>
                <Toolbar
                    editorTheme={this.state.editorTheme}
                    onEditorThemeChange={this.handleEditorThemeChange}
                    fontSize={this.state.fontSize}
                    onFontSizeChange={this.handleFontSizeChange}
                    language={this.state.language}
                    onLanguageChange={this.handleLanguageChange}
                    onCompileClick={this.compile}
                    onOpenClick={this.handleFileOpenClick}
                    onSaveClick={this.handleFileSaveClick}
                    onNewFileClick={this.handleNewFileClick}
                    fileSaved={this.state.fileSaved}
                    autoCompile={this.state.autoCompile}
                    onAutoCompileFlagChange={this.handleAutoCompileFlagChange}
                    onCodePanelVisibilityChange={this.toggleCodePanelVisibility}
                    onPlaygroundPanelVisibilityChange={this.togglePlaygroundPanelVisibility}
                    onOutputPanelVisibilityChange={this.toggleOutputPanelVisibility}
                    showCodePanel={this.state.showCodePanel}
                    showPlaygroundPanel={this.state.showPlaygroundPanel}
                    showOutputPanel={this.state.showOutputPanel}
                    ref={(node) => {
                        if(node && !this.toolbarDiv) {
                            this.toolbarDiv = ReactDOM.findDOMNode(node)
                        }
                    }}
                />
                <MainWindow
                    ref={(node) => {
                        if(node) {
                            this.mainWindow = ReactDOM.findDOMNode(node)
                        }
                    }}
                    fontSize={this.state.fontSize}
                    tabSize={this.state.tabSize}
                    keyboardHandler={this.state.keyboardHandler}
                    code={this.state.code}
                    playgroundCode={this.state.playgroundCode}
                    output={this.state.output}
                    compiling={this.state.compiling}
                    onCodeChange={this.handleCodeChange}
                    onPlaygroundCodeChange={this.handlePlaygroundCodeChange}
                    onSavePlaygroundClick={this.handleSavePlaygroundClick}
                    editorMode={compilers[this.state.language].editorMode}
                    showCodePanel={this.state.showCodePanel}
                    showPlaygroundPanel={this.state.showPlaygroundPanel}
                    showOutputPanel={this.state.showOutputPanel}
                    editorHeight={this.state.editorHeight}
                    editorTheme={this.state.editorTheme}
                    playgroundFilePath={getPlaygroundFilePath(this.state.openFilePath, this.state.playgroundFilePath)}
                    />
                <Footer
                    fileSaved={this.state.fileSaved}
                    openFilePath={this.state.openFilePath}
                    ref={(node) => {
                        if(node && !this.footerDiv) {
                            this.footerDiv = ReactDOM.findDOMNode(node)
                        }
                    }}
                    />
                {this.state.showSettings
                    ?
                    <Settings
                        onClose={this.handleSettingsClose}
                        editorTheme={this.state.editorTheme}
                        onEditorThemeChange={this.handleEditorThemeChange}
                        fontSize={this.state.fontSize}
                        onFontSizeChange={this.handleFontSizeChange}
                        tabSize={this.state.tabSize}
                        onTabSizeChange={this.handleTabSizeChange}
                        keyboardHandler={this.state.keyboardHandler}
                        onKeyboardHandlerChange={this.handleKeyboardHandlerChange}
                        />
                    : null}
            </div>
        )
    }
}
<commit_msg>persist preferences to disk and load them on application start<commit_after>import _ from 'lodash'
import Promise from 'bluebird'
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
// import Mousetrap from 'mousetrap'
var fs = require('fs')
var writeFile = Promise.promisify(fs.writeFile)
var appendFile = Promise.promisify(fs.appendFile)
var readFile = Promise.promisify(fs.readFile)
var fileAccess = Promise.promisify(fs.access)

const storage = require('electron-json-storage');
const getFromStorage = Promise.promisify(storage.get)
const setToStorage = Promise.promisify(storage.set)

// utils
import { saveFile, openFile } from '../utils/fileops.js'

import styles from './AppStyles.css'
// our components
import Settings from './Settings/index.js'
import Toolbar from './Toolbar/index.js'
import MainWindow from './MainWindow/index.js'
import Footer from './Footer/index.js'
import { compiler as elmCompiler } from '../compilers/elm/elm.js'

const {
    compile: compileElm,
    cleanUp: cleanUpElm,
    onNewFileLoad: onNewFileLoadElm,
    formatCode: formatCodeElm,
    generateTests: generateTestsElm } = elmCompiler()

import { compiler as purescriptCompiler } from '../compilers/purescript/purescript.js'
const { compile: compilePurescript, cleanUp: cleanUpPurescript } = purescriptCompiler()

import {ipcRenderer} from 'electron'

const compilers = {
    elm: {
        compile: compileElm,
        cleanUp: cleanUpElm,
        formatCode: formatCodeElm,
        onNewFileLoad: onNewFileLoadElm,
        editorMode: 'elm',
        generateTests: generateTestsElm,
    },
    purescript: {
        compile: compilePurescript,
        cleanUp: cleanUpPurescript,
        editorMode: 'haskell',
    }
}

function getFileNameWithoutExtension(fileName) {
    if(fileName.indexOf('.') >= 0) {
        return _.initial(fileName.split('.')).join('.')
    } else {
        return fileName // no extension in the file name
    }
}

function getPlaygroundFilePath(codeFilePath, playgroundFilePath) {
    if(playgroundFilePath) {
        return playgroundFilePath
    }

    if(!codeFilePath) {
        return null
    }

    const codeFileName = _.last(codeFilePath.split('/'))
    const codeFileFolderPath = _.initial(codeFilePath.split('/')).join('/')
    return codeFileFolderPath + '/' + getFileNameWithoutExtension(codeFileName) + '.frolic'
}

function savePreferences(preferences) {
    setToStorage('preferences', preferences)
        .then(() => console.log('preferences stored', preferences))
        .catch(err => console.log('error saving preferences', err))
}

function getSavedPreferences() {
    return getFromStorage('preferences')
            .then((preferences) => {
                if(_.isEmpty(preferences)) {
                    return {
                        fontSize: 14,
                        tabSize: 4,
                        keyboardHandler: 'ace',
                        theme: 'terminal'
                    }
                } else {
                    return preferences
                }
            })
}

export default class App extends Component {
    constructor(props) {
        super(props)

        this.handleCodeChange = this.handleCodeChange.bind(this)
        this.handlePlaygroundCodeChange = this.handlePlaygroundCodeChange.bind(this)
        this.compile = _.debounce(this.compile.bind(this), 1000)

        this.handleLanguageChange = this.handleLanguageChange.bind(this)
        this.handleEditorThemeChange = this.handleEditorThemeChange.bind(this)
        this.handleFontSizeChange = this.handleFontSizeChange.bind(this)
        this.handleTabSizeChange = this.handleTabSizeChange.bind(this)
        this.handleAutoCompileFlagChange = this.handleAutoCompileFlagChange.bind(this)
        this.handleFileOpenClick = _.debounce(this.handleFileOpenClick.bind(this), 500)
        this.handleFileSaveClick = _.debounce(this.handleFileSaveClick.bind(this), 500)
        this.handleNewFileClick = _.debounce(this.handleNewFileClick.bind(this), 500)
        this.handleSavePlaygroundClick = _.debounce(this.handleSavePlaygroundClick.bind(this), 500)
        this.toggleCodePanelVisibility = this.toggleCodePanelVisibility.bind(this)
        this.togglePlaygroundPanelVisibility = this.togglePlaygroundPanelVisibility.bind(this)
        this.toggleOutputPanelVisibility = this.toggleOutputPanelVisibility.bind(this)
        this.loadFileFromHistory = this.loadFileFromHistory.bind(this)
        this.handleWindowResize = _.debounce(this.handleWindowResize.bind(this), 300)
        this.loadPlaygroundFile = this.loadPlaygroundFile.bind(this)
        this.openPlaygroundFile = this.openPlaygroundFile.bind(this)
        this.handleGenerateTestClick = this.handleGenerateTestClick.bind(this)
        this.handleSettingsClose = this.handleSettingsClose.bind(this)
        this.handleKeyboardHandlerChange = this.handleKeyboardHandlerChange.bind(this)
        this.savePreferences = this.savePreferences.bind(this)

        this.state = {
            code: 'add x y = x + y',
            playgroundCode: 'add 2 3',
            output: '',
            compiling: false,
            language: 'elm',
            autoCompile: true,
            openFilePath: null,
            showCodePanel: true,
            showPlaygroundPanel: true,
            showOutputPanel: true,
            editorTheme: 'terminal',
            autoCompile: true,
            editorHeight: 1000,
            fontSize: 14,
            tabSize: 4,
            keyboardHandler: 'ace',
            showSettings: false
        }
    }

    componentWillMount() {
        ipcRenderer.on('menuActions', (event, message) => {
            if(!message || !message.action) {
                return
            }

            switch(message.action) {
                case 'newFile':
                    this.handleNewFileClick()
                    break;
                case 'openFile':
                    this.handleFileOpenClick()
                    break;
                case 'openPlaygroundFile':
                    this.openPlaygroundFile()
                    break;
                case 'saveFile':
                    this.handleFileSaveClick()
                    break;
                case 'savePlaygroundFile':
                    this.handleSavePlaygroundClick()
                    break;
                case 'generateTests':
                    this.handleGenerateTestClick()
                    break;
                case 'showPreferences':
                    this.handleShowPreferences()
                    break;
                default:
                    console.log('don\'t understand the menu action', message.action)
            }
        })

        getSavedPreferences().then(preferences => this.setState({...preferences}))
    }

    componentDidMount() {
        window.onresize = this.handleWindowResize
        this.handleWindowResize()

        if(this.state.autoCompile) {
            this.compile()
        }
    }

    componentWillUnmount() {
        this.storeFilePathInDb()

        Object.keys(compilers).map((compilerKey) => {
            compilers[compilerKey].cleanUp()
        })
    }

    handleWindowResize() {
        this.setState({
            editorHeight: this.mainWindow.clientHeight
        })
    }

    loadFileFromHistory() {
        getFromStorage('fileData')
                .then((file) => {
                    if(file.filePath) {
                        readFile(file.filePath)
                            .then((content) => this.setState({code: content.toString()}))
                    }
                })
    }

    storeFilePathInDb() {
        return setToStorage('fileData', {filePath: this.state.openFilePath})
                .then(() => console.log('file path stored ', this.state.openFilePath))
                .catch((err) => {
                    console.log('error setting filePath', err)
                })
    }

    compile() {
        this.setState({
            compiling: true,
        }, () => {
            compilers[this.state.language]
                .compile(this.state.code, this.state.playgroundCode, this.state.openFilePath)
                .then((output) => this.setState({output, compiling: false}))
                .catch((output) => this.setState({output, compiling: false}))
        })
    }

    handleCodeChange(newCode) {
        this.setState({
            code: newCode,
            fileSaved: false
        }, () => {
            if(this.state.autoCompile) {
                this.compile()
            }
        })
    }

    handlePlaygroundCodeChange(newCode) {
        this.setState({
            playgroundCode: newCode
        }, () => {
            if(this.state.autoCompile) {
                this.compile()
            }
        })
    }

    handleLanguageChange(e) {
        compilers[this.state.language].cleanUp()
        this.setState({language: e.target.value})
    }

    handleNewFileClick() {
        this.setState({
            openFilePath: null,
            playgroundFilePath: null,
            fileSaved: false,
            code: '',
            playgroundCode: ''
        })
    }

    handleFileSaveClick() {
        return saveFile(this.state.code, this.state.openFilePath, ['elm'])
                .then((filePath) => {
                    compilers[this.state.language]
                        .formatCode(this.state.code)
                        .then((formattedCode) => {
                            this.setState({
                                code: formattedCode,
                                openFilePath: filePath,
                                fileSaved: true
                            })
                        })
                })
                .catch((err) => console.log('error saving file ', err.message))
    }

    handleGenerateTestClick() {
        if(compilers[this.state.language].generateTests) {
            compilers[this.state.language].generateTests(this.state.code, this.state.playgroundCode, this.state.openFilePath)
                .then((tests) => console.log('generated tests', tests))
        } else {
            alert('This compiler, ' + this.state.language + ', does not support test generation')
        }
    }

    handleSettingsClose() {
        this.setState({showSettings: false})
    }

    handleShowPreferences() {
        this.setState({showSettings: true})
    }

    openPlaygroundFile() {
        openFile(['frolic'])
            .then(({filePath, content}) => {
                this.setState({
                    playgroundCode: content.toString(),
                    playgroundFilePath: filePath,
                }, () => {
                    if(this.state.autoCompile) {
                        this.compile()
                    }
                })
            })
            .catch((err) => console.log('error opening playground file', err.message))
    }

    loadPlaygroundFile(codeFile, playgroundFilePath) {
        return fileAccess(getPlaygroundFilePath(codeFile.filePath, playgroundFilePath))
                .then((content) => {
                    return readFile(getPlaygroundFilePath(codeFile.filePath, playgroundFilePath))
                            .then((content) => {
                                return {
                                    codeFile,
                                    playgroundFile: {content: content.toString(), filePath: getPlaygroundFilePath(codeFile.filePath, playgroundFilePath)},
                                }
                            })
                })
                .catch((err) => {
                    console.log('error reading playground file', err.message)
                    return {codeFile, playgroundFile: {content: '', filePath: null}}
                })
    }

    handleSavePlaygroundClick() {
        saveFile(
            this.state.playgroundCode,
            getPlaygroundFilePath(this.state.openFilePath, this.state.playgroundFilePath),
            ['frolic'],
            'Save Playground')
            .then((filePath) => {
                console.log('playground code saved to', filePath)
            })
            .catch((err) => console.log('error saving file ', err.message))
    }

    handleFileOpenClick() {
        openFile(['elm'])
            .then((codeFile) => this.loadPlaygroundFile(codeFile, null))
            .then(({codeFile, playgroundFile}) => {
                this.setState({
                    openFilePath: codeFile.filePath,
                    code: codeFile.content,
                    playgroundCode: playgroundFile.content,
                    playgroundFilePath: playgroundFile.filePath,
                    fileSaved: true
                }, () => {
                    this.storeFilePathInDb()
                    compilers[this.state.language].onNewFileLoad(this.state.openFilePath)
                    if(this.state.autoCompile) {
                        this.compile()
                    }
                })
            })
            .catch((err) => {
                console.log('error opening file ', err.toString())
            })
    }

    handleAutoCompileFlagChange(e) {
        this.setState({autoCompile: e.target.checked})
    }

    savePreferences() {
        savePreferences(_.pick(this.state, ['fontSize', 'tabSize', 'editorTheme', 'keyboardHandler']))
    }

    handleEditorThemeChange(e) {
        this.setState({editorTheme: e.target.value}, this.savePreferences)
    }

    handleFontSizeChange(e) {
        this.setState({fontSize: parseInt(e.target.value)}, this.savePreferences)
    }

    handleTabSizeChange(e) {
        this.setState({tabSize: parseInt(e.target.value)}, this.savePreferences)
    }

    handleKeyboardHandlerChange(e) {
        this.setState({keyboardHandler: e.target.value}, this.savePreferencesg)
    }

    toggleCodePanelVisibility(showCodePanel) {
        this.setState({showCodePanel})
    }

    togglePlaygroundPanelVisibility(showPlaygroundPanel) {
        this.setState({showPlaygroundPanel})
    }

    toggleOutputPanelVisibility(showOutputPanel) {
        this.setState({showOutputPanel})
    }

    render() {
        return (
            <div className={styles['root-container']}>
                <Toolbar
                    editorTheme={this.state.editorTheme}
                    onEditorThemeChange={this.handleEditorThemeChange}
                    fontSize={this.state.fontSize}
                    onFontSizeChange={this.handleFontSizeChange}
                    language={this.state.language}
                    onLanguageChange={this.handleLanguageChange}
                    onCompileClick={this.compile}
                    onOpenClick={this.handleFileOpenClick}
                    onSaveClick={this.handleFileSaveClick}
                    onNewFileClick={this.handleNewFileClick}
                    fileSaved={this.state.fileSaved}
                    autoCompile={this.state.autoCompile}
                    onAutoCompileFlagChange={this.handleAutoCompileFlagChange}
                    onCodePanelVisibilityChange={this.toggleCodePanelVisibility}
                    onPlaygroundPanelVisibilityChange={this.togglePlaygroundPanelVisibility}
                    onOutputPanelVisibilityChange={this.toggleOutputPanelVisibility}
                    showCodePanel={this.state.showCodePanel}
                    showPlaygroundPanel={this.state.showPlaygroundPanel}
                    showOutputPanel={this.state.showOutputPanel}
                    ref={(node) => {
                        if(node && !this.toolbarDiv) {
                            this.toolbarDiv = ReactDOM.findDOMNode(node)
                        }
                    }}
                />
                <MainWindow
                    ref={(node) => {
                        if(node) {
                            this.mainWindow = ReactDOM.findDOMNode(node)
                        }
                    }}
                    fontSize={this.state.fontSize}
                    tabSize={this.state.tabSize}
                    keyboardHandler={this.state.keyboardHandler}
                    code={this.state.code}
                    playgroundCode={this.state.playgroundCode}
                    output={this.state.output}
                    compiling={this.state.compiling}
                    onCodeChange={this.handleCodeChange}
                    onPlaygroundCodeChange={this.handlePlaygroundCodeChange}
                    onSavePlaygroundClick={this.handleSavePlaygroundClick}
                    editorMode={compilers[this.state.language].editorMode}
                    showCodePanel={this.state.showCodePanel}
                    showPlaygroundPanel={this.state.showPlaygroundPanel}
                    showOutputPanel={this.state.showOutputPanel}
                    editorHeight={this.state.editorHeight}
                    editorTheme={this.state.editorTheme}
                    playgroundFilePath={getPlaygroundFilePath(this.state.openFilePath, this.state.playgroundFilePath)}
                    />
                <Footer
                    fileSaved={this.state.fileSaved}
                    openFilePath={this.state.openFilePath}
                    ref={(node) => {
                        if(node && !this.footerDiv) {
                            this.footerDiv = ReactDOM.findDOMNode(node)
                        }
                    }}
                    />
                {this.state.showSettings
                    ?
                    <Settings
                        onClose={this.handleSettingsClose}
                        editorTheme={this.state.editorTheme}
                        onEditorThemeChange={this.handleEditorThemeChange}
                        fontSize={this.state.fontSize}
                        onFontSizeChange={this.handleFontSizeChange}
                        tabSize={this.state.tabSize}
                        onTabSizeChange={this.handleTabSizeChange}
                        keyboardHandler={this.state.keyboardHandler}
                        onKeyboardHandlerChange={this.handleKeyboardHandlerChange}
                        />
                    : null}
            </div>
        )
    }
}
<|endoftext|>


<commit_before><commit_msg>some new text<commit_after><|endoftext|>


<commit_before>import { createStore } from 'redux'
import { geolocalize } from '../reducers/reducers.js'

let store = createStore(geolocalize)

<commit_msg>change name to reducer imported<commit_after>import { createStore } from 'redux'
import { katangapp } from '../reducers/reducers.js'

export store = createStore(katangapp)

<|endoftext|>