reactstrap#Spinner JavaScript Examples

The following examples show how to use reactstrap#Spinner. 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 gobench with Apache License 2.0 6 votes vote down vote up
render() {
    return (
      <div>
        <h5 className="mb-4">
          <strong>Default Progress</strong>
        </h5>
        <div className="mb-5">
          <Spinner color="primary" />
          <Spinner color="secondary" />
          <Spinner color="success" />
          <Spinner color="danger" />
          <Spinner color="warning" />
          <Spinner color="info" />
          <Spinner color="light" />
          <Spinner color="dark" />
        </div>
        <h5 className="mb-4">
          <strong>Growing Spinner</strong>
        </h5>
        <div className="mb-5">
          <Spinner type="grow" color="primary" />
          <Spinner type="grow" color="secondary" />
          <Spinner type="grow" color="success" />
          <Spinner type="grow" color="danger" />
          <Spinner type="grow" color="warning" />
          <Spinner type="grow" color="info" />
          <Spinner type="grow" color="light" />
          <Spinner type="grow" color="dark" />
        </div>
      </div>
    )
  }
Example #2
Source File: ProductPage.js    From mattress-store with MIT License 6 votes vote down vote up
ProductPage = props => {
    const { Id } = props.match.params;
    const [userProducts, dispatch] = useReducer(productsReducer, null);
    const {
        isLoading,
        error,
        responseData,
        sendRequest,
        values,
        reqIdentifer,
    } = useHttp();

    useEffect(() => {
        sendRequest(
            `http://localhost:3000/api/products/${Id}`,
            'GET',
            null,
            null,
            'GET_ONE_PRODUCT'
        );
    }, []);

    useEffect(() => {
        setTimeout(() => {
            dispatch({ type: 'SET', products: responseData });
        }, 2000);
    }, [responseData, values, reqIdentifer, isLoading, error]);

    let product = <Spinner color="primary" />;
    if (userProducts !== null)
        product = <ProductInfo productData={userProducts} />;

    return <div>{product}</div>;
}
Example #3
Source File: MainNav.js    From hivemind with Apache License 2.0 6 votes vote down vote up
navItems = {
  auth: [
    <NavItem key="mmaps">
      <Link href={'/mmaps'} passHref>
        <NavLink>Mind Maps</NavLink>
      </Link>
    </NavItem>,
  ],
  anon: [],
  unknown: [
    <NavItem key={'loading'}>
      <Spinner />
    </NavItem>,
  ],
}
Example #4
Source File: NavItemLogin.js    From hivemind with Apache License 2.0 6 votes vote down vote up
NavItemLogin = () => {
  const { user, logout } = useUser()

  return typeof user === 'undefined' ? (
    <NavItem>
      <NavbarText>
        <Spinner size={'sm'} />
      </NavbarText>
    </NavItem>
  ) : user ? (
    <NavItem>
      <NavLink href={'#'} onClick={logout}>
        <LogOut />
      </NavLink>
    </NavItem>
  ) : (
    <NavItem>
      <Link href={'/auth'} passHref>
        <NavLink>
          <LogIn />
        </NavLink>
      </Link>
    </NavItem>
  )
}
Example #5
Source File: NavItemUser.js    From hivemind with Apache License 2.0 6 votes vote down vote up
NavItemUser = () => {
  const { user } = useUser()

  return typeof user === 'undefined' ? (
    <NavItem>
      <NavbarText>
        <Spinner size={'sm'} />
      </NavbarText>
    </NavItem>
  ) : user ? (
    <NavItem>
      <NavbarText>{user.email}</NavbarText>
    </NavItem>

  ) : null
}
Example #6
Source File: ReindexDokus.jsx    From Edlib with GNU General Public License v3.0 6 votes vote down vote up
ReindexDokus = () => {
    const [{ loading, error, success }, setStatus] = React.useState({
        loading: false,
        error: false,
    });

    const onClick = React.useCallback(() => {
        setStatus({
            loading: true,
            error: false,
        });

        request('/dokus/v1/recommender/index-all', 'POST', { json: false })
            .then(() => {
                setStatus({
                    loading: false,
                    error: false,
                    success: true,
                });
            })
            .catch((error) => {
                setStatus({
                    loading: false,
                    error: true,
                });
            });
    }, []);

    return (
        <>
            {error && <Alert color="danger">Noe skjedde</Alert>}
            {success && <Alert color="success">Vellykket!</Alert>}
            <Button color="primary" onClick={onClick} disabled={loading}>
                {loading && <Spinner />}
                {!loading && 'Indekser dokus'}
            </Button>
        </>
    );
}
Example #7
Source File: index.js    From hivemind with Apache License 2.0 6 votes vote down vote up
Page = () => {
  const { user } = useUser()
  const router = useRouter()

  useEffect(() => {
    if (user) {
      router.replace('/mmaps')
    }
  }, [user, router])

  return typeof user === 'undefined' ? (
    <Spinner />
  ) : user ? (
    <p>Redirecting...</p>
  ) : (
    <AuthPrompt />
  )
}
Example #8
Source File: auth.js    From hivemind with Apache License 2.0 6 votes vote down vote up
Page = () => {
  const { user } = useUser()
  const router = useRouter()

  useEffect(() => {
    if (user) {
      router.replace('/')
    }
  }, [user, router])

  return typeof user === 'undefined' ? (
    <Spinner />
  ) : user ? (
    <p>Redirecting...</p>
  ) : (
    <FirebaseAuth />
  )
}
Example #9
Source File: Contacts.js    From ReactJS-Projects with MIT License 5 votes vote down vote up
Contacts = () => {
  const { state, dispatch } = useContext(ContactContext);

  const { contacts, isLoading } = state;

  const history = useHistory();

  const AddContact = () => {
    dispatch({
      type: CONTACT_TO_UPDATE,
      payload: null,
      key: null
    })
    history.push("/contact/add");
  };

  if (isLoading) {
    return (
      <div className="Center">
        <Spinner color="primary" />
        <div className="text-primary">Loading...</div>
      </div>
    );
  }

  return (
    <Container className="mt-4">
      {
        contacts.length === 0 && !isLoading ?
          (
            <div className="Center text-large text-primary">
              No Contacts Found.
            </div>
          )
          :
          (
            <ListGroup>
              {Object.entries(contacts).map(([key, value]) => (
                <ListGroupItem key={key}>
                  <Contact contact={value} contactKey={key} />
                </ListGroupItem>
              ))}
            </ListGroup>
          )
      }
      <MdAdd className="fab icon " onClick={AddContact} />
    </Container>
  );
}
Example #10
Source File: Login.js    From react-js-chat-webapp-example with MIT License 5 votes vote down vote up
function Login() {
    const history = useHistory();
    const [creds, setCreds] = useState({ nickname: '' });
    const [showLoading, setShowLoading] = useState(false);
    const ref = firebase.database().ref('users/');

    const login = (e) => {
        e.preventDefault();
        setShowLoading(true);
        ref.orderByChild('nickname').equalTo(creds.nickname).once('value', snapshot => {
            if (snapshot.exists()) {
                localStorage.setItem('nickname', creds.nickname);
                history.push('/roomlist');
                setShowLoading(false);
            } else {
                const newUser = firebase.database().ref('users/').push();
                newUser.set(creds);
                localStorage.setItem('nickname', creds.nickname);
                history.push('/roomlist');
                setShowLoading(false);
            }
        });
    };

    const onChange = (e) => {
        e.persist();
        setCreds({...creds, [e.target.name]: e.target.value});
    }

    return (
        <div>
            {showLoading &&
                <Spinner color="primary" />
            }
            <Jumbotron>
                <Form onSubmit={login}>
                    <FormGroup>
                        <Label>Nickname</Label>
                        <Input type="text" name="nickname" id="nickname" placeholder="Enter Your Nickname" value={creds.nickname} onChange={onChange} />
                    </FormGroup>
                    <Button variant="primary" type="submit">
                        Login
                    </Button>
                </Form>
            </Jumbotron>
        </div>
    );
}
Example #11
Source File: AddRoom.js    From react-js-chat-webapp-example with MIT License 5 votes vote down vote up
function AddRoom() {
    const history = useHistory();
    const [room, setRoom] = useState({ roomname: '' });
    const [showLoading, setShowLoading] = useState(false);
    const ref = firebase.database().ref('rooms/');

    const save = (e) => {
        e.preventDefault();
        setShowLoading(true);
        ref.orderByChild('roomname').equalTo(room.roomname).once('value', snapshot => {
            if (snapshot.exists()) {
                return (
                    <div>
                        <Alert color="primary">
                            Room name already exist!
                        </Alert>
                    </div>
                );
            } else {
                const newRoom = firebase.database().ref('rooms/').push();
                newRoom.set(room);
                history.goBack();
                setShowLoading(false);
            }
        });
    };

    const onChange = (e) => {
        e.persist();
        setRoom({...room, [e.target.name]: e.target.value});
    }

    return (
        <div>
            {showLoading &&
                <Spinner color="primary" />
            }
            <Jumbotron>
                <h2>Please enter new Room</h2>
                <Form onSubmit={save}>
                    <FormGroup>
                        <Label>Room Name</Label>
                        <Input type="text" name="roomname" id="roomname" placeholder="Enter Room Name" value={room.roomname} onChange={onChange} />
                    </FormGroup>
                    <Button variant="primary" type="submit">
                        Add
                    </Button>
                </Form>
            </Jumbotron>
        </div>
    );
}
Example #12
Source File: BlogsPage.js    From Website2020 with MIT License 5 votes vote down vote up
render() {
    console.log(this.state.blogsArray);
    const blogList = this.state.blogsArray.map((recievedBlog) => {
      return (
        // <h1>{recievedBlog.heading}</h1>
        <div>
          <Blog
            heading={recievedBlog.heading}
            author={recievedBlog.author}
            date={recievedBlog.date}
            bannerImage={recievedBlog.bannerImage}
            abstract={recievedBlog.abstract}
            id={recievedBlog.blogId}
          ></Blog>
        </div>
      );
    });

    // console.log(this.state.laoding)

    const display =
      this.state.loading == "true" ? (
        <Spinner className="blogs-page-spinner" />
      ) : (
        blogList
      );
    return (
      <>
        <ExamplesNavbar activePage="/blogs" />
        <div className="section text-center ">
          <Container className="reduce-margin">
            <Row>
              <h2 className="heading-main" style={{ fontSize: "4.3rem" }}>BLOGS</h2>
            </Row>
          </Container>
        </div>

        <div className="main">{display}</div>
      </>
    );
  }
Example #13
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 #14
Source File: RoomList.js    From react-js-chat-webapp-example with MIT License 4 votes vote down vote up
function RoomList() {
    const [room, setRoom] = useState([]);
    const [showLoading, setShowLoading] = useState(true);
    const [nickname, setNickname] = useState('');
    const history = useHistory();

    useEffect(() => {
        const fetchData = async () => {
            setNickname(localStorage.getItem('nickname'));
            firebase.database().ref('rooms/').on('value', resp => {
                setRoom([]);
                setRoom(snapshotToArray(resp));
                setShowLoading(false);
            });
        };
      
        fetchData();
    }, []);

    const snapshotToArray = (snapshot) => {
        const returnArr = [];

        snapshot.forEach((childSnapshot) => {
            const item = childSnapshot.val();
            item.key = childSnapshot.key;
            returnArr.push(item);
        });

        return returnArr;
    }

    const enterChatRoom = (roomname) => {
        const chat = { roomname: '', nickname: '', message: '', date: '', type: '' };
        chat.roomname = roomname;
        chat.nickname = nickname;
        chat.date = Moment(new Date()).format('DD/MM/YYYY HH:mm:ss');
        chat.message = `${nickname} enter the room`;
        chat.type = 'join';
        const newMessage = firebase.database().ref('chats/').push();
        newMessage.set(chat);

        firebase.database().ref('roomusers/').orderByChild('roomname').equalTo(roomname).on('value', (resp) => {
            let roomuser = [];
            roomuser = snapshotToArray(resp);
            const user = roomuser.find(x => x.nickname === nickname);
            if (user !== undefined) {
              const userRef = firebase.database().ref('roomusers/' + user.key);
              userRef.update({status: 'online'});
            } else {
              const newroomuser = { roomname: '', nickname: '', status: '' };
              newroomuser.roomname = roomname;
              newroomuser.nickname = nickname;
              newroomuser.status = 'online';
              const newRoomUser = firebase.database().ref('roomusers/').push();
              newRoomUser.set(newroomuser);
            }
        });
    
        history.push('/chatroom/' + roomname);
    }

    const logout = () => {
        localStorage.removeItem('nickname');
        history.push('/login');
    }

    return (
        <div>
            {showLoading &&
                <Spinner color="primary" />
            }
            <Jumbotron>
                <h3>{nickname} <Button onClick={() => { logout() }}>Logout</Button></h3>
                <h2>Room List</h2>
                <div>
                    <Link to="/addroom">Add Room</Link>
                </div>
                <ListGroup>
                    {room.map((item, idx) => (
                        <ListGroupItem key={idx} action onClick={() => { enterChatRoom(item.roomname) }}>{item.roomname}</ListGroupItem>
                    ))}
                </ListGroup>
            </Jumbotron>
        </div>
    );
}
Example #15
Source File: [key].js    From hivemind with Apache License 2.0 4 votes vote down vote up
Page = () => {
  const { user } = useUser()
  const router = useRouter()
  const [timestamp, setTimestamp] = useState(
    typeof window === 'undefined'
      ? null
      : parseFloat(new URLSearchParams(location.search).get('timestamp'))
  )
  const { key } = router.query
  const { data, error } = useFetch(
    user ? user : null,
    `/api/mindmaps/${key}?timestamp=${timestamp || ''}`
  )
  const { data: edata, error: eerror } = useFetch(
    user ? user : null,
    `/api/timeline/events?key=${key}`
  )
  const [title, setTitle] = useState(key)

  useEffect(() => {
    if (user) {
      mutate(
        [`/api/mindmaps/${key}?timestamp=${timestamp || ''}`, user.token],
        null,
        true
      )
    }
  }, [user, timestamp, key])

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

  useEffect(() => {
    if (data && data.ok) {
      setTitle(data.data.meta.name)
    }
  }, [data])

  useEffect(() => {
    const handleRouteChange = (url) => {
      const fullURL = new URL(url, location.origin)
      const toTs = fullURL.searchParams.get('timestamp')
      const toTsF = parseFloat(toTs) || null

      if ((!toTsF && timestamp) || toTsF !== timestamp) {
        setTimestamp(toTsF)
      }
    }

    router.events.on('routeChangeComplete', handleRouteChange)

    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events, timestamp])

  if (typeof user === 'undefined') {
    return <Spinner />
  }

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

    window.notify(options)
  }

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

    window.notify(options)
  }

  const gotEventData = !eerror && edata && edata.ok
  const cEvents = gotEventData && edata.data
  const prevDisabled = !gotEventData || timestamp === cEvents[0].lctime
  const nextDisabled = !gotEventData || timestamp === last(cEvents).lctime

  async function jump(to) {
    if (to === 'now') {
      await router.push('/mmaps/[key]', `/mmaps/${key}`, { shallow: true })
      setTimestamp(null)
    } else if (gotEventData) {
      let toTS, idx

      switch (to) {
        case 'first':
          toTS = cEvents[0].lctime
          break

        case 'prev':
          idx = timestamp
            ? findIndex(cEvents, { lctime: timestamp })
            : cEvents.length
          toTS = cEvents[idx - 1].lctime
          break

        case 'next':
          idx = timestamp
            ? findIndex(cEvents, { lctime: timestamp })
            : cEvents.length - 2
          toTS = cEvents[idx + 1].lctime
          break

        case 'last':
          toTS = last(cEvents).lctime
          break

        default:
          toTS = to
      }

      await router.push(
        '/mmaps/[key]',
        {
          pathname: `/mmaps/${key}`,
          query: { timestamp: toTS },
        },
        { shallow: true }
      )
      setTimestamp(toTS)
    }
  }

  if (user) {
    const output = [
      <Row key="title">
        <Col xs="auto" md={7}>
          <h3>
            {title}
            {timestamp ? (
              <>
                &nbsp;
                <small className={'text-muted'}>
                  {' '}
                  @ {new Date(timestamp * 1000).toLocaleString()}
                </small>
              </>
            ) : null}
          </h3>
        </Col>
        <Col xs="auto" md={5} className={'text-right'}>
          <ShowAll />
          <Fit />
          <Search />
          &nbsp;&nbsp;|&nbsp;
          <ToolTippedButton
            className="ml-1"
            outline
            color="secondary"
            id="tag"
            disabled={true}
            tooltip="Tag (Coming Soon)"
          >
            <Tag size={16} />
          </ToolTippedButton>
          <ToolTippedButton
            className="ml-1"
            outline
            color="secondary"
            id="first"
            disabled={prevDisabled}
            tooltip="First"
            onClick={() => jump('first')}
          >
            <SkipBack size={16} />
          </ToolTippedButton>
          <ToolTippedButton
            className="ml-1"
            outline
            color="secondary"
            id="prev"
            disabled={prevDisabled}
            tooltip="Previous"
            onClick={() => jump('prev')}
          >
            <Rewind size={16} />
          </ToolTippedButton>
          <ToolTippedButton
            className="ml-1"
            outline
            color="secondary"
            id="next"
            disabled={nextDisabled}
            tooltip="Next"
            onClick={() => jump('next')}
          >
            <FastForward size={16} />
          </ToolTippedButton>
          <ToolTippedButton
            className="ml-1"
            outline
            color="secondary"
            id="last"
            disabled={nextDisabled}
            tooltip="Last"
            onClick={() => jump('last')}
          >
            <SkipForward size={16} />
          </ToolTippedButton>
          &nbsp;&nbsp;|&nbsp;
          <Rename
            nameChangedCallBack={setTitle}
            disabled={!!timestamp}
            rootNode={get(data, ['data', 'meta'], {})}
          />
          <ToolTippedButton
            className="ml-1"
            outline
            color={timestamp ? 'secondary' : 'danger'}
            id="now"
            tooltip={timestamp ? 'Click to unlock' : 'Click to lock'}
            onClick={() => jump(timestamp ? 'now' : 'last')}
          >
            {timestamp ? <Lock size={16} /> : <Unlock size={16} />}
          </ToolTippedButton>
        </Col>
      </Row>,
    ]

    if (error && data) {
      output.push(
        <Row key="content">
          <Col>
            <Error statusCode={data.status} />
          </Col>
        </Row>
      )
    } else if (eerror && edata) {
      output.push(
        <Row key="content">
          <Col>
            <Error statusCode={edata.status} />
          </Col>
        </Row>
      )
    } else {
      output.push(
        <Row key="content">
          <Col>
            <MindMap
              data={data}
              edata={edata}
              timestamp={timestamp}
              jump={jump}
            />
          </Col>
        </Row>
      )
    }

    return output
  }

  return <AuthPrompt />
}
Example #16
Source File: edit.js    From hivemind with Apache License 2.0 4 votes vote down vote up
PopperCard = ({ el, poppers }) => {
  const data = el.data()
  const [coll] = data.id.split('/')
  const { user } = useUser()
  const [title, setTitle] = useState(data.title)
  const [summary, setSummary] = useState(data.summary || '')
  const [content, setContent] = useState(data.content || '')
  const [audio, setAudio] = useState(data.audio || '')
  const [spinnerDisplay, setSpinnerDisplay] = useState('d-none')
  const inputRef = useRef(null)

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus()
    }
  }, [])

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

    const rootId = el.cy().nodes().id()
    const key = rootId.split('/')[1]
    const { ok, data: result, status } = await fetcher(
      `/api/${coll}`,
      user.token,
      'PATCH',
      JSON.stringify({
        title,
        summary,
        content,
        audio,
        _id: data.id,
        _rev: data._rev,
      })
    )
    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 = 'Updated node!'
      options.type = 'success'
    } else {
      options.message = `Failed to update node! - ${JSON.stringify(
        result || status
      )}`
      options.type = 'danger'
    }

    if (window.notify) {
      window.notify(options)
    }
    setSpinnerDisplay('d-none')

    removePopper(el.id(), `popper-${el.id()}`, poppers)
  }
  const getChangeHandler = (setter) => (event) => setter(event.target.value)

  return (
    <Card className="border-dark">
      <CardBody>
        <CardTitle
          tag="h5"
          className="mw-100 mb-4"
          style={{ minWidth: '50vw' }}
        >
          Edit {data.title}
          <CloseButton
            divKey={`popper-${el.id()}`}
            popperKey={el.id()}
            poppers={poppers}
          />
        </CardTitle>
        <CardText tag="div">
          <Form onSubmit={handleSubmit}>
            <FormGroup>
              <Label for="title">Title</Label>
              <Input
                type="text"
                name="title"
                id="title"
                value={title}
                required
                maxLength="50"
                autoComplete="off"
                onChange={getChangeHandler(setTitle)}
                innerRef={inputRef}
              />
            </FormGroup>
            <FormGroup>
              <Label for="summary">Summary</Label>
              <Input
                type="text"
                name="summary"
                id="summary"
                value={summary}
                maxLength="100"
                autoComplete="off"
                onChange={getChangeHandler(setSummary)}
              />
            </FormGroup>
            <FormGroup>
              <Label for="summary">Content</Label>
              <Input
                type="textarea"
                name="content"
                id="content"
                value={content}
                onChange={getChangeHandler(setContent)}
              />
            </FormGroup>
            <FormGroup>
              <Label for="audio">Audio (URL)</Label>
              <Input
                type="url"
                name="audio"
                id="audio"
                value={audio}
                maxLength="2048"
                autoComplete="off"
                onChange={getChangeHandler(setAudio)}
              />
            </FormGroup>
            <Row form>
              <Col xs={'auto'}>
                <FormGroup>
                  <Button color="primary">
                    <Save /> Save
                  </Button>
                </FormGroup>
              </Col>
              <Col xs={'auto'}>
                <FormGroup>
                  <Spinner className={spinnerDisplay} />
                </FormGroup>
              </Col>
            </Row>
          </Form>
        </CardText>
      </CardBody>
    </Card>
  )
}
Example #17
Source File: add.js    From hivemind with Apache License 2.0 4 votes vote down vote up
PopperCard = ({ el, poppers }) => {
  const { user } = useUser()
  const [spinnerDisplay, setSpinnerDisplay] = useState('d-none')
  const [title, setTitle] = useState('')
  const inputRef = useRef(null)

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus()
    }
  }, [])

  const handleChange = (event) => {
    setTitle(event.target.value)
  }

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

    const rootId = el.cy().nodes().id()
    const key = rootId.split('/')[1]
    const { ok, data: result, status } = await fetcher(
      `/api/nodes?parentId=${el.id()}`,
      user.token,
      'POST',
      JSON.stringify({ title })
    )
    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 = 'Added node!'
      options.type = 'success'
    } else {
      options.message = `Failed to add node! - ${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' }}
        >
          Add Child Node{' '}
          <small className="text-muted">(of {el.data('title')})</small>
          <CloseButton
            divKey={`popper-${el.id()}`}
            popperKey={el.id()}
            poppers={poppers}
          />
        </CardTitle>
        <CardText tag="div" className="mw-100">
          <Form onSubmit={handleSubmit} inline>
            <FormGroup className="mb-2 mr-sm-2 mb-sm-0">
              <Input
                type="text"
                name="title"
                id="title"
                placeholder="Type a title and hit ⏎"
                value={title}
                onChange={handleChange}
                required
                maxLength="50"
                autoComplete="off"
                innerRef={inputRef}
              />
            </FormGroup>
            <FormGroup className={spinnerDisplay}>
              <Spinner />
            </FormGroup>
          </Form>
        </CardText>
      </CardBody>
    </Card>
  )
}
Example #18
Source File: Timeline.js    From hivemind with Apache License 2.0 4 votes vote down vote up
Timeline = ({ data, timestamp, jump }) => {
  const timelineRef = useRef()
  const timeline = useRef()
  const {
    cyWrapper: { cy, viewApi },
  } = useContext(GlobalContext)
  const [modal, setModal] = useState(false)
  const [target, setTarget] = useState('timeline')
  const [node, setNode] = useState(<Spinner />)
  const [showJump, setShowJump] = useState('d-block')
  const [showFind, setShowFind] = useState('d-none')
  const [items, setItems] = useState([])

  const toggle = () => setModal(!modal)
  const jumpTo = async (lctime) => {
    if (lctime !== timestamp) {
      jump(lctime)
    }

    setModal(false)
  }
  const locate = (item) => {
    if (item && item.event !== 'deleted') {
      const node = cy.$id(item.nid)

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

    setModal(false)
  }

  useEffect(() => {
    if (get(data, 'ok')) {
      setItems(
        data.data.map((event, idx) => ({
          id: idx,
          className: event.lctime === timestamp ? 'pinned' : '',
          title: event.event,
          content: '',
          start: event.lctime * 1000,
          style: `background-color: ${bgColors[event.event]};`,
          lctime: event.lctime,
          nid: event.nids[0] || event.mid,
          event: event.event,
        }))
      )
    }
  }, [data, timestamp])

  useEffect(() => {
    if (items.length) {
      if (timeline.current) {
        timeline.current.setItems(items)
      } else {
        const container = timelineRef.current
        if (container.firstChild) {
          container.removeChild(container.firstChild)
        }

        const margin = (items[items.length - 1].start - items[0].start) * 0.05
        const options = {
          width: '100%',
          height: '120px',
          type: 'box',
          stack: false,
          horizontalScroll: false,
          verticalScroll: false,
          cluster: {
            titleTemplate: '{count}',
            maxItems: 1,
            showStipes: true,
            fitOnDoubleClick: true,
          },
          max: items[items.length - 1].start + margin,
          min: items[0].start - margin,
          selectable: false,
          dataAttributes: ['id'],
          zoomMin: 60000,
        }

        timeline.current = new VisTimeline(container, items, options)
      }

      timeline.current.on('click', (properties) => {
        const { what, isCluster, item } = properties

        if (what === 'item' && !isCluster) {
          setNode(<Spinner />)
          setTarget(item)
          setModal(true)

          if (items[item].className === 'pinned') {
            setShowJump('d-none')

            if (items[item].event !== 'deleted') {
              setShowFind('d-block')
            }
          } else {
            setShowJump('d-block')
            setShowFind('d-none')
          }
        } else {
          setModal(false)
          setTarget('timeline')
        }
      })
      timeline.current.on('doubleClick', (properties) => {
        const { what, item, isCluster } = properties

        switch (what) {
          case 'background':
            timeline.current.fit()

            break
          case 'item':
            if (!isCluster) {
              timeline.current.focus(item)
            }

            break
        }
      })

      defer(() => { // To ensure focus/fit on first load.
        if (timestamp) {
          const idx = findIndex(items, { lctime: timestamp })
          timeline.current.focus(idx)
        } else {
          timeline.current.fit()
        }
      })
    }
  }, [items, timestamp])

  useEffect(
    () => () => {
      timeline.current.destroy()
      timeline.current = null
    },
    []
  )

  return (
    <div className={'border border-secondary rounded'}>
      <div id={'timeline'} ref={timelineRef} className={'m-1'} >
        <Spinner/>
      </div>
      <Modal
        isOpen={modal}
        toggle={toggle}
        fade={false}
        centered={true}
        size={'lg'}
        scrollable={true}
      >
        <ModalHeader toggle={toggle}>
          <b>{node}</b> | {get(items, [target, 'event'], 'NA')}{' '}
          {new Date(get(items, [target, 'start'], Date.now())).toLocaleString()}
        </ModalHeader>
        <ModalBody>
          {data && data.data[target] ? (
            <EventDetail event={data.data[target]} setNode={setNode} />
          ) : null}
        </ModalBody>
        <ModalFooter>
          <Button
            className={`ml-1 ${showJump}`}
            outline
            color="secondary"
            id="jump"
            onClick={() => jumpTo(items[target].lctime)}
          >
            <MapPin size={16} /> Jump
          </Button>
          &nbsp;
          <Button
            className={`ml-1 ${showFind}`}
            outline
            color="secondary"
            id="find"
            onClick={() => locate(items[target])}
          >
            <Search size={16} /> Find
          </Button>
          &nbsp;
          <ToolTippedButton
            className="ml-1"
            outline
            color="secondary"
            id="tag"
            disabled={true}
            tooltip={'Coming Soon'}
          >
            <Tag size={16} /> Tag
          </ToolTippedButton>
        </ModalFooter>
      </Modal>
    </div>
  )
}
Example #19
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 #20
Source File: Layout.js    From hivemind with Apache License 2.0 4 votes vote down vote up
Layout = ({ children }) => {
  const [isOpen, setOpen] = useState(false)
  const [dropdownOpen, setDropdownOpen] = useState(false)
  const { pageVars } = useContext(GlobalContext)
  const notifyRef = useCallback((node) => {
    if (typeof window !== 'undefined') {
      if (node) {
        window.notify = node.notificationAlert.bind(node)
      } else {
        window.notify = null
      }
    }
  }, [])

  function toggleCollapse() {
    setOpen(!isOpen)
  }

  function toggleDropdown() {
    setDropdownOpen(!dropdownOpen)
  }

  return (
    <Container fluid>
      <Head>
        <script type="text/javascript" src="/js/pace.min.js" async />
        <title>{pageVars.title}</title>
        <link
          rel="apple-touch-icon"
          sizes="57x57"
          href="/img/logo/apple-icon-57x57.png"
        />
        <link
          rel="apple-touch-icon"
          sizes="60x60"
          href="/img/logo/apple-icon-60x60.png"
        />
        <link
          rel="apple-touch-icon"
          sizes="72x72"
          href="/img/logo/apple-icon-72x72.png"
        />
        <link
          rel="apple-touch-icon"
          sizes="76x76"
          href="/img/logo/apple-icon-76x76.png"
        />
        <link
          rel="apple-touch-icon"
          sizes="114x114"
          href="/img/logo/apple-icon-114x114.png"
        />
        <link
          rel="apple-touch-icon"
          sizes="120x120"
          href="/img/logo/apple-icon-120x120.png"
        />
        <link
          rel="apple-touch-icon"
          sizes="144x144"
          href="/img/logo/apple-icon-144x144.png"
        />
        <link
          rel="apple-touch-icon"
          sizes="152x152"
          href="/img/logo/apple-icon-152x152.png"
        />
        <link
          rel="apple-touch-icon"
          sizes="180x180"
          href="/img/logo/apple-icon-180x180.png"
        />
        <link
          rel="icon"
          type="image/png"
          sizes="192x192"
          href="/img/logo/android-icon-192x192.png"
        />
        <link
          rel="icon"
          type="image/png"
          sizes="32x32"
          href="/img/logo/favicon-32x32.png"
        />
        <link
          rel="icon"
          type="image/png"
          sizes="96x96"
          href="/img/logo/favicon-96x96.png"
        />
        <link
          rel="icon"
          type="image/png"
          sizes="16x16"
          href="/img/logo/favicon-16x16.png"
        />
        <link rel="manifest" href="/img/logo/manifest.json" />
        <meta name="msapplication-TileColor" content="#ffffff" />
        <meta
          name="msapplication-TileImage"
          content="/img/logo/ms-icon-144x144.png"
        />
        <meta name="theme-color" content="#ffffff" />
      </Head>
      <Navbar color="inverse" light expand="md" className="border-bottom mb-2">
        <Link href="/" passHref>
          <ForwardedNavbarBrand className="text-wrap">
            <img
              src="/img/logo/Logo.svg"
              style={{ height: '35px' }}
              alt="Logo"
            />
            &nbsp;
          </ForwardedNavbarBrand>
        </Link>
        <NavbarToggler onClick={toggleCollapse} />
        <Collapse isOpen={isOpen} navbar>
          <MainNav />
          <Nav className="ml-auto" navbar>
            <NavItem>
              <NavbarText>
                <Spinner
                  type="grow"
                  color="dark"
                  id={'loading'}
                  className={'invisible mx-2'}
                />
              </NavbarText>
            </NavItem>
            <NavItemUser />
            <Dropdown
              nav
              inNavbar
              isOpen={dropdownOpen}
              toggle={toggleDropdown}
            >
              <DropdownToggle nav caret>
                <HelpCircle /> Help
              </DropdownToggle>
              <DropdownMenu right>
                <DropdownItem>
                  <Link href={'/help'} passHref>
                    <NavLink>
                      <Info /> User Guide
                    </NavLink>
                  </Link>
                </DropdownItem>
                <DropdownItem divider />
                <DropdownItem>
                  <NavLink
                    href={'https://github.com/adityamukho/hivemind/discussions'}
                    target="_blank"
                  >
                    <MessageCircle /> Ask a Question (Hivemind)
                  </NavLink>
                </DropdownItem>
                <DropdownItem>
                  <NavLink
                    href={'https://gitter.im/recallgraph/community'}
                    target="_blank"
                  >
                    <MessageCircle /> Ask a Question (RecallGraph)
                  </NavLink>
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>
            <NavItem>
              <NavLink
                href="https://github.com/adityamukho/hivemind"
                target="_blank"
              >
                <GitHub />
              </NavLink>
            </NavItem>
            <NavItemLogin />
          </Nav>
        </Collapse>
      </Navbar>
      <Container fluid>
        <NotificationAlert ref={notifyRef} />
        <Row>
          <Col>{children}</Col>
        </Row>
      </Container>
    </Container>
  )
}
Example #21
Source File: AddContact.js    From ReactJS-Projects with MIT License 4 votes vote down vote up
AddContact = () => {
  const { state, dispatch } = useContext(ContactContext)

  const { contactToUpdate, contactToUpdateKey } = state

  const history = useHistory()

  const [name, setName] = useState("")
  const [email, setEmail] = useState("")
  const [phoneNumber, setPhoneNumber] = useState("")
  const [address, setAddress] = useState("")
  const [isUploading, setIsUploading] = useState(false)
  const [downloadUrl, setDownloadUrl] = useState(null)
  const [star, setStar] = useState(false)
  const [isUpdate, setIsUpdate] = useState(false)

  useEffect(() => {
    if (contactToUpdate) {
      setName(contactToUpdate.name)
      setEmail(contactToUpdate.email)
      setPhoneNumber(contactToUpdate.phoneNumber)
      setAddress(contactToUpdate.address)
      setStar(contactToUpdate.star)
      setDownloadUrl(contactToUpdate.picture)
      setIsUpdate(true)
    }
  }, [contactToUpdate])

  const imagePicker = async e => {
    try {
      const file = e.target.files[0]

      var metadata = {
        contentType: file.type
      }

      let resizedImage = await readAndCompressImage(file, imageConfig)

      const storageRef = await firebase.storage().ref()
      var upload = storageRef.child('iamges/' + file.name).put(resizedImage, metadata)

      upload.on(
        firebase.storage.TaskEvent.STATE_CHANGED,
        snapshot => {
          setIsUploading(true)
          var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100

          switch (snapshot.state) {
            case firebase.storage.TaskState.PAUSED:
              setIsUploading(false)
              console.log('Uploading Paused.')
              break;
            case firebase.storage.TaskState.RUNNING:
              console.log('Uploading In Progress.')
              break;
            case firebase.storage.TaskState.FAILED:
              setIsUploading(false)
              console.log('Uploading Failed.')
              break;
            case firebase.storage.TaskState.SUCCESS:
              console.log('Uploading Successful.')
              break;
          }

          if (progress == 100) {
            setIsUploading(false);
            toast("Uploaded!", { type: "success" })
          }
        },
        error => {
          toast('Something went wrong.', { type: 'error' })
        }, () => {
          upload.snapshot.ref.getDownloadURL().then(downloadUrl => {
            setDownloadUrl(downloadUrl)
          }).catch(err => console.log(err))
        }

      )

    } catch (err) {
      console.log(err)
      toast('Something went wrong', { type: "error" })
    }
  }

  const addContact = async () => {
    try {
      firebase.database().ref('contacts/' + v4()).set({
        name,
        email,
        phoneNumber,
        address,
        picture: downloadUrl,
        star
      })
    } catch (err) {
      console.log(err)
    }
  }

  const updateContact = async () => {
    try {
      firebase.database().ref('contacts/' + contactToUpdateKey).set(
        {
          name,
          email,
          phoneNumber,
          address,
          picture: downloadUrl,
          star
        }
      )
    } catch (err) {
      console.log(err)
      toast('Failed to update', { type: 'error' })
    }
  }

  const handleSubmit = e => {
    e.preventDefault()
    isUpdate ? updateContact() : addContact()

    toast('Success', { type: 'success' })

    dispatch({
      type: CONTACT_TO_UPDATE,
      payload: null,
      key: null
    })

    history.push("/")
  }

  return (
    <Container fluid className="mt-5">
      <Row>
        <Col md="6" className="offset-md-3 p-2">
          <Form onSubmit={handleSubmit}>
            <div className="text-center">
              {isUploading ? (
                <Spinner type="grow" color="primary" />
              ) : (
                <div>
                  <label htmlFor="imagepicker" className="">
                    <img src={downloadUrl} alt="" className="profile" />
                  </label>
                  <input
                    type="file"
                    name="image"
                    id="imagepicker"
                    accept="image/*"
                    multiple={false}
                    onChange={e => imagePicker(e)}
                    className="hidden"
                  />
                </div>
              )}
            </div>

            <FormGroup>
              <Input
                type="text"
                name="name"
                id="name"
                placeholder="Name"
                value={name}
                onChange={e => setName(e.target.value)}
              />
            </FormGroup>
            <FormGroup>
              <Input
                type="email"
                name="email"
                id="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="Email"
              />
            </FormGroup>
            <FormGroup>
              <Input
                type="number"
                name="number"
                id="phonenumber"
                value={phoneNumber}
                onChange={e => setPhoneNumber(e.target.value)}
                placeholder="phone number"
              />
            </FormGroup>
            <FormGroup>
              <Input
                type="textarea"
                name="area"
                id="area"
                value={address}
                onChange={e => setAddress(e.target.value)}
                placeholder="address"
              />
            </FormGroup>
            <FormGroup check>
              <Label check>
                <Input
                  type="checkbox"
                  onChange={() => {
                    setStar(!star)
                  }}
                  checked={star}
                />{" "}
                <span className="text-right">Mark as Star</span>
              </Label>
            </FormGroup>
            <Button
              type="submit"
              color="primary"
              block
              className="text-uppercase"
            >
              {isUpdate ? "Update Contact" : "Add Contact"}
            </Button>
          </Form>
        </Col>
      </Row>
    </Container>
  )
}
Example #22
Source File: index.js    From hivemind with Apache License 2.0 3 votes vote down vote up
Page = () => {
  const { user } = useUser()
  const { data, error } = useFetch(user, '/api/mindmaps')
  const inputRef = useRef(null)
  const [name, setName] = useState('')
  const [spinnerDisplay, setSpinnerDisplay] = useState('d-none')
  const [popoverOpen, setPopoverOpen] = useState(false)

  const toggle = () => {
    setPopoverOpen(!popoverOpen)

    if (inputRef.current) {
      inputRef.current.focus()
    }
  }

  if (typeof user === 'undefined') {
    return <Spinner />
  }

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

    window.notify(options)
  }

  if (user) {
    const handleChange = (event) => setName(event.target.value)
    const handleSubmit = async (event) => {
      event.preventDefault()
      setSpinnerDisplay('d-block')
      const { data: result, ok } = await fetcher(
        '/api/mindmaps',
        user.token,
        'POST',
        JSON.stringify({ name })
      )
      const options = {
        place: 'tr',
        autoDismiss: 7,
      }

      if (ok) {
        options.message = 'Added mindmap!'
        options.type = 'success'
        setName('')
        mutate(['/api/mindmaps', user.token])
        setPopoverOpen(false)
      } else {
        options.message = `Failed to add mindmap! - ${JSON.stringify(result)}`
        options.type = 'danger'
      }

      setSpinnerDisplay('d-none')
      if (window.notify) {
        window.notify(options)
      }
    }

    const output = [
      <Row key="title">
        <Col xs="auto">
          <h3>My Mind Maps</h3>
        </Col>
        <Col xs="auto">
          <Button color="success" size="sm" id="create">
            <Plus /> Create
          </Button>
          <Popover
            placement="bottom"
            target="create"
            isOpen={popoverOpen}
            toggle={toggle}
          >
            <PopoverHeader>Create Mind Map</PopoverHeader>
            <PopoverBody>
              <Form onSubmit={handleSubmit} inline>
                <FormGroup className="mb-2 mr-sm-2 mb-sm-0">
                  <Input
                    type="text"
                    name="name"
                    id="name"
                    placeholder="Type a name and hit ⏎"
                    value={name}
                    onChange={handleChange}
                    required
                    maxLength="20"
                    autoComplete="off"
                    innerRef={inputRef}
                  />
                </FormGroup>
                <FormGroup className={spinnerDisplay}>
                  <Spinner />
                </FormGroup>
              </Form>
            </PopoverBody>
          </Popover>
        </Col>
      </Row>,
    ]

    output.push(
      <Row key="content">
        <Col>
          {data && !error ? <MindMaps data={data.data} /> : <Spinner />}
        </Col>
      </Row>
    )

    return output
  }

  return <AuthPrompt />
}
Example #23
Source File: Rename.js    From hivemind with Apache License 2.0 3 votes vote down vote up
export default function Rename({
  rootNode,
  nameChangedCallBack,
  disabled = false,
}) {
  const { user } = useUser()
  const [popoverOpen, setPopoverOpen] = useState(false)
  const [spinnerDisplay, setSpinnerDisplay] = useState('d-none')
  const [name, setName] = useState()
  const [rev, setRev] = useState()
  const inputRef = useRef(null)

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

    const { data: result, ok, status } = await fetcher(
      `/api/mindmaps`,
      user.token,
      'PATCH',
      JSON.stringify({
        name: name,
        _id: rootNode._id,
        _rev: rev,
      })
    )
    const options = {
      place: 'tr',
      autoDismiss: 7,
    }

    if (ok) {
      setRev(result._rev)
      mutate(
        [`/api/timeline/events?key=${rootNode._key}`, user.token],
        null,
        true
      )

      options.message = 'Renamed mindmap!'
      options.type = 'success'
      setPopoverOpen(false)

      if (nameChangedCallBack) {
        nameChangedCallBack(name)
      }
    } else {
      options.message = `Failed to rename mindmap! - ${JSON.stringify(
        result || status
      )}`
      options.type = 'danger'
    }

    setSpinnerDisplay('d-none')
    if (window.notify) {
      window.notify(options)
    }
  }

  useEffect(() => {
    setName(rootNode.name)
    setRev(rootNode._rev)
  }, [rootNode])

  useEffect(() => {
    if (popoverOpen && inputRef.current) {
      inputRef.current.focus()
    }
  }, [popoverOpen])

  return (
    <>
      <ToolTippedButton
        tooltip="Rename"
        className="ml-1"
        outline
        color={disabled ? 'secondary' : 'primary'}
        id="rename"
        disabled={disabled}
      >
        <Edit3 size={16} />
      </ToolTippedButton>
      <Popover
        target="rename"
        isOpen={popoverOpen}
        toggle={() => setPopoverOpen(!popoverOpen)}
        boundariesElement={'rename'}
        placement={'bottom-end'}
      >
        <PopoverHeader>
          Rename <small>{rootNode.name}</small>
        </PopoverHeader>
        <PopoverBody>
          <Card>
            <CardBody>
              <CardText tag="div">
                <Form onSubmit={handleSubmit} inline>
                  <FormGroup className="mb-2 mr-sm-2 mb-sm-0">
                    <Input
                      type="text"
                      name="name"
                      id="name"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      autoComplete="off"
                      required
                      innerRef={inputRef}
                    />
                    <Button
                      className="ml-1"
                      onSubmit={handleSubmit}
                      color="primary"
                      id="save"
                    >
                      <Save /> Save
                    </Button>
                  </FormGroup>
                  <FormGroup className={spinnerDisplay}>
                    <Spinner />
                  </FormGroup>
                </Form>
              </CardText>
            </CardBody>
          </Card>
        </PopoverBody>
      </Popover>
    </>
  )
}
Example #24
Source File: UiGeneral.js    From gedge-platform with Apache License 2.0 3 votes vote down vote up
render() {
        return (
            <React.Fragment>
                <div className="page-content">
                    <Container fluid>

                    <Breadcrumbs title="General" breadcrumbItems={this.state.breadcrumbItems} />
                    <Row>
                            <Col lg={12}>
                                <Card>
                                    <CardBody>
                                        <Row>
                                            <Col lg={6}>
                                                <div>
                                                    <h4 className="card-title">Badges</h4>
                                                    <p className="card-title-desc">Add any of the below mentioned modifier classes to change the appearance of a badge.</p>
                                                    <div>
                                                        <Badge color="primary" className="mr-1">Primary</Badge>
                                                        <Badge color="success" className="mr-1">Success</Badge>
                                                        <Badge color="info" className="mr-1">Info</Badge>
                                                        <Badge color="warning" className="mr-1">Warning</Badge>
                                                        <Badge color="danger" className="mr-1">Danger</Badge>
                                                        <Badge color="dark" className="mr-1">Dark</Badge>
                                                    </div>

                                                    <div className="mt-1">
                                                        <Badge className="badge-soft-primary mr-1">Primary</Badge>
                                                        <Badge className="badge-soft-success mr-1">Success</Badge>
                                                        <Badge className="badge-soft-info mr-1">Info</Badge>
                                                        <Badge className="badge-soft-warning mr-1">Warning</Badge>
                                                        <Badge className="badge-soft-danger mr-1">Danger</Badge>
                                                        <Badge className="badge-soft-dark mr-1">Dark</Badge>
                                                    </div>
                                                </div>
                                            </Col>
                                            <Col lg={6}>
                                                <div className="mt-4 mt-lg-0">
                                                    <h4 className="card-title">Pill badges</h4>
                                                    <p className="card-title-desc">Use the <code>.badge-pill</code> modifier class to make
                                                    badges more rounded (with a larger <code>border-radius</code>
                                                    and additional horizontal <code>padding</code>).
                                                    Useful if you miss the badges from v3.</p>
        
                                                    <div>
                                                        <Badge color="primary" pill className="mr-1">Primary</Badge>
                                                        <Badge color="success" pill className="mr-1">Success</Badge>
                                                        <Badge color="info" pill className="mr-1">Info</Badge>
                                                        <Badge color="warning" pill className="mr-1">Warning</Badge>
                                                        <Badge color="danger" pill className="mr-1">Danger</Badge>
                                                        <Badge color="dark" pill className="mr-1">Dark</Badge>
                                                    </div>

                                                    <div className="mt-1">
                                                        <Badge pill className="badge-soft-primary mr-1">Primary</Badge>
                                                        <Badge pill className="badge-soft-success mr-1">Success</Badge>
                                                        <Badge pill className="badge-soft-info mr-1">Info</Badge>
                                                        <Badge pill className="badge-soft-warning mr-1">Warning</Badge>
                                                        <Badge pill className="badge-soft-danger mr-1">Danger</Badge>
                                                        <Badge pill className="badge-soft-dark mr-1">Dark</Badge>
                                                    </div>
                                                </div>
                                            </Col>
                                        </Row>
                                       
                                    </CardBody>
                                </Card>
                                
                            </Col>
                        </Row>
                       
        
                        <Row>
                            <Col lg={6}>
                                <Card>
                                    <CardBody>
        
                                        <h4 className="card-title">Popovers</h4>
                                        <p className="card-title-desc">Add small overlay content, like those found in iOS, to any element for housing secondary information.</p>
        
                                        <div className="button-items">
                                            <Button type="button" color="light" id="Popovertop"  className="waves-effect mr-1" >
                                                Popover on top
                                            </Button>
                                            <Popover placement="top" isOpen={this.state.popovertop} target="Popovertop" toggle={this.toggletop}>
                                                <PopoverHeader>Popover Title</PopoverHeader>
                                                <PopoverBody>Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.</PopoverBody>
                                            </Popover>
            
                                            <Button type="button"  id="Popoverright"  color="light" className="waves-effect mr-1">
                                                Popover on right
                                            </Button>
                                            <Popover placement="right" isOpen={this.state.popoverright} target="Popoverright" toggle={this.toggleright}>
                                                <PopoverHeader>Popover Title</PopoverHeader>
                                                <PopoverBody>Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.</PopoverBody>
                                            </Popover>
            
                                            <Button type="button" id="Popoverbottom" color="light" className="waves-effect mr-1">
                                                Popover on bottom
                                            </Button>
                                            <Popover placement="bottom" isOpen={this.state.popoverbottom} target="Popoverbottom" toggle={this.togglebottom}>
                                                <PopoverHeader>Popover Title</PopoverHeader>
                                                <PopoverBody>Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.</PopoverBody>
                                            </Popover> 
            
                                            <Button type="button"  id="Popoverleft" color="light" className="waves-effect mr-1">
                                                Popover on left
                                            </Button>
                                            <Popover placement="left" isOpen={this.state.popoverleft} target="Popoverleft" toggle={this.toggleleft}>
                                                <PopoverHeader>Popover Title</PopoverHeader>
                                                <PopoverBody>Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.</PopoverBody>
                                            </Popover>
            
                                            <Button type="button" color="success" id="popover5" className="waves-effect waves-light">Dismissible popover</Button>
                                            <UncontrolledPopover trigger="focus" target="popover5" placement="right">
                                                <PopoverHeader>
                                                    Dismissible popover
                                                </PopoverHeader>
                                                <PopoverBody>
                                                    Vivamus sagittis lacus vel augue laoreet rutrum faucibus
                                                </PopoverBody>
                                            </UncontrolledPopover>
                                        </div>
        
                                    </CardBody>
                                </Card>
        
                            </Col>
        
                            <Col lg={6}>
                                <Card>
                                    <CardBody>
        
                                        <h4 className="card-title">Tooltips</h4>
                                        <p className="card-title-desc">Hover over the links below to see tooltips:</p>
        
                                        <div className="button-items">
                                            <Tooltip placement="top" isOpen={this.state.tttop} target="TooltipTop" toggle={() => this.setState({ tttop: !this.state.tttop })}>Hello world!</Tooltip>
                                            <Tooltip placement="right" isOpen={this.state.ttright} target="TooltipRight" toggle={() => this.setState({ ttright: !this.state.ttright })}>Hello world!</Tooltip>
                                            <Tooltip placement="bottom" isOpen={this.state.ttbottom} target="TooltipBottom" toggle={() => this.setState({ ttbottom: !this.state.ttbottom })}>Hello world!</Tooltip>
                                            <Tooltip placement="left" isOpen={this.state.ttleft} target="TooltipLeft" toggle={() => this.setState({ ttleft: !this.state.ttleft })}>Hello world!</Tooltip>

                                            <Button type="button" color="primary" className="mr-1" id="TooltipTop"> Tooltip on top</Button>
                                            <Button type="button" color="primary" className="mr-1" id="TooltipRight"> Tooltip on Right</Button>
                                            <Button type="button" color="primary" className="mr-1" id="TooltipBottom"> Tooltip on Bottom</Button>
                                            <Button type="button" color="primary" className="mr-1" id="TooltipLeft"> Tooltip on Left</Button>
                                            
                                        </div>
                                        
                                    </CardBody>
                                </Card>
        
                            </Col>
                        </Row>
                       
        
                        <Row>
                            <Col lg={12}>
                                <Card>
                                    <CardBody>
                                        <h4 className="card-title mb-4">Pagination</h4>
        
                                        <Row>
                                            <Col lg={6}>
                                                <h5 className="font-size-14">Default Example</h5>
                                                <p className="card-title-desc">Pagination links indicate a series of related content exists across multiple pages.</p>
        
                                                
                                                    <Pagination aria-label="Page navigation example">
                                                        <PaginationItem><PaginationLink href="#">Previous</PaginationLink></PaginationItem>
                                                        <PaginationItem><PaginationLink href="#">1</PaginationLink></PaginationItem>
                                                        <PaginationItem><PaginationLink href="#">2</PaginationLink></PaginationItem>
                                                        <PaginationItem><PaginationLink href="#">3</PaginationLink></PaginationItem>
                                                        <PaginationItem><PaginationLink href="#">Next</PaginationLink></PaginationItem>
                                                    </Pagination>
                                                
                
                                                
                                                    <Pagination aria-label="Page navigation example">
                                                        <PaginationItem>
                                                            <PaginationLink href="#" previous>
                                                                <i className="mdi mdi-chevron-left"></i>
                                                            </PaginationLink>
                                                        </PaginationItem>
                                                        <PaginationItem><PaginationLink href="#">1</PaginationLink></PaginationItem>
                                                        <PaginationItem><PaginationLink href="#">2</PaginationLink></PaginationItem>
                                                        <PaginationItem><PaginationLink href="#">3</PaginationLink></PaginationItem>
                                                        <PaginationItem>
                                                            <PaginationLink next>
                                                                <i className="mdi mdi-chevron-right"></i>
                                                            </PaginationLink>
                                                        </PaginationItem>
                                                    </Pagination>
                                                
            
                                            </Col>
        
                                            <Col lg={6}>
                                                <div className="mt-4 mt-lg-0">
                                                    <h5 className="font-size-14">Disabled and active states</h5>
                                                    <p className="card-title-desc">Pagination links are customizable for
                                                            different circumstances. Use <code>.disabled</code> for links that appear
                                                            un-clickable and <code>.active</code> to
                                                            indicate the current page.</p>
                
            
                                                    
                                                        <Pagination aria-label="Page navigation example">
                                                            <PaginationItem disabled>
                                                                <PaginationLink href="#" tabIndex="-1">Previous</PaginationLink>
                                                            </PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">1</PaginationLink></PaginationItem>
                                                            <PaginationItem active>
                                                                <PaginationLink href="#">2 <span className="sr-only">(current)</span></PaginationLink>
                                                            </PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">3</PaginationLink></PaginationItem>
                                                            <PaginationItem>
                                                                <PaginationLink href="#">Next</PaginationLink>
                                                            </PaginationItem>
                                                        </Pagination>
                    
                                                    
                                                        <Pagination aria-label="Page navigation example">
                                                            <PaginationItem disabled>
                                                                <PaginationLink><i className="mdi mdi-chevron-left"></i></PaginationLink>
                                                            </PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">1</PaginationLink></PaginationItem>
                                                            <PaginationItem active>
                                                                <PaginationLink>
                                                                    2
                                                                    <span className="sr-only">(current)</span>
                                                                </PaginationLink>
                                                            </PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">3</PaginationLink></PaginationItem>
                                                            <PaginationItem>
                                                                <PaginationLink href="#"><i className="mdi mdi-chevron-right"></i></PaginationLink>
                                                            </PaginationItem>
                                                        </Pagination>
                                                </div>
                                            </Col>
                                        </Row>
                                       
        
                                        <Row>
                                            <Col lg={6}>
                                                <div className="mt-4">
                                                    <h5 className="font-size-14">Sizing</h5>
                                                    <p className="card-title-desc">Fancy larger or smaller pagination? Add <code>.pagination-lg</code> or <code>.pagination-sm</code> for additional
                                                            sizes.</p>
                
                                                    
                                                        <Pagination size="lg" aria-label="Page navigation example">
                                                            <PaginationItem disabled>
                                                                <PaginationLink href="#" tabIndex="-1">Previous</PaginationLink>
                                                            </PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">1</PaginationLink></PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">2</PaginationLink></PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">3</PaginationLink></PaginationItem>
                                                            <PaginationItem>
                                                                <PaginationLink href="#">Next</PaginationLink>
                                                            </PaginationItem>
                                                        </Pagination>
                    
                                                    
                                                        <Pagination size="sm" aria-label="Page navigation example">
                                                            <PaginationItem disabled>
                                                                <PaginationLink href="#" tabIndex="-1">Previous</PaginationLink>
                                                            </PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">1</PaginationLink></PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">2</PaginationLink></PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">3</PaginationLink></PaginationItem>
                                                            <PaginationItem>
                                                                <PaginationLink href="#">Next</PaginationLink>
                                                            </PaginationItem>
                                                        </Pagination>
                                                </div>
                    
                                            </Col>
        
                                            <Col lg={6}>
                                                <div className="mt-4">
                                                    <h5 className="card-title">Alignment</h5>
                                                    <p className="card-title-desc">Change the alignment of pagination
                                                            components with flexbox utilities.</p>
                
                                                    
                                                        <Pagination aria-label="Page navigation example" listClassName="justify-content-center">
                                                            <PaginationItem disabled>
                                                                <PaginationLink href="#" tabIndex="-1">Previous</PaginationLink>
                                                            </PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">1</PaginationLink></PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">2</PaginationLink></PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">3</PaginationLink></PaginationItem>
                                                            <PaginationItem>
                                                                <PaginationLink href="#">Next</PaginationLink>
                                                            </PaginationItem>
                                                        </Pagination>
                    
                                                    
                                                        <Pagination aria-label="Page navigation example" listClassName="justify-content-end">
                                                            <PaginationItem disabled>
                                                                <PaginationLink href="#" tabIndex="-1">Previous</PaginationLink>
                                                            </PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">1</PaginationLink></PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">2</PaginationLink></PaginationItem>
                                                            <PaginationItem><PaginationLink href="#">3</PaginationLink></PaginationItem>
                                                            <PaginationItem>
                                                                <PaginationLink href="#">Next</PaginationLink>
                                                            </PaginationItem>
                                                        </Pagination>
                                                    
                                                </div>
                                            </Col>
                                        </Row>
                                       

                                        <Row className=" mt-4">
                                            <Col lg={6}>
                                                <h5 className="font-size-14">Rounded Example</h5>
                                                <p className="card-title-desc">Add <code>.pagination-rounded</code> for rounded pagination.</p>
        
                                                
                                                    <Pagination aria-label="Page navigation example" className="pagination-rounded">
                                                        <PaginationItem disabled>
                                                            <PaginationLink href="#" tabIndex="-1">Previous</PaginationLink>
                                                        </PaginationItem>
                                                        <PaginationItem><PaginationLink href="#">1</PaginationLink></PaginationItem>
                                                        <PaginationItem active>
                                                            <PaginationLink href="#">2 <span className="sr-only">(current)</span></PaginationLink>
                                                        </PaginationItem>
                                                        <PaginationItem><PaginationLink href="#">3</PaginationLink></PaginationItem>
                                                        <PaginationItem>
                                                            <PaginationLink href="#">Next</PaginationLink>
                                                        </PaginationItem>
                                                    </Pagination>
                
                                                
                                                    <Pagination aria-label="Page navigation example" className="pagination-rounded">
                                                        <PaginationItem disabled>
                                                            <span className="page-link"><i className="mdi mdi-chevron-left"></i></span>
                                                        </PaginationItem>
                                                        <PaginationItem><PaginationLink href="#">1</PaginationLink></PaginationItem>
                                                        <PaginationItem active>
                                                            <span className="page-link">
                                                                2
                                                                <span className="sr-only">(current)</span>
                                                            </span>
                                                        </PaginationItem>
                                                        <PaginationItem><PaginationLink href="#">3</PaginationLink></PaginationItem>
                                                        <PaginationItem>
                                                            <PaginationLink href="#"><i className="mdi mdi-chevron-right"></i></PaginationLink>
                                                        </PaginationItem>
                                                    </Pagination>
                                            </Col> 
                                        </Row>
                                       
                                    </CardBody>
                                </Card>
                                
                            </Col>
                        </Row>
                       
        
                        <Row>
                            <Col lg={6}>
                                <Card>
                                    <CardBody>
                                        <h4 className="card-title">Border spinner</h4>
                                        <p className="card-title-desc">Use the border spinners for a lightweight loading indicator.</p>
                                        <div>
                                        <Spinner className="mr-2" color="primary" />
                                        <Spinner className="mr-2" color="secondary" />
                                        <Spinner className="mr-2" color="success" />
                                        <Spinner className="mr-2" color="danger" />
                                        <Spinner className="mr-2" color="warning" />
                                        <Spinner className="mr-2" color="info" />
                                        <Spinner className="mr-2" color="light" />
                                        <Spinner className="mr-2" color="dark" />
                                        </div>
        
                                    </CardBody>
                                </Card>
                            </Col>
                            <Col lg={6}>
                                <Card>
                                    <CardBody>
                                        <h4 className="card-title">Growing spinner</h4>
                                        <p className="card-title-desc">If you don’t fancy a border spinner, switch to the grow spinner. While it doesn’t technically spin, it does repeatedly grow!</p>
                                        <div>
                                        <Spinner type="grow" className="mr-2" color="primary" />
                                        <Spinner type="grow" className="mr-2" color="secondary" />
                                        <Spinner type="grow" className="mr-2" color="success" />
                                        <Spinner type="grow" className="mr-2" color="danger" />
                                        <Spinner type="grow" className="mr-2" color="warning" />
                                        <Spinner type="grow" className="mr-2" color="info" />
                                        <Spinner type="grow" className="mr-2" color="light" />
                                        <Spinner type="grow" className="mr-2" color="dark" />
                                        </div>
        
                                    </CardBody>
                                </Card>
                            </Col>
                        </Row>
                    </Container>
                </div>
            </React.Fragment >
        );
    }