lodash#remove JavaScript Examples

The following examples show how to use lodash#remove. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultiFilter.js    From haven with MIT License 6 votes vote down vote up
onChange(val, idx, isExclusive) {
    const { selected, options } = this.props;
    const exclusiveIdx = findIndex(options, val => get(val, 'exclusive', false));
    const exclusiveVal = get(options, `[${exclusiveIdx}].value`, 'exclusive_value');
    if (idx === -1) {
      if (isExclusive) {
        selected.length = 0;
        selected.push(val);
      } else {
        selected.push(val);
        remove(selected, o => o === exclusiveVal);
      }
    } else {
      remove(selected, o => o === val);
    }
    this.props.onChange(selected);
  }
Example #2
Source File: addShippingMethod.js    From haven with MIT License 6 votes vote down vote up
constructor(props) {
    super(props);
    const { shippingOptions } = this.props;
    if (hasIn(props.navigation.state.params, 'idx')) {
      const idx = props.navigation.getParam('idx');
      const selectableCountry = [{ label: '? Worldwide', value: 'ALL' }, ...countryList];
      shippingOptions.forEach((val, i) => {
        if (idx !== i) {
          val.regions.forEach((region) => { remove(selectableCountry, o => o.value === region.value); });
        }
      });
      this.state = {
        name: shippingOptions[idx].name,
        type: shippingOptions[idx].type,
        selectableCountry,
        regions: [...shippingOptions[idx].regions],
        services: [...shippingOptions[idx].services],
      };
    } else {
      const selectableCountry = [{ label: '? Worldwide', value: 'ALL' }, ...countryList];
      shippingOptions.forEach((val) => {
        val.regions.forEach((region) => { remove(selectableCountry, o => o.value === region.value); });
      });
      this.state = {
        name: '',
        type: 'FIXED_PRICE',
        selectableCountry,
        regions: [],
        services: [],
      };
    }
  }
Example #3
Source File: TableBlockEdit.jsx    From volto-slate with MIT License 6 votes vote down vote up
/**
   * Delete column handler. Changes the selected cell if the last table column
   * is selected.
   * @returns {undefined}
   */
  onDeleteCol() {
    const table = this.props.data.table;

    if (this.state.selected.cell === table.rows[0].cells.length - 1) {
      this.setState({
        selected: {
          row: this.state.selected.row,
          cell: this.state.selected.cell - 1,
        },
      });
    }

    this.props.onChangeBlock(this.props.block, {
      ...this.props.data,
      table: {
        ...table,
        rows: map(table.rows, (row) => ({
          ...row,
          cells: remove(
            row.cells,
            (cell, index) => index !== this.state.selected.cell,
          ),
        })),
      },
    });
  }
Example #4
Source File: TableBlockEdit.jsx    From volto-slate with MIT License 6 votes vote down vote up
/**
   * Delete row handler. Changes the selected cell if the last table row is
   * selected.
   * @method onDeleteRow
   * @returns {undefined}
   */
  onDeleteRow() {
    const table = this.props.data.table;

    if (this.state.selected.row === table.rows.length - 1) {
      this.setState({
        selected: {
          row: this.state.selected.row - 1,
          cell: this.state.selected.cell,
        },
      });
    }

    this.props.onChangeBlock(this.props.block, {
      ...this.props.data,
      table: {
        ...table,
        rows: remove(
          table.rows,
          (row, index) => index !== this.state.selected.row,
        ),
      },
    });
  }
Example #5
Source File: UploadButton.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
@Bind()
  onRemove(file) {
    const { onRemove, bucketName, onRemoveSuccess, single = false, tenantId } = this.props;
    const { fileList } = this.state;
    if (file.url) {
      if (onRemove) {
        return onRemove(file);
      }
      const splitDatas = (file.url && file.url.split('=')) || [];
      const fileUrl = splitDatas[splitDatas.length - 1];
      return removeUploadFile({
        tenantId,
        bucketName,
        urls: [fileUrl],
      }).then((res) => {
        if (getResponse(res)) {
          if (onRemoveSuccess) {
            onRemoveSuccess();
          }

          if (single) {
            this.setState({
              fileList: [],
            });
          } else {
            remove(fileList, (n) => n.uid === file.uid);
            this.setState({
              fileList,
            });
          }
          return true;
        }
        return false;
      });
    }
    this.setState({
      fileList: fileList.filter((list) => list.uid !== file.uid),
    });
  }
Example #6
Source File: index.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
@Bind()
  onCheckboxChange(params) {
    const { receiveCode, type, flag } = params;
    const { checkedList } = this.state;
    const index = findIndex(checkedList, (v) => v.receiveCode === receiveCode);
    const checkItem = checkedList[index];

    const addOrRemove = (item) => {
      // flag为true,代表当前已经被勾选,需要去除勾选
      if (flag) {
        remove(item && item.receiveTypeList, (v) => v === type);
      } else if (
        indexOf(item && item.receiveTypeList, type) < 0 &&
        indexOf(item.defaultReceiveTypeList, type) > -1
      ) {
        (item.receiveTypeList || []).push(type);
      }
    };
    addOrRemove(checkItem);

    /**
     * 根据父节点,选择所有的子节点
     *
     * @param {*} parentId
     */
    const iterator = (parentId) => {
      const subList = [];
      forEach(checkedList, (v) => {
        if (v.parentId === parentId) {
          addOrRemove(v);
          subList.push(v);
        }
      });
      if (subList && subList.length > 0) {
        forEach(subList, (v) => iterator(v.receiveCode));
      }
    };
    iterator(checkItem.receiveCode);

    /**
     * 反向勾选,即根据子节点反向勾选父节点
     *
     * @param {*} parentId 父节点的receiveCode
     */
    const reverseCheck = (parentId) => {
      if (!parentId) {
        return;
      }
      const sameParents = checkedList.filter((v) => v.parentId === parentId) || [];
      const temp = sameParents.filter((v) => {
        if (indexOf(v.defaultReceiveTypeList, type) < 0) {
          return true;
        }
        const idx = indexOf(v && v.receiveTypeList, type);
        return flag ? idx < 0 : idx > -1;
      });
      if (sameParents.length === temp.length || (sameParents.length !== temp.length && flag)) {
        const parentIndex = findIndex(checkedList, (v) => v.receiveCode === parentId);
        const parent = checkedList[parentIndex];
        addOrRemove(parent);

        reverseCheck(parent.parentId);
      }
    };

    reverseCheck(checkItem.parentId);

    this.setState({ checkedList });
  }
Example #7
Source File: Inventory.js    From CyberStateRP with MIT License 4 votes vote down vote up
Inventory = props => {
    const itemMenus = popupSettings()

    const updateDraggedItem = item => {
        setInv(prevState => { // eslint-disable-line no-use-before-define
            return {
                ...prevState,
                draggedItem: item,
            }
        })
    }
    const updateInventory = inventory => {
        // сохранение clientStorage.inventoryItems
        setInv(prevState => { // eslint-disable-line no-use-before-define
            return {
                ...prevState,
                personInventory: inventory,
            }
        })
    }
    const updateVehicleInventory = inventory => {
        // сохранение clientStorage.inventoryItems
        //console.log(`inventory: ${JSON.stringify(inventory)}`)
        setInv(prevState => { // eslint-disable-line no-use-before-define
            return {
                ...prevState,
                vehicleInventory: inventory,
            }
        })
    }
    const updateHoverIndexes = indx => {
        // сохранение clientStorage.inventoryItems
        setInv(prevState => { // eslint-disable-line no-use-before-define
            return {
                ...prevState,
                hoverIndexes: indx,
            }
        })
    }
    const updateVehicleInventorySettings = settings => {
        // сохранение clientStorage.inventoryItems
        setInv(prevState => { // eslint-disable-line no-use-before-define
            return {
                ...prevState,
                vehicleInventorySettings: settings,
            }
        })
    }
    const updateItemPos = (sqlId, parentId, index, inVehicle) => {
        alt.emit(
            'events.emitServer',
            'item.updatePos',
            JSON.stringify([sqlId, parentId, index, inVehicle])
        )
    }
    const mergeItems = (sqlId, targetSqlId) => {
        alt.emit(
            'events.emitServer',
            'items.merge',
            JSON.stringify([sqlId, targetSqlId])
        )
    }
    const updatePersonItems = personItems => {
        // сохранение clientStorage.inventoryItems
        setInv(prevState => { // eslint-disable-line no-use-before-define
            return {
                ...prevState,
                personItems,
            }
        })
    }
    const findItemBySqlId = sqlId => {
        const aItem = find(inv.personInventory, { sqlId }) // eslint-disable-line
        if (aItem) return aItem
        for (let i = 0; i < inv.personInventory.length; i++) { // eslint-disable-line
            const bItem = find(inv.personInventory[i].items, { sqlId }) // eslint-disable-line
            if (bItem) return bItem
        }
    }
    const findVehItemBySqlId = (vehInv, sqlId) => {
        const aItem = find(
            vehInv, // eslint-disable-line
            item => item.sqlId === sqlId
        )
        if (aItem) return aItem
        return null
    }
    const showModal = (modalVisible, item, bounds) => {
        setInv(prevState => { // eslint-disable-line no-use-before-define
            return {
                ...prevState,
                modal: {
                    active: modalVisible,
                    top: bounds.top - 25,
                    left: bounds.right + 5,
                    desc: getItemName(item.sqlId), // eslint-disable-line no-use-before-define
                },
            }
        })
    }
    const hideItemMenu = () => {
        setInv(prevState => { // eslint-disable-line no-use-before-define
            return {
                ...prevState,
                itemMenu: {
                    active: false,
                },
            }
        })
    }
    const hideModal = () => {
        setInv(prevState => { // eslint-disable-line no-use-before-define
            return {
                ...prevState,
                modal: {
                    active: false,
                },
            }
        })
    }
    const hideModals = () => {
        setInv(prevState => { // eslint-disable-line no-use-before-define
            return {
                ...prevState,
                modal: {
                    active: false,
                },
                itemMenu: {
                    active: false,
                },
            }
        })
    }
    const showItemMenu = (modalVisible, item, bounds) => {
        setInv(prevState => { // eslint-disable-line no-use-before-define
            //console.log(bounds)
            return {
                ...prevState,
                itemMenu: {
                    active: modalVisible,
                    top: bounds.bottom + 5,
                    left: bounds.right + 5,
                    sqlId: item.sqlId,
                    menu: itemMenus[item.itemId],
                },
            }
        })
    }

    const inventoryData = {
        personInventory: [],
        vehicleInventory: [],
        draggedItem: {},
        forbiddenItems: {
            7: [3, 7, 8, 9, 13],
            8: [3, 7, 8, 9, 13],
            13: [13],
        },
        modal: {
            active: false,
            top: 0,
            left: 0,
            desc: '',
        },
        itemMenu: {
            active: false,
            top: 0,
            left: 0,
            desc: '',
        },
        vehicleInventorySettings: {
            width: 5,
            height: 10,
            sqlId: -1,
            name: '',
        },
        personItems: {
            money: 0,
            bankMoney: 0,
            health: 0,
            satiety: 0,
            thirst: 0,
            armor: 0,
        },
        weaponAmmo: {
            20: 37, // 9mm
            21: 38, // 12mm
            22: 40, // 5.56mm
            23: 39, // 7.62mm
            44: 37,
            45: 37,
            46: 37,
            47: 37,
            48: 37,
            49: 38,
            50: 39,
            51: 40,
            52: 39,
            53: 39,
            100: 39,
        },
        drugsIds: [55, 56, 57, 58],
        hoverIndexes: {},
        updateDraggedItem,
        updateInventory,
        updateVehicleInventory,
        updateHoverIndexes,
        updatePersonItems,
        updateItemPos,
        updateVehicleInventorySettings,
        showModal,
        showItemMenu,
        hideItemMenu,
        hideModal,
        findVehItemBySqlId,
        findItemBySqlId,
        mergeItems,
    }
    // set extra fields
    const [inv, setInv] = useState(inventoryData)
    const [active, setActive] = useState(false)
    // settings defaults

    useEffect(() => {
        initEvents()
    }, [])
    // findItem
    const findArrayItemByItemId = itemIds => {
        const array = {}
        for (let i = 0; i < itemIds.length; i++) {
            find(inv.personInventory, item => item.itemId === itemIds[i])
        }
        return array
    }
    const updateItemInInv = (sqlId, params, inventory) => {
        const immInv = inventory
        const item = find(immInv, { sqlId })
        if (item) {
            const newItem = { ...item, params }
            remove(
                immInv,
                aItem => aItem.sqlId === sqlId
            )
            immInv.push(newItem)
        } else {
            for (let i = 0; i < immInv.length; i++) {
                if (Object.prototype.hasOwnProperty.call(immInv[i], 'items')) {
                    const parentItem = immInv[i]
                    const finalItem = find(parentItem.items, { sqlId })
                    if (finalItem) {
                        const newItem = { ...finalItem, params }
                        remove(
                            parentItem.items,
                            aItem => aItem.sqlId === sqlId
                        )
                        parentItem.items.push(newItem)
                        const parentIndex = findIndex(
                            immInv,
                            singleItem => singleItem.sqlId === parentItem.sqlId
                        )
                        immInv.splice(parentIndex, 1, parentItem)
                    }
                }
            }
        }
        return immInv
    }

    const invItemNames = {
        3: item => { // armour
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            let { name } = info
            if (item.params.faction) name += ` ${getNameByFactionId(item.params.faction)}`
            return `${name} [${item.params.armour}%]`
        },
        5: item => { // VISA
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} ${item.params.count}$`
        },
        6: item => { // hat
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            if (item.params.faction) return `${info.name} ${getNameByFactionId(item.params.faction)}`
            return info.name
        },
        7: item => { // top
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            if (item.params.faction) return `${info.name} ${getNameByFactionId(item.params.faction)}`
            return info.name
        },
        8: item => { // legs
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            if (item.params.faction) return `${info.name} ${getNameByFactionId(item.params.faction)}`
            return info.name
        },
        9: item => { // feets
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            if (item.params.faction) return `${info.name} ${getNameByFactionId(item.params.faction)}`
            return info.name
        },
        24: item => { // аптечка
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.count} ед.]`
        },
        25: item => { // пластырь
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.count} ед.]`
        },
        29: item => { // удостоверение PD
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name}${item.params.owner}`
        },
        34: item => { // пачка сигарет
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.count} шт.]`
        },
        36: item => { // канистра
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.count}/${item.params.maxCount} л.]`
        },
        37: item => { // патроны
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.ammo} шт.]`
        },
        38: item => { // патроны
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.ammo} шт.]`
        },
        39: item => { // патроны
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.ammo} шт.]`
        },
        40: item => { // патроны
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.ammo} шт.]`
        },
        54: item => { // ключи авто
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} ${item.params.model}`
        },
        55: item => { // нарко
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.count} г.]`
        },
        56: item => { // нарко
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.count} г.]`
        },
        57: item => { // нарко
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.count} г.]`
        },
        58: item => { // нарко
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name} [${item.params.count} г.]`
        },
        59: item => { // ключи дома
            const info = window.clientStorage.inventoryItems[item.itemId - 1]
            return `${info.name}${item.params.house}`
        },
    }
    const getItemName = sqlId => {
        let item = findItemBySqlId(sqlId)
        if (!item) item = window.inventoryAPI.getVehItem(sqlId);
        if (!item) return 'Неизвестный'
        if (!invItemNames[item.itemId]) return window.clientStorage.inventoryItems[item.itemId - 1].name
        return invItemNames[item.itemId](item)
    }

    const handleUserKeyPress = useCallback(event => {
        const { keyCode } = event
        if (keyCode === 73) {
            window.inventoryAPI.show(!window.inventoryAPI.active())
        }
    }, [])

    window.inventoryAPI = {
        active: () => {
            return active
        },
        add: (_sqlId, _item) => {
            const item = _item
            const { personInventory } = inv
            const fullInv = personInventory
            // console.log(`isPersonItem item: ${JSON.stringify(item)}`)
            if (isPersonItem(item)) {
                const newItem = {
                    ...item,
                    gridX: 0,
                    gridY: 0,
                    width: window.clientStorage.inventoryItems[item.itemId - 1].width,
                    height: window.clientStorage.inventoryItems[item.itemId - 1].height,
                    parentId: -1,
                }
                if (isContainerItem(item)) {
                    newItem.items = []
                    // console.log(`Container item: ${JSON.stringify(item)}`)
                    Object.keys(item.items).forEach(key => {
                        const { gridX, gridY } = indexToXY(
                            window.clientStorage.inventoryItems[item.itemId - 1].width,
                            window.clientStorage.inventoryItems[item.itemId - 1].height,
                            item.items[key].index
                        )
                        const subItem = {
                            ...item.items[key],
                            gridX,
                            gridY,
                            width: window.clientStorage.inventoryItems[item.items[key].itemId - 1].width,
                            height: window.clientStorage.inventoryItems[item.items[key].itemId - 1].height,
                        }
                        newItem.items.push(subItem)
                    })
                }
                // console.log(`newItem ${JSON.stringify(newItem)}`)
                fullInv.push(newItem)
            } else {
                // console.log(`item: ${JSON.stringify(item)}`)
                const parentItem = window.inventoryAPI.getItem(item.parentId)
                // console.log(`parentItem: ${JSON.stringify(parentItem)}`)
                const { gridX, gridY } = indexToXY(
                    window.clientStorage.inventoryItems[parentItem.itemId - 1].width,
                    window.clientStorage.inventoryItems[parentItem.itemId - 1].height,
                    item.index
                )
                const newItem = {
                    ...item,
                    gridX,
                    gridY,
                    width: window.clientStorage.inventoryItems[item.itemId - 1].width,
                    height: window.clientStorage.inventoryItems[item.itemId - 1].height,
                }
                if (isContainerItem(newItem)) {
                    newItem.items = []
                    Object.keys(item.items).forEach(key => {
                        const { aGridX, aGridY } = indexToXY(
                            window.clientStorage.inventoryItems[item.itemId - 1].width,
                            window.clientStorage.inventoryItems[item.items[key].itemId - 1].height,
                            item.items[key].index
                        )
                        const subItem = {
                            ...item.items[key],
                            aGridX,
                            aGridY,
                            width: window.clientStorage.inventoryItems[item.items[key].itemId - 1].width,
                            height: window.clientStorage.inventoryItems[item.items[key].itemId - 1].height,
                        }
                        newItem.items.push(subItem)
                    })
                }
                parentItem.items.push(newItem)
                const parentIndex = findIndex(
                    fullInv,
                    singleItem => singleItem.sqlId === parentItem.sqlId
                )
                fullInv.splice(parentIndex, 1, parentItem)
            }
            //console.log(JSON.stringify(inv.personInventory))
            updateInventory(fullInv)
        },
        updateData: (sqlId, newSqlId, parentSqlId) => {
            // могут быть баги
            //console.log(`${sqlId}, ${newSqlId}, ${parentSqlId}`)
            const newInv = updateItemInInv(
                sqlId,
                { parentId: parentSqlId, sqlId: newSqlId },
                inv.personInventory
            )
            updateInventory(newInv)

            //console.log(`1: ${JSON.stringify(newInv)}`)
        },
        updateDataVeh: (sqlId, newSqlId, parentSqlId) => {
            // могут быть баги
            //console.log(`${sqlId}, ${newSqlId}, ${parentSqlId}`)
            const vehInv = updateItemInInv(sqlId, { sqlId: newSqlId }, inv.vehicleInventory)
            updateVehicleInventory(vehInv)

            //console.log(`10: ${JSON.stringify(vehInv)}`)
        },
        addVehicleItems: (_items, _veh, rows, cols) => {
            const items = _items
            const veh = _veh

            //console.log(`VEHITEMS: ${JSON.stringify(_items)}`)

            const immVehInv = []
            updateVehicleInventorySettings(
                {
                    width: cols,
                    height: rows,
                    name: veh.name,
                    sqlId: veh.sqlId,
                }
            )
            updateVehicleInventory([])
            Object.keys(items).forEach(key => {
                const vehItem = items[key]
                const { gridX, gridY } = indexToXY(cols, rows, vehItem.index)
                const fullItem = { 
                    ...vehItem, 
                    gridX, 
                    gridY, 
                    width: window.clientStorage.inventoryItems[vehItem.itemId - 1].width,
                    height: window.clientStorage.inventoryItems[vehItem.itemId - 1].height, 
                    inVehicle: true 
                }
                
                immVehInv.push(fullItem)
            })
            updateVehicleInventory(immVehInv)

            //console.log(`2: ${JSON.stringify(immVehInv)}`)
        },
        delete: sqlId => {
            const invImm = inv.personInventory
            // console.log(`SQLID: ${sqlId}`)
            const item = findItemBySqlId(sqlId)
           // console.log(`ITEM: ${JSON.stringify(item)}`)
            if (item) {
                if (item.parentId === -1 || !item.parentId) {
                    //console.log(`ITEM: ${JSON.stringify(item)}`)
                    remove(invImm, aItem => aItem.sqlId === sqlId)
                } else {
                    const parentItem = findItemBySqlId(item.parentId)
                    //console.log(`PARENT: ${JSON.stringify(parentItem)}`)
                    remove(parentItem.items, aItem => aItem.sqlId === sqlId)
                    const parentIndex = findIndex(
                        invImm,
                        singleItem => singleItem.sqlId === parentItem.sqlId
                    )
                    invImm.splice(parentIndex, 1, parentItem)
                }

                updateInventory(invImm)
                // window.clientStorage.inventoryWeight = window.inventoryAPI.getCommonWeight()
                // выставить размер инвентаря
                // $('#inventory .weight').text(clientStorage.inventoryWeight.toFixed(1))
            }
        },
        deleteVehicleItems: () => {
            updateVehicleInventory([])
        },
        enable: enable => {
            if (enable) {
                window.addEventListener('keydown', handleUserKeyPress)
            } else {
                window.inventoryAPI.show(enable)
                window.removeEventListener('keydown', handleUserKeyPress)
            }
        },
        getItem: sqlId => {
            return findItemBySqlId(sqlId)
        },
        getArrayByItemId: _itemIds => {
            let itemIds = ''
            if (typeof _itemIds === 'string') itemIds = JSON.parse(_itemIds)
            if (!Array.isArray(itemIds)) itemIds = [itemIds]
            return findArrayItemByItemId(itemIds)
        },
        getVehItem: (sqlId) => {
            const aItem = find(
                inv.vehicleInventory, // eslint-disable-line
                item => item.sqlId === sqlId
            )
            if (aItem) return aItem
            return null
        },
        setHealth: _value => {
            const value = parseInt(_value, 10)
            updatePersonItems({ health: value })
        },
        setSatiety: _value => {
            const value = parseInt(_value, 10)
            updatePersonItems({ satiety: value })
        },
        setThirst: _value => {
            const value = parseInt(_value, 10)
            updatePersonItems({ thirst: value })
        },
        setArmour: _value => {
            const value = parseInt(_value, 10)
            const immInv = inv.personInventory
            const item = find(immInv, aItem => (aItem.itemId === 3 && aItem.parentId === -1))
            if (!item) {
                const newItem = { ...item, params: { armour: value } }
                remove(immInv, aItem => (aItem.itemId === 3 && aItem.parentId === -1))
                immInv.push(newItem)
            }
            updatePersonItems(immInv)
        },
        show: enable => {
            if (enable) {
                if (window.medicTablet.active()
                || window.pdTablet.active()
                || window.clientStorage.hasCuffs
                || window.telePhone.active()
                //|| window.armyTablet.active()
                // || window.sheriffTablet.active()
                //|| window.fibTablet.active()
                || window.playerMenu.active()
                || window.consoleAPI.active()
                || window.modalAPI.active()
                || window.playerMenu.active()
                || window.chatAPI.active()
                //|| window.tradeAPI.active()
                || window.documentsAPI.active()
                || window.houseMenu.__vue__.active()) return
                alt.emit('Cursor::show', true)
                alt.emit('setInventoryActive', true)
                alt.emit('setBlockControl', true)
                alt.emit('toBlur', 200)
                setActive(enable)
            } else {
                if (window.consoleAPI.active()) return
                alt.emit('setInventoryActive', false)
                alt.emit('Cursor::show', false)
                alt.emit('setBlockControl', false)
                hideItemMenu()
                hideModal()
                alt.emit('fromBlur', 200)
                setActive(enable)
            }
        },
        updateParams: (_sqlId, _params) => {
            const sqlId = parseInt(_sqlId, 10)
            const params = _params
            const newInv = updateItemInInv(sqlId, params, inv.personInventory)
            updateInventory(newInv)
        },
        updateParamsVeh: (_sqlId, _params) => {
            const sqlId = parseInt(_sqlId, 10)
            const params = JSON.parse(_params)
            const newInv = updateItemInInv(sqlId, { params }, inv.vehicleInventory)
            updateInventory(newInv)
        },
        vehAdd: (_sqlId, _item) => {
            // const sqlId = parseInt(_sqlId, 10)
            const item = _item
            const { vehicleInventory } = inv
            const fullInv = vehicleInventory
            let newItem = item
            newItem.inVehicle = true

            if (!item.parentId || item.parentId === -1) {
                delete item.parentId
            }
            const { gridX, gridY } = indexToXY(
                inv.vehicleInventorySettings.width,
                inv.vehicleInventorySettings.height,
                item.index
            )
            newItem = {
                ...newItem,
                gridX,
                gridY,
                width: window.clientStorage.inventoryItems[item.itemId - 1].width,
                height: window.clientStorage.inventoryItems[item.itemId - 1].height,
                inVehicle: true,
            }
            fullInv.push(newItem)
            updateVehicleInventory(fullInv)
            //console.log(`3: ${JSON.stringify(fullInv)}`)
        },
        vehDelete: sqlId => {
            const invImm = inv.vehicleInventory
            const item = findVehItemBySqlId(invImm, sqlId)
            if (item.parentId === -1 || !item.parentId) {
                remove(invImm, { sqlId })
            } else {
                const parentItem = findItemBySqlId(item.parentId)
                remove(parentItem.items, { sqlId })
                const parentIndex = findIndex(
                    invImm,
                    singleItem => singleItem.sqlId === parentItem.sqlId
                )
                invImm.splice(parentIndex, 1, parentItem)
            }
            // vehicle check weight
        },
    }
    return (
        active &&
        <DndProvider backend={MouseBackEnd}>
            <InventoryContext.Provider
                value={{ inv }}
            >
                <div id="invWrapper">
                    <ResponsiveStyler>
                        <div
                            id="playerInventory"
                            style={{ display: active ? 'grid' : 'none' }}
                            role="presentation"
                            onClick={hideModals}
                        >
                            { window.clientStorage.bootVehicleId !== -1
                                && <LeftInventory />
                            }
                            <PersonInventory />
                            <RightInventory />
                        </div>
                    </ResponsiveStyler>
                    <InventoryMenu />
                    <InventoryModal />
                    <InventoryDragModal />
                </div>
            </InventoryContext.Provider>
        </DndProvider>
    )
}
Example #8
Source File: Phone.js    From CyberStateRP with MIT License 4 votes vote down vote up
Phone = props => {
    const setActiveTab = (tab, sub = 0) => {
        setPhone(prevState => {
            return {
                ...prevState,
                activeTab: tab,
                subTab: sub,
            }
        })
    }
    const setInteracting = id => {
        setPhone(prevState => {
            return {
                ...prevState,
                interactingWith: id,
            }
        })
    }
    const setMessaging = (num) => {
        setPhone(prevState => {
            return {
                ...prevState,
                messagingWith: num,
            }
        })
    }
    const setVisibility = visible => {
        setPhone(prevState => {
            return {
                ...prevState,
                active: visible,
            }
        })
    }
    const fetchContact = num => {
        const _num = parseInt(num, 10)
        const contact = phone.contacts.find(c => c.num === _num)
        if (!contact) return _num
        return contact.name
    }
    const callId = num => {
        // позвонить кому-то
        setPhone(prevState => {
            return {
                ...prevState,
                activeTab: 3,
                talkingToPhone: false,
                callingNumber: num,
            }
        })
    }
    const receiveCall = num => {
        // новый входящий
        setPhone(prevState => {
            return {
                ...prevState,
                activeTab: 4,
                talkingToPhone: false,
                incomingCall: num,
            }
        })
    }
    const callAccepted = () => {
        // принят исходящий тем, кому звонишь
        setPhone(prevState => {
            return {
                ...prevState,
                talkingToPhone: true,
            }
        })
    }
    const acceptCall = () => {
        // ты принял входящий
        setPhone(prevState => {
            return {
                ...prevState,
                activeTab: 3,
                talkingToPhone: true,
                callingNumber: prevState.incomingCall,
            }
        })
    }
    const declineCall = () => {
        // отклонен входящий
        setPhone(prevState => {
            return {
                ...prevState,
                activeTab: 0,
                talkingToPhone: false,
                callingNumber: -1,
                incomingCall: -1,
            }
        })
    }
    const setNumber = num => {
        // отклонен входящий
        setPhone(prevState => {
            return {
                ...prevState,
                myNumber: num
            }
        })
    }
    const sendMessage = ({ id, text, sender_num, creator_num }) => {
        // отправить сообщение
        const newMessages = phone.messages
        const _id = parseInt(id, 10)
        const _creatorNum = parseInt(creator_num, 10)
        const _senderNum = parseInt(sender_num, 10)
        newMessages.push({ id: _id, text, sender_num: _senderNum, creator_num: _creatorNum })
        setPhone(prevState => {
            return {
                ...prevState,
                messages: newMessages,
            }
        })
    }
    const createContact = ({ id, name, num }) => {
        const newContacts = phone.contacts
        newContacts.push({ id, name, num })
        setPhone(prevState => {
            return {
                ...prevState,
                contacts: newContacts,
            }
        })
    }
    const editContact = ({ id, name, num }) => {
        // редактировать контакт
        const newContacts = phone.contacts
        const item = find(newContacts, c => c.id === id)
        if (item) {
            remove(newContacts, c => c.id === id)
            newContacts.push({ id, name, num })
             setPhone(prevState => {
                return {
                    ...prevState,
                    contacts: newContacts,
                }
            })
        }
    }
    const deleteContact = id => {
        // удалить контакт
        //console.log(id)
        const newContacts = phone.contacts
        const item = find(newContacts, c => c.id === id)
        if (item) {
             remove(newContacts, c => c.id === id)
             setPhone(prevState => {
                return {
                    ...prevState,
                    contacts: newContacts,
                }
            })
        }
    }
    const emitCallAccept = num => {
        alt.emit(`accept.telephone.call`, num)
    }
    const emitCallDecline = num => {
        alt.emit(`call.decline`, num)
    }
    const emitPhoneCallId = num => {
        alt.emit(`phone.callId`, num)
    }
    const emitSaveContact = values => {
        if (Object.prototype.hasOwnProperty.call(values, 'id')) {
            alt.emit(`selectChangeContact`, values.id, `${values.firstName} ${values.lazstName}`, values.num)
        } else {
            alt.emit(`select.add.contact`, `${values.firstName} ${values.lastName}`, values.num)
        }
    }
    const emitDeleteContact = id => {
        alt.emit(`deleteContact`, id)

        setInteracting(-1)
        setActiveTab(1, 1)
    }
    const emitSendMessage = (messagingWith, messageText) => {
        alt.emit(`sendMessage`, messagingWith, messageText)
    }
    const phoneState = {
        active: false,
        myNumber: 0,
        messages: [],
        contacts: [{id: 24224, name: "Полиция", num: 103}, {id: 24225, name: "Скорая помощь", num: 105}],
        lastCalls: [],
        currentMessages: [],
        activeTab: 0,
        subTab: 1,
        interactingWith: -1,
        messagingWith: -1,
        callingNumber: -1,
        incomingCall: -1,
        talkingToPhone: false,
        setActiveTab,
        setInteracting,
        setMessaging,
        createContact,
        editContact,
        fetchContact,
        deleteContact,
        setNumber,
        callId,
        sendMessage,
        acceptCall,
        callAccepted,
        declineCall,
        receiveCall,
        emitCallAccept,
        emitCallDecline,
        emitPhoneCallId,
        emitSaveContact,
        emitDeleteContact,
        emitSendMessage,
    }

    const [phone, setPhone] = useState(phoneState)

    useEffect(() => {
        initEvents()
    }, [])

    const keyPressHandler = useCallback(event => {
        const { keyCode } = event
        if (keyCode === 40) {
            alt.emit('telephone.active', false)
            window.telePhone.show(false)
        } else if (keyCode === 38) {
            if (window.medicTablet.active()
            || window.pdTablet.active()
            || window.clientStorage.hasCuffs
            || window.selectMenuAPI.active()
            // || window.armyTablet.active()
            // || window.sheriffTablet.active()
            // || window.fibTablet.active()
            || window.playerMenu.active()
            || window.consoleAPI.active()
            || window.modalAPI.active()
            || window.playerMenu.active()
            || window.chatAPI.active()
            // || window.tradeAPI.active()
            || window.documentsAPI.active()
            || window.houseMenu.__vue__.active()) return
            alt.emit('telephone.active', true)
            window.telePhone.show(true)
        }
    }, [])

    window.telePhone = {
        active: () => {
            return phone.active
        },
        show: visible => {
            setVisibility(visible)
        },
        enable: enable => {
            if (enable) {
                window.addEventListener('keydown', keyPressHandler)
            } else {
                window.telePhone.show(enable)
                window.removeEventListener('keydown', keyPressHandler)
            }
        },
        setNumber: num => {
            phone.setNumber(num);
        },
        createContact: data => {
            phone.createContact(data)
        },
        editContact: data => {
            phone.editContact(data)
        },
        deleteContact: id => {
            phone.deleteContact(id)
        },
        sendMessage: data => {
            phone.sendMessage(data)
        },
        call: num => {
            // исходящий
            phone.callId(num)
        },
        startedTalking: () => {
            // человек взял трубку
            phone.callAccepted()
        },
        acceptCall: () => {
            // входящий
            phone.acceptCall()
        },
        receiveCall: num => {
            phone.receiveCall(num);
        },
        finishCall: () => {
            // конец/отмена звонка
            phone.declineCall()
        },
    }
    return (
        <PhoneContext.Provider value={{ phone }}>
            <PhoneAnimate pose={phone.active ? 'visible' : 'hidden'}>
                <PhoneLayout>
                    { phone.activeTab === 0 && <HomeScreen /> }
                    { phone.activeTab === 1 && <ContactsApp />}
                    { phone.activeTab === 2 && <MessagesApp />}
                    { phone.activeTab === 3 && <Caller />}
                    { phone.activeTab === 4 && <IncomingCall />}
                </PhoneLayout>
            </PhoneAnimate>
        </PhoneContext.Provider>
    )
}
Example #9
Source File: index.js    From hzero-front with Apache License 2.0 4 votes vote down vote up
export default function VirtualTable(props) {
  const tableRef = useRef();
  const {
    columns,
    expandedRowKeys = [],
    onExpandChange = (e) => e,
    rowKey = 'id',
    data,
    isTree,
    height,
    minHeight = 100,
    childrenColumnName = 'children',
    rowSelection = {},
    shouldUpdateScroll = true,
    rowHeight = 36,
    autoInitHeight,
    parentClassName,
    isIndeterminate = false,
  } = props;
  const [trueDataSource, setTrueDataSource] = useState(data);
  const [expandKeys, setExpandKeys] = useState(expandedRowKeys);
  const [selectKeys, setSelectKeys] = useState(rowSelection.selectedRowKeys);
  const [selectRows, setSelectRows] = useState(rowSelection.selectedRowKeys);
  const [selectAllKeys, setSelectAllKeys] = useState([]);
  const [height2, setHeight] = useState(height);
  const [pathMap, setPathMap] = useState({});

  const mergedColumns = columns.map((column, index) => {
    if (index === 0 && isTree) {
      const tempColumn = cloneDeep(column);
      const tempRender = column.render;
      if (column.render) {
        tempColumn.render = (columnData) => {
          const { rowData: record, rowIndex } = columnData;
          return (
            <span
              style={{
                paddingLeft: record[childrenColumnName]
                  ? (record.INDENT_INDEX || 0) * 12 + 8
                  : (record.INDENT_INDEX || 0) * 12 + 34,
              }}
            >
              {/* eslint-disable-next-line no-nested-ternary */}
              {record[childrenColumnName] ? (
                expandKeys.includes(record[rowKey]) ? (
                  <Icon
                    type="indeterminate_check_box-o"
                    className={styles['expand-icon']}
                    onClick={() => {
                      handleExpand(false, record, rowIndex);
                    }}
                  />
                ) : (
                  <Icon
                    className={styles['expand-icon']}
                    type="add_box-o"
                    onClick={() => {
                      handleExpand(true, record, rowIndex);
                    }}
                  />
                )
              ) : null}
              <span />
              {tempRender(columnData)}
            </span>
          );
        };
      } else {
        tempColumn.render = ({ rowData: record, dataIndex, rowIndex }) => {
          const val = record[dataIndex];
          return (
            <span
              style={{
                paddingLeft: record[childrenColumnName]
                  ? (record.INDENT_INDEX || 0) * 12 + 8
                  : (record.INDENT_INDEX || 0) * 12 + 34,
              }}
            >
              {/* eslint-disable-next-line no-nested-ternary */}
              {record[childrenColumnName] ? (
                expandKeys.includes(record[rowKey]) ? (
                  <Icon
                    className={styles['expand-icon']}
                    type="indeterminate_check_box-o"
                    onClick={() => {
                      handleExpand(false, record, rowIndex);
                    }}
                  />
                ) : (
                  <Icon
                    className={styles['expand-icon']}
                    type="add_box-o"
                    onClick={() => {
                      handleExpand(true, record, rowIndex);
                    }}
                  />
                )
              ) : null}
              <span />
              {val}
            </span>
          );
        };
      }
      return tempColumn;
    }
    return column;
  });

  useEffect(() => {
    if (autoInitHeight) {
      // eslint-disable-next-line
      const childrenRefWrapperDom = ReactDOM.findDOMNode(tableRef.current);
      const childrenRefDom = childrenRefWrapperDom;
      const { top: offsetTop } = childrenRefDom.getBoundingClientRect();
      if (parentClassName) {
        const parentRefDom = document.querySelector(`.${parentClassName}`);
        const { top } = parentRefDom.getBoundingClientRect();
        setHeight(
          minHeight > parentRefDom.offsetHeight - (offsetTop - top) - 10
            ? minHeight
            : parentRefDom.offsetHeight - (offsetTop - top) - 10
        );
      } else {
        setHeight(
          minHeight > window.innerHeight - offsetTop - 30
            ? minHeight
            : window.innerHeight - offsetTop - 30
        );
      }
    }
  }, []);

  useEffect(() => {
    if (isUndefined(expandedRowKeys) && !isTree) {
      setTrueDataSource(data);
    } else {
      const { rowKeys } = flatTree(data, [], expandedRowKeys);
      setTrueDataSource(rowKeys);
    }
    if (!isUndefined(rowSelection.selectedRowKeys)) {
      const { rowKeys } = selectAllTree(data, []);
      setSelectAllKeys(rowKeys);
    }
    if (tableRef.current && shouldUpdateScroll) {
      tableRef.current.scrollTop(0);
    }
  }, [data]);

  useEffect(() => {
    setExpandKeys(expandedRowKeys);
    if (Math.abs(expandedRowKeys.length - expandKeys.length) > 1 && tableRef.current) {
      tableRef.current.scrollTop(0);
    }
  }, [expandedRowKeys]);

  useEffect(() => {
    const { rowKeys } = flatTree(data, [], expandedRowKeys);
    if (
      tableRef.current &&
      -tableRef.current.minScrollY - (trueDataSource.length - rowKeys.length) * rowHeight <
        -tableRef.current.scrollY - height
    ) {
      tableRef.current.scrollTop(0);
    }
    setTrueDataSource(rowKeys);
  }, [expandKeys]);

  useEffect(() => {
    setSelectKeys(rowSelection.selectedRowKeys);
  }, [rowSelection.selectedRowKeys]);

  useEffect(() => {
    const { pathMap2, rowKeys } = selectTree(data, [], selectKeys);
    if (isIndeterminate) {
      setPathMap(pathMap2);
    }
    setSelectRows(rowKeys);
  }, [selectKeys]);

  const SelectColumn = !isEmpty(rowSelection) && {
    title: (
      <Checkbox
        checked={selectAllKeys.length !== 0 && selectKeys.length === selectAllKeys.length}
        onChange={(e) => {
          if (e.target.checked) {
            rowSelection.onChange(
              selectAllKeys.map((item) => item[rowKey]),
              selectAllKeys
            );
          } else {
            rowSelection.onChange([], []);
          }
        }}
        indeterminate={!isEmpty(selectKeys) && selectKeys.length !== selectAllKeys.length}
      />
    ),
    dataIndex: '',
    width: 60,
    align: 'center',
    render: ({ rowData: record }) => {
      const val = record[rowKey];
      return (
        <Checkbox
          checked={selectKeys.includes(val)}
          indeterminate={
            isIndeterminate &&
            selectKeys.includes(val) &&
            !(pathMap[val] || []).every((item) => selectKeys.includes(item))
          }
          onChange={(e) => {
            if (e.target.checked) {
              rowSelection.onChange([...selectKeys, val], [...selectRows, record]);
              rowSelection.onSelect(record, e.target.checked, [...selectRows, record], e);
            } else {
              rowSelection.onChange(
                selectKeys.filter((item) => item !== val),
                selectRows.filter((item) => item[rowKey] !== val)
              );
              rowSelection.onSelect(
                record,
                e.target.checked,
                selectRows.filter((item) => item[rowKey] !== val),
                e
              );
            }
          }}
        />
      );
    },
  };

  const handleExpand = (flag, record, rowIndex) => {
    onExpandChange(flag, record);
    if (isUndefined(expandedRowKeys) && record[childrenColumnName]) {
      if (flag) {
        setExpandKeys(Array.from(new Set(expandKeys.concat(record[rowKey]))));
        setTrueDataSource(
          slice(trueDataSource, 0, rowIndex + 1)
            .concat(
              record[childrenColumnName].map((item) => {
                return { ...item, INDENT_INDEX: (record.INDENT_INDEX || 0) + 1 };
              })
            )
            .concat(slice(trueDataSource, rowIndex + 1, trueDataSource.length))
        );
      } else {
        const { rowKeys, i } = literateTree([record], [], expandKeys);
        let length = 0;
        i.forEach((v) => {
          length += v;
        });
        setExpandKeys(
          Array.from(
            new Set(
              remove(expandKeys, (item) => {
                return !rowKeys.includes(item);
              })
            )
          )
        );
        setTrueDataSource(
          slice(trueDataSource, 0, rowIndex + 1).concat(
            slice(trueDataSource, rowIndex + 1 + length, trueDataSource.length)
          )
        );
      }
    }
  };

  const literateTree = (collections = [], rowKeys = [], expandArr = [], i = []) => {
    const arr = rowKeys;
    const j = i;
    const renderTree = collections.map((item) => {
      const temp = item;
      if (temp[childrenColumnName] && expandArr.includes(temp[rowKey])) {
        arr.push(temp[rowKey]);
        j.push(temp[childrenColumnName].length);
        temp[childrenColumnName] = [
          ...literateTree(temp[childrenColumnName] || [], arr, expandArr, j).renderTree,
        ];
      }
      return temp;
    });
    return {
      renderTree,
      rowKeys,
      expandArr,
      i,
    };
  };

  const flatTree = (collections = [], rowKeys = [], expandArr = [], INDENT_INDEX = -1) => {
    const arr = rowKeys;
    const renderTree = collections.map((item) => {
      const temp = item;
      arr.push({ ...temp, INDENT_INDEX: (INDENT_INDEX || 0) + 1 });
      if (temp[childrenColumnName] && expandArr.includes(temp[rowKey])) {
        temp[childrenColumnName] = [
          ...flatTree(temp[childrenColumnName] || [], arr, expandArr, (INDENT_INDEX || 0) + 1)
            .renderTree,
        ];
      }
      return temp;
    });
    return {
      renderTree,
      rowKeys,
      expandArr,
      INDENT_INDEX,
    };
  };

  const selectTree = (collections = [], rowKeys = [], selectArr = [], levelPath = {}) => {
    const arr = rowKeys;
    const pathMap2 = levelPath;
    const renderTree = collections.map((item) => {
      const temp = item;
      pathMap2[temp[rowKey]] = [
        temp[rowKey],
        ...(temp[childrenColumnName] || []).map((res) => res[rowKey]),
      ];
      if (selectArr.includes(temp[rowKey])) {
        arr.push(temp);
      }
      if (temp[childrenColumnName]) {
        temp[childrenColumnName] = [
          ...selectTree(temp[childrenColumnName] || [], arr, selectArr, pathMap2).renderTree,
        ];
      }
      return temp;
    });
    return {
      renderTree,
      rowKeys,
      selectArr,
      pathMap2,
    };
  };

  const selectAllTree = (collections = [], rowKeys = []) => {
    const arr = rowKeys;
    const renderTree = collections.map((item) => {
      const temp = item;
      arr.push(temp);
      if (temp[childrenColumnName]) {
        temp[childrenColumnName] = [
          ...selectAllTree(temp[childrenColumnName] || [], arr).renderTree,
        ];
      }
      return temp;
    });
    return {
      renderTree,
      rowKeys,
    };
  };

  return (
    <PerformanceTable
      className="virtual-table"
      {...props}
      ref={tableRef}
      isTree={false}
      virtualized
      data={trueDataSource}
      columns={isEmpty(rowSelection) ? mergedColumns : [SelectColumn, ...mergedColumns]}
      pagination={false}
      shouldUpdateScroll={false}
      height={height2}
    />
  );
}