lodash#castArray JavaScript Examples

The following examples show how to use lodash#castArray. 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: index.js    From Lambda with MIT License 6 votes vote down vote up
TreeBeard = ({
  animations,
  decorators,
  data,
  onToggle,
  style,
  onSelect,
  customStyles,
}) => (
  <Ul style={{ ...defaultTheme.tree.base, ...style.tree.base }}>
    {castArray(data).map((node) => (
      <TreeNode
        decorators={decorators}
        node={node}
        onToggle={onToggle}
        animations={animations}
        onSelect={onSelect}
        customStyles={customStyles}
        key={node.id || randomString()}
        style={{ ...defaultTheme.tree.node, ...style.tree.node }}
      />
    ))}
  </Ul>
)
Example #2
Source File: selection.js    From volto-slate with MIT License 6 votes vote down vote up
/**
 * Get the nodes with a type included in `types` in the selection (from root to leaf).
 *
 * @param {} editor
 * @param {} types
 * @param {} options
 */
export function getSelectionNodesByType(editor, types, options = {}) {
  types = castArray(types);

  return Editor.nodes(editor, {
    match: (n) => {
      return types.includes(n.type);
    },
    ...options,
  });
}
Example #3
Source File: api.js    From mapstore2-cadastrapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get Parcelle(s) from the getParcelle service.
 * @param {string|string[]} params.comptecommunal array of comptecommunal to add
 */
export function getParcelleByCompteCommunal({
    comptecommunal
}) {
    const params = new URLSearchParams();
    castArray(comptecommunal).forEach(v => params.append('comptecommunal', v));
    return axios.post(`${baseURL}/services/getParcelle`, params ).then(({ data }) => data);
}
Example #4
Source File: api.js    From mapstore2-cadastrapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get Parcelle(s) from the getParcelle service. Used also in plot selection.
 * @param {string|string[]} params.comptecommunal array of comptecommunal to add
 */
export function exportLotsAsCSV({
    parcelle,
    dnubat
}) {
    const params = new URLSearchParams();
    castArray(parcelle).forEach(v => params.append('parcelle', v));
    castArray(dnubat).forEach(v => params.append('dnubat', v));
    return axios.post(`${baseURL}/services/exportLotsAsCSV`, params, { responseType: 'arraybuffer' });
}
Example #5
Source File: api.js    From mapstore2-cadastrapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get Parcelle(s) from the getParcelle service.
 * @param {string|string[]} params.comptecommunal array of comptecommunal to add
 */
export function exportLotsAsPDF({
    parcelle,
    dnubat
}) {
    const params = new URLSearchParams();
    castArray(parcelle).forEach(v => params.append('parcelle', v));
    castArray(dnubat).forEach(v => params.append('dnubat', v));
    return axios.post(`${baseURL}/services/exportLotsAsPDF`, params, { responseType: 'arraybuffer' });
}
Example #6
Source File: api.js    From mapstore2-cadastrapp with GNU General Public License v3.0 6 votes vote down vote up
// DOWNLOAD (PLOT SELECTION)
/**
 * Download parcelles as CSV
 * @param {string|string[]} params.parcelles array or comma separated list of parcelles
 */
export function exportParcellesAsCSV({
    parcelles
}) {
    const params = new URLSearchParams();
    params.append('parcelles', castArray(parcelles).join(','));
    return axios.post(`${baseURL}/services/exportParcellesAsCSV`, params, { responseType: 'arraybuffer' });
}
Example #7
Source File: api.js    From mapstore2-cadastrapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Download proprietaire as CSV
 * @param {string|string[]} params.parcelles array or comma separated list of parcelles
 */
export function exportProprietaireByParcelles({
    parcelles
}) {
    const params = new URLSearchParams();
    params.append('parcelles', castArray(parcelles).join(','));
    return axios.post(`${baseURL}/services/exportProprietaireByParcelles`, params, { responseType: 'arraybuffer' });
}
Example #8
Source File: api.js    From mapstore2-cadastrapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Download co-proprietaire as CSV
 * @param {string|string[]} params.parcelles array or comma separated list of parcelles
 */
export function exportCoProprietaireByParcelles({
    parcelles
}) {
    const params = new URLSearchParams();
    params.append('parcelles', castArray(parcelles).join(','));
    return axios.post(`${baseURL}/services/exportCoProprietaireByParcelles`, params, { responseType: 'arraybuffer' });
}
Example #9
Source File: api.js    From mapstore2-cadastrapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Utility function. Export as csv the passed data (array (rows), of array(columns)).
 * @param {array[]} params.data rows, each row is an array of columns
 */
export function exportAsCsv({data}) {
    const params = new URLSearchParams();
    castArray(data).forEach(dd => params.append('data', castArray(dd).join(',')));
    return axios.get(`${baseURL}/services/exportAsCsv`, {params}, { responseType: 'arraybuffer' });
}
Example #10
Source File: extensions.js    From volto-slate with MIT License 5 votes vote down vote up
getPointBefore = (editor, at, options) => {
  if (!options || (!options.match && !options.matchString)) {
    return Editor.before(editor, at, options);
  }

  let beforeAt = at;
  let previousBeforePoint = Editor.point(editor, at, { edge: 'end' });

  const stackLength = (options.matchString?.length || 0) + 1;
  const stack = Array(stackLength);

  const unitOffset = !options.unit || options.unit === 'offset';

  let count = 0;
  while (true) {
    const beforePoint = Editor.before(editor, beforeAt, options);

    // not found
    if (!beforePoint) return;

    // different path
    if (
      !options.multiPaths &&
      !Path.equals(beforePoint.path, previousBeforePoint.path)
    ) {
      return;
    }

    const beforeString = Editor.string(editor, {
      anchor: beforePoint,
      focus: previousBeforePoint,
    });

    const matchString = castArray(options.matchString);

    let beforeStringToMatch = beforeString;

    if (unitOffset && stackLength) {
      stack.unshift({
        point: beforePoint,
        text: beforeString,
      });
      stack.pop();

      beforeStringToMatch = map(stack.slice(0, -1), 'text').join('');
    }

    if (
      matchString.includes(beforeStringToMatch) ||
      options.match?.({ beforeString: beforeStringToMatch, beforePoint, at })
    ) {
      if (options.afterMatch) {
        if (stackLength && unitOffset) {
          return stack[stack.length - 1]?.point;
        }
        return previousBeforePoint;
      }
      return beforePoint;
    }

    previousBeforePoint = beforePoint;
    beforeAt = beforePoint;

    count += 1;

    if (!options.skipInvalid) {
      if (!matchString || count > matchString.length) return;
    }
  }
}
Example #11
Source File: extensions.js    From volto-slate with MIT License 5 votes vote down vote up
withAutoformat = ({ rules }) => (editor) => {
  const { insertText } = editor;

  editor.insertText = (text) => {
    if (!isCollapsed(editor.selection)) return insertText(text);

    for (const {
      trigger = ' ',
      type,
      markup,
      preFormat,
      format,
      mode,
      between,
      ignoreTrim,
      insertTrigger,
    } of rules) {
      const triggers = castArray(trigger);

      // Check trigger
      if (!triggers.includes(text)) continue;

      const markups = castArray(markup);

      const rangeFromBlockStart = getRangeFromBlockStart(editor);
      const textFromBlockStart = getText(editor, rangeFromBlockStart);

      const valid = () => insertTrigger && insertText(text);

      if (markups.includes(textFromBlockStart)) {
        // Start of the block
        autoformatBlock(editor, type, rangeFromBlockStart, {
          preFormat,
          format,
        });
        return valid();
      }

      if (mode === 'inline-block') {
        if (
          autoformatInlineBlock(editor, { preFormat, markup, format, type })
        ) {
          return valid();
        }
      }

      if (mode === 'inline') {
        if (
          autoformatInline(editor, {
            type,
            between,
            ignoreTrim,
            markup: Array.isArray(markup) ? markup[0] : markup,
          })
        ) {
          return valid();
        }
      }
    }

    insertText(text);
  };

  return editor;
}
Example #12
Source File: index.js    From sampo-ui with MIT License 4 votes vote down vote up
createBackendSearchConfig().then(backendSearchConfig => {
  const DEFAULT_PORT = 3001
  const app = express()
  app.set('port', process.env.SAMPO_UI_EXPRESS_PORT || DEFAULT_PORT)
  app.use(bodyParser.json())
  app.disable('x-powered-by')

  // NODE_ENV is defined in package.json when running in localhost
  const isDevelopment = process.env.NODE_ENV === 'development'

  // CORS middleware
  app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
    // handle pre-flight request
    if (req.method === 'OPTIONS') {
      return res.status(200).end()
    }
    next()
  })

  // Generate API docs from YAML file with Swagger UI
  let swaggerDocument
  try {
    swaggerDocument = yaml.safeLoad(fs.readFileSync(path.join(__dirname, './openapi.yaml'), 'utf8'))
  } catch (e) {
    console.log(e)
  }
  app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument))

  // Express server is used to serve the React app only in production
  let publicPath = null
  if (!isDevelopment) {
    // The root directory from which to serve static assets
    publicPath = path.join(__dirname, './../public/')
    // app.use(express.static(publicPath))
    app.use('/', expressStaticGzip(publicPath))
  }

  // React app makes requests to these api urls
  const apiPath = '/api/v1'

  const validator = OpenApiValidator.middleware({
    apiSpec: swaggerDocument,
    validateResponses: true
  })
  app.use(validator)

  // https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
  app.post(`${apiPath}/faceted-search/:resultClass/paginated`, async (req, res, next) => {
    const { params, body } = req
    try {
      const data = await getPaginatedResults({
        backendSearchConfig,
        resultClass: params.resultClass,
        page: body.page,
        pagesize: parseInt(body.pagesize),
        sortBy: body.sortBy,
        sortDirection: body.sortDirection,
        constraints: body.constraints,
        resultFormat: 'json'
      })
      res.json(data)
    } catch (error) {
      console.log(error)
      next(error)
    }
  })

  app.post(`${apiPath}/faceted-search/:resultClass/all`, async (req, res, next) => {
    const { params, body } = req
    const resultFormat = 'json'
    try {
      const data = await getAllResults({
        backendSearchConfig,
        perspectiveID: body.perspectiveID,
        resultClass: params.resultClass,
        facetClass: body.facetClass,
        uri: body.uri,
        constraints: body.constraints,
        resultFormat: resultFormat,
        limit: body.limit,
        optimize: body.optimize,
        fromID: body.fromID,
        toID: body.toID,
        period: body.period,
        province: body.province
      })
      if (resultFormat === 'csv') {
        res.writeHead(200, {
          'Content-Type': 'text/csv',
          'Content-Disposition': 'attachment; filename=results.csv'
        })
        res.end(data)
      } else {
        res.json(data)
      }
    } catch (error) {
      next(error)
    }
  })

  // GET endpoint for supporting CSV button
  app.get(`${apiPath}/faceted-search/:resultClass/all`, async (req, res, next) => {
    try {
      const resultFormat = req.query.resultFormat == null ? 'json' : req.query.resultFormat
      const data = await getAllResults({
        backendSearchConfig,
        perspectiveID: req.body.perspectiveID,
        resultClass: req.params.resultClass,
        facetClass: req.query.facetClass || null,
        constraints: req.query.constraints == null ? null : req.query.constraints,
        resultFormat: resultFormat
      })
      if (resultFormat === 'csv') {
        res.writeHead(200, {
          'Content-Type': 'text/csv',
          'Content-Disposition': 'attachment; filename=results.csv'
        })
        res.end(data)
      } else {
        res.json(data)
      }
    } catch (error) {
      next(error)
    }
  })

  app.post(`${apiPath}/faceted-search/:resultClass/count`, async (req, res, next) => {
    const { params, body } = req
    try {
      const data = await getResultCount({
        backendSearchConfig,
        resultClass: params.resultClass,
        constraints: body.constraints,
        resultFormat: 'json'
      })
      res.json(data)
    } catch (error) {
      next(error)
    }
  })

  app.post(`${apiPath}/:resultClass/page/:uri`, async (req, res, next) => {
    const { params, body } = req
    try {
      const data = await getByURI({
        backendSearchConfig,
        perspectiveID: body.perspectiveID,
        resultClass: params.resultClass,
        uri: params.uri,
        facetClass: body.facetClass,
        constraints: body.constraints,
        resultFormat: 'json'
      })
      res.json(data)
    } catch (error) {
      next(error)
    }
  })

  app.post(`${apiPath}/faceted-search/:facetClass/facet/:id`, async (req, res, next) => {
    const { params, body } = req
    try {
      const data = await getFacet({
        backendSearchConfig,
        facetClass: params.facetClass,
        facetID: params.id,
        sortBy: body.sortBy,
        sortDirection: body.sortDirection,
        constraints: body.constraints,
        resultFormat: 'json',
        constrainSelf: body.constrainSelf
      })
      res.json(data)
    } catch (error) {
      next(error)
    }
  })

  app.get(`${apiPath}/full-text-search`, async (req, res, next) => {
    try {
      const data = await queryJenaIndex({
        backendSearchConfig,
        queryTerm: req.query.q,
        resultClass: 'fullTextSearch',
        resultFormat: 'json'
      })
      res.json(data)
    } catch (error) {
      next(error)
    }
  })

  app.get(`${apiPath}/federated-search`, async (req, res, next) => {
    const perspectiveID = req.query.perspectiveID
    let queryTerm = ''
    let latMin = 0
    let longMin = 0
    let latMax = 0
    let longMax = 0
    if (has(req.query, 'q')) {
      queryTerm = req.query.q
    }
    if (has(req.query, 'latMin')) {
      latMin = req.query.latMin
      longMin = req.query.longMin
      latMax = req.query.latMax
      longMax = req.query.longMax
    }
    try {
      const data = await getFederatedResults({
        perspectiveID,
        federatedSearchDatasets: backendSearchConfig[perspectiveID].datasets,
        queryTerm,
        latMin,
        longMin,
        latMax,
        longMax,
        datasets: castArray(req.query.dataset),
        resultFormat: req.query.resultFormat == null ? 'json' : req.query.resultFormat
      })
      res.json(data)
    } catch (error) {
      next(error)
    }
  })

  app.get(`${apiPath}/wfs`, async (req, res, next) => {
    const layerIDs = castArray(req.query.layerID)
    try {
      const data = await Promise.all(layerIDs.map(layerID => fetchGeoJSONLayer({ layerID })))
      res.json(data)
    } catch (error) {
      next(error)
    }
  })

  // https://www.maanmittauslaitos.fi/karttakuvapalvelu/tekninen-kuvaus-wmts
  app.get(`${apiPath}/nls-wmts`, async (req, res, next) => {
    const url = `https://karttakuva.maanmittauslaitos.fi/maasto/wmts/1.0.0/${req.query.layerID}/default/WGS84_Pseudo-Mercator/${req.query.z}/${req.query.y}/${req.query.x}.png`
    const headers = {
      'Content-Type': 'image/png',
      Authorization: `Basic ${process.env.NLS_WMTS_BASIC_AUTH}`
    }
    try {
      const response = await axios({
        method: 'get',
        url,
        responseType: 'arraybuffer',
        headers
      })
      res.end(response.data, 'base64')
    } catch (error) {
      next(error)
    }
  })

  // https://www.maanmittauslaitos.fi/karttakuvapalvelu/tekninen-kuvaus-wmts
  app.get(`${apiPath}/nls-wmts-open`, async (req, res, next) => {
    const url = `https://avoin-karttakuva.maanmittauslaitos.fi/avoin/wmts/1.0.0/${req.query.layerID}/default/WGS84_Pseudo-Mercator/${req.query.z}/${req.query.y}/${req.query.x}.png`
    const headers = {
      'Content-Type': 'image/png',
      Authorization: `Basic ${process.env.NLS_API_KEY_BASE64}`
    }
    try {
      const response = await axios({
        method: 'get',
        url,
        responseType: 'arraybuffer',
        headers
      })
      res.end(response.data, 'base64')
    } catch (error) {
      next(error)
    }
  })

  // // https://www.maanmittauslaitos.fi/karttakuvapalvelu/tekninen-kuvaus-vektoritiilet
  app.get(`${apiPath}/nls-vectortiles-open`, async (req, res, next) => {
    const url = 'https://avoin-karttakuva.maanmittauslaitos.fi/vectortiles/stylejson/v20/taustakartta.json?TileMatrixSet=WGS84_Pseudo-Mercator'
    const headers = {
      Authorization: `Basic ${process.env.NLS_API_KEY_BASE64}`
    }
    try {
      const response = await axios({
        method: 'get',
        url,
        headers
      })
      res.json(response.data)
    } catch (error) {
      next(error)
    }
  })

  app.get(`${apiPath}/fha-wms`, async (req, res, next) => {
    const headers = {
      Authorization: `Basic ${process.env.FHA_WMS_BASIC_AUTH}`
    }
    const { service, request, layers, styles, format, transparent, version, width, height, crs, bbox } = req.query
    const mapServerParams = {
      service,
      request,
      layers,
      styles,
      format,
      transparent,
      version,
      width,
      height,
      crs,
      bbox
    }
    const url = `http://137.116.207.73/geoserver/ows?${querystring.stringify(mapServerParams)}`
    try {
      const response = await axios({
        method: 'get',
        url,
        responseType: 'arraybuffer',
        headers
      })
      res.end(response.data, 'base64')
    } catch (error) {
      console.log(error)
      next(error)
    }
  })

  app.get(`${apiPath}/wfs`, async (req, res, next) => {
    const layerIDs = castArray(req.query.layerID)
    try {
      const data = await Promise.all(layerIDs.map(layerID => fetchGeoJSONLayer({ layerID })))
      res.json(data)
    } catch (error) {
      next(error)
    }
  })

  app.get(`${apiPath}/void/:perspectiveID/:resultClass`, async (req, res, next) => {
    const { params } = req
    try {
      const data = await getAllResults({
        backendSearchConfig,
        perspectiveID: params.perspectiveID,
        resultClass: params.resultClass,
        resultFormat: 'json'
      })
      res.json(data)
    } catch (error) {
      next(error)
    }
  })

  // Express server is used to serve the React app only in production
  if (!isDevelopment) {
    /*  Routes are matched to a url in order of their definition
        Redirect all the the rest for react-router to handle */
    app.get('*', function (request, response) {
      response.sendFile(path.join(publicPath, 'index.html'))
    })
  }

  const servingInfo = isDevelopment
    ? 'NODE_ENV=development, so Webpack serves the React app'
    : `Static files (e.g. the React app) will be served from ${publicPath}`

  const port = app.get('port')

  app.listen(port, () =>
    console.log(`
          Express server listening on port ${port}
          API path is ${apiPath}
          ${servingInfo}
        `)
  )
})
Example #13
Source File: index.js    From iceberg-editor with GNU General Public License v2.0 4 votes vote down vote up
render() {
		const { postType } = this.props;

		if ( ! postType ) {
			return null;
		}

		const POPOVER_PROPS = {
			className:
				'components-iceberg-shortcuts__content components-iceberg-popover',
			position: 'top right',
			focusOnMount: 'container',
		};

		const TOGGLE_PROPS = {
			tooltipPosition: 'bottom',
		};

		const ShortcutList = ( { shortcuts } ) => {
			const singular = get(
				postType,
				[ 'labels', 'singular_name' ],
				'Posts'
			).toLowerCase();
			const plural = get(
				postType,
				[ 'labels', 'name' ],
				'Posts'
			).toLowerCase();
			return (
				<dl className="components-iceberg-shortcuts__shortcut-list">
					{ shortcuts.map(
						(
							{ keyCombination, description, override, single },
							index
						) => {
							if ( typeof override !== 'undefined' && override ) {
								if ( typeof single !== 'undefined' && single ) {
									description = description.replace(
										'{type}',
										singular
									);
								} else {
									description = description.replace(
										'{type}',
										plural
									);
								}
							}
							return (
								<div
									className="components-iceberg-shortcuts__shortcut"
									key={ index }
								>
									<div className="components-iceberg-shortcuts__shortcut-description">
										{ description }
									</div>
									<div className="components-iceberg-shortcuts__shortcut-term">
										{ mapKeyCombination(
											castArray( keyCombination )
										) }
									</div>
								</div>
							);
						}
					) }
				</dl>
			);
		};

		const ShortcutSection = ( {
			title,
			shortcuts,
			panel,
			initialOpen,
		} ) => (
			<section className="components-iceberg-shortcuts__section">
				{ panel ? (
					<PanelBody title={ title } initialOpen={ initialOpen }>
						<ShortcutList shortcuts={ shortcuts } />
					</PanelBody>
				) : (
					<Fragment>
						<BaseControl className="components-iceberg-menu-title">
							{ title }
						</BaseControl>
						<ShortcutList shortcuts={ shortcuts } />
					</Fragment>
				) }
			</section>
		);

		const mapKeyCombination = ( keyCombination ) =>
			keyCombination.map( ( character, index ) => {
				return (
					<kbd
						key={ index }
						className="components-iceberg-shortcuts__shortcut-key"
					>
						{ character }
					</kbd>
				);
			} );

		return (
			<Fragment>
				<div className="components-iceberg-shortcuts">
					<DropdownMenu
						className="components-iceberg-shortcuts__trigger"
						label={ __( 'Open shortcuts', 'iceberg' ) }
						icon={ icons.shortcuts }
						popoverProps={ POPOVER_PROPS }
						toggleProps={ TOGGLE_PROPS }
					>
						{ () => (
							<Fragment>
								{ shortcutConfig.map( ( config, index ) => (
									<ShortcutSection
										key={ index }
										{ ...config }
									/>
								) ) }
							</Fragment>
						) }
					</DropdownMenu>
				</div>
			</Fragment>
		);
	}