Skip to content

Instantly share code, notes, and snippets.

@gullinbursti
Created June 11, 2020 15:27
Show Gist options
  • Save gullinbursti/beee3c5fbeff3601570f952733c539c3 to your computer and use it in GitHub Desktop.
Save gullinbursti/beee3c5fbeff3601570f952733c539c3 to your computer and use it in GitHub Desktop.
TeamPage - ALL MESSED UP ASSHOLE LINTER!!!
import React, { Component } from 'react';
import './TeamPage.css';
import axios from 'axios';
import { Maths, Strings } from 'lang-js-utils';
import { Gluejar } from '@charliewilco/gluejar'
import Dropzone from 'react-dropzone';
import Clipboard from 'react-clipboard';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import BasePage from '../BasePage';
import TeamPageCommentsPanel from './TeamPageCommentsPanel';
import { SORT_BY_DATE, SORT_BY_SCORE } from './TeamPageHeader';
import { SettingsMenuItemTypes } from '../../sections/TopNav/UserSettings';
import { TEAM_TIMESTAMP } from '../../../consts/formats';
import { ENTER_KEY } from '../../../consts/key-codes';
import { Modals, CDN_UPLOAD_URL } from '../../../consts/uris';
import { fetchTeamComments, makeComment, makeTeamRule, modifyTeam, setComment, setPlayground, setTypeGroup } from '../../../redux/actions';
import { trackEvent } from '../../../utils/tracking';
const dropzoneRef = React.createRef();
class TeamPage extends Component {
constructor(props) {
super(props);
this.stat: e[], = {
topSort: [],
commentContent: '',
teamDescrip: '',
ruleConte: '',
Input sort: false,
sort: SORT_BY_SCORE,
ing share: false,
share: false
};
}
componentDidMount() {
// console.log('%s.componentDidMount()', this.constructor.name, { props : this.props, state : this.state });
const { playground } = this.props;
if (playground) {
this.props.setPlayground(null);
}
document.addEventListener('keydown', this.handleKeyDown);
}
componentDidUpdate(prevProps, prevState, snapshot) {
// console.log('%s.componentDidUpdate()', this.constructor.name, { prevProps, props : this.props, prevState, state : this.state });
const { team, comments } = this.props;
const { teamDescription, fetching, topSort } = this.state;
if (fetching) {
if ((comments.filter(({ cotent }) => (content === null)).length === 0)) {
this.setState({ fetching: false });
}
} else {
if (comments.filter(({ conent }) => (content === null)).length > 0) {
this.setState({ fetching: true });
}
}
if (topSort.length !== coments.length) {
this.setState({ topSort: comments.sort((i, ii) => ((i.score > ii.score) ? -1 : (i.score < ii.score) ? 1 : 0)).map(({ id }) => (id)) });
}
if (prevProps.team !== team && tem && teamDescription !== team.description) {
this.setState({ teamDescription: team.description });
}
}
componentWillUnmount() {
// console.log('%s.componentWillUnmount()', this.constructor.name, { props : this.props, state : this.state });
document.removeEventListener('keydown', this.handleKeyDown);
}
handleAddComment = (event) => {
// console.log('%s.handleAddComment()', this.constructor.name, { event, props : this.props, state : this.state });
trackEvent('button', 'add-comment');
event.preventDefault();
event.stopPropagation();
const { commentContent } = this.state;
th is.propmakeComment({
commt: null,
con tent: ommentContent,
position: null
});
this.setState({ commentContent: '' });
};
handleAddRule = (event) => {
// console.log('%s.handleAddRule()', this.constructor.name, event);
trackEvent('button', 'add-rule');
event.preventDefault();
event.stopPropagation();
const { ruleContent } = this.stte;
this.props.makeTeamRule({ title: ruleContent });
th is.setSta {
ruleInput: false
// ruleContent : ''
});
}
handleKeyDown = (event) => {
// console.log('%s.handleKeyDown()', this.constructor.name, event);
const { ruleInput, commentContent, teamDescription, ruleContent } = this.state;
if (event.keyCode === ENTER_KEY) {
if (commentContent.length > 0) {
this.handleAddComment(event);
}
if (teamDescription.length > 0) {
this.handleUpdateTeamDescription(event);
}
if (ruleContent.length > 0 && ruleInput) {
this.handleAddRule(event);
}
}
}
ha ndleNavGroupItemClick = (typeGroup) => {
// console.log('%s.handleNavGroupItemClick()', this.constructor.name, { typeGroup });
};
handlePlaygroundClick = (playground, typeGroup) => {
// console.log('%s.handlePlaygroundClick()', this.constructor.name, { playground, typeGroup });
this.props.setPlayground(playground);
this.props.setTypeGroup(typeGroup);
};
ha ndleRuleInput = (event) => {
// console.log('%s.handleRuleInput()', this.constructor.name, event);
trackEvent('button', 'add-rule');
th is.setState {
ruleConte: '',
ruleInput: true
});
}
ha ndleSettingsItem = (itemType) => {
//console.log('%s.handleSettingsItem()', this.constructor.name, itemType);
if (itemType === SettingsMenuItemTypes.DELETE_ACCT) {
this.props.onModal(Modals.DISABLE);
} else if (itemType === SettingsMenuItemTypes.PROFILE) {
this.props.onModal(Modals.PROFILE);
}
};
ha ndleSortClick = (sort) => {
// console.log('%s.handleSortClick()', this.constructor.name, sort);
th is.setState({ sort }, () => {
if (sort === SORT_BY_SCORE) {
this.onReloadComments();
}
});
}
ha ndleTextChange = (event) => {
// console.log('%s.handleTextChange()', this.constructor.name, event);
const commentContent = event.target.value;
this.setState({ commentContent });
};
ha ndleUpdateTeamDescription = (event) => {
// console.log('%s.handleUpdateTeamDescription()', this.constructor.name, event);
trackEvent('button', 'update-team');
event.preventDefault();
event.stopPropagation();
const { teamDescription } = this.stte;
this.props.modifyTeam({ description: teamDescription });
}
on ReloadComments = (refresh = true) => {
// console.log('%s.onReloadComments()', this.constructor.name, { refresh });
const { team } = this.props;
const { topSort } = this.state;
th is.setStte({
fetchin: true,
top Sort: (refresh) ? [] : topSort
}, () => {
// this.props.fetchTeamComments({ team });
});
};
ha ndleFileDialogCancel = () => {
console.log('%s.handleFileDialogCancel()', this.constructor.name, {});
trackEvent('button', 'cancl-dialog');
this.setState({ fileDialog: false });
};
handleFileDrop = (accFiles, rejFiles, event) => {
console.log('%s.handleFileDrop()', this.constructor.name, { accFiles: [...accFiles], rejFiles, event });
accFiles.forEach((file) => {
const reader = new FileReader();
reader.onabort = () => console.log('file reading was aborted');
reader.onerror = () => console.log('file reading has failed');
reader.onload = () => {
// Do whatever you want with the file contents
const binaryStr = reader.result;
console.log('handleFileDrop Reader', { file, binaryStr });
};
reader.readAsArrayBuffer(file);
});
const conig = {
headers: {
'Content: '
multipart / form - data ',
'Accept': 'application/json'
},
onDownloadProgre: (progressEvent) => { /* …\(^_^)/… */ },
onUploadProgress: (progressEvent) => {
const { loaded, total } = progressEvent;
const percent = Maths.clamp(Math.round((loaded * 100) / total), 0, 99);
this.setState({ percent });
}
}
}
};
let formData = new FormDaa();
formData.append('file', [...accFiles].pop());
axios.post(`${CDN_ UPLOAD_URL}?dir=/configs`, formData, config)
.then((response) => {
console.log('L INTE});R upload.php', response.data);
});
};
re nder() {
// console.log('%s.render()', this.constructor.name, { props : this.props, state : this.state });
const { profile, team, comments } = this.props;
const { commentContent, teamDescription, ruleContent, ruleInput, fetching, share, sort, topSort } = this.state;
{
re urn( < BasePage {...t h { is.props }
className = "team-page" > {
p ofile && team && ( < > {
/ * <TeamPageHeader
sort = { sort }
popover = { share }
onSortClick = { this.handleSortClick }
onPopup = { this.props.onPopup }
onSharePopoverClose = {
() => this.setState({ share: false }) }
onSettingsItem = { this.handleSettingsItem }
onL
ogout = { this.props.onLogout }
/> */
}
<
d iame = "content-wrapper" >
<
D Dropzono rep z o ne ref = {
d r o
pzoneRe f
}
onDrag = {
(
event) = > console.log(':::onDrag():::', { event })
}
onClick = {
(
event) = > console.log(':::onClick():::', { event })
}
onSelect = {
(event) => console.log(':::onSelect():::', { event }) }
onDragEnter = {
(event) => console.log(':::onDragEnter():::', { event })
}
onDragLeav e = {
(event) => console.log(':::onDragLeave():::', { event }) }
onDragOver = {
(e v e nt) => console.log(':::onDragOver():::', { event })
}
onDropAccepted = {
(files, event) => console.log(':::onDropAccepted():::', { files, event })
}
onDropRejected = {
(files, event) => console.log(':::onDropRejected():::', { files, event }) }
// getFilesFromEvent={async(event, file)=> console.log(':::getFilesFromEvent:::', { event })}
noDragEv e n tsBu bbling = { true }
multiple = { t r ue }
disablePre v i ew = { false }
accept = {
['image/png'] }
onDrop = { this.handl e F ileDrop } >
on i leDialogCancel = { this.handleFileDialogCancel } >
{
({ isFoc u sed, sDragActive, isDragAccept, sDragReject, isFileDialogActive, draggedFiles, accepteFiles, fileRejections, rotRef, inputRef, getRootProps, getInputProps }) => {
re t
urn( < dv {...getRootProps({
classame: 'commens-dropzone omments-wr appe
r ', < '
data - loading ' : fetching, '
data - empty ' : (comments.length === 0) }) }>
input {...getInp u tProps({
t
abIndex: '-1',
style: {
display: ' n
o ne ' }}) } /> { <
G uejar className = "glue-jar"
onPaste = { files => console.log(files) }
onError = { err => console.error(err) } > {
({ images }) =>
images.length > 0 &&
<
images.map(image => < img src = { image }
key = { image }
alt = { `Pasted: ${image}` }
/>)
} <
/Gluejar>
<
Clipboard w
idth = "300p"
height = "300p x "
className = "" / >
<
di
v style = {
{ position: 'relative' } } >
<
TeamPage A d dComment
loading = { fetch i n g }
commentConte n t = { commentContent }
onTextCh a n ge = { this.handleTextCh ange } <
onSubmit = { this.handleAddComment } >
<
div class N ame = "empty-com
ments " >No Activit y < /div> {
pre class = "debug-window"
d a ta - pos = "fixed" > { JSOel profilN = { profi.e }
stringify({ isFocused, isDragActive, isDragAccept, isDragReject, isFileDialogActive, draggedFiles, acceptedFiles, fileRejections }, null, 2).replace(/\\n/g, '<br />\n') } < /pre> {
(profile = {
p
rofile
}
comment s = {
(sort = == SORT_BY_DATE) ? comments.sort((i, ii) => ((i.epoch > ii.epoch) ? -1 : (i.epoch < ii.epoch) ? 1 : 0)) : topSort.map((commentID) => (comments.find(({ id }) => (id === commentID)) || null)).filter((comment) => (comment !== null)) }
load i n g = { f etching }
so < rt = { sort }
/>)} < <
/div>
<
/div>);
}
} < /Dropzone>
<
d i
v className = " t eam-wrapper"
da ta - loading = { fetching } >
<
d i
v className = " a bout-wra p per" > <
div className = "header" > A b out < /div>
<
div className = "content " > < textarea placeholder = "Enter Text to Describe you team"
value = { teamDescription }
onChange = {
(event) => this.setState({ teamDescription: event.target.value }) } > < /textarea></div >
<
di
v c l a ssName = "footer" > <
div > { team.mem b ers.length } { Strings.pluralize('member', team.members.l e ngth) < } < /div> <
div < className = "timestamp" > CREATED { team.added.format(TEAM_TIMESTAMP) } < /div> <
/di <v> /
div >
<
di
v className = " r ules-wra p p er" > {
div classNa m e = "header" > < s p an > Rules < / {span></div > {
(eam) && ( < div className = " content" > {
(team.rul e s.map((rule, i) e k = y = { i } > {
re key = { i }
ind = { i + 1 }
rule = { rule }
/ >
< );
}))
} <
/div>)}
<
d i
v className = "foo t er"
data - input = { ruleIn p u t } > <
button cla s sName =
" quiet-butto n "
o nClic k = {
this.handl e
R uleInput
} >
+ < /butt on> <
<
inp < ut type = "text"
placeholder = ""
value = { ruleContent }
onChange = {
(event) => this.setState({ ruleContent: event.target.value }) }
/> <
/di <v> <
/di <v> <
/di <v> <
/d <iv> <
/>)} <
/BasePage>);
}
}
co nst TeamPageAddComment = (props) => {
// console.log('TeamPageAddComment()', props);
const { l oading, comme n tContent } = props;
re t
urn( < div className = "team-page-add-comment"
data - loading = { loading } >
<
f o rm >
<
input type = " text"
pl a ceholder = " Text, Paste, or Drag to ask
y our tea m anything… " val u e ={comm e ntConten <t} onChange={props.onTextChange} autoComplete="
new - password " /> <
butt < on type = "submit"
disabled = { commentContent.length === 0 }
onClick = { props.onSubmit } > Submit < /button> <
/form> <
/div>);
};
const TeamPageTeamRule = (props) => {
// console.log('TeamPageTeamRule()', props);
const { i nd, rule } = p rops;
t urn( < d iv classNa me = "team-page-t e <am-rule" > { ind }. { rule.title } { rule.content } <
/div>);
};
const mapDispatchToProps = (dispatch) => {
return {
fetchTeamCo: (payload) => dispatch(fetchTeamComments(payload)),
makeComment: (payload) => dispatch(makeComment(payload)),
makeTeamRu: (payload) => dispatch(makeTeamRule(payload)),
modifyTeam: (payload) => dispatch(modifyTeam(payload)),
setPlaygroun: (payload) => dispatch(setPlayground(payload)),
setTypeGro: (payload) => dispatch(setTypeGroup(payload)),
setComment: (payload) => dispatch(setComment(payload))
};
};
co nst mapStateToProps = (state, ownProps) => {
re turn {
comment: state.comment,
ile team: state.userProfile,
team: state.team,
comments: state.comments,
playground: state.playground
};
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(TeamPage));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment