All files / client/components/Notification WatchButton.tsx

0% Statements 0/21
0% Branches 0/7
0% Functions 0/4
0% Lines 0/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75                                                                                                                                                     
import React from 'react'
import { withTranslation, WithTranslation } from 'react-i18next'
import { Button } from 'reactstrap'
import Icon from 'components/Common/Icon'
import Crowi from 'client/util/Crowi'
 
interface Props extends WithTranslation {
  pageId: string | null
  crowi: Crowi
}
 
interface State {
  watching: boolean
  isChanging: boolean
  creationError: boolean
}
 
class WatchButton extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props)
 
    this.state = {
      watching: false,
      isChanging: false,
      creationError: false,
    }
 
    this.watch = this.watch.bind(this)
  }
 
  async componentDidMount() {
    try {
      const { watching = false } = await this.props.crowi.apiGet('/pages.watch.status', { page_id: this.props.pageId })
      this.setState({ watching })
    } catch (err) {
      if (process.env.NODE_ENV === 'development') {
        console.error(err.message)
      }
    }
  }
 
  async watch() {
    const { crowi, pageId } = this.props
    const { watching } = this.state
    this.setState({ isChanging: true, creationError: false })
    try {
      const {
        ok,
        watcher: { status },
      } = await crowi.apiPost('/pages.watch', { page_id: pageId, status: !watching })
      if (ok) {
        this.setState({ watching: status === 'WATCH' })
      }
    } catch (err) {
      this.setState({ creationError: true })
    } finally {
      this.setState({ isChanging: false })
    }
  }
 
  render() {
    const { t } = this.props
    const { watching } = this.state
    const text = watching ? 'Watched' : 'Watch'
 
    return (
      <Button outline size="sm" onClick={this.watch} active={watching}>
        <Icon name="eye" /> {t(text)}
      </Button>
    )
  }
}
 
export default withTranslation()(WatchButton)