Skip to content

Instantly share code, notes, and snippets.

@stopsopa
Last active October 26, 2020 14:42
Show Gist options
  • Save stopsopa/3f076fd92b03136cc28b8b91a1ffdad8 to your computer and use it in GitHub Desktop.
Save stopsopa/3f076fd92b03136cc28b8b91a1ffdad8 to your computer and use it in GitHub Desktop.
☢ es6
- basic auth
// es6 https://babeljs.io/learn-es2015/
// git flow: http://nvie.com/archives/323 http://nvie.com/posts/a-successful-git-branching-model/
// context:
// https://medium.freecodecamp.org/how-react-context-can-come-to-the-rescue-if-you-dont-know-redux-5452464642ee
// https://stopsopa.github.io/roderic-legacy/router/001/app.html
// history.push() https://stackoverflow.com/a/42121109/5560682
// https://stackoverflow.com/a/44400555/5560682
// https://github.com/ReactTraining/react-router/issues/3498#issuecomment-301057248
// MOST IMPORTANT: https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux (yarn install react-router-redux@next)
// https://hackernoon.com/using-a-react-16-portal-to-do-something-cool-2a2d627b0202 portal
// https://stopsopa.github.io/roderic/motion/index.html
// https://www.mozilla.org/en-US/developer/css-grid/
// https://stopsopa.github.io/roderic/other/flexbox/index.html
// lifecycle callbacks:
// http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
// http://busypeoples.github.io/post/react-component-lifecycle/
// https://i.imgur.com/RTMQS6m.png - diagram
// jest https://facebook.github.io/jest/docs/en/using-matchers.html
'use strict';
import React, { Component } from 'react';
import ReactDOM, { render } from 'react-dom';
import { BrowserRouter as Router, Route, Redirect, Link, NavLink, withRouter } from 'react-router-dom';
import { autobind } from 'core-decorators';
// https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes
// https://github.com/facebook/prop-types#usage
import PropTypes from 'prop-types';
import trim from 'lodash/trim';
import classnames from 'classnames';
const packageJson = eval('require')(path.resolve(__dirname, '..', 'react', 'package.json'));
// https://react.semantic-ui.com/introduction
import {
Button,
Container,
Header,
List
} from 'semantic-ui-react';
class Sandbox extends React.Component {
static displayName = 'Sandbox'; // https://reactjs.org/docs/react-component.html#displayname
MAX_RANGE = 100
// https:1//facebook.github.io/react/docs/typechecking-with-proptypes.html
// https://babeljs.io/blog/2015/06/07/react-on-es6-plus#property-initializers
static defaultProps = {
maxLoops: 10,
}
static propTypes = {
// input: React.PropTypes.string.isRequired
input: PropTypes.string.isRequired,
children: PropTypes.func.isRequired // https://www.youtube.com/watch?v=WE3XAt9P8Ek
};
state = {
loopsRemaining: this.props.maxLoops,
cachedSomeProp: null,
}
static getDerivedStateFromProps(nextProps, prevState) {
return {
cachedSomeProp: nextProps.someProp,
};
}
constructor(...args) { // equivalent of componentWillMount see https://babeljs.io/blog/2015/06/07/react-on-es6-plus#classes
super(...args);
this.state = {
input: '',
};
}
shouldComponentUpdate(nextProps, nextState) {
if (location && location.pathname) {
if (this.pathname !== location.pathname) {
this.pathname = location.pathname;
this.getData({
hash: location.pathname.replace(/\/[^\/]+\/([^\/]+)/, '$1')
});
}
}
return true;
}
// WARNING: this syntax is experimental!
// Using an arrow here binds the method:
// mentioned in https://reactjs.org/docs/react-without-es6.html
// this syntax doesn't need manual binding https://babeljs.io/blog/2015/06/07/react-on-es6-plus#arrow-functions
handleOptionsButtonClick = (e) => {
this.setState({
// template string https://babeljs.io/blog/2015/06/07/react-on-es6-plus#dynamic-property-names--template-strings
[`${inputName}Value`]: e.target.value
});
}
getChildContext() {
return {
store: this.props.store
}
}
setState() { // override
log('setState')
return super.setState.apply(this, arguments);
}
@autobind
onChange(e) {
this.setState((prevState, props) => ({
input: !prevState.input
}), () => {
log('logic after state change')
});
}
render() {
const { component: Component, ...rest } = this.props;
return (
// local className will override className from 'rest'
// https://babeljs.io/blog/2015/06/07/react-on-es6-plus#destructuring--spread-attributes
<form {...rest} className="override" onSubmit={this.onSubmit}>
<label>
<input type="text" value={this.state.input} onChange={this.onChange} />
</label>
<div dangerouslySetInnerHTML={{ __html: howtodesc }} />
{this.state.multiple.map(function (i) {
return <img key={i} src={'/bundles/img/' + i + '.bmp'} />
})}
{Object.keys(this.state.list).map((i) => {
var item = this.state.list[i];
return <div key={i}>{item.name}</div>
})}
{{
info: <Info text={text} />,
warning: <Warning text={text} />,
error: <Error text={text} />,
}[state]}
<button onClick={this.onFetch.bind(this, 'json')}></button>
</form>
);
}
}
// context that we want to pass down
Sandbox.childContextType = {
store: PropTypes.object
};
// context that we want receive
Sandbox.contextTypes = {
store: PropTypes.object
};
// context that we want receive
Sandbox.defaultProps = {
text: 'test'
};
// context that we want receive
Sandbox.propTypes = {
store: PropTypes.object,
obj: PropTypes.instanceOf(Message)
};
ReactDOM.render(
<Sandbox />,
document.getElementById('app')
);
// functional component
const FilterLink = ({
component: Component,
filter,
children,
...rest
}) => {
return (
<a href="javascript;">
onClick={e => {
e.preventDefault();
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter
});
}}
>
{children}
</a>
)
};
export default Sandbox;
const laststatus = ((def) => (state = def, action) => {
switch (action.type) {
case FORM_ITEM_STATUS_CHANGE:
return parseInt(action.value, 10) || 0;
case FORM_ITEM_FETCH_SUCCESS:
return action.data.laststatus;
case FORM_ITEM_STATUS_RESET:
return def;
default:
return state;
}
})(0);
import {
loginSignOut
} from '../actions';
import {
getAuthenticated,
getLoading,
getLoginError
} from '../reducers';
// fetchData and reloading on navigation
class ListVisible extends Component {
static fetchData = (store, routerParams) => {
return store.dispatch(listLoad());
}
getData = () => this.props.listLoad()
componentDidMount() {
const { list, history: { action } } = this.props;
( ! list || ! list.length || action === 'PUSH' ) && this.getData('first');
if (window && window.gtagpageview && window.responsestatuscode === 200) {
// but before add to gtag.js additional code
//function gtagpageview(path) {
// path = path || location.href.substring(location.origin.length).split('#')[0];
// gtag('config', '<%= gaid %>', {'page_path': path});
//}
gtagpageview();
}
}
render() {
return (
<List {...this.props} />
);
}
}
import { connect } from 'react-redux';
// https://codesandbox.io/s/react-router-contextual-return-pages-with-location-state-rl6t7
import {
Link,
Switch,
Route,
useParams,
useHistory,
useLocation,
withRouter,
} from "react-router-dom";
export default () => <Route component={PageNotFound} />
// https://egghead.io/lessons/javascript-redux-using-mapdispatchtoprops-shorthand-notation
// about ownProps https://egghead.io/lessons/javascript-redux-filtering-redux-state-with-react-router-params
const mapStateToProps = (state, ownProps) => ({ // https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options
authenticated: getAuthenticated(state, ownProps.match.props.id),
loading: getLoading(state),
error: getLoginError(state)
});
// https://egghead.io/lessons/javascript-redux-using-mapdispatchtoprops-shorthand-notation
// const mapDispatchToProps = (dispatch, ownProps) => (
// {
// onSignOut(id) {
// dispatch(loginSignOut(id));
// }
// } // or by mapping when arguments are the same
// );
// https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md#quick-solution
export default withRouter(connect(
mapStateToProps,
{
onSignOut: loginSignOut
}
))(LoginForm);
// action
export const loginRequest = (username, password) => (dispatch, getState) => {
const state = getState();
if (getLoading(state)) {
return Promise.resolve('canceled');
}
dispatch(loaderOn());
return new Promise(resolve => {
setTimeout(() => {
dispatch(loaderOff());
resolve('done');
}, 1000);
});
}
import set from 'nlab/set';
const [ featuredButton, dispatchFeaturedButton ] = useReducer((state, action) => {
try {
switch (action.type) {
case 'init':
state = action.value;
return state;
case 'key':
state = {...state};
if (action.key) {
state[action.key] = action.value;
}
else {
throw new Error(`action.key is not defined: ` + JSON.stringify(action, null, 4))
}
return state;
case 'set':
state = {...state};
set(state, action.key, action.value);
return state;
// case 'decrement':
// return {count: state.count - 1};
default:
throw new Error(`featuredButton unhandled action: ` + JSON.stringify(action, null, 4));
}
}
catch (e) {
throw new Error(`featuredButton reducer error2: ` + String(e));
}
}, {})
// Date vvv
Object.getOwnPropertyNames(Date.prototype).forEach(m => console.log('val', m, '-----', (new Date())[m]()));
(new Date()).toISOString().substring(0, 19).replace('T', ' ')
// "2020-10-26 14:42:19"
(new Date()).toISOString().substring(0, 19).replace('T', '_').replace(/:/g, '-')
// "2020-10-26_14-42-12"
// UK
(new Date()).toGMTString().replace(/^\w+, (\d+) (\w+) (\d+) 0*(\d+):0*(\d+):0*(\d+).*/i, '$1 $2 $3 $4:$5:$6')
(new Date()).toGMTString().replace(/^\w+, (\d+) (\w+) (\d+) (\d+):(\d+):(\d+).*/i, '$1 $2 $3 $4:$5:$6')
(new Date()).toISOString() // https://stackoverflow.com/a/58347604
// Date ^^^
const node = Object.prototype.toString.call(global.process) === '[object process]';
'use strict';
var React = require('react');
var createReactClass = require('create-react-class');
var ReactDOM = require('react-dom');
/**
* https://facebook.github.io/react/docs/react-without-es6.html
*/
var Sandbox = createReactClass({ // https://reactjs.org/docs/react-without-es6.html
displayName: 'Sandbox',
propTypes: {
leave: React.PropTypes.bool,
appearTimeout: React.PropTypes.number
},
getDefaultProps() { // called first
return {};
},
getInitialState: function() {
return {count: this.props.initialCount};
},
componentDidMount() {
this.setState({
items: [{key: 'a', size: 10}, {key: 'b', size: 20}], // remove c.
});
},
onChange: function () {
this.setState((prevState, props) => ({
input: !prevState.input
}));
},
render: function () {
return (
<form onSubmit={this.onSubmit}>
<label>
<input type="text" value={this.state.input} onChange={this.onChange} />
</label>
{this.state.multiple.map(function (i) {
return <img key={i} src={'/bundles/img/' + i + '.bmp'} />
})}
{Object.keys(this.state.list).map((i) => {
var item = this.state.list[i];
return <div key={i}>{item.name}</div>
})}
</form>
);
}
});
ReactDOM.render(<App />, document.getElementById('app'));
const laststatus = (state, action) => {
const def = 0;
if (state === undefined) {
state = def;
}
switch (action.type) {
case FORM_ITEM_STATUS_CHANGE:
return parseInt(action.value, 10) || 0;
case FORM_ITEM_FETCH_SUCCESS:
return action.data.laststatus;
case FORM_ITEM_STATUS_RESET:
return def;
default:
return state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment