Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

URL queries to better support iframe usage #884

Merged
merged 2 commits into from
Feb 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs-src/docs/advanced-functionality/view-settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,10 @@ All URL queries modify the view away from the default settings -- if you change
| `n` | Narrative page number | `n=1` goes to the first page |
| `s` | Selected strain | `s=1_0199_PF` |
| `clade` | Labeled clade that tree is zoomed to | `clade=B3` (numeric values are buggy) |
| `sidebar` | Force the sidebar into a certain state | `sidebar=closed` or `sidebar=open` |
| `onlyPanels` | Do not display the footer / header. Useful for iframes. | `onlyPanels` |


**See this in action:**

For instance, go to [nextstrain.org/flu/seasonal/h3n2/ha/2y?c=num_date&d=tree,map&m=div&r=region](https://nextstrain.org/flu/seasonal/h3n2/ha/2y?c=num_date&d=tree,map&m=div&p=grid&r=region) and you'll see how we've changed the coloring to a temporal scale (`c=num_date`), we're only showing the tree & map panels (`d=tree,map`), the tree x-axis is divergence (`m=div`) and the map resolution is region (`r=region`).
For instance, go to [nextstrain.org/flu/seasonal/h3n2/ha/2y?c=num_date&d=tree,map&m=div&r=region](https://nextstrain.org/flu/seasonal/h3n2/ha/2y?c=num_date&d=tree,map&m=div&p=grid&r=region) and you'll see how we've changed the coloring to a temporal scale (`c=num_date`), we're only showing the tree & map panels (`d=tree,map`), the tree x-axis is divergence (`m=div`) and the map resolution is region (`r=region`).
55 changes: 46 additions & 9 deletions src/actions/recomputeReduxState.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,19 @@ const modifyStateViaURLQuery = (state, query) => {
} else {
state.animationPlayPauseButton = "Play";
}
if (query.sidebar) {
if (query.sidebar === "open") {
state.defaults.sidebarOpen = true;
state.sidebarOpen = true;
} else if (query.sidebar === "closed") {
state.defaults.sidebarOpen = false;
state.sidebarOpen = false;
}
}
if ("onlyPanels" in query) {
state.showOnlyPanels = true;
}

return state;
};

Expand Down Expand Up @@ -164,17 +177,29 @@ const modifyStateViaMetadata = (state, metadata) => {
console.warn("JSON did not include any filters");
}
if (metadata.displayDefaults) {
const keysToCheckFor = ["geoResolution", "colorBy", "distanceMeasure", "layout", "mapTriplicate"];
const expectedTypes = ["string", "string", "string", "string", "boolean"];
const keysToCheckFor = ["geoResolution", "colorBy", "distanceMeasure", "layout", "mapTriplicate", 'sidebar'];
const expectedTypes = ["string", "string", "string", "string", "boolean", 'string'];

for (let i = 0; i < keysToCheckFor.length; i += 1) {
if (metadata.displayDefaults[keysToCheckFor[i]]) {
if (typeof metadata.displayDefaults[keysToCheckFor[i]] === expectedTypes[i]) { // eslint-disable-line valid-typeof
/* e.g. if key=geoResoltion, set both state.geoResolution and state.defaults.geoResolution */
state[keysToCheckFor[i]] = metadata.displayDefaults[keysToCheckFor[i]];
state.defaults[keysToCheckFor[i]] = metadata.displayDefaults[keysToCheckFor[i]];
if (keysToCheckFor[i] === "sidebar") {
if (metadata.displayDefaults[keysToCheckFor[i]] === "open") {
state.defaults.sidebarOpen = true;
state.sidebarOpen = true;
} else if (metadata.displayDefaults[keysToCheckFor[i]]=== "closed") {
state.defaults.sidebarOpen = false;
state.sidebarOpen = false;
} else {
console.error("Skipping 'display_default' for sidebar as it's not 'open' or 'closed'");
}
} else {
/* most of the time if key=geoResoltion, set both state.geoResolution and state.defaults.geoResolution */
state[keysToCheckFor[i]] = metadata.displayDefaults[keysToCheckFor[i]];
state.defaults[keysToCheckFor[i]] = metadata.displayDefaults[keysToCheckFor[i]];
}
} else {
console.error("Skipping (meta.json) default for ", keysToCheckFor[i], "as it is not of type ", expectedTypes[i]);
console.error("Skipping 'display_default' for ", keysToCheckFor[i], "as it is not of type ", expectedTypes[i]);
}
}
}
Expand Down Expand Up @@ -318,7 +343,7 @@ const modifyControlsStateViaTree = (state, tree, treeToo, colorings) => {
return state;
};

const checkAndCorrectErrorsInState = (state, metadata, query, tree) => {
const checkAndCorrectErrorsInState = (state, metadata, query, tree, viewingNarrative) => {
/* want to check that the (currently set) colorBy (state.colorBy) is valid,
* and fall-back to an available colorBy if not
*/
Expand Down Expand Up @@ -433,6 +458,16 @@ const checkAndCorrectErrorsInState = (state, metadata, query, tree) => {
delete query.m;
}

if (!(query.sidebar === "open" || query.sidebar === "closed")) {
delete query.sidebar; // invalid value
}
if (viewingNarrative) {
// We must prevent a narrative closing the sidebar, either via a JSON display_default
// or a URL query anywhere within the narrative.
if ("sidebarOpen" in state.defaults) delete state.defaults.sidebarOpen;
state.sidebarOpen=true;
}

return state;
};

Expand Down Expand Up @@ -547,7 +582,8 @@ const createMetadataStateFromJSON = (json) => {
geo_resolution: "geoResolution",
distance_measure: "distanceMeasure",
map_triplicate: "mapTriplicate",
layout: "layout"
layout: "layout",
sidebar: "sidebar"
};
for (const [jsonKey, auspiceKey] of Object.entries(jsonKeyToAuspiceKey)) {
if (json.meta.display_defaults[jsonKey]) {
Expand Down Expand Up @@ -638,7 +674,8 @@ export const createStateFromQueryOrJSONs = ({
controls = modifyStateViaURLQuery(controls, query);
}

controls = checkAndCorrectErrorsInState(controls, metadata, query, tree); /* must run last */
const viewingNarrative = (narrativeBlocks || (oldState && oldState.narrative.display));
controls = checkAndCorrectErrorsInState(controls, metadata, query, tree, viewingNarrative); /* must run last */


/* calculate colours if loading from JSONs or if the query demands change */
Expand Down
1 change: 1 addition & 0 deletions src/actions/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,4 @@ export const TOGGLE_TANGLE = "TOGGLE_TANGLE";
export const UPDATE_PATHNAME = "UPDATE_PATHNAME";
export const CHANGE_ZOOM = "CHANGE_ZOOM";
export const SET_AVAILABLE = "SET_AVAILABLE";
export const TOGGLE_SIDEBAR = "TOGGLE_SIDEBAR";
18 changes: 15 additions & 3 deletions src/components/framework/monitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import React from "react";
import PropTypes from 'prop-types';
import { connect } from "react-redux";
import _throttle from "lodash/throttle";
import { BROWSER_DIMENSIONS, CHANGE_PANEL_LAYOUT } from "../../actions/types";
import { BROWSER_DIMENSIONS, CHANGE_PANEL_LAYOUT, TOGGLE_SIDEBAR } from "../../actions/types";
import { changePage } from "../../actions/navigation";
import { twoColumnBreakpoint } from "../../util/globals";
import { twoColumnBreakpoint, controlsHiddenWidth} from "../../util/globals";

@connect((state) => ({
displayNarrative: state.narrative.display,
canTogglePanelLayout: state.controls.canTogglePanelLayout
canTogglePanelLayout: state.controls.canTogglePanelLayout,
controlDefaults: state.controls.defaults
}))
class Monitor extends React.Component {
constructor(props) {
Expand Down Expand Up @@ -50,6 +51,17 @@ class Monitor extends React.Component {
docHeight: window.document.body.clientHeight /* background needs docHeight because sidebar creates absolutely positioned container and blocks height 100% */
};
dispatch({type: BROWSER_DIMENSIONS, data: newBrowserDimensions});

/* Should the sidebar toggle open / closed because we've crossed some threshold? */
/* Do not do this if a default has been set -- this is only set via JSON / URL query & must be obeyed */
if (!this.props.displayNarrative && !("sidebarOpen" in this.props.controlDefaults)) {
if (oldBrowserDimensions.width > controlsHiddenWidth && newBrowserDimensions.width < controlsHiddenWidth) {
dispatch({type: TOGGLE_SIDEBAR, value: false});
} else if (oldBrowserDimensions.width < controlsHiddenWidth && newBrowserDimensions.width > controlsHiddenWidth) {
dispatch({type: TOGGLE_SIDEBAR, value: true});
}
}

/* if we are _not_ in narrative mode, then browser resizing may change between grid & full layouts automatically */
if (!this.props.displayNarrative && this.props.canTogglePanelLayout) {
if (oldBrowserDimensions.width < twoColumnBreakpoint && newBrowserDimensions.width >= twoColumnBreakpoint) {
Expand Down
48 changes: 24 additions & 24 deletions src/components/main/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import Footer from "../framework/footer";
import DownloadModal from "../download/downloadModal";
import { analyticsNewPage } from "../../util/googleAnalytics";
import handleFilesDropped from "../../actions/filesDropped";
import { TOGGLE_SIDEBAR } from "../../actions/types";
import AnimationController from "../framework/animationController";
import { calcUsableWidth } from "../../util/computeResponsive";
import { renderNarrativeToggle } from "../narrative/renderNarrativeToggle";
Expand All @@ -35,41 +36,35 @@ const Frequencies = lazy(() => import("../frequencies"));
browserDimensions: state.browserDimensions.browserDimensions,
frequenciesLoaded: state.frequencies.loaded,
metadataLoaded: state.metadata.loaded,
treeLoaded: state.tree.loaded
treeLoaded: state.tree.loaded,
sidebarOpen: state.controls.sidebarOpen,
showOnlyPanels: state.controls.showOnlyPanels
}))
class Main extends React.Component {
constructor(props) {
super(props);
/* window listener to see when width changes cross threshold to toggle sidebar */
/* window listner employed to toggle switch to mobile display.
NOTE: this used to toggle sidebar open boolean when that was stored
as state here, but his has since ben moved to redux state. The mobile
display should likewise be lifted to redux state */
const mql = window.matchMedia(`(min-width: ${controlsHiddenWidth}px)`);
mql.addListener(() => this.setState({
sidebarOpen: this.state.mql.matches,
mobileDisplay: !this.state.mql.matches
}));
this.state = {
mql,
sidebarOpen: mql.matches,
mobileDisplay: !mql.matches,
showSpinner: !(this.props.metadataLoaded && this.props.treeLoaded)
};
analyticsNewPage();
if (window.location.pathname.includes("gisaid")) { // TODO fix this hack by moving sidebar state to URL
this.state.sidebarOpen = false;
}
this.toggleSidebar = this.toggleSidebar.bind(this);
}
static propTypes = {
dispatch: PropTypes.func.isRequired
}
componentWillReceiveProps(nextProps) {
if (this.state.showSpinner && nextProps.metadataLoaded && nextProps.treeLoaded) {
this.setState({showSpinner: false});
return;
}
if (
(this.state.mql.matches) ||
(nextProps.displayNarrative && !this.props.displayNarrative)
) {
this.setState({sidebarOpen: true});
}
}
componentDidMount() {
Expand All @@ -79,6 +74,9 @@ class Main extends React.Component {
return this.props.dispatch(handleFilesDropped(e.dataTransfer.files));
}, false);
}
toggleSidebar() {
this.props.dispatch({type: TOGGLE_SIDEBAR, value: !this.props.sidebarOpen});
}
render() {
if (this.state.showSpinner) {
return (<Spinner/>);
Expand All @@ -101,9 +99,11 @@ class Main extends React.Component {
* (a) all non-narrative displays (including on mobile)
* (b) narrative display for non-mobile (i.e. display side-by-side)
*/
const {availableWidth, availableHeight, sidebarWidth, overlayStyles} = calcStyles(this.props.browserDimensions, this.props.displayNarrative, this.state.sidebarOpen, this.state.mobileDisplay);
const overlayHandler = () => {this.setState({sidebarOpen: false});};
const {big, chart} = calcPanelDims(this.props.panelLayout === "grid", this.props.panelsToDisplay, this.props.displayNarrative, availableWidth, availableHeight);
const {availableWidth, availableHeight, sidebarWidth, overlayStyles} =
calcStyles(this.props.browserDimensions, this.props.displayNarrative, this.props.sidebarOpen, this.state.mobileDisplay);
const overlayHandler = () => {this.props.dispatch({type: TOGGLE_SIDEBAR, value: false});};
const {big, chart} =
calcPanelDims(this.props.panelLayout === "grid", this.props.panelsToDisplay, this.props.displayNarrative, availableWidth, availableHeight);
return (
<span>
<AnimationController/>
Expand All @@ -113,25 +113,25 @@ class Main extends React.Component {
</ThemeProvider>
</ErrorBoundary>
<SidebarToggle
sidebarOpen={this.state.sidebarOpen}
sidebarOpen={this.props.sidebarOpen}
mobileDisplay={this.state.mobileDisplay}
handler={() => {this.setState({sidebarOpen: !this.state.sidebarOpen});}}
handler={this.toggleSidebar}
/>
<Sidebar
sidebarOpen={this.state.sidebarOpen}
sidebarOpen={this.props.sidebarOpen}
width={sidebarWidth}
height={availableHeight}
displayNarrative={this.props.displayNarrative}
panelsToDisplay={this.props.panelsToDisplay}
narrativeTitle={this.props.narrativeTitle}
mobileDisplay={this.state.mobileDisplay}
navBarHandler={() => {this.setState({sidebarOpen: !this.state.sidebarOpen});}}
navBarHandler={this.toggleSidebar}
/>
<PanelsContainer width={availableWidth} height={availableHeight} left={this.state.sidebarOpen ? sidebarWidth : 0}>
<PanelsContainer width={availableWidth} height={availableHeight} left={this.props.sidebarOpen ? sidebarWidth : 0}>
{this.props.narrativeIsLoaded && !this.props.panelsToDisplay.includes("EXPERIMENTAL_MainDisplayMarkdown") ?
renderNarrativeToggle(this.props.dispatch, this.props.displayNarrative) : null
}
{this.props.displayNarrative ? null : <Info width={calcUsableWidth(availableWidth, 1)} />}
{this.props.displayNarrative || this.props.showOnlyPanels ? null : <Info width={calcUsableWidth(availableWidth, 1)} />}
{this.props.panelsToDisplay.includes("tree") ? <Tree width={big.width} height={big.height} /> : null}
{this.props.panelsToDisplay.includes("map") ? <Map width={big.width} height={big.height} justGotNewDatasetRenderNewMap={false} /> : null}
{this.props.panelsToDisplay.includes("entropy") ?
Expand All @@ -146,7 +146,7 @@ class Main extends React.Component {
</Suspense>) :
null
}
{this.props.displayNarrative ? null : <Footer width={calcUsableWidth(availableWidth, 1)} />}
{this.props.displayNarrative|| this.props.showOnlyPanels ? null : <Footer width={calcUsableWidth(availableWidth, 1)} />}
{this.props.displayNarrative && this.props.panelsToDisplay.includes("EXPERIMENTAL_MainDisplayMarkdown") ?
<MainDisplayMarkdown width={calcUsableWidth(availableWidth, 1)}/> :
null
Expand Down
9 changes: 9 additions & 0 deletions src/middleware/changeURL.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@ export const changeURLMiddleware = (store) => (next) => (action) => {
query.p = action.notInURLState === true ? undefined : action.data;
break;
}
case types.TOGGLE_SIDEBAR: {
// we never add this to the URL on purpose -- it should be manually set as it specifies a world
// where resizes can not open / close the sidebar. The exception is if it's toggled, we
// remove it from the URL query, as it's no longer valid to call it open if it's closed!
if ("sidebar" in query) {
query.sidebar = undefined;
}
break;
}
case types.TOGGLE_PANEL_DISPLAY: {
if (state.controls.panelsAvailable.length === action.panelsToDisplay.length) {
query.d = undefined;
Expand Down
26 changes: 25 additions & 1 deletion src/reducers/controls.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { defaultGeoResolution,
defaultDistanceMeasure,
defaultLayout,
defaultMutType,
controlsHiddenWidth,
twoColumnBreakpoint } from "../util/globals";
import * as types from "../actions/types";
import { calcBrowserDimensionsInitialState } from "./browserDimensions";
Expand All @@ -21,6 +22,13 @@ export const getDefaultControlsState = () => {
filters: {},
colorBy: defaultColorBy
};
// a default sidebarOpen status is only set via JSON, URL query
// _or_ if certain URL keywords are triggered
const initialSidebarState = getInitialSidebarState();
if (initialSidebarState.setDefault) {
defaults.sidebarOpen = initialSidebarState.sidebarOpen;
}

const dateMin = numericToCalendar(currentNumDate() - defaultDateRange);
const dateMax = currentCalDate();
const dateMinNumeric = calendarToNumeric(dateMin);
Expand Down Expand Up @@ -68,7 +76,9 @@ export const getDefaultControlsState = () => {
showTangle: false,
zoomMin: undefined,
zoomMax: undefined,
branchLengthsToDisplay: "divAndDate"
branchLengthsToDisplay: "divAndDate",
sidebarOpen: initialSidebarState.sidebarOpen,
showOnlyPanels: false
};
};

Expand Down Expand Up @@ -237,6 +247,8 @@ const Controls = (state = getDefaultControlsState(), action) => {
return Object.assign({}, state, {showTangle: !state.showTangle});
}
return state;
case types.TOGGLE_SIDEBAR:
return Object.assign({}, state, {sidebarOpen: action.value});
case types.ADD_COLOR_BYS:
for (const colorBy of Object.keys(action.newColorings)) {
state.coloringsPresentOnTree.add(colorBy);
Expand All @@ -248,3 +260,15 @@ const Controls = (state = getDefaultControlsState(), action) => {
};

export default Controls;

function getInitialSidebarState() {
/* The following "hack" was present when `sidebarOpen` wasn't URL customisable. It can be removed
from here once the GISAID URLs (iFrames) are updated */
if (window.location.pathname.includes("gisaid")) {
return {sidebarOpen: false, setDefault: true};
}
return {
sidebarOpen: window.innerWidth > controlsHiddenWidth,
setDefault: false
};
}