lodash#pick JavaScript Examples

The following examples show how to use lodash#pick. 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: apiConstants.js    From lens-extension-cc with MIT License 6 votes vote down vote up
apiCredentialTypes = Object.freeze(
  pick(apiResourceTypes, [
    // NOTE: these are KEYS from the apiResourceTypes map
    'OPENSTACK_CREDENTIAL',
    'AWS_CREDENTIAL',
    'EQUINIX_CREDENTIAL',
    'VSPHERE_CREDENTIAL',
    'AZURE_CREDENTIAL',
    'BYO_CREDENTIAL',
  ])
)
Example #2
Source File: ButtonLink.jsx    From v3-ui with MIT License 6 votes vote down vote up
export function ButtonLink(props) {
  let { children, as, href, onClick } = props

  const classes = getButtonClasses(props)

  const linkProps = pick(props, ['target', 'rel'])

  return (
    <Link href={href} as={as} scroll={false}>
      <a
        {...linkProps}
        className={classes}
        onClick={(e) => {
          e.stopPropagation()
          if (onClick) {
            onClick()
          }
        }}
      >
        {children}
      </a>
    </Link>
  )
}
Example #3
Source File: ButtonLink.jsx    From pooltogether-community-ui with MIT License 6 votes vote down vote up
export function ButtonLink(props) {
  let { children, as, href, disabled } = props

  const classes = getButtonClasses(props)

  const linkProps = pick(props, ['target', 'rel'])

  if (disabled) {
    return (
      <a {...linkProps} className={classes}>
        {children}
      </a>
    )
  } else if (!as) {
    return (
      <a {...linkProps} href={href} className={classes} onClick={(e) => e.stopPropagation()}>
        {children}
      </a>
    )
  } else {
    return (
      <Link href={href} as={as} scroll={false}>
        <a {...linkProps} className={classes} onClick={(e) => e.stopPropagation()}>
          {children}
        </a>
      </Link>
    )
  }
}
Example #4
Source File: NextScrollBehavior.browser.test.js    From next-router-scroll with MIT License 6 votes vote down vote up
describe('on route change complete', () => {
    it('should update prevContext and context', () => {
        Router.pathname = '/';
        Router.asPath = '/?foo=1';
        Router.query = { foo: '1' };

        const router1 = pick(Router, 'pathname', 'asPath', 'query');

        scrollBehavior = new NextScrollBehavior();

        Router.pathname = '/bar';
        Router.asPath = '/bar';
        Router.query = {};

        const router2 = pick(Router, 'pathname', 'asPath', 'query');

        Router.events.emit('routeChangeComplete');

        expect(scrollBehavior._context).toEqual({ location: expect.any(Location), router: router2 });
        expect(scrollBehavior._prevContext).toEqual({ location: expect.any(Location), router: router1 });
    });

    it('should not save scroll position', async () => {
        scrollBehavior = new NextScrollBehavior();

        Router.events.emit('routeChangeComplete');

        await sleep(50);

        expect(mockStateStorage.save).toHaveBeenCalledTimes(0);
    });
});
Example #5
Source File: ColGroup.jsx    From kube-design with MIT License 6 votes vote down vote up
render() {
    return (
      <TableContext.Consumer>
        {({ columns, rowSelection, expandedRowRender }) => (
          <colgroup>
            {rowSelection && <col width="12" />}
            {columns.map((column) => (
              <col
                key={column.key || column.dataIndex}
                {...pick(column, ["width"])}
              />
            ))}
            {expandedRowRender && <col width="12" />}
          </colgroup>
        )}
      </TableContext.Consumer>
    );
  }
Example #6
Source File: layout.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
layoutEdgesSelector = createSelector(
  [
    graphEdgesSelector,
    layoutNodesSelector,
    focusedNodesIdsSelector,
  ],
  (graphEdges, layoutNodes, focusedNodesIds) => (
    // Update the edges in the circular layout to link the nodes in a straight line.
    graphEdges.map((edge) => {
      const source = edge.get('source');
      const target = edge.get('target');
      if (includes(focusedNodesIds, source) || includes(focusedNodesIds, target)) {
        return edge.set('points', fromJS([
          pick(layoutNodes.get(source).toJS(), ['x', 'y']),
          pick(layoutNodes.get(target).toJS(), ['x', 'y']),
        ]));
      }
      return edge;
    })
  )
)
Example #7
Source File: zoomable-canvas.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
// Decides which part of the zoom state is cachable depending
  // on the horizontal/vertical degrees of freedom.
  cachableState(state = this.state) {
    const cachableFields = []
      .concat(this.props.fixHorizontal ? [] : ['scaleX', 'translateX'])
      .concat(this.props.fixVertical ? [] : ['scaleY', 'translateY']);

    return pick(state, cachableFields);
  }
Example #8
Source File: proxy-request.js    From mox with MIT License 6 votes vote down vote up
manualProxy = async (targetUrl: string, req: $Request): Promise<ManualProxyInfo> => {
  const requestBody = await defaultBodyHandler.serializeRequestBody(req);
  const details = pick(
    req,
    'httpVersion',
    'httpVersionMajor',
    'httpVersionMinor',
    'method',
    'url',
    'headers'
  );
  const gzip = details.headers?.['accept-encoding'] ? true : false;
  const opts = {
    ...details,
    headers: {
      ...details.headers,
      host: undefined,
      ...(requestBody != null ? { 'content-length': requestBody.length } : {}),
    },
    body: requestBody,
    method: details.method,
    gzip,
    url: targetUrl + req.url,
  };
  const proxyResponse = await new Promise<ManualProxyInfo>((resolve, reject) => {
    request(opts, (error, response, body) => {
      if (error) {
        reject(error);
      } else {
        resolve({ body, response });
      }
    });
  });
  return proxyResponse;
}
Example #9
Source File: InstructorEnrollmentList.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
componentDidUpdate(prevProps, prevState) {
    if (
      prevState.totalPages === 0 &&
      this.state.totalPages > prevState.totalPages
    ) {
      const pageMax = this.state.totalPages - 1;
      if (pageMax < this.state.page) {
        this.onPageChange(pageMax);
      }
    }

    setUrlParamsFromState(
      pick(this.state, ['inbox', 'page', 'sorted', 'filtered'])
    );
  }
Example #10
Source File: InstructorEnrollmentList.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
async componentDidMount() {
    try {
      const newState = getStateFromUrlParams(
        pick(this.state, [
          'inbox',
          'page',
          'sorted',
          'filtered',
          'previouslySelectedEnrollmentId',
        ])
      );
      this.setState(newState);
    } catch (e) {
      // silently fail, if the state from url is not properly formatted we do not apply url params
      console.error(e);
    }
  }
Example #11
Source File: apiConstants.js    From lens-extension-cc with MIT License 6 votes vote down vote up
apiCredentialKinds = Object.freeze(
  pick(apiKinds, [
    // NOTE: these are KEYS from the apiResourceTypes map
    'AWS_CREDENTIAL',
    'AZURE_CREDENTIAL',
    'BYO_CREDENTIAL',
    'EQUINIX_CREDENTIAL',
    'OPENSTACK_CREDENTIAL',
    'VSPHERE_CREDENTIAL',
  ])
)
Example #12
Source File: githubClient.js    From rate-repository-api with MIT License 6 votes vote down vote up
static fromHttpClientError(error) {
    const githubError = new GithubError('GitHub API request failed', {
      response: pick(error.response, [
        'status',
        'statusText',
        'headers',
        'data',
      ]),
    });

    githubError[HTTP_CLIENT_ERROR] = error;

    return githubError;
  }
Example #13
Source File: NextScrollBehavior.browser.js    From next-router-scroll with MIT License 5 votes vote down vote up
_createContext() {
        return { location, router: pick(Router, 'pathname', 'asPath', 'query') };
    }
Example #14
Source File: NextScrollBehavior.browser.test.js    From next-router-scroll with MIT License 5 votes vote down vote up
describe('constructor()', () => {
    beforeAll(() => {
        Object.defineProperty(navigator, 'userAgent', { value: navigator.userAgent, writable: true });
        Object.defineProperty(navigator, 'platform', { value: navigator.platform, writable: true });
    });

    it('should setup router', () => {
        const beforePopState = Router.beforePopState;

        scrollBehavior = new NextScrollBehavior();

        expect(Router.beforePopState).not.toBe(beforePopState);
    });

    it('should setup listeners', () => {
        scrollBehavior = new NextScrollBehavior();

        expect(window.addEventListener).toHaveBeenCalledTimes(1);
        expect(window.removeEventListener).toHaveBeenCalledTimes(0);
        expect(Router.events.on).toHaveBeenCalledTimes(1);
        expect(Router.events.off).toHaveBeenCalledTimes(0);
    });

    it('should forward shouldUpdateScroll to ScrollBehavior', () => {
        const shouldUpdateScroll = () => {};

        scrollBehavior = new NextScrollBehavior(shouldUpdateScroll);

        expect(scrollBehavior._shouldUpdateScroll).toBe(shouldUpdateScroll);
    });

    it('should set history.scrollRestoration to manual, even on Safari iOS', () => {
        // eslint-disable-next-line max-len
        navigator.userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/605.1';
        navigator.platform = 'iPhone';

        scrollBehavior = new NextScrollBehavior();

        expect(history.scrollRestoration).toBe('manual');
    });

    it('should set current context correctly', () => {
        Router.pathname = '/bar';
        Router.asPath = '/bar';
        Router.query = {};

        const router = pick(Router, 'pathname', 'asPath', 'query');

        scrollBehavior = new NextScrollBehavior();

        expect(scrollBehavior._context).toEqual({ location, router });
        expect(scrollBehavior._prevContext).toBe(null);
    });
});
Example #15
Source File: NextScrollBehavior.browser.test.js    From next-router-scroll with MIT License 5 votes vote down vote up
describe('updateScroll()', () => {
    it('should inject prevContext and context', () => {
        const shouldUpdateScroll = jest.fn(() => false);

        Router.pathname = '/';
        Router.asPath = '/?foo=1';
        Router.query = { foo: '1' };

        scrollBehavior = new NextScrollBehavior(shouldUpdateScroll);
        scrollBehavior.updateScroll();

        const router1 = pick(Router, 'pathname', 'asPath', 'query');

        expect(shouldUpdateScroll).toHaveBeenNthCalledWith(
            1,
            null,
            { location: expect.any(Location), router: router1 },
        );

        Router.pathname = '/bar';
        Router.asPath = '/bar';
        Router.query = {};

        Router.events.emit('routeChangeComplete');
        scrollBehavior.updateScroll();

        const router2 = pick(Router, 'pathname', 'asPath', 'query');

        expect(shouldUpdateScroll).toHaveBeenNthCalledWith(
            2,
            { location: expect.any(Location), router: router1 },
            { location: expect.any(Location), router: router2 },
        );
    });

    it('should shallow merge prevContext and context', () => {
        const shouldUpdateScroll = jest.fn(() => false);

        Router.pathname = '/';
        Router.asPath = '/?foo=1';
        Router.query = { foo: '1' };

        scrollBehavior = new NextScrollBehavior(shouldUpdateScroll);
        scrollBehavior.updateScroll({ foo: 'bar' }, { foz: 'baz' });

        const router = pick(Router, 'pathname', 'asPath', 'query');

        expect(shouldUpdateScroll).toHaveBeenNthCalledWith(
            1,
            { foo: 'bar' },
            { foz: 'baz', location: expect.any(Location), router },
        );
    });

    it('should call super', () => {
        const shouldUpdateScroll = jest.fn(() => false);

        scrollBehavior = new NextScrollBehavior(shouldUpdateScroll);
        scrollBehavior.updateScroll();

        expect(shouldUpdateScroll).toHaveBeenCalledTimes(1);
    });
});
Example #16
Source File: NextScrollBehavior.browser.test.js    From next-router-scroll with MIT License 5 votes vote down vote up
describe('registerElement()', () => {
    it('should inject context', () => {
        const element = document.createElement('div');
        const shouldUpdateScroll = jest.fn(() => false);

        scrollBehavior = new NextScrollBehavior(shouldUpdateScroll);
        scrollBehavior.registerElement('foo', element, shouldUpdateScroll);

        const router = pick(Router, 'pathname', 'asPath', 'query');

        expect(shouldUpdateScroll).toHaveBeenCalledTimes(1);
        expect(shouldUpdateScroll).toHaveBeenNthCalledWith(
            1,
            null,
            { location: expect.any(Location), router },
        );
    });

    it('should shallow merge context', () => {
        const element = document.createElement('div');
        const shouldUpdateScroll = jest.fn(() => false);

        scrollBehavior = new NextScrollBehavior(shouldUpdateScroll);
        scrollBehavior.registerElement('foo', element, shouldUpdateScroll, { foo: 'bar' });

        const router = pick(Router, 'pathname', 'asPath', 'query');

        expect(shouldUpdateScroll).toHaveBeenCalledTimes(1);
        expect(shouldUpdateScroll).toHaveBeenNthCalledWith(
            1,
            null,
            { foo: 'bar', location: expect.any(Location), router },
        );
    });

    it('should call super', () => {
        const element = document.createElement('div');

        scrollBehavior = new NextScrollBehavior();
        scrollBehavior.registerElement('foo', element);

        expect(scrollBehavior._scrollElements.foo).toBeTruthy();
    });
});
Example #17
Source File: Credential.js    From lens-extension-cc with MIT License 5 votes vote down vote up
/**
   * @constructor
   * @param {Object} params
   * @param {Object} params.data Raw data payload from the API.
   * @param {Namespace} params.namespace Namespace to which the object belongs.
   * @param {Cloud} params.cloud Reference to the Cloud used to get the data.
   */
  constructor({ data, namespace, cloud }) {
    super({
      data,
      namespace,
      cloud,
      // NOTE: BYOCredential objects do not have a `status` for some reason
      typeset:
        data.kind === apiCredentialKinds.BYO_CREDENTIAL
          ? pick(credentialTs, ['metadata', 'spec'])
          : credentialTs,
    });

    /** @member {string} region */
    Object.defineProperty(this, 'region', {
      enumerable: true,
      get() {
        return data.metadata.labels?.[apiLabels.KAAS_REGION] || null;
      },
    });

    /** @member {string} provider */
    Object.defineProperty(this, 'provider', {
      enumerable: true,
      get() {
        return data.metadata.labels?.[apiLabels.KAAS_PROVIDER] || null;
      },
    });

    /** @member {boolean} valid */
    Object.defineProperty(this, 'valid', {
      enumerable: true,
      get() {
        // NOTE: BYOCredential objects do not have a `status` for some reason
        return !!data.status?.valid;
      },
    });
  }
Example #18
Source File: index.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
getDynamicComponent() {
    const { context, template = {} } = this.props;
    let dynamicComponent = null;
    let props = {};
    // DynamicModal
    if (template.templateType === 'DynamicModal') {
      const otherProps = omit(this.props, dynamicComponentOmitProps);
      const configProps = omit(template, dynamicComponentOmitConfigProps);
      // 处理 Modal 的 afterSave 属性, afterHide, afterShow
      forEach(template.props, (v, k) => {
        switch (k) {
          case 'afterSave':
          case 'afterHide':
          case 'afterShow':
            if (template.props[k]) {
              if (isString(template.props[k]) && startsWith(template.props[k], contextPrefix)) {
                const attributePath = template.props[k].substr(5);
                Object.defineProperty(props, k, {
                  get: () => get(context, attributePath),
                  enumerable: true,
                });
              } else {
                props[k] = v;
              }
            }
            break;
          default:
            props[k] = v;
        }
      });
      forEach(otherProps, (v, k) => {
        props[k] = v;
      });
      forEach(configProps, (v, k) => {
        props[k] = v;
      });
    } else {
      props = this.dealCommonContainerProps();
    }
    // DynamicModal
    switch (template.templateType) {
      case 'DynamicForm':
        dynamicComponent = React.createElement(DynamicForm, props);
        break;
      case 'DynamicToolbar':
        dynamicComponent = React.createElement(DynamicToolbar, props);
        break;
      case 'DynamicSearchForm':
        dynamicComponent = React.createElement(DynamicSearchForm, props);
        break;
      case 'DynamicTable':
        dynamicComponent = React.createElement(DynamicTable, {
          ...props,
          ...pick(template.props, contextOmitDynamicTableProps),
        });
        break;
      case 'DynamicModal':
        dynamicComponent = React.createElement(DynamicModal, props);
        break;
      case 'DynamicTabs':
        dynamicComponent = React.createElement(DynamicTabs, props);
        break;
      default:
        dynamicComponent = null;
        break;
    }
    return dynamicComponent;
  }
Example #19
Source File: index.js    From hivemind with Apache License 2.0 4 votes vote down vote up
NodesAPI = async (req, res) => {
  const { token } = req.headers

  try {
    const claims = await verifyIdToken(token)
    const key = claims.uid
    const userId = `users/${key}`
    const nodeMetas = []

    let node, response, message, parentId, title
    switch (req.method) {
      case 'POST':
        parentId = req.query.parentId
        title = req.body.title

        if (await hasWriteAccess(parentId, userId)) {
          node = { title, createdBy: userId }
          response = await rg.post('/document/nodes', node)

          if (response.statusCode === 201) {
            node = response.body
            nodeMetas.push(node)

            const link = {
              _from: parentId,
              _to: node._id,
              createdBy: userId,
            }
            response = await rg.post('/document/links', link)
            if (response.statusCode === 201) {
              message = 'Node created.'
              nodeMetas.push(response.body)

              await recordCompoundEvent('created', userId, nodeMetas)
            } else {
              message = response.body

              await rg.delete(
                '/history/purge',
                { path: `/n/${node._id}` },
                { silent: true, deleteUserObjects: true }
              )
            }
          } else {
            message = response.body
          }

          return res.status(response.statusCode).json({ message })
        } else {
          return res.status(401).json({ message: 'Access Denied.' })
        }

      case 'PATCH':
        if (await hasWriteAccess(req.body._id, userId)) {
          node = pick(req.body, 'title', 'summary', 'content', 'audio', '_rev', '_id')
          node.lastUpdatedBy = userId

          response = await rg.patch('/document/nodes', node, {
            keepNull: false,
            ignoreRevs: false,
          })

          await recordCompoundEvent('updated', userId, [response.body])

          return res.status(response.statusCode).json(response.body)
        } else {
          return res.status(401).json({ message: 'Access Denied.' })
        }

      case 'DELETE':
        if (await hasDeleteAccess(req.body._id, userId)) {
          let query = aql`
            return merge(
              let nodes = flatten(
                for v, e in 1..${Number.MAX_SAFE_INTEGER}
                outbound ${req.body._id}
                graph 'mindmaps'
                
                return (
                    for node in [v, e]
                    
                    return keep(node, '_id', '_key', '_rev')
                )
              )
              
              for node in nodes
              let idParts = parse_identifier(node)
              collect coll = idParts.collection aggregate n = unique(node)
              
              return {[coll]: n}
            )
          `
          let cursor = await db.query(query)
          const data = await cursor.next()

          let coll = req.body._id.split('/')[0]
          if (!data[coll]) {
            data[coll] = []
          }
          data[coll].unshift(pick(req.body, '_id', '_key', '_rev'))

          query = aql`
            for v, e, p in 1
            inbound ${req.body._id}
            graph 'mindmaps'
            
            filter !p.vertices[0].isRoot
            
            return keep(e, '_id', '_key', '_rev')
          `
          cursor = await db.query(query)
          if (cursor.hasNext) {
            const incoming = await cursor.next()

            coll = incoming._id.split('/')[0]
            if (!data[coll]) {
              data[coll] = []
            }
            data[coll].unshift(incoming)
          }

          const nKeys = {}
          let failed = false
          for (const coll in data) {
            const nodes = data[coll]
            nKeys[coll] = []
            nKeys[coll].push(...map(nodes, '_key'))

            response = await rg.delete(`/document/${coll}`, nodes, {
              ignoreRevs: false,
            })

            if (response.statusCode === 200) {
              nodeMetas.push(...response.body)
            } else {
              const path = createNodeBracePath(nKeys)
              await rg.post('/document/_restore', { path }, { silent: true })
              failed = true

              break
            }
          }

          if (failed) {
            return res.status(500).json({ message: 'Failed to delete nodes.' })
          } else {
            await recordCompoundEvent('deleted', userId, nodeMetas)

            return res.status(200).json({ message: 'Nodes deleted.' })
          }
        } else {
          return res.status(401).json({ message: 'Access Denied.' })
        }
    }
  } catch (error) {
    console.error(error.message, error.stack)
    return res.status(401).json({ message: 'Access Denied.' })
  }
}
Example #20
Source File: del.js    From hivemind with Apache License 2.0 4 votes vote down vote up
PopperCard = ({ el, poppers }) => {
  const data = el.data()
  const { user } = useUser()
  const [spinnerDisplay, setSpinnerDisplay] = useState('d-none')

  const handleSubmit = async (event) => {
    event.preventDefault()
    setSpinnerDisplay('d-block')

    const rootId = el.cy().nodes().id()
    const key = rootId.split('/')[1]
    const data = cy2rg([pick(el.data(), 'id', '_rev', '_key')]).nodes[0]
    const { ok, data: result, status } = await fetcher(
      '/api/nodes',
      user.token,
      'DELETE',
      JSON.stringify(data)
    )
    const options = {
      place: 'tr',
      autoDismiss: 7,
    }

    if (ok) {
      mutate([`/api/timeline/events?key=${key}`, user.token], null, true)
      mutate([`/api/mindmaps/${key}?timestamp=`, user.token], null, true)

      options.message = 'Deleted node(s)!'
      options.type = 'success'
    } else {
      options.message = `Failed to delete node(s)! - ${JSON.stringify(
        result || status
      )}`
      options.type = 'danger'
    }

    if (window.notify) {
      window.notify(options)
    }

    setSpinnerDisplay('d-none')

    removePopper(el.id(), `popper-${el.id()}`, poppers)
  }

  return (
    <Card className="border-dark">
      <CardBody>
        <CardTitle
          tag="h5"
          className="mw-100 mb-4"
          style={{ minWidth: '50vw' }}
        >
          Delete {data.title}
          <CloseButton
            divKey={`popper-${el.id()}`}
            popperKey={el.id()}
            poppers={poppers}
          />
        </CardTitle>
        <CardText tag="div" className="mw-100">
          <p>
            Are you sure? This will remove the selected node and ALL its
            descendants!
          </p>
          <Form onSubmit={handleSubmit} inline>
            <Row form>
              <Col xs={'auto'}>
                <FormGroup>
                  <Button color="danger" onClick={handleSubmit}>
                    <Trash2 /> Delete
                  </Button>
                </FormGroup>
              </Col>
              <Col xs={'auto'}>
                <FormGroup>
                  <Button
                    color="secondary"
                    onClick={() =>
                      removePopper(el.id(), `popper-${el.id()}`, poppers)
                    }
                  >
                    <XCircle /> Cancel
                  </Button>
                </FormGroup>
              </Col>
              <Col xs={'auto'}>
                <FormGroup>
                  <Spinner className={spinnerDisplay} />
                </FormGroup>
              </Col>
            </Row>
          </Form>
        </CardText>
      </CardBody>
    </Card>
  )
}
Example #21
Source File: Search.js    From hivemind with Apache License 2.0 4 votes vote down vote up
export default function Search() {
  const { cyWrapper } = useContext(GlobalContext)
  const [data, setData] = useState([])
  const [modal, setModal] = useState(false)
  const { cy, viewApi } = cyWrapper

  const toggle = () => {
    const { cy } = cyWrapper

    setData(
      cy.nodes(':visible').map((node) => {
        const data = node.data()
        const path = getPath(node)
        const item = pick(data, 'id', 'title')
        item.path = path.join(' ⟶ ')
        item.depth = path.length - 1

        return item
      })
    )

    setModal(!modal)
  }

  const columns = [
    {
      dataField: 'title',
      text: 'Title',
      sort: true,
      filter: textFilter(),
    },
    {
      dataField: 'path',
      text: 'Path',
      sort: true,
      filter: textFilter(),
    },
    {
      dataField: 'depth',
      text: 'Depth',
      sort: true,
      filter: numberFilter(),
    },
  ]

  const selectRow = {
    mode: 'radio',
    clickToSelect: true,
    bgColor: '#00BFFF',
    onSelect: (row) => {
      const node = cy.$id(row.id)

      viewApi.zoomToSelected(node)
      viewApi.removeHighlights(cy.elements())
      viewApi.highlight(node)

      toggle()
    },
  }

  return (
    <>
      <ToolTippedButton
        tooltip="Search"
        className="ml-1"
        outline
        color="secondary"
        id="search"
        onClick={toggle}
      >
        <SearchIcon size={16} />
      </ToolTippedButton>
      <Modal
        isOpen={modal}
        toggle={toggle}
        style={{ minWidth: '50vw', maxWidth: '90vw' }}
        fade={false}
      >
        <ModalHeader toggle={toggle}>
          Search <small className="text-muted">(Jump to Node)</small>
        </ModalHeader>
        <ModalBody>
          <BootstrapTable
            bootstrap4
            keyField="id"
            data={data}
            columns={columns}
            hover
            condensed
            selectRow={selectRow}
            filter={filterFactory()}
            wrapperClasses="search"
            defaultSorted={[{ dataField: 'depth', order: 'asc' }]}
            defaultSortDirection={'asc'}
          />
        </ModalBody>
      </Modal>
    </>
  )
}
Example #22
Source File: EventDetail.js    From hivemind with Apache License 2.0 4 votes vote down vote up
EventDetail = ({ event, setNode }) => {
  const { user } = useUser()
  const { data, error } = useFetch(user, getDiffURL(event))
  const diffRef = useRef(null)

  if (error && window.notify) {
    const options = {
      place: 'tr',
      message: 'Failed to fetch event details!',
      type: 'danger',
      autoDismiss: 7,
    }

    window.notify(options)
  }

  useEffect(() => {
    const container = diffRef.current

    if (!error && data && data.ok) {
      const diff = data.data
      let contents, node, baseText, newText

      switch (event.event) {
        case 'updated':
          baseText = JSON.stringify(
            omitBy(
              pick(diff.v1, 'name', 'title', 'summary', 'content', 'audio'),
              isEmpty
            ),
            null,
            2
          )
          newText = JSON.stringify(
            omitBy(
              pick(diff.v2, 'name', 'title', 'summary', 'content', 'audio'),
              isEmpty
            ),
            null,
            2
          )
          contents = difflib.buildView({
            baseText,
            newText,
            baseTextName: 'Previous Version',
            newTextName: 'This Version',
            inline: false,
          })

          if (diff.v1.title !== diff.v2.title) {
            node = `${diff.v1.title} : ${diff.v2.title}`
          } else {
            node = diff.v1.title
          }

          break

        case 'created':
        case 'restored':
          node = diff.v2.title
          contents = document.createElement('span')
          contents.innerHTML = `<b>Title:</b> ${diff.v2.title}`

          break

        case 'deleted':
          node = `[${diff.v1.length} item(s)]`
          contents = document.createElement('div')
          diff.v1.forEach((d) => {
            const rows = document.createElement('div')
            rows.classNames = ['row']

            const title = document.createElement('div')
            title.classNames = ['row']
            title.innerHTML = `<b>Title:</b> ${d.title}`
            rows.appendChild(title)

            if (d.summary) {
              const summary = document.createElement('div')
              summary.classNames = ['row']
              summary.innerHTML = `<b>Summary:</b> ${d.summary}`
              rows.appendChild(summary)
            }

            if (d.content) {
              const content = document.createElement('div')
              content.classNames = ['row']
              content.innerHTML = `<b>Content:</b> ${d.content}`
              rows.appendChild(content)
            }
            
            if (d.audio) {
              const content = document.createElement('div')
              audio.classNames = ['row']
              audio.innerHTML = `<b>Audio:</b> ${d.content}`
              rows.appendChild(content)
            }

            contents.appendChild(rows)
            contents.appendChild(document.createElement('hr'))
          })

          break

        default:
          contents = document.createTextNode('WTF!')
          node = 'WTF!'
      }
      setNode(node)

      if (container.firstChild) {
        container.replaceChild(contents, container.firstChild)
      } else {
        container.appendChild(contents)
      }
    } else {
      ReactDOM.render(<Spinner />, container)
    }
  }, [data, error, event, setNode])

  return <div id={'diff'} ref={diffRef} />
}
Example #23
Source File: index.js    From strapi-plugins with MIT License 4 votes vote down vote up
AuthPage = ({
  hasAdminUser,
  // -- add locationState from location props
  location: { search, state: locationState },
  // -- --- --
  match: {
    params: { authType },
  },
}) => {
  const [reducerState, dispatch] = useReducer(reducer, initialState);
  const codeRef = useRef();
  const abortController = new AbortController();

  const { signal } = abortController;
  codeRef.current = getQueryParameters(search, 'code');

  // -- small hack if coming from logout
  // -- for Strapi to reload content-types
  const history = useHistory();

  useEffect(() => {
    if (locationState && locationState.reload) {
      history.replace({
        pathname: `/auth/${authType}`,
        state: {},
      });

      window.location.reload();
    }
  }, []);
  // -- --- --

  useEffect(() => {
    // Set the reset code provided by the url
    if (authType === 'reset-password') {
      dispatch({
        type: 'ON_CHANGE',
        keys: ['code'],
        value: codeRef.current,
      });
    } else {
      // Clean reducer upon navigation
      dispatch({
        type: 'RESET_PROPS',
      });
    }

    return () => {
      abortController.abort();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [authType, codeRef]);
  const { didCheckErrors, errors, modifiedData, submitSuccess, userEmail } = reducerState.toJS();
  const handleChange = ({ target: { name, value } }) => {
    dispatch({
      type: 'ON_CHANGE',
      keys: name.split('.'),
      value,
    });
  };

  const handleSubmit = async e => {
    e.preventDefault();
    const schema = forms[authType].schema;
    let formErrors = {};

    try {
      await schema.validate(modifiedData, { abortEarly: false });

      if (modifiedData.news === true) {
        request('https://analytics.strapi.io/register', {
          method: 'POST',
          body: pick(modifiedData, ['email', 'username']),
          signal,
        }).catch(() => {
          // ignore error
        });
      }

      try {
        const requestEndPoint = forms[authType].endPoint;
        const requestURL = `/admin/auth/${requestEndPoint}`;
        const body = omit(modifiedData, 'news');

        if (authType === 'forgot-password') {
          set(body, 'url', `${strapi.remoteURL}/auth/reset-password`);
        }

        const { jwt, user, ok } = await request(requestURL, {
          method: 'POST',
          body,
          signal,
        });

        if (authType === 'forgot-password' && ok === true) {
          dispatch({
            type: 'SUBMIT_SUCCESS',
            email: modifiedData.email,
          });
        } else {
          auth.setToken(jwt, modifiedData.rememberMe);
          auth.setUserInfo(user, modifiedData.rememberMe);
        }
      } catch (err) {
        const formattedError = formatErrorFromRequest(err);

        if (authType === 'login') {
          formErrors = {
            global: formattedError,
            identifier: formattedError,
            password: formattedError,
          };
        } else if (authType === 'forgot-password') {
          formErrors = { email: formattedError[0] };
        } else {
          strapi.notification.error(get(formattedError, '0.id', 'notification.error'));
        }
      }
    } catch (err) {
      formErrors = getYupInnerErrors(err);
    }

    dispatch({
      type: 'SET_ERRORS',
      formErrors,
    });
  };

  // Redirect the user to the login page if the endpoint does not exist
  if (!Object.keys(forms).includes(authType)) {
    return <Redirect to="/" />;
  }

  // Redirect the user to the homepage if he is logged in
  if (auth.getToken()) {
    return <Redirect to="/" />;
  }

  if (!hasAdminUser && authType !== 'register') {
    return <Redirect to="/auth/register" />;
  }

  // Prevent the user from registering to the admin
  if (hasAdminUser && authType === 'register') {
    return <Redirect to="/auth/login" />;
  }

  const globalError = get(errors, 'global.0.id', '');
  const shouldShowFormErrors = !isEmpty(globalError);

  return (
    <>
      <PageTitle title={upperFirst(authType)} />
      <Wrapper authType={authType} withSuccessBorder={submitSuccess}>
        <NavTopRightWrapper>
          <LocaleToggle isLogged className="localeDropdownMenuNotLogged" />
        </NavTopRightWrapper>
        <div className="wrapper">
          <div className="headerContainer">
            {authType === 'register' ? (
              <FormattedMessage id="Auth.form.header.register" />
            ) : (
                <img src={LogoStrapi} alt="strapi-logo" />
              )}
          </div>
          <div className="headerDescription">
            {authType === 'register' && <FormattedMessage id="Auth.header.register.description" />}
          </div>
          {/* TODO Forgot success style */}
          <div className="formContainer bordered">
            <form onSubmit={handleSubmit}>
              <div className="container-fluid">
                {shouldShowFormErrors && (
                  <div className="errorsContainer">
                    <FormattedMessage id={globalError} />
                  </div>
                )}
                <div className="row" style={{ textAlign: 'start' }}>
                  {submitSuccess && (
                    <div className="forgotSuccess">
                      <FormattedMessage id="Auth.form.forgot-password.email.label.success" />
                      <br />
                      <p>{userEmail}</p>
                    </div>
                  )}
                  {!submitSuccess &&
                    forms[authType].inputs.map((row, index) => {
                      return row.map(input => {
                        return (
                          <Input
                            {...input}
                            autoFocus={index === 0}
                            didCheckErrors={didCheckErrors}
                            errors={errors}
                            key={input.name}
                            noErrorsDescription={shouldShowFormErrors}
                            onChange={handleChange}
                            value={modifiedData[input.name]}
                          />
                        );
                      });
                    })}
                  <div
                    className={`${
                      authType === 'login' ? 'col-6 loginButton' : 'col-12 buttonContainer'
                      }`}
                  >
                    <Button
                      color="primary"
                      className={submitSuccess ? 'buttonForgotSuccess' : ''}
                      type="submit"
                      style={authType === 'login' ? {} : { width: '100%' }}
                    >
                      <FormattedMessage
                        id={`Auth.form.button.${
                          submitSuccess ? 'forgot-password.success' : authType
                          }`}
                      />
                    </Button>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <div className="linkContainer">
            {authType !== 'register' && authType !== 'reset-password' && (
              <Link to={`/auth/${authType === 'login' ? 'forgot-password' : 'login'}`}>
                <FormattedMessage
                  id={`Auth.link.${authType === 'login' ? 'forgot-password' : 'ready'}`}
                />
              </Link>
            )}
          </div>
          {authType === 'register' && (
            <div className="logoContainer">
              <img src={LogoStrapi} alt="strapi-logo" />
            </div>
          )}
        </div>
      </Wrapper>
    </>
  );
}