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

Refactor code base to stop using defaultProps #414

Merged
merged 5 commits into from
Jul 9, 2024
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
55 changes: 28 additions & 27 deletions baby-gru/src/components/MoorhenContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,6 @@ export const MoorhenContainer = (props: moorhen.ContainerProps) => {
const innerActiveMapRef = useRef<null | moorhen.Map>(null)
const innerlastHoveredAtomRef = useRef<null | moorhen.HoveredAtom>(null)

const dispatch = useDispatch()
const maps = useSelector((state: moorhen.State) => state.maps)
const molecules = useSelector((state: moorhen.State) => state.molecules.moleculeList)
const cursorStyle = useSelector((state: moorhen.State) => state.hoveringStates.cursorStyle)
Expand All @@ -191,15 +190,17 @@ export const MoorhenContainer = (props: moorhen.ContainerProps) => {
const modificationCountBackupThreshold = useSelector((state: moorhen.State) => state.backupSettings.modificationCountBackupThreshold)
const activeMap = useSelector((state: moorhen.State) => state.generalStates.activeMap)

const innerStatesMap: moorhen.ContainerRefs = {
const dispatch = useDispatch()

const innerRefsMap: moorhen.ContainerRefs = {
glRef: innerGlRef, timeCapsuleRef: innerTimeCapsuleRef, commandCentre: innnerCommandCentre,
moleculesRef: innerMoleculesRef, mapsRef: innerMapsRef, activeMapRef: innerActiveMapRef,
lastHoveredAtomRef: innerlastHoveredAtomRef, videoRecorderRef: innerVideoRecorderRef,
}

let refs = {} as moorhen.ContainerRefs
Object.keys(innerStatesMap).forEach(key => {
refs[key] = props[key] ? props[key] : innerStatesMap[key]
Object.keys(innerRefsMap).forEach(key => {
refs[key] = props[key] ? props[key] : innerRefsMap[key]
})

const {
Expand All @@ -210,12 +211,32 @@ export const MoorhenContainer = (props: moorhen.ContainerProps) => {
moleculesRef.current = molecules
mapsRef.current = maps

const defaultProps = {
onUserPreferencesChange: () => {},
urlPrefix: '.',
monomerLibraryPath: './monomers',
setMoorhenDimensions: null,
disableFileUploads: false,
includeNavBarMenuNames: [],
extraNavBarModals: [],
extraNavBarMenus: [],
extraFileMenuItems: [],
extraEditMenuItems: [],
extraCalculateMenuItems: [],
extraDraggableModals: [],
viewOnly: false,
allowScripting: true,
backupStorageInstance: createLocalStorageInstance('Moorhen-TimeCapsule'),
aceDRGInstance: null,
store: MoorhenReduxStore
}

const {
disableFileUploads, urlPrefix, extraNavBarMenus, viewOnly, extraDraggableModals,
monomerLibraryPath, extraFileMenuItems, allowScripting, backupStorageInstance,
extraEditMenuItems, aceDRGInstance, extraCalculateMenuItems, setMoorhenDimensions,
onUserPreferencesChange, extraNavBarModals, includeNavBarMenuNames, store
} = props
} = { ...defaultProps, ...props }

const collectedProps: moorhen.CollectedProps = {
glRef, commandCentre, timeCapsuleRef, disableFileUploads, extraDraggableModals, aceDRGInstance,
Expand All @@ -228,7 +249,7 @@ export const MoorhenContainer = (props: moorhen.ContainerProps) => {
useLayoutEffect(() => {
let head = document.head
let style: any = document.createElement("link")
style.href = `${props.urlPrefix}/moorhen.css`
style.href = `${urlPrefix}/moorhen.css`
style.rel = "stylesheet"
style.async = true
style.type = 'text/css'
Expand Down Expand Up @@ -486,7 +507,7 @@ export const MoorhenContainer = (props: moorhen.ContainerProps) => {

<MoorhenSnackBarManager {...collectedProps}/>

<MoorhenUpdatingMapsManager commandCentre={props.commandCentre} glRef={props.glRef}/>
<MoorhenUpdatingMapsManager commandCentre={commandCentre} glRef={glRef}/>

{/**
<MoorhenSharedSessionManager
Expand Down Expand Up @@ -528,23 +549,3 @@ export const MoorhenContainer = (props: moorhen.ContainerProps) => {
</Container>
</SnackbarProvider>
}

MoorhenContainer.defaultProps = {
onUserPreferencesChange: () => {},
urlPrefix: '.',
monomerLibraryPath: './monomers',
setMoorhenDimensions: null,
disableFileUploads: false,
includeNavBarMenuNames: [],
extraNavBarModals: [],
extraNavBarMenus: [],
extraFileMenuItems: [],
extraEditMenuItems: [],
extraCalculateMenuItems: [],
extraDraggableModals: [],
viewOnly: false,
allowScripting: true,
backupStorageInstance: createLocalStorageInstance('Moorhen-TimeCapsule'),
aceDRGInstance: null,
store: MoorhenReduxStore
}
22 changes: 10 additions & 12 deletions baby-gru/src/components/card/MoorhenAddCustomRepresentationCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ export const MoorhenAddCustomRepresentationCard = (props: {

const { enqueueSnackbar } = useSnackbar()

const mode = props.mode ?? "add"

const ribbonSettingsProps = {
ribbonCoilThickness, setRibbonCoilThickness, ribbonHelixWidth, setRibbonHelixWidth,
ribbonStrandWidth, setRibbonStrandWidth, ribbonArrowWidth, setRibbonArrowWidth, ribbonDNARNAWidth,
Expand Down Expand Up @@ -249,7 +251,7 @@ export const MoorhenAddCustomRepresentationCard = (props: {
}
}

if (props.mode === 'add') {
if (mode === 'add') {
const representation = await props.molecule.addRepresentation(
styleSelectRef.current.value,
cidSelection,
Expand All @@ -260,7 +262,7 @@ export const MoorhenAddCustomRepresentationCard = (props: {
residueEnvSettings
)
dispatch( addCustomRepresentation(representation) )
} else if (props.mode === 'edit' && props.representation.uniqueId) {
} else if (mode === 'edit' && props.representation.uniqueId) {
const representation = props.molecule.representations.find(item => item.uniqueId === props.representation.uniqueId)
if (representation) {
representation.cid = cidSelection
Expand All @@ -277,7 +279,7 @@ export const MoorhenAddCustomRepresentationCard = (props: {
props.setShow(false)
props.setBusy?.(false)
}, [
colour, props.molecule, props.representation, props.mode, bondWidth, atomRadiusBondRatio, bondSmoothness,
colour, props.molecule, props.representation, mode, bondWidth, atomRadiusBondRatio, bondSmoothness,
nucleotideRibbonStyle, ribbonArrowWidth, ribbonAxialSampling, ribbonCoilThickness, ribbonDNARNAWidth,
ribbonHelixWidth, ribbonStrandWidth, maxEnvDist, labelledEnv, showEnvContacts, showEnvHBonds
])
Expand All @@ -287,17 +289,17 @@ export const MoorhenAddCustomRepresentationCard = (props: {
await createRepresentation()
} catch (err) {
console.warn(err)
enqueueSnackbar(`Something went wrong while ${props.mode === "edit" ? "editing" : "creating a new"} custom representation`, { variant: "error" })
enqueueSnackbar(`Something went wrong while ${mode === "edit" ? "editing" : "creating a new"} custom representation`, { variant: "error" })
}
}, [createRepresentation])

const handleColourModeChange = useCallback((evt) => {
if (evt.target.value === "mol-symm" && !ncsColourRuleRef.current && props.mode === "edit") {
if (evt.target.value === "mol-symm" && !ncsColourRuleRef.current && mode === "edit") {
const representation = props.molecule.representations.find(item => item.uniqueId === props.representation.uniqueId)
if (representation?.colourRules?.length > 0) ncsColourRuleRef.current = representation.colourRules[0]
}
setColourMode(evt.target.value)
}, [props.molecule, props.mode, props.representation])
}, [props.molecule, mode, props.representation])

const applyNcsColourChange = useCallback(async () => {
await props.molecule.redraw()
Expand Down Expand Up @@ -445,7 +447,7 @@ export const MoorhenAddCustomRepresentationCard = (props: {
<div style={{borderColor: 'rgb(0, 0, 255)', borderWidth:'5px', backgroundColor: 'rgb(0, 0, 255)', height:'20px', width:'5px', marginTop: '0.2rem', padding: '0rem'}}/>
</>
: colourMode === "mol-symm" ?
props.mode === "edit" ?
mode === "edit" ?
<NcsColourSwatch style={{cursor: "pointer", height:'30px', width:'36px', padding: "0px", borderStyle: 'solid', borderColor: '#ced4da', borderWidth: '3px', borderRadius: '8px'}} rule={ncsColourRuleRef?.current} applyColourChange={applyNcsColourChange} />
:
<GrainOutlined style={{height:'30px', width:'36px', padding:0, borderStyle: 'solid', borderColor: '#ced4da', borderWidth: '3px', borderRadius: '8px'}}/>
Expand Down Expand Up @@ -490,12 +492,8 @@ export const MoorhenAddCustomRepresentationCard = (props: {
</>
}
<Button onClick={handleCreateRepresentation}>
{props.mode === 'add' ? 'Create' : 'Apply'}
{mode === 'add' ? 'Create' : 'Apply'}
</Button>
</Stack>
</Popover>
}

MoorhenAddCustomRepresentationCard.defaultProps = {
mode: 'add'
}
18 changes: 8 additions & 10 deletions baby-gru/src/components/card/MoorhenLigandCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,18 @@ export const MoorhenLigandCard = (props: {
const height = useSelector((state: moorhen.State) => state.sceneSettings.height)
const width = useSelector((state: moorhen.State) => state.sceneSettings.width)

const { ligand, molecule } = props
const defaultValidationStyles = [
'contact_dots', 'chemical_features', 'ligand_environment', 'ligand_validation'
]

const { ligand, molecule, validationStyles } = { validationStyles: defaultValidationStyles, ...props }

useEffect(() => {
const changedState = { ...showState }
props.validationStyles.forEach(style => changedState[style] = molecule.representations.some(representation => representation.style === style && representation.visible))
validationStyles.forEach(style => changedState[style] = molecule.representations.some(representation => representation.style === style && representation.visible))
setShowState(changedState)
return () => {
props.validationStyles.forEach(key => {
validationStyles.forEach(key => {
molecule.hide(key, ligand.cid)
})
}
Expand Down Expand Up @@ -120,7 +124,7 @@ export const MoorhenLigandCard = (props: {
<CenterFocusStrongOutlined style={{marginRight: '0.5rem'}}/>
{ligand.cid}
</Button>
{props.validationStyles.map(style => {
{validationStyles.map(style => {
return getToggleButton(style, validationLabels[style])
})}
{ligand.chem_comp_info?.length > 0 &&
Expand All @@ -135,9 +139,3 @@ export const MoorhenLigandCard = (props: {
</Card.Body>
</Card>
}

MoorhenLigandCard.defaultProps = {
validationStyles: [
'contact_dots', 'chemical_features', 'ligand_environment', 'ligand_validation'
]
}
37 changes: 16 additions & 21 deletions baby-gru/src/components/card/MoorhenMapCard.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { forwardRef, useImperativeHandle, useEffect, useState, useRef, useCallback, useMemo, Fragment } from "react"
import { Card, Form, Button, Col, DropdownButton, Stack, OverlayTrigger, ToggleButton, Spinner } from "react-bootstrap"
import { doDownload, rgbToHex } from '../../utils/utils'
import { convertRemToPx, doDownload, rgbToHex } from '../../utils/utils'
import { getNameLabel } from "./cardUtils"
import { VisibilityOffOutlined, VisibilityOutlined, ExpandMoreOutlined, ExpandLessOutlined, DownloadOutlined, Settings, FileCopyOutlined, RadioButtonCheckedOutlined, RadioButtonUncheckedOutlined, AddCircleOutline, RemoveCircleOutline } from '@mui/icons-material';
import { MoorhenMapSettingsMenuItem } from "../menu-item/MoorhenMapSettingsMenuItem";
Expand All @@ -26,14 +26,6 @@ type ActionButtonType = {
}

interface MoorhenMapCardPropsInterface extends moorhen.CollectedProps {
dropdownId: number;
accordionDropdownId: number;
setAccordionDropdownId: React.Dispatch<React.SetStateAction<number>>;
sideBarWidth: number;
showSideBar: boolean;
busy: boolean;
key: number;
index: number;
map: moorhen.Map;
initialContour?: number;
initialRadius?: number;
Expand All @@ -42,20 +34,26 @@ interface MoorhenMapCardPropsInterface extends moorhen.CollectedProps {
}

export const MoorhenMapCard = forwardRef<any, MoorhenMapCardPropsInterface>((props, cardRef) => {
const defaultProps = {
initialContour: 0.8, initialRadius: 13
}

const { initialContour, initialRadius } = {...defaultProps, ...props}

const mapRadius = useSelector((state: moorhen.State) => {
const map = state.mapContourSettings.mapRadii.find(item => item.molNo === props.map.molNo)
if (map) {
return map.radius
} else {
return props.initialRadius
return initialRadius
}
})
const mapContourLevel = useSelector((state: moorhen.State) => {
const map = state.mapContourSettings.contourLevels.find(item => item.molNo === props.map.molNo)
if (map) {
return map.contourLevel
} else {
return props.initialContour
return initialContour
}
})
const mapStyle = useSelector((state: moorhen.State) => {
Expand Down Expand Up @@ -272,8 +270,9 @@ export const MoorhenMapCard = forwardRef<any, MoorhenMapCardPropsInterface>((pro
},
}

const getButtonBar = (sideBarWidth: number) => {
const maximumAllowedWidth = sideBarWidth * 0.55
const getButtonBar = () => {
const minWidth = convertRemToPx(20)
const maximumAllowedWidth = minWidth * 0.55
let currentlyUsedWidth = 0
let expandedButtons: JSX.Element[] = []
let compressedButtons: JSX.Element[] = []
Expand Down Expand Up @@ -577,15 +576,15 @@ export const MoorhenMapCard = forwardRef<any, MoorhenMapCardPropsInterface>((pro
</OverlayTrigger>
}

return <Card ref={cardRef} className="px-0" style={{ display: 'flex', minWidth: props.sideBarWidth, marginBottom: '0.5rem', padding: '0' }} key={props.map.molNo}>
return <Card ref={cardRef} className="px-0" style={{ display: 'flex', minWidth: convertRemToPx(20), marginBottom: '0.5rem', padding: '0' }} key={props.map.molNo}>
<Card.Header style={{ padding: '0.1rem' }}>
<Stack gap={2} direction='horizontal'>
<Col className='align-items-center' style={{ display: 'flex', justifyContent: 'left', color: isDark ? 'white' : 'black' }}>
{getNameLabel(props.map)}
{getMapColourSelector()}
</Col>
<Col style={{ display: 'flex', justifyContent: 'right' }}>
{getButtonBar(props.sideBarWidth)}
{getButtonBar()}
</Col>
</Stack>
</Card.Header>
Expand Down Expand Up @@ -616,7 +615,7 @@ export const MoorhenMapCard = forwardRef<any, MoorhenMapCardPropsInterface>((pro
logScale={true}
showSliderTitle={false}
isDisabled={!mapIsVisible}
initialValue={props.initialContour}
initialValue={initialContour}
externalValue={mapContourLevel}
setExternalValue={(newVal) => dispatch( setContourLevel({molNo: props.map.molNo, contourLevel: newVal}) )}
/>
Expand All @@ -633,7 +632,7 @@ export const MoorhenMapCard = forwardRef<any, MoorhenMapCardPropsInterface>((pro
sliderTitle="Radius"
decimalPlaces={2}
isDisabled={!mapIsVisible}
initialValue={props.initialRadius}
initialValue={initialRadius}
externalValue={mapRadius}
setExternalValue={(newVal) => dispatch( setMapRadius({molNo: props.map.molNo, radius: newVal}) )}
/>
Expand All @@ -657,7 +656,3 @@ export const MoorhenMapCard = forwardRef<any, MoorhenMapCardPropsInterface>((pro
</Card.Body>
</Card >
})

MoorhenMapCard.defaultProps = {
initialContour: 0.8, initialRadius: 13
}
4 changes: 2 additions & 2 deletions baby-gru/src/components/card/MoorhenMoleculeCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -697,7 +697,7 @@ export const MoorhenMoleculeCard = forwardRef<any, MoorhenMoleculeCardPropsInter
Ligands
</AccordionSummary>
<AccordionDetails style={{padding: '0.2rem', backgroundColor: isDark ? '#ced5d6' : 'white'}}>
<MoorhenLigandList setBusy={setBusyLoadingLigands} commandCentre={props.commandCentre} molecule={props.molecule} glRef={props.glRef} height={convertViewtoPx(40, height)}/>
<MoorhenLigandList setBusy={setBusyLoadingLigands} commandCentre={props.commandCentre} molecule={props.molecule} height={convertViewtoPx(40, height)}/>
</AccordionDetails>
</Accordion>
{props.molecule.hasGlycans &&
Expand All @@ -706,7 +706,7 @@ export const MoorhenMoleculeCard = forwardRef<any, MoorhenMoleculeCardPropsInter
Carbohydrates
</AccordionSummary>
<AccordionDetails style={{padding: '0.2rem', backgroundColor: isDark ? '#ced5d6' : 'white'}}>
<MoorhenCarbohydrateList setBusy={setBusyLoadingCarbohydrates} commandCentre={props.commandCentre} molecule={props.molecule} glRef={props.glRef} height={convertViewtoPx(40, height)}/>
<MoorhenCarbohydrateList setBusy={setBusyLoadingCarbohydrates} molecule={props.molecule} height={convertViewtoPx(40, height)}/>
</AccordionDetails>
</Accordion>
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ import { useSelector } from "react-redux";
export const MoorhenAddTerminalResidueButton = (props: moorhen.ContextButtonProps) => {

const [toolTip, setToolTip] = useState<string>("Add Residue")

const shortCuts = useSelector((state: moorhen.State) => state.shortcutSettings.shortCuts)

const { selectedMolecule, chosenAtom, urlPrefix } = { ...props }

const getCootCommandInput = (selectedMolecule: moorhen.Molecule, chosenAtom: moorhen.ResidueSpec, localParameters?: string): moorhen.cootCommandKwargs => {
return {
message: 'coot_command',
Expand All @@ -27,12 +30,10 @@ export const MoorhenAddTerminalResidueButton = (props: moorhen.ContextButtonProp
}, [shortCuts])

return <MoorhenContextButtonBase
icon={<img className="moorhen-context-button__icon" src={`${props.urlPrefix}/pixmaps/add-peptide-1.svg`} alt='Add Residue' />}
icon={<img className="moorhen-context-button__icon" src={`${urlPrefix}/pixmaps/add-peptide-1.svg`} alt='Add Residue' />}
needsMapData={true}
toolTipLabel={toolTip}
cootCommandInput={getCootCommandInput(props.selectedMolecule, props.chosenAtom)}
cootCommandInput={getCootCommandInput(selectedMolecule, chosenAtom)}
{...props}
/>
}

MoorhenAddTerminalResidueButton.defaultProps = { mode: 'edit' }
Loading
Loading