import {List} from 'immutable';
import {CompiledProject} from '../records';

const initialState = new List();

function trimRight(list, maxLength) {
  if (list.size <= maxLength) {
    return list;
  }

  return list.splice(0, list.size - maxLength);
}

export default function compiledProjects(stateIn, action) {
  let state = stateIn;
  if (state === undefined) {
    state = initialState;
  }

  switch (action.type) {
    case 'PROJECT_COMPILED':
      return trimRight(
        state.push(new CompiledProject({
          source: action.payload.source,
          title: action.payload.title,
          timestamp: action.meta.timestamp,
        })),
        2,
      );

    case 'USER_DONE_TYPING':
      return trimRight(state, 1);

    case 'VALIDATED_SOURCE':
      if (action.payload.errors.length) {
        return initialState;
      }
      return state;
  }

  return state;
}

import {List} from 'immutable';
import {CompiledProject} from '../records';

const initialState = new List();

function trimRight(list, maxLength) {
  if (list.size <= maxLength) {
    return list;
  }

  return list.splice(0, list.size - maxLength);
}

export default function compiledProjects(stateIn, action) {
  let state = stateIn;
  if (state === undefined) {
    state = initialState;
  }

  switch (action.type) {
    case 'PROJECT_CREATED':
      return initialState;

    case 'CHANGE_CURRENT_PROJECT':
      return initialState;

    case 'PROJECT_COMPILED':
      return trimRight(
        state.push(new CompiledProject({
          source: action.payload.source,
          title: action.payload.title,
          timestamp: action.meta.timestamp,
        })),
        2,
      );

    case 'USER_DONE_TYPING':
      return trimRight(state, 1);

    case 'VALIDATED_SOURCE':
      if (action.payload.errors.length) {
        return initialState;
      }
      return state;
  }

  return state;
}

Clear compiled projects when a project is created or switched to
Clear compiled projects when a project is created or switched to

If you create a new project, or start the process of switching to an
existing project, we want to clear the preview state. Otherwise:

* When you create a new project, the old project sticks around
* When switching projects, the preview is unpleasantly flashy between
  old and new state
