import * as types from 'app/types' import { store } from 'app/store' import actions from 'app/actions' import { default as debounce } from 'lodash.debounce' import { post } from 'app/utils' const url = { sortTiles: (id) => '/api/v1/page/' + id + '/sort', } // Add tile form export const showAddTileForm = () => dispatch => { dispatch({ type: types.page.show_add_tile_form }) } export const hideAddTileForm = () => dispatch => { dispatch({ type: types.page.hide_add_tile_form }) } export const toggleAddTileForm = () => dispatch => { dispatch({ type: types.page.toggle_add_tile_form }) } // Edit tile form export const showEditTileForm = tile_id => dispatch => { dispatch({ type: types.page.show_edit_tile_form, tile_id }) } export const hideEditTileForm = () => dispatch => { dispatch({ type: types.page.hide_edit_tile_form }) } export const toggleEditTileForm = () => dispatch => { dispatch({ type: types.page.toggle_edit_tile_form }) } // Tile list export const showTileList = () => dispatch => { dispatch({ type: types.page.show_tile_list }) } export const hideTileList = () => dispatch => { dispatch({ type: types.page.hide_tile_list }) } export const toggleTileList = () => dispatch => { dispatch({ type: types.page.toggle_tile_list }) } // Update local page tile state when we change it export const updatePageTile = tile => dispatch => { dispatch({ type: types.page.update_page_tile, tile }) } // Fetch graph/page when loading a new URL export const showGraphAndPageIfUnloaded = ({ graph_name, page_name }) => dispatch => ( new Promise((resolve, reject) => { showGraphIfUnloaded({ graph_name })(dispatch) .then(graph => ( actions.page.show('name/' + graph_name + '/' + page_name) .then(resolve) .catch(reject) )) .catch(reject) }) ) export const showGraphIfUnloaded = ({ graph_name }) => dispatch => ( new Promise((resolve, reject) => { const { res: graph } = store.getState().graph.show if (graph && graph.path === graph_name) { return resolve(graph) } actions.graph.show('name/' + graph_name) .then(resolve) .catch(reject) }) ) // Sorting tiles in the tile list export const setTileSortOrder = (tiles) => dispatch => { let oldTiles = store.getState().page.show.res.tiles if (!isSameTileOrder(tiles, oldTiles)) { updateTileSortOrder(tiles, dispatch) } dispatch({ type: types.page.set_tile_sort_order, tiles }) } export const isSameTileOrder = (newTiles, oldTiles) => { for (let i = 0; i < newTiles.length; i++) { if (newTiles[i].id !== oldTiles[i].id) { return false } } return true } export const updateTileSortOrder = debounce((tiles, dispatch) => { const { page_id } = tiles[0] const order = tiles.map(tile => (tile.id)) console.log(page_id, order) post(dispatch, types.page, 'sort', url.sortTiles(page_id), order) }, 1000)