lodash#get JavaScript Examples

The following examples show how to use lodash#get. 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: firebaseFunctions.js    From app with MIT License 6 votes vote down vote up
/**
 * Get config variable from environment. Throws clear message for non existent variables.
 * @param {string} getPath - Path of config var to get from environment
 * @param {string} defaultVal - Default value to fallback to if environment config is not defined
 * @example <caption>Basic</caption>
 * const frontEndConfig = getEnvConfig('frontend') // functions.config().frontend
 * @example <caption>Deep Value</caption>
 * const frontEndUrl = getEnvConfig('frontend.url') // functions.config().frontend.url
 * @example <caption>Prevent Throwing</caption>
 * // Falsey default value (other than undefined) prevents throw
 * const someVal = getEnvConfig('some.empty, null) || 'asdf' // defaults to asdf without throwing
 * @returns {any} - Value of environment variable
 */
export function getEnvConfig(getPath, defaultVal) {
  if (!getPath) {
    console.warn(
      'Getting top level config can cause things to break, pass a get path to getEnvConfig',
    );
    return functions.config();
  }
  const varValue = get(functions.config(), getPath) || defaultVal;
  if (typeof varValue === 'undefined') {
    throw new Error(
      `${getPath} functions config variable not set, check functions/.runtimeconfig.json`,
    );
  }
  return varValue;
}
Example #2
Source File: index.jsx    From redive_linebot with MIT License 6 votes vote down vote up
MyPieCard = ({ rank = [] }) => {
  const { userId } = liff.getContext();
  const data = rank.find(item => item.userId === userId);
  const pieData = genPieData({
    text: get(data, "textCnt", 0),
    image: get(data, "imageCnt", 0),
    sticker: get(data, "stickerCnt", 0),
    unsend: get(data, "unsendCnt", 0),
  });

  return <PieCard title={get(data, "displayName", "-")} subtitle="個人數據分析" data={pieData} />;
}
Example #3
Source File: service.js    From d2-crud-plus-with-d2admin-starter with MIT License 6 votes vote down vote up
/**
 * @description 创建请求方法
 * @param {Object} service axios 实例
 */
function createRequestFunction (service) {
  return function (config) {
    const token = util.cookies.get('token')
    const configDefault = {
      headers: {
        Authorization: token,
        'Content-Type': get(config, 'headers.Content-Type', 'application/json')
      },
      timeout: 5000,
      baseURL: process.env.VUE_APP_API,
      data: {}
    }
    return service(Object.assign(configDefault, config))
  }
}
Example #4
Source File: favorites.js    From goodhere with MIT License 6 votes vote down vote up
function normalizeFavorites(data) {
  if (!data) return null

  return data.favorites.map((entity) => ({
    ...get(entity, 'organization.data'),
    favorite: {
      id: entity.id,
      count: get(entity, 'favorite_count.count'),
    }
  }))
}
Example #5
Source File: chart.js    From gobench with Apache License 2.0 6 votes vote down vote up
makeChartDataByTimeRange = (rawData = [], timeRange = 3600) => {
  const timeRangeMiliseconds = timeRange * 1000
  return rawData.map((seri) => {
    const seriData = get(seri, 'data', [])
    if (seriData.length === 0) {
      return []
    }
    const seriDataLength = seriData.length || 0
    const firstData = seriData[0]
    const lastData = seriData[seriDataLength - 1]
    const lastDataTime = get(lastData, 'x', 0)
    const firstDataTime = get(firstData, 'x', 0)
    const dataTime = fixSecond(lastDataTime - firstDataTime)

    if (dataTime < timeRangeMiliseconds) {
      const extraTime = timeRangeMiliseconds - dataTime
      return {
        ...seri,
        data: [...seriData.map(s => ({
          x: Math.round(s.x / 1000) * 1000, y: s.y
        })), { x: lastDataTime + extraTime, y: DEFAULT_VALUE }]
      }
    }
    return {
      ...seri,
      data: seriData.filter(d => d.x >= (fixSecond(lastDataTime) - timeRangeMiliseconds))
    }
  })
}
Example #6
Source File: setup.js    From mapstore2-cadastrapp with GNU General Public License v3.0 6 votes vote down vote up
cadastrappTearDown = (action$, store) =>
    action$.ofType(SET_CONTROL_PROPERTIES, SET_CONTROL_PROPERTY, TOGGLE_CONTROL)
        .filter(({ control }) => control === CONTROL_NAME && !isCadastrappOpen(store))
        .switchMap(() => {
            const state = store.getState();
            const cadastrappIsDrawOwner = get(state, 'draw.drawOwner', false) === 'cadastrapp';
            return Rx.Observable.from([
                updateDockPanelsList(CONTROL_NAME, 'remove', 'right'),
                toggleSelectionTool(null, cadastrappIsDrawOwner),
                removeAdditionalLayer({id: CADASTRAPP_RASTER_LAYER_ID, owner: CADASTRAPP_OWNER}),
                removeAdditionalLayer({id: CADASTRAPP_VECTOR_LAYER_ID, owner: CADASTRAPP_OWNER}),
                cleanPopups(),
                unRegisterEventListener(MOUSE_EVENT, CONTROL_NAME) // Reset map's mouse event trigger
            ]).concat([...(!get(state, "mapInfo.enabled") ? [toggleMapInfoState()] : [])]);
        })
Example #7
Source File: MappingProfileDetailsRoute.js    From ui-data-export with Apache License 2.0 6 votes vote down vote up
MappingProfileDetailsRoute = ({
  resources: {
    mappingProfile,
    jobProfiles,
  },
  allTransformations,
  mutator: { mappingProfile: { DELETE } },
  history,
  match: { params },
  location,
  onCancel,
}) => {
  // `find` is used to make sure the matched job profile, mapping profile are displayed to avoid
  // the flickering because of the disappearing of the previous and appearing of the new ones
  // TODO: try `useManifest` hook once it is ready to avoid that
  const mappingProfileRecord = find([get(mappingProfile, 'records.0', {})], { id: params.id });
  const isProfileUsed = Boolean(find([get(jobProfiles, 'records.0', {})], { mappingProfileId: params.id }));
  const isDefaultProfile = mappingProfileRecord?.default;

  return (
    <MappingProfileDetails
      allTransformations={allTransformations}
      mappingProfile={mappingProfileRecord}
      isProfileUsed={isProfileUsed}
      isDefaultProfile={isDefaultProfile}
      isLoading={!mappingProfileRecord || (!isDefaultProfile && !jobProfiles.hasLoaded)}
      onEdit={() => history.push(`/settings/data-export/mapping-profiles/edit/${params.id}${location.search}`)}
      onDuplicate={() => history.push(`/settings/data-export/mapping-profiles/duplicate/${params.id}${location.search}`)}
      onCancel={onCancel}
      onDelete={() => DELETE({ id: mappingProfileRecord?.id })}
    />
  );
}
Example #8
Source File: service.js    From django-vue-admin-pro with Apache License 2.0 6 votes vote down vote up
refreshTken = function () {
  const refresh = util.cookies.get('refresh')
  return request({
    url: 'token/refresh/',
    method: 'post',
    data: {
      refresh: refresh
    }
  })
}
Example #9
Source File: node-details-table.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
function getMetaDataSorters(nodes) {
  // returns an array of sorters that will take a node
  return get(nodes, [0, 'metadata'], []).map((field, index) => (node) => {
    const nodeMetadataField = node.metadata && node.metadata[index];
    if (nodeMetadataField) {
      if (isNumber(nodeMetadataField)) {
        return parseFloat(nodeMetadataField.value);
      }
      return nodeMetadataField.value;
    }
    return null;
  });
}
Example #10
Source File: templates.js    From gutenberg-forms with GNU General Public License v2.0 6 votes vote down vote up
function Templates(props) {


    const { templates, currentTemplate } = props;

    const currentTemplateName = get(currentTemplate, 'fields.Name');

    return (
        <div className="cwp-templates">
            <Panel header={__(<strong>Available Templates</strong>, "cwp-gutenberg-forms")}>
                <MenuGroup>
                    {
                        templates.map((template, index) => {

                            const name = get(template, 'fields.Name');

                            return <MenuItem onClick={() => props.onSelect(template)} isDefault={isEqual(currentTemplateName, name)} key={index}>{name}</MenuItem>

                        })
                    }
                </MenuGroup>
            </Panel>
        </div>
    )
}
Example #11
Source File: StepperSection.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
StepperSection = () => {
  const location = useLocation();

  return (
    <>
      {!isEmpty(get(location, 'state.fromFranceConnectedAPI')) && (
        <div>
          <p>La procédure consiste en 2 demandes d’habilitation distinctes :</p>
          <Stepper
            steps={[
              'franceconnect',
              get(location, 'state.fromFranceConnectedAPI'),
            ]}
            currentStep="franceconnect"
          />
        </div>
      )}
      {get(location, 'state.fromFranceConnectedAPI') ===
        'api_impot_particulier_fc_sandbox' && (
        <div>
          <p>La procédure consiste en 3 demandes d’habilitation distinctes :</p>
          <Stepper
            steps={[
              'franceconnect',
              'api_impot_particulier_fc_sandbox',
              'api_impot_particulier_fc_production',
            ]}
            currentStep="franceconnect"
          />
        </div>
      )}
    </>
  );
}
Example #12
Source File: index.js    From holo-schedule with MIT License 6 votes vote down vote up
i18n = {
  messages,
  locale: supportedLocales[0],
  async init(store) {
    const localeFromBrowser = browser.i18n.getUILanguage()
    if (supportedLocales.find(locale => locale.startsWith(localeFromBrowser))) {
      this.locale = localeFromBrowser
    }

    const localeFromStore = workflows.getLocale()
    this.locale = localeFromStore ?? this.locale

    await store.set({ [LOCALE]: this.locale })

    store.subscribe(LOCALE, locale => {
      this.locale = locale
    })
  },
  getMessage(path, msg = {}) {
    return get(this.messages[this.locale], path, '')
      .replace(/{([^}]+?)}/, (_, p1) => get(msg, p1, ''))
  },
}
Example #13
Source File: stream.js    From haven with MIT License 6 votes vote down vote up
getFilteredList = state => (filter, sort, peerID) => {
  const blockedNodes = getBlockedNodes(state);

  const list = filter !== 'local' ?
    get(state.stream, `${filter}Feeds.${sort}`, [])
    : get(state.stream, `${filter}Feeds`, []);
  const blockNodeFiltered = list.filter((feed) => {
    const peerID = get(state.stream.feeds, `${feed}.actor.id`);
    return !blockedNodes.find(node => node === peerID);
  });
  if (!isEmpty(peerID)) {
    return blockNodeFiltered.filter(feed => get(state.stream.feeds, `${feed}.actor.id`) === peerID);
  }
  return blockNodeFiltered;
}
Example #14
Source File: getRepositories.js    From rate-repository-api with MIT License 6 votes vote down vote up
getRepositoryPayload = (
  repository,
  githubRepository,
  reviewCount,
  ratingAverage,
) => ({
  id: repository.id,
  name: repository.name,
  ownerName: repository.ownerName,
  createdAt: repository.createdAt ? new Date(repository.createdAt) : null,
  fullName: [repository.ownerName, repository.name].join('/'),
  reviewCount,
  ratingAverage: Math.round(ratingAverage),
  forksCount: get(githubRepository, 'forks_count') || 0,
  stargazersCount: get(githubRepository, 'stargazers_count') || 0,
  description: get(githubRepository, 'description') || null,
  language: get(githubRepository, 'language') || null,
  ownerAvatarUrl: get(githubRepository, 'owner.avatar_url') || null,
})
Example #15
Source File: OrderFulfillment.js    From haven with MIT License 6 votes vote down vote up
renderDetail() {
    const { detail } = this.props;
    const physical = get(detail, 'physicalDelivery[0]');
    const digital = get(detail, 'digitalDelivery[0]');

    const { copied } = this.state;

    if (!isEmpty(physical)) {
      return (
        <View style={styles.detailWrapper}>
          <StaticField label="Shipping via" value={physical.shipper} />
          <StaticField
            label="Tracking #"
            value={physical.trackingNumber}
            onCopy={this.handleCopy}
          />
          {copied && (
            <View style={styles.overlay}>
              <Text style={styles.overlayText}>Tracking number copied!</Text>
            </View>
          )}
        </View>
      );
    } else if (!isEmpty(digital)) {
      return (
        <View style={styles.detailWrapper}>
          <StaticField label="File URL:" value={digital.url} isLink />
          <StaticField label="Password:" value={digital.password} />
        </View>
      );
    }

    return (
      <Text style={styles.description}>
        This order has been fulfilled!
      </Text>
    );
  }
Example #16
Source File: githubClient.js    From rate-repository-api with MIT License 6 votes vote down vote up
async getRequest(url, options = {}) {
    try {
      const response = await this.httpClient.get(url, {
        ...options,
        auth: this.getAuth(),
      });

      return response;
    } catch (error) {
      throw GithubError.fromHttpClientError(error);
    }
  }
Example #17
Source File: OrderDispute.js    From haven with MIT License 6 votes vote down vote up
render() {
    const { orderDetails, onMessage } = this.props;
    const dispute = get(orderDetails, 'contract.dispute');
    if (isEmpty(dispute)) {
      return null;
    }

    const disputeResolution = get(orderDetails, 'contract.disputeResolution');
    const {
      buyerProfile, sellerProfile, sellerStarted,
    } = this.state;
    const profile = sellerStarted ? sellerProfile : buyerProfile;
    const name = get(profile, 'name');
    return (
      <View>
        {this.renderDisputeExpire()}
        {!isEmpty(disputeResolution) && this.renderDisputePayout()}
        <InputGroup
          title={`Dispute started by ${name || (sellerStarted ? 'the seller' : 'the buyer')}`}
          actionTitle={timeSince(new Date(dispute.timestamp))}
          actionStyle={styles.timestamp}
        >
          <View style={styles.memoContainer}>
            <Text style={styles.memo}>
              {decode(dispute.claim)}
            </Text>
          </View>
          <Text style={styles.memoComment}>
            {'The moderator has stepped in to help. Start chatting to provide more details.'}
          </Text>
          <TouchableWithoutFeedback onPress={onMessage}>
            <View style={styles.messageButton}>
              <Text style={styles.messageText}>Message</Text>
            </View>
          </TouchableWithoutFeedback>
        </InputGroup>
      </View>
    );
  }
Example #18
Source File: githubClient.js    From rate-repository-api with MIT License 6 votes vote down vote up
async getRequestWithCache(cacheKey, url, options) {
    const cachedPromise = this.cache.get(cacheKey);

    if (cachedPromise) {
      const { data } = await cachedPromise;

      return data;
    }

    const promise = this.getRequest(url, options);

    this.cache.set(cacheKey, promise);

    try {
      const { data } = await promise;

      return data;
    } catch (e) {
      this.cache.del(cacheKey);

      throw e;
    }
  }
Example #19
Source File: OrderDispute.js    From haven with MIT License 6 votes vote down vote up
renderDisputeExpire() {
    const { orderDetails } = this.props;

    const { state } = orderDetails;
    if (!['DISPUTE_EXPIRED', 'PAYMENT_FINALIZED'].includes(state)) {
      return null;
    }

    const disputeTimestamp = get(orderDetails, 'contract.dispute.timestamp');

    if (!disputeTimestamp) {
      return null;
    }

    const disputeStartDay = new Date(disputeTimestamp);
    const timeoutDay = disputeStartDay.setHours(disputeStartDay.getHours() + EXPIRE_IN_HOURS);

    return (
      <InputGroup
        title="Dispute expired"
        actionTitle={timeSince(new Date(timeoutDay))}
        actionStyle={styles.timestamp}
      >
        <Text style={styles.memoComment}>
          {'The moderator has not proposed an outcome. The seller can claim the payment.'}
        </Text>
        <View style={styles.spacer} />
      </InputGroup>
    );
  }
Example #20
Source File: components.js    From e-Pola with MIT License 6 votes vote down vote up
/**
 * Show a loading spinner while props are loading . Checks
 * for undefined, null, or a value (as well as handling `auth.isLoaded` and
 * `profile.isLoaded`). **NOTE:** Meant to be used with props which are passed
 * as props from state.firebase using connect (from react-redux), which means
 * it could have unexpected results for other props
 * @param {Array} propNames - List of prop names to check loading for
 * @returns {HigherOrderComponent}
 * @example <caption>Spinner While Data Loading</caption>
 * import { compose } from 'redux'
 * import { connect } from 'react-redux'
 * import firebaseConnect from 'react-redux-firebase/lib/firebaseConnect'
 *
 * const enhance = compose(
 *   firebaseConnect(() => ['projects']),
 *   connect(({ firebase: { data: { projects } } }) => ({ projects })),
 *   spinnerWhileLoading(['projects'])
 * )
 *
 * export default enhance(SomeComponent)
 */
export function spinnerWhileLoading(propNames) {
  if (!propNames || !Array.isArray(propNames)) {
    const missingPropNamesErrMsg =
      'spinnerWhileLoading requires propNames array'
    console.error(missingPropNamesErrMsg) // eslint-disable-line no-console
    throw new Error(missingPropNamesErrMsg)
  }
  return spinnerWhile((props) =>
    propNames.some((name) => !isLoaded(get(props, name)))
  )
}
Example #21
Source File: FeedImageGrid.js    From haven with MIT License 6 votes vote down vote up
renderFlatList(images, isFirstOfGrid, moreCount) {
    return (
      <FlatList
        style={styles.imagesList(get(images, 'length', 0), isFirstOfGrid)}
        keyExtractor={(item, index) => `image_item_${index}`}
        data={images}
        renderItem={this.renderImageItem(images, moreCount)}
        horizontal
        pointerEvents="auto"
        scrollEnabled={false}
      />
    );
  }
Example #22
Source File: components.js    From e-Pola with MIT License 6 votes vote down vote up
/**
 * HOC that shows a component while any of a list of props loaded from Firebase
 * is empty (uses react-redux-firebase's isEmpty).
 * @param {Array} propNames - List of prop names to check loading for
 * @param {React.Component} component - React component to render if prop loaded
 * from Firebase is empty
 * @returns {HigherOrderComponent}
 * @example
 * renderWhileEmpty(['todos'], () => <div>Todos Not Found</div>),
 */
export function renderWhileEmpty(propNames, component) {
  if (!propNames || !Array.isArray(propNames)) {
    const missingPropNamesErrMsg = 'renderWhileEmpty requires propNames array'
    console.error(missingPropNamesErrMsg) // eslint-disable-line no-console
    throw new Error(missingPropNamesErrMsg)
  }
  return renderWhile(
    // Any of the listed prop name correspond to empty props (supporting dot path names)
    (props) =>
      propNames.some(propNames, (name) => {
        const propValue = get(props, name)
        return (
          isLoaded(propValue) &&
          (isEmpty(propValue) ||
            (Array.isArray(propValue) && !Object.keys(propValue).length))
        )
      }),
    component
  )
}
Example #23
Source File: MultiFilter.js    From haven with MIT License 6 votes vote down vote up
render() {
    const {
      selected, options, title, style, hasScroll,
    } = this.props;
    const Wrapper = hasScroll ? ScrollView : View;
    return (
      <Section title={title}>
        <Wrapper style={[styles.wrapper, style]}>
          {options.map((val, key) => {
            const idx = findIndex(selected, o => o === val.value);
            const isLast = key === options.length - 1;
            return (
              <TouchableWithoutFeedback
                key={key}
                onPress={() => {
                  this.onChange(val.value, idx, get(val, 'exclusive', false));
                }}
              >
                <View style={styles.itemWrapper}>
                  {idx >= 0 ? (
                    <Ionicons name="ios-checkmark" size={28} style={styles.checkmark} />
                  ) : (
                    <Ionicons size={28} style={styles.checkmark} />
                  )}
                  <View style={[styles.itemTextWrapper, !isLast && styles.bottomBorder]}>
                    <Text style={styles.itemText}>{val.label}</Text>
                  </View>
                </View>
              </TouchableWithoutFeedback>
            );
          })}
        </Wrapper>
      </Section>
    );
  }
Example #24
Source File: wallpaper-app-container.js    From React-Messenger-App with MIT License 6 votes vote down vote up
componentDidMount() {
        const url = 'https://api.unsplash.com/photos/random?count=50&client_id=896979fdb70f80865638d7a4648bf9ce309675335318933eab2bf990af42e295';
        axios.get( url ).then( ( response ) => {
            console.log( 'Network Request Successful', response.data.results );
            this.setState( {
                images: response.data,
                isLoading: false
            } );
        } ).catch( ( error ) => {
            console.log( error );
        } ).finally( () => {
            console.log( 'Network request Completed' );
        } );
    }
Example #25
Source File: setup.js    From mapstore2-cadastrapp with GNU General Public License v3.0 5 votes vote down vote up
tearDownCadastrappOnDrawToolActive = (action$, store) => shutdownToolOnAnotherToolDrawing(action$, store, 'cadastrapp',
    (state) => {
        const cadastrappIsDrawOwner = get(state, 'draw.drawOwner', false) === 'cadastrapp';
        return Rx.Observable.from([
            toggleSelectionTool(null, cadastrappIsDrawOwner)]);
    })
Example #26
Source File: group.js    From gobench with Apache License 2.0 5 votes vote down vote up
DefaultPage = ({ group, graphs = [], timestamp, expandDefault = false, dispatch }) => {
  const [collapsed, toggleCollapse] = useState(!expandDefault)
  const [_graphs, setGraphs] = useState([])
  const ag = graphs.some(x => x.groupId === group.id)
  useEffect(() => {
    if (group && !collapsed) {
      if (graphs.every(x => x.groupId !== group.id)) {
        dispatch({
          type: 'application/GRAPHS',
          payload: { id: group.id }
        })
      }
    }
  }, [group, collapsed])
  useEffect(() => {
    if (ag) {
      setGraphs(graphs.filter(x => x.groupId === group.id))
    }
  }, [graphs])
  return (
    <>
      <div className='application-group'>
        <div className='group'>
          <div
            className='group-header clickable'
            onClick={() => toggleCollapse(!collapsed)}
          >
            <h3 title={_graphs.id || ''} className='group-title'>{get(group, 'name', '')}</h3>
            <span className='collapse-button'>
              {collapsed ? <CaretDownOutlined /> : <CaretUpOutlined />}
            </span>
          </div>
          <div className={`group-graphs ${collapsed ? 'collapse' : ''}`}>
            {
              !collapsed &&
                <Row gutter={[16, 16]}>
                  {
                    _graphs.length > 0
                      ? _graphs.map((graph, index) => {
                        return (
                          <Col key={graph.id || index} xs={24} sm={24} md={24} lg={12} xl={8}>
                            <Graph graph={graph} timestamp={timestamp} />
                          </Col>
                        )
                      })
                      : <p className='text-center'>Cannot load graphs.</p>
                  }
                </Row>
            }
          </div>
        </div>
      </div>
    </>
  )
}
Example #27
Source File: selectors.js    From EthereumPonzi with MIT License 5 votes vote down vote up
web3 = state => get(state, 'web3.connection', null)
Example #28
Source File: setup.js    From mapstore2-cadastrapp with GNU General Public License v3.0 5 votes vote down vote up
cadastrappSetup = (action$, store) =>
    action$.ofType(SETUP).switchMap(() => {
        // initStream loads configuration if not loaded yet
        let initStream$ = Rx.Observable.defer(() => getConfiguration())
            .switchMap(data => {
                return Rx.Observable.of(setConfiguration(data));
            })
            .startWith(updateDockPanelsList(CONTROL_NAME, 'add', 'right'));
        return initStream$.concat(
            Rx.Observable.defer(() => {
                // here the configuration has been loaded
                const {
                    cadastreWMSLayerName,
                    cadastreWMSURL,
                    cadastreWFSLayerName,
                    cadastreWFSURL
                } = configurationSelector(store.getState());
                return Rx.Observable.from([
                    updateAdditionalLayer(
                        CADASTRAPP_RASTER_LAYER_ID,
                        CADASTRAPP_OWNER,
                        'overlay',
                        {
                            id: CADASTRAPP_RASTER_LAYER_ID,
                            type: "wms",
                            name: cadastreWMSLayerName,
                            url: cadastreWMSURL,
                            visibility: true,
                            search: {
                                url: cadastreWFSURL,
                                name: cadastreWFSLayerName,
                                type: "wfs"
                            }
                        }, true),
                    updateAdditionalLayer(
                        CADASTRAPP_VECTOR_LAYER_ID,
                        CADASTRAPP_OWNER,
                        'overlay',
                        {
                            id: CADASTRAPP_VECTOR_LAYER_ID,
                            features: [],
                            type: "vector",
                            name: "searchPoints",
                            visibility: true
                        }),
                    registerEventListener(MOUSE_EVENT, CONTROL_NAME), // Set map's mouse event trigger type
                    ...(get(store.getState(), "mapInfo.enabled") ? [toggleMapInfoState(), hideMapinfoMarker()] : [])
                ]);
            })
        )
            .concat(Rx.Observable.of(setupCompleted())) // required to sync the layer the first time (if closed/reopen)
            .let(
                wrapStartStop(
                    loading(true, 'configuration'),
                    loading(false, 'configuration'),
                    e => {
                        console.log(e); // eslint-disable-line no-console
                        return Rx.Observable.of(error({ title: "Error", message: "Unable to setup cadastrapp" }), loading(false, 'configuration'));
                    }
                )
            );
    })
Example #29
Source File: TransformationsForm.js    From ui-data-export with Apache License 2.0 5 votes vote down vote up
TransformationsFormComponent = memo(({
  searchResults,
  form,
  validatedTransformations = {},
  isSelectAllChecked = false,
  stateRef,
  setValidatedTransformations,
  setIsSubmitButtonDisabled,
  onSelectChange,
}) => {
  stateRef.current = form;

  const {
    change: changeFormField,
    getState: getFormState,
  } = form;

  const handleSelectChange = useCallback(() => {
    const transformations = get(getFormState(), 'values.transformations', []);
    const selectedTransformations = generateSelectedTransformations(
      transformations,
      transformation => transformation.isSelected && transformation
    );

    onSelectChange(selectedTransformations);
  }, [getFormState, onSelectChange]);

  const handleSelectAll = useCallback(() => {
    searchResults.forEach(transformation => {
      changeFormField(`transformations[${transformation.order}].isSelected`, !isSelectAllChecked);
    });

    handleSelectChange();
  }, [searchResults, isSelectAllChecked, handleSelectChange, changeFormField]);

  return (
    <form className={commonCss.fullScreen}>
      <TransformationField
        contentData={searchResults}
        validatedTransformations={validatedTransformations}
        isSelectAllChecked={isSelectAllChecked}
        setValidatedTransformations={setValidatedTransformations}
        setIsSubmitButtonDisabled={setIsSubmitButtonDisabled}
        onSelectChange={handleSelectChange}
        onSelectAll={handleSelectAll}
      />
    </form>
  );
})