fix: User Preferences Issues (#1207)

* fix: study list translations

* Don't render until translations are ready

* Try to wait for translations to load

* Use null to render "nothing"

* Try toggling useSuspense off up a layer

* logging

* Remove useSuspense false flags

* DO NOT OPEN A PR WITH IT.
Experimental changes only.
Try to solve issues with useTranslation hooks
 #Please enter the commit message for your changes. Lines starting

* Remove unecessary changes

* feat: 🎸 useMedia hook to not use one more prop for upd state vl

* docs: Add license scan report and status (#1161)

Signed-off-by: fossabot <badges@fossa.io>

* fix: 🐛 Fix for JS breaking on header (#1164)

* feat: 🎸 Code review and refact

Revised code based on PRs(variable alias,...). Changed hook for
useMedia. Now, it provides two hooks: one to get displayMediaSize and
other to get Entity(component, objects...) based on displayMediaSize.
Implemented a similar solution for state manager to store
mediaQueryList(s) and displaySize for app.

* feat: 🎸 Fine tunning on mediaQuery value, fixed issue about it

* fix: 🐛 Fixed issue and refactoring

Fixed js exception and also refactoring userPreferences components to
functional component

* fix: 🐛 Code review. Localstorage fix minor bugs

* fix: 🐛 Ensure hotkey lower case always

* fix: translation switcher

* chore(release): publish [skip ci]

 - @ohif/extension-vtk@0.53.6
 - @ohif/ui@0.62.1
 - @ohif/viewer@2.8.2

* Add new modal service

* Change serviceManager prop to servicesManager

* CR Update: fix casing and add required proptypes to providers

* CR Update: Improve ohifmodal proptypes

* CR Update: Fix typo in extensionmanager

* CR Update: add default props to service and check service in provider

* Refactor modal provider to better use its own state

* ci: don't build our master branch (#1177)

* ci: don't build our master branch

* Add netlify-cli as a dev dependency

* ci: trying a sheltered merge flow for promotions

* Use modal instead of modal context

* Ci/promotable builds (#1179)

* ci: don't build our master branch

* Add netlify-cli as a dev dependency

* ci: trying a sheltered merge flow for promotions

* ci: try building with QUICK_BUILD flag

* Change modal children order

* Ci/promotable builds (#1180)

* ci: don't build our master branch

* Add netlify-cli as a dev dependency

* ci: trying a sheltered merge flow for promotions

* ci: try building with QUICK_BUILD flag

* Try using ~/repo prefix in command

* Ci/promotable builds (#1181)

* ci: don't build our master branch

* Add netlify-cli as a dev dependency

* ci: trying a sheltered merge flow for promotions

* ci: try building with QUICK_BUILD flag

* Try using ~/repo prefix in command

* ci: make sure netlify command is available

* Ci/promotable builds (#1182)

* ci: don't build our master branch

* Add netlify-cli as a dev dependency

* ci: trying a sheltered merge flow for promotions

* ci: try building with QUICK_BUILD flag

* Try using ~/repo prefix in command

* ci: make sure netlify command is available

* ci: use sudo for global command

* Fix OHIFModal proptypes

* Ci/promotable builds (#1183)

* ci: don't build our master branch

* Add netlify-cli as a dev dependency

* ci: trying a sheltered merge flow for promotions

* ci: try building with QUICK_BUILD flag

* Try using ~/repo prefix in command

* ci: make sure netlify command is available

* ci: use sudo for global command

* Inline personal access token w/ env var

* Ci/promotable builds (#1184)

* ci: don't build our master branch

* Add netlify-cli as a dev dependency

* ci: trying a sheltered merge flow for promotions

* ci: try building with QUICK_BUILD flag

* Try using ~/repo prefix in command

* ci: make sure netlify command is available

* ci: use sudo for global command

* Inline personal access token w/ env var

* ci: workaround for sudo limitations

* ci: restore release workflow (#1185)

* ci: don't build our master branch

* Add netlify-cli as a dev dependency

* ci: trying a sheltered merge flow for promotions

* ci: try building with QUICK_BUILD flag

* Try using ~/repo prefix in command

* ci: make sure netlify command is available

* ci: use sudo for global command

* Inline personal access token w/ env var

* ci: workaround for sudo limitations

* ci: restore release workflow

* Pass services to each module, improve tests

* Add servicesManager test and registerServices method

* Fix key warning of snackbar elements

* Remove netlify-cli; we';ll install this on CI server

* Update staging and prod netlify site IDs

* Clean up NPM_PUBLISH step

* Clean up DOCS_PUBLISH step

* Clean up Deploy workflow

* Custom executor to override cypress config

* Spacing

* Use an existing docker hub image

* Switch to npx instead of digging into npm bin location

* Remove e2e test before prod deploy

* Add workflow images

* docs: continous integrationn

* Add default props to modal

* chore(release): publish [skip ci]

 - @ohif/extension-cornerstone@1.5.1
 - @ohif/extension-vtk@0.53.7
 - @ohif/core@1.9.1
 - @ohif/ui@0.62.2
 - @ohif/viewer@2.8.3

* chore(release): publish [skip ci]

 - @ohif/extension-vtk@0.53.8
 - @ohif/core@1.10.0
 - @ohif/ui@0.62.3
 - @ohif/viewer@2.8.4

* ci: Redirect site traffic to index.html if file is not resolved

* ci: fix typo

* fix: 🐛 Code review. Remove 'global state' for displaySize

* fix: 🐛 Code review. Ref back to useMedia and pass value down

Code review. Ref back to useMedia and pass value down (components)
instead of creating a specialized hook to tied any component on it

* fix: translation switcher

* fix

* cleanup

* add missed translation

* fix: 🐛 Code review

* fix: 🐛 Fix unit tests

* fix: 🐛 Fix unit test

* fix: 🐛 Code merge solve conflicts. Missing files changes

* Merge from master. Missing files changes

* feat: 🎸 Code review. Fix issues with DatePicker

Fixed at least the minimum issue with datePicker and update some content
on every translation changed

* fix: 🐛 Code review. Style fix on modal

* fixes in general preferences after merge

* fix

* export default i18n language

* translation fixes

* increase snackbar zindex

* initialize language

* WIP propagate props<>state fixes

* fix state propagation

* remove hotkey error when reset default

* fix datePicker

* i18n updates

* fix i18n strings

* fix reset default -- set right input value

* fix default language

* fix e2e for user preferences

* small fix datePicker props

* remove i18n from window -- debugging purposes only

* lint fixes
This commit is contained in:
Rodrigo Antinarelli 2019-11-28 02:48:27 -03:00 committed by Danny Brown
parent fd1a9e2abe
commit 1df21a9e07
31 changed files with 1332 additions and 737 deletions

View File

@ -1,4 +1,3 @@
import cloneDeep from 'lodash.clonedeep';
import hotkeys from './hotkeys';
import log from './../log.js';
@ -44,20 +43,68 @@ export class HotkeysManager {
}
/**
* Registers a list of hotkeydefinitions. Optionally, sets the
* default hotkey bindings for all provided definitions. These
* Registers a list of hotkeydefinitions.
*
* @param {HotkeyDefinition[] | Object} hotkeyDefinitions Contains hotkeys definitions
*/
setHotkeys(hotkeyDefinitions) {
const definitions = Array.isArray(hotkeyDefinitions)
? [...hotkeyDefinitions]
: this._parseToArrayLike(hotkeyDefinitions);
definitions.forEach(definition => this.registerHotkeys(definition));
}
/**
* Set default hotkey bindings. These
* values are used in `this.restoreDefaultBindings`.
*
* @param {HotkeyDefinition[]} hotkeyDefinitions
* @param {Boolean} [isDefaultDefinitions]
* @param {HotkeyDefinition[] | Object} hotkeyDefinitions Contains hotkeys definitions
*/
setHotkeys(hotkeyDefinitions, isDefaultDefinitions = false) {
const definitions = cloneDeep(hotkeyDefinitions);
definitions.forEach(definition => this.registerHotkeys(definition));
setDefaultHotKeys(hotkeyDefinitions) {
const definitions = Array.isArray(hotkeyDefinitions)
? [...hotkeyDefinitions]
: this._parseToArrayLike(hotkeyDefinitions);
if (isDefaultDefinitions) {
this.hotkeyDefaults = definitions;
}
this.hotkeyDefaults = definitions;
}
/**
* It parses given object containing hotkeyDefinition to array like.
* Each property of given object will be mapped to an object of an array. And its property name will be the value of a property named as commandName
*
* @param {HotkeyDefinition[] | Object} hotkeyDefinitions Contains hotkeys definitions
* @returns {HotkeyDefinition[]}
*/
_parseToArrayLike(hotkeyDefinitionsObj) {
const copy = { ...hotkeyDefinitionsObj };
return Object.entries(copy).map(entryValue =>
this._parseToHotKeyObj(entryValue[0], entryValue[1])
);
}
/**
* Return HotkeyDefinition object like based on given property name and property value
* @param {string} propertyName property name of hotkey definition object
* @param {object} propertyValue property value of hotkey definition object
*
* @example
*
* const hotKeyObj = {hotKeyDefA: {keys:[],....}}
*
* const parsed = _parseToHotKeyObj(Object.keys(hotKeyDefA)[0], hotKeyObj[hotKeyDefA]);
* {
* commandName: hotKeyDefA,
* keys: [],
* ....
* }
*
*/
_parseToHotKeyObj(propertyName, propertyValue) {
return {
commandName: propertyName,
...propertyValue,
};
}
/**

View File

@ -94,18 +94,20 @@ describe('HotkeysManager', () => {
expect(firstCallArgs).toEqual(hotkeyDefinitions[0]);
expect(secondCallArgs).toEqual(hotkeyDefinitions[1]);
});
it('does not set this.hotkeyDefaults by default', () => {
it('does not set this.hotkeyDefaults when calling setHotKeys', () => {
const hotkeyDefinitions = [{ commandName: 'dance', keys: '+' }];
hotkeysManager.setHotkeys(hotkeyDefinitions);
expect(hotkeysManager.hotkeyDefaults).toEqual([]);
});
it('sets this.hotkeyDefaults when isDefaultDefinitions is true', () => {
const hotkeyDefinitions = [{ commandName: 'dance', keys: '+' }];
const isDefaultDefinitions = true;
});
hotkeysManager.setHotkeys(hotkeyDefinitions, isDefaultDefinitions);
describe('setDefaultHotKeys()', () => {
it('it sets default hotkeys', () => {
const hotkeyDefinitions = [{ commandName: 'dance', keys: '+' }];
hotkeysManager.setDefaultHotKeys(hotkeyDefinitions);
expect(hotkeysManager.hotkeyDefaults).toEqual(hotkeyDefinitions);
});

View File

@ -11,12 +11,15 @@ const defaultState = {
// order, description, window (int), level (int)
// 0: { description: 'Soft tissue', window: '', level: '' },
},
generalPreferences: {
// language: 'en-US'
},
};
const preferences = (state, action) => {
switch (action.type) {
case 'SET_USER_PREFERENCES': {
const newState = action.state ? action.state : cloneDeep(defaultState);
const newState = action.state || cloneDeep(defaultState);
return Object.assign({}, state, newState);
}

View File

@ -42,6 +42,7 @@ const locizeOptions = {
const envUseLocize = !!config.USE_LOCIZE;
const envApiKeyAvailable = !!config.LOCIZE_API_KEY;
const DEFAULT_LANGUAGE = 'en-US';
function initI18n(
detection = detectionOptions,
@ -74,7 +75,7 @@ function initI18n(
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
fallbackLng: 'en-US',
fallbackLng: DEFAULT_LANGUAGE,
saveMissing: apiKeyAvailable,
debug: debugMode,
keySeparator: false,
@ -111,7 +112,7 @@ function initI18n(
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
fallbackLng: 'en-US',
fallbackLng: DEFAULT_LANGUAGE,
resources: locales,
debug: debugMode,
keySeparator: false,
@ -136,5 +137,6 @@ customDebug(`version ${pkg.version} loaded.`, 'info');
i18n.initializing = initI18n();
i18n.initI18n = initI18n;
i18n.addLocales = addLocales;
i18n.defaultLanguage = DEFAULT_LANGUAGE;
export default i18n;

View File

@ -0,0 +1,3 @@
{
"No hotkeys found": "Nenhuma tecla de atalho está configurada para este aplicativo. As teclas de atalho podem ser configuradas no arquivo app-config.js do aplicativo."
}

View File

@ -0,0 +1,7 @@
import UserPreferencesModal from "./UserPreferencesModal.json";
export default {
'ar': {
UserPreferencesModal,
}
};

View File

@ -1,6 +1,9 @@
{
"Cancel": "$t(Buttons:Cancel)",
"No hotkeys found": "No hotkeys are configured for this application. Hotkeys can be configured in the application's app-config.js file.",
"Reset to Defaults": "$t(Buttons:Reset to Defaults)",
"ResetDefaultMessage": "Preferences successfully reset to default. <br /> You must <strong>Save</strong> to perform this action.",
"Save": "$t(Buttons:Save)",
"SaveMessage": "Preferences saved",
"User Preferences": "User Preferences"
}

View File

@ -1,3 +1,4 @@
import ar from './ar/';
import en_US from './en-US/';
import es from './es/';
import ja_JP from './ja-JP/';
@ -7,6 +8,7 @@ import vi from './vi/';
import zh from './zh/';
export default {
...ar,
...en_US,
...es,
...ja_JP,

View File

@ -1,6 +1,8 @@
{
"Cancel": "Cancelar",
"Reset to Defaults": "Restaurar Default",
"ResetDefaultMessage": "Preferências resetadas com sucesso. <br /> Você deve <strong>Salvar</strong> para que essa ação seja realizada.",
"Save": "Salvar",
"SaveMessage": "Preferências salvas",
"User Preferences": "Preferências do Usuário"
}

View File

@ -1,14 +1,12 @@
import React, { useState, useEffect } from 'react';
import i18n from '@ohif/i18n';
import React from 'react';
import PropTypes from 'prop-types';
import './LanguageSwitcher.styl';
import { withTranslation } from '../../contextProviders';
const LanguageSwitcher = () => {
const getCurrentLanguage = (language = i18n.language) =>
language.split('-')[0];
const LanguageSwitcher = ({ language, onLanguageChange }) => {
const parseLanguage = lang => lang.split('-')[0];
const [currentLanguage, setCurrentLanguage] = useState(getCurrentLanguage());
const languages = [
// TODO: list of available languages should come from i18n.options.resources
{
@ -21,46 +19,31 @@ const LanguageSwitcher = () => {
},
];
const onChange = () => {
const onChange = event => {
const { value } = event.target;
const language = getCurrentLanguage(value);
setCurrentLanguage(language);
i18n.init({
fallbackLng: language,
lng: language,
});
onLanguageChange(parseLanguage(value));
};
useEffect(() => {
let mounted = true;
i18n.on('languageChanged', () => {
if (mounted) {
setCurrentLanguage(getCurrentLanguage());
}
});
return () => {
mounted = false;
};
}, []);
return (
<select
name="language-select"
id="language-select"
className="language-select"
value={currentLanguage}
value={parseLanguage(language)}
onChange={onChange}
>
{languages.map(language => (
<option key={language.value} value={language.value}>
{language.label}
{languages.map(lng => (
<option key={lng.value} value={lng.value}>
{lng.label}
</option>
))}
</select>
);
};
LanguageSwitcher.propTypes = {
language: PropTypes.string.isRequired,
onLanguageChange: PropTypes.func.isRequired,
};
export default withTranslation('UserPreferencesModal')(LanguageSwitcher);

View File

@ -131,7 +131,6 @@ CustomDateRangePicker.propTypes = {
end: PropTypes.required,
})
),
autoFocus: PropTypes.bool.isRequired,
onDatesChange: PropTypes.func.isRequired,
startDate: PropTypes.instanceOf(Date),
endDate: PropTypes.instanceOf(Date),

View File

@ -81,7 +81,7 @@ function StudyList(props) {
const mediumTableMeta = [
{
displayText: `${t('Patient')} / ${t('MRN')}`,
displayText: `${t('PatientName')} / ${t('MRN')}`,
fieldName: 'patientNameOrId',
inputType: 'text',
size: 250,
@ -187,7 +187,6 @@ function StudyList(props) {
studyDate={study.studyDate}
studyDescription={study.studyDescription || ''}
studyInstanceUid={study.studyInstanceUid}
t={t}
displaySize={displaySize}
/>
))}
@ -239,10 +238,11 @@ function TableRow(props) {
studyDescription,
studyInstanceUid,
onClick: handleClick,
t,
displaySize,
} = props;
const { t } = useTranslation('StudyList');
const largeRowTemplate = (
<tr
onClick={() => handleClick(studyInstanceUid)}

View File

@ -103,15 +103,14 @@ function TableSearchFilter(props) {
// https://github.com/airbnb/react-dates
<CustomDateRangePicker
// Required
startDate={getDateEntry(studyDateTo, defaultStartDate)}
startDate={getDateEntry(studyDateFrom, defaultStartDate)}
startDateId="start-date"
endDate={getDateEntry(studyDateFrom, defaultEndDate)}
endDate={getDateEntry(studyDateTo, defaultEndDate)}
endDateId="end-date"
autoFocus={false}
// TODO: We need a dynamic way to determine which fields values to update
onDatesChange={({ startDate, endDate, preset = false }) => {
onValueChange('studyDateTo', startDate);
onValueChange('studyDateFrom', endDate);
onValueChange('studyDateFrom', startDate);
onValueChange('studyDateTo', endDate);
}}
focusedInput={focusedInput}
onFocusChange={updatedVal => setFocusedInput(updatedVal)}

View File

@ -1,17 +1,57 @@
import React, { Component } from 'react';
import React from 'react';
import PropTypes from 'prop-types';
import LanguageSwitcher from '../languageSwitcher';
import i18n from '@ohif/i18n';
export class GeneralPreferences extends Component {
render() {
return (
<div className="general-preferences-wrapper">
<div className="col-sm-3">
<label htmlFor="language-select" className="p-r-1">
Language
</label>
<LanguageSwitcher />
</div>
/**
* General Preferences tab
*/
/**
* General Preferences tab
* It renders the General Preferences content
*
* It stores current state and whenever it changes, component messages parent of new value (through function callback)
* @param {object} props component props
* @param {string} props.name Tab`s name
* @param {object} props.generalPreferences Data for initial state
* @param {function} props.onTabStateChanged Callback function to communicate parent in case its states changes
* @param {function} props.onTabErrorChanged Callback Function in case any error on tab
*/
function GeneralPreferences({
generalPreferences,
name,
onTabStateChanged,
onTabErrorChanged,
}) {
const { language = i18n.language } = generalPreferences;
const onLanguageChange = language => {
onTabStateChanged(name, {
generalPreferences: { ...generalPreferences, language },
});
};
return (
<div className="general-preferences-wrapper">
<div className="col-sm-3">
<label htmlFor="language-select" className="p-r-1">
Language
</label>
<LanguageSwitcher
language={language}
onLanguageChange={onLanguageChange}
/>
</div>
);
}
</div>
);
}
GeneralPreferences.propTypes = {
generalPreferences: PropTypes.any,
name: PropTypes.string,
onTabStateChanged: PropTypes.func,
onTabErrorChanged: PropTypes.func,
};
export { GeneralPreferences };

View File

@ -1,80 +1,238 @@
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import './HotKeysPreferences.styl';
import React, { Component } from 'react';
import {
allowedKeys,
disallowedCombinations,
specialKeys,
} from './hotKeysConfig.js';
import PropTypes from 'prop-types';
import isEqual from 'lodash.isequal';
export class HotKeysPreferences extends Component {
static propTypes = {
hotkeyDefinitions: PropTypes.arrayOf(
PropTypes.shape({
commandName: PropTypes.string,
keys: PropTypes.arrayOf(PropTypes.string),
label: PropTypes.string,
})
).isRequired,
const getKeysPressedArray = keyDownEvent => {
const keysPressedArray = [];
const { ctrlKey, altKey, shiftKey } = keyDownEvent;
if (ctrlKey && !altKey) {
keysPressedArray.push('ctrl');
}
if (shiftKey && !altKey) {
keysPressedArray.push('shift');
}
if (altKey && !ctrlKey) {
keysPressedArray.push('alt');
}
return keysPressedArray;
};
const findConflictingCommand = (
originalHotKeys,
currentCommandName,
currentHotKeys
) => {
let firstConflictingCommand = undefined;
for (const commandName in originalHotKeys) {
const toolHotKeys = originalHotKeys[commandName].keys;
if (
isEqual(toolHotKeys, currentHotKeys) &&
commandName !== currentCommandName
) {
firstConflictingCommand = originalHotKeys[commandName];
break;
}
}
return firstConflictingCommand;
};
/**
* Splits given keysObj into arrays. Each array item will be a representation of column
* @param {obj} keysObj objects to be splitted into columns
* @param {number} columnSize How many rows per column
*/
const getHotKeysArrayColumns = (keysObj = {}, columnSize) => {
if (isNaN(columnSize)) {
return keysObj;
}
const keys = Object.keys(keysObj);
const keysValues = Object.values(keysObj);
const keysLength = keys.length;
// Columns from left should be bigger;
let currentColumn = 0;
const dividedKeys = [];
for (
let it = 0;
it < keysLength;
it++, it % columnSize === 0 ? currentColumn++ : currentColumn
) {
if (!dividedKeys[currentColumn]) {
dividedKeys[currentColumn] = [];
}
dividedKeys[currentColumn][keys[it]] = keysValues[it];
}
return dividedKeys;
};
const NO_FIELD_ERROR_MESSAGE = undefined;
const formatPressedKeys = pressedKeysArray => pressedKeysArray.join('+');
const unFormatPressedKeys = (pressedKeysStr = '') => pressedKeysStr.split('+');
const inputValidators = (
commandName,
inputValue,
pressedKeys,
lastPressedKey,
originalHotKeys
) => {
let hasError = false;
let errorMessage = NO_FIELD_ERROR_MESSAGE;
const modifierValidator = ({ lastPressedKey }) => {
// Check if it has a valid modifier
const isModifier = ['ctrl', 'alt', 'shift'].includes(lastPressedKey);
if (isModifier) {
hasError = true;
errorMessage =
"It's not possible to define only modifier keys (ctrl, alt and shift) as a shortcut";
return {
hasError,
errorMessage,
};
}
};
constructor(props) {
super(props);
this.state = {
hotKeys: this.props.hotkeyDefinitions,
errorMessages: {},
};
this.onInputKeyDown = this.onInputKeyDown.bind(this);
}
/**
* Normalizes the keys used in a KeyPress event and returns an array of the
* keys pressed
*
* @param {KeyDownEvent} keyDownEvent
* @returns {string[]}
*/
getKeysPressedArray(keyDownEvent) {
const keysPressedArray = [];
const { ctrlKey, altKey, shiftKey } = keyDownEvent;
if (ctrlKey && !altKey) {
keysPressedArray.push('ctrl');
const emptyValidator = ({ inputValue }) => {
if (!inputValue) {
hasError = true;
errorMessage = "Field can't be empty.";
return {
hasError,
errorMessage,
};
}
if (shiftKey && !altKey) {
keysPressedArray.push('shift');
};
const conflictingValidator = ({
commandName,
pressedKeys,
originalHotKeys,
}) => {
const conflictingCommand = findConflictingCommand(
originalHotKeys,
commandName,
pressedKeys
);
if (conflictingCommand) {
hasError = true;
errorMessage = `"${conflictingCommand.label}" is already using the "${pressedKeys}" shortcut.`;
return {
hasError,
errorMessage,
};
}
};
if (altKey && !ctrlKey) {
keysPressedArray.push('alt');
const disallowedValidator = ({ inputValue, pressedKeys, lastPressedKey }) => {
const modifierCommand = formatPressedKeys(
pressedKeys.slice(0, pressedKeys.length - 1)
);
const disallowedCombination = disallowedCombinations[modifierCommand];
const hasDisallowedCombinations = disallowedCombination
? disallowedCombination.includes(lastPressedKey)
: false;
if (hasDisallowedCombinations) {
hasError = true;
errorMessage = `"${inputValue}" shortcut combination is not allowed`;
return {
hasError,
errorMessage,
};
}
};
return keysPressedArray;
}
const validators = [
emptyValidator,
modifierValidator,
conflictingValidator,
disallowedValidator,
];
getConflictingCommand(currentCommandName, currentHotKeys) {
return this.state.hotKeys.find((tool, index) => {
const toolHotKeys = tool.keys[0];
return (
toolHotKeys &&
toolHotKeys === currentHotKeys &&
tool.commandName !== currentCommandName
);
for (const validator of validators) {
const validation = validator({
commandName,
inputValue,
pressedKeys,
lastPressedKey,
originalHotKeys,
});
if (validation && validation.hasError) {
return validation;
}
}
/**
*
* @param {String} commandName
* @param {KeyDownEvent} keyDownEvent
* @param {Boolean} [displayPressedKey=false]
*/
updateInputText(commandName, keyDownEvent, displayPressedKey = false) {
const pressedKeys = this.getKeysPressedArray(keyDownEvent);
// validation has passed successfully
return {
hasError,
errorMessage,
};
};
/**
* HotKeysPreferencesRow
* Renders row for hotkey preference
* It stores current state and whenever it changes, component messages parent of new value (through function callback)
* @param {object} props component props
* @param {string} props.commandName command name associated to given row
* @param {string[]} props.hotkeys keys associated to given command
* @param {object} props.originalHotKeys original hotkeys values
* @param {function} props.onSuccessChanged Callback function to communicate parent in case its states changes
* @param {function} props.onFailureChanged Callback Function in case any error on row
*/
function HotKeyPreferencesRow({
commandName,
hotkeys,
label,
originalHotKeys,
tabError,
onSuccessChanged,
onFailureChanged,
}) {
const [inputValue, setInputValue] = useState(formatPressedKeys(hotkeys));
const [error, setError] = useState(false);
const [fieldErrorMessage, setFieldErrorMessage] = useState(
NO_FIELD_ERROR_MESSAGE
);
// reset error count if tab has no errors
useEffect(() => {
if (!tabError) {
setError(false);
setFieldErrorMessage(NO_FIELD_ERROR_MESSAGE);
setInputValue(formatPressedKeys(hotkeys));
}
}, [tabError]);
// update state values if props changes
useEffect(() => {
setInputValue(formatPressedKeys(hotkeys));
}, [hotkeys]);
const updateInputText = (keyDownEvent, displayPressedKey = false) => {
const pressedKeys = getKeysPressedArray(keyDownEvent);
if (displayPressedKey) {
const specialKeyName = specialKeys[keyDownEvent.which];
@ -82,183 +240,213 @@ export class HotKeysPreferences extends Component {
specialKeyName ||
keyDownEvent.key ||
String.fromCharCode(keyDownEvent.keyCode);
// ensure lowerCase
pressedKeys.push(keyName.toLowerCase());
}
this.updateHotKeysState(commandName, pressedKeys.join('+'));
}
setInputValue(formatPressedKeys(pressedKeys));
};
updateHotKeysState(commandName, keys) {
const hotKeys = this.state.hotKeys;
const hotKeyIndex = this.state.hotKeys.findIndex(
x => x.commandName === commandName
// validate input value
const validateInput = () => {
const pressedKeys = unFormatPressedKeys(inputValue);
const lastPressedKey = pressedKeys[pressedKeys.length - 1];
const {
hasError = false,
errorMessage = NO_FIELD_ERROR_MESSAGE,
} = inputValidators(
commandName,
inputValue,
pressedKeys,
lastPressedKey,
originalHotKeys
);
hotKeys[hotKeyIndex].keys[0] = keys;
this.setState({ hotKeys });
}
updateErrorsState(toolKey, errorMessage) {
const errorMessages = this.state.errorMessages;
errorMessages[toolKey] = errorMessage;
this.setState({ errorMessages });
}
if (hasError) {
setInputValue('');
} else {
onSuccessChanged([inputValue]);
}
onInputKeyDown(event, commandName) {
if (hasError !== error) {
setError(hasError);
}
setFieldErrorMessage(errorMessage);
};
useEffect(() => {
onFailureChanged(error);
}, [error]);
const onInputKeyDown = event => {
// Prevent ESC key from propagating and closing the modal
if (event.key === 'Escape') {
event.stopPropagation();
}
if (allowedKeys.includes(event.keyCode)) {
this.updateInputText(commandName, event, true);
} else {
this.updateInputText(commandName, event, false);
}
updateInputText(event, allowedKeys.includes(event.keyCode));
event.preventDefault();
}
};
onChange(event, commandName) {
if (event.ctrlKey || event.altKey || event.shiftKey) {
return;
return (
<tr key={commandName}>
<td className="text-right p-r-1">{label}</td>
<td width="200">
<label
className={`wrapperLabel ${
fieldErrorMessage !== undefined ? 'state-error' : ''
} `}
data-key="defaultTool"
>
<input
readOnly={true}
type="text"
value={inputValue}
className="form-control hotkey text-center"
onKeyDown={onInputKeyDown}
onBlur={validateInput}
/>
<span className="wrapperText" />
<span className="errorMessage">{fieldErrorMessage}</span>
</label>
</td>
</tr>
);
}
HotKeyPreferencesRow.propTypes = {
commandName: PropTypes.string.isRequired,
hotkeys: PropTypes.array.isRequired,
label: PropTypes.string.isRequired,
originalHotKeys: PropTypes.object.isRequired,
tabError: PropTypes.bool.isRequired,
onSuccessChanged: PropTypes.func.isRequired,
onFailureChanged: PropTypes.func.isRequired,
};
/**
* HotKeysPreferences tab
* It renders all hotkeys displayed into columns/rows
*
* It stores current state and whenever it changes, component messages parent of new value (through function callback)
* @param {object} props component props
* @param {string} props.name Tab`s name
* @param {object} props.hotkeyDefinitions Data for initial state
* @param {function} props.onTabStateChanged Callback function to communicate parent in case its states changes
* @param {function} props.onTabErrorChanged Callback Function in case any error on tab
*/
function HotKeysPreferences({
hotkeyDefinitions,
name,
tabError,
onTabStateChanged,
onTabErrorChanged,
}) {
const [tabState, setTabState] = useState(hotkeyDefinitions);
const [tabErrorCounter, setTabErrorCounter] = useState(0);
const [numColumns] = useState(2);
const [columnSize] = useState(() =>
Math.ceil(Object.keys(tabState || {}).length / numColumns)
);
const splittedHotKeys = getHotKeysArrayColumns(tabState, columnSize);
const onHotKeyChanged = (commandName, hotkeyDefinition, keys) => {
const newState = {
...tabState,
[commandName]: { ...hotkeyDefinition, keys },
};
setTabState(newState);
onTabStateChanged(name, { hotkeyDefinitions: newState });
};
const onErrorChanged = (toInc = true) => {
const increment = toInc ? 1 : -1;
const newValue = tabErrorCounter + increment;
if (newValue >= 0) {
setTabErrorCounter(newValue);
}
};
// reset error count if tab has no errors
useEffect(() => {
if (!tabError) {
setTabErrorCounter(0);
// update tab state
setTabState({ ...hotkeyDefinitions });
}
}, [tabError]);
// tell parent to update its state
useEffect(() => {
if (tabErrorCounter === 0) {
onTabErrorChanged(name, false);
}
const hotKeyIndex = this.state.hotKeys.findIndex(
x => x.commandName === commandName
);
const hotKey = this.state.hotKeys[hotKeyIndex];
const keys = hotKey.keys[0];
const pressedKeys = keys.split('+');
const lastPressedKey = pressedKeys[pressedKeys.length - 1].toLowerCase();
if (tabErrorCounter === 1) {
onTabErrorChanged(name, true);
}
}, [tabErrorCounter]);
// clear the prior errors
this.setState({ errorMessages: {} }, () => {
// Check if it has a valid modifier
const isModifier = ['ctrl', 'alt', 'shift'].includes(lastPressedKey);
if (isModifier) {
this.updateHotKeysState(commandName, '');
this.updateErrorsState(
commandName,
"It's not possible to define only modifier keys (ctrl, alt and shift) as a shortcut"
);
return;
}
// update local state if parent updates
useEffect(() => {
setTabState({ ...hotkeyDefinitions });
}, [hotkeyDefinitions]);
/*
* Check if it has some conflict
*/
const conflictedCommand = this.getConflictingCommand(commandName, keys);
if (conflictedCommand) {
this.updateHotKeysState(commandName, '');
this.updateErrorsState(
commandName,
`"${conflictedCommand.label}" is already using the "${keys}" shortcut.`
);
return;
}
/*
* Check if is a valid combination
*/
const modifierCommand = pressedKeys
.slice(0, pressedKeys.length - 1)
.join('+')
.toLowerCase();
const disallowedCombination = disallowedCombinations[modifierCommand];
const hasDisallowedCombinations = disallowedCombination
? disallowedCombination.includes(lastPressedKey)
: false;
if (hasDisallowedCombinations) {
this.updateHotKeysState(commandName, '');
this.updateErrorsState(
commandName,
`"${pressedKeys.join('+')}" shortcut combination is not allowed`
);
return;
}
});
}
renderRow({ commandName, label, keys }) {
return (
<tr key={commandName}>
<td className="text-right p-r-1">{label}</td>
<td width="200">
<label
className={`wrapperLabel ${
this.state.errorMessages[commandName] !== undefined
? 'state-error'
: ''
} `}
ref={input => (this[commandName] = input)}
data-key="defaultTool"
>
<input
readOnly={true}
type="text"
value={keys[0]}
vali="true"
className="form-control hotkey text-center"
onKeyDown={event => this.onInputKeyDown(event, commandName)}
onKeyUp={event => this.onChange(event, commandName)}
/>
<span className="wrapperText" />
<span className="errorMessage">
{this.state.errorMessages[commandName]}
</span>
</label>
</td>
</tr>
);
}
render() {
const halfWayThough = Math.floor(this.state.hotKeys.length / 2);
const firstHalfHotkeys = this.state.hotKeys.slice(0, halfWayThough);
const secondHalfHotkeys = this.state.hotKeys.slice(
halfWayThough,
this.state.hotKeys.length
);
return this.state.hotKeys.length > 0 ? (
<div className="HotKeysPreferences">
{/* <!-- Column 1 --> */}
<div className="column">
<table className="full-width">
<thead>
<tr>
<th className="text-right p-r-1">Function</th>
<th className="text-center">Shortcut</th>
</tr>
</thead>
<tbody>
{firstHalfHotkeys.map(hotkeyDefinition =>
this.renderRow(hotkeyDefinition)
)}
</tbody>
</table>
</div>
{/* <!-- Column 2 --> */}
<div className="column">
<table className="full-width">
<thead>
<tr>
<th className="text-right p-r-1">Function</th>
<th className="text-center">Shortcut</th>
</tr>
</thead>
<tbody>
{secondHalfHotkeys.map(hotkeyDefinition =>
this.renderRow(hotkeyDefinition)
)}
</tbody>
</table>
</div>
</div>
) : (
<p>{`No hotkeys are configured for this application. Hotkeys can be configured in the application's app-config.js file.`}</p>
);
}
return (
<div className="HotKeysPreferences">
{splittedHotKeys.length > 0
? splittedHotKeys.map((columnHotKeys, index) => {
return (
<div className="column" key={index}>
<table className="full-width">
<thead>
<tr>
<th className="text-right p-r-1">Function</th>
<th className="text-center">Shortcut</th>
</tr>
</thead>
<tbody>
{Object.entries(columnHotKeys).map(
hotkeyDefinitionTuple => (
<HotKeyPreferencesRow
key={hotkeyDefinitionTuple[0]}
commandName={hotkeyDefinitionTuple[0]}
hotkeys={hotkeyDefinitionTuple[1].keys}
label={hotkeyDefinitionTuple[1].label}
originalHotKeys={tabState}
tabError={tabError}
onSuccessChanged={keys =>
onHotKeyChanged(
hotkeyDefinitionTuple[0],
hotkeyDefinitionTuple[1],
keys
)
}
onFailureChanged={onErrorChanged}
></HotKeyPreferencesRow>
)
)}
</tbody>
</table>
</div>
);
})
: null}
</div>
);
}
HotKeysPreferences.propTypes = {
hotkeyDefinitions: PropTypes.any,
name: PropTypes.string,
tabError: PropTypes.bool,
onTabStateChanged: PropTypes.func,
onTabErrorChanged: PropTypes.func,
};
export { HotKeysPreferences };

View File

@ -10,7 +10,7 @@ export class UserPreferences extends Component {
static defaultProps = {
hotkeyDefinitions: [],
windowLevelData: {},
generalData: {},
generalPreferences: {},
};
// TODO: Make this more generic. Tabs should not be restricted to these entries
@ -23,7 +23,8 @@ export class UserPreferences extends Component {
})
).isRequired,
windowLevelData: PropTypes.object.isRequired,
generalData: PropTypes.object.isRequired,
generalPreferences: PropTypes.object.isRequired,
updatePropValue: PropTypes.func.isRequired,
};
state = {
@ -64,7 +65,10 @@ export class UserPreferences extends Component {
return (
<form className="form-themed themed">
<div className="form-content">
<GeneralPreferences generalData={this.props.generalData} />
<GeneralPreferences
generalPreferences={this.props.generalPreferences}
updatePropValue={this.props.updatePropValue}
/>
</div>
</form>
);

View File

@ -1,101 +1,219 @@
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { useSnackbarContext } from '@ohif/ui';
import './UserPreferencesForm.styl';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withTranslation } from '../../contextProviders';
import { useTranslation } from 'react-i18next';
import cloneDeep from 'lodash.clonedeep';
import isEqual from 'lodash.isequal';
import { UserPreferences } from './UserPreferences';
// Tabs Component wrapper
import { UserPreferencesTabs } from './UserPreferencesTabs';
class UserPreferencesForm extends Component {
// TODO: Make this component more generic to allow things other than W/L and hotkeys...
static propTypes = {
onClose: PropTypes.func,
onSave: PropTypes.func,
onResetToDefaults: PropTypes.func,
windowLevelData: PropTypes.object,
hotkeyDefinitions: PropTypes.arrayOf(
PropTypes.shape({
commandName: PropTypes.string,
keys: PropTypes.arrayOf(PropTypes.string),
label: PropTypes.string,
})
).isRequired,
t: PropTypes.func,
// Tabs
import { HotKeysPreferences } from './HotKeysPreferences';
import { WindowLevelPreferences } from './WindowLevelPreferences';
import { GeneralPreferences } from './GeneralPreferences';
/**
@typedef TabObject
@type {Object}
@property {string} name Name for given tab
@property {ReactComponent} Component React component for given tab.
@property {object} props Props State for given tab component
@property {boolean} [hidden] To hidden tab or not
*/
/**
* Create tabs obj.
* @returns {TabObject[]} Array of TabObjs.
*/
const createTabs = () => {
return [
{
name: 'Hotkeys',
Component: HotKeysPreferences,
props: {},
},
{
name: 'General',
Component: GeneralPreferences,
props: {},
},
{
name: 'Window Level',
Component: WindowLevelPreferences,
props: {},
hidden: true,
},
];
};
/**
* Main form component to render preferences tabs and buttons
* @param {object} props component props
* @param {string} props.name Tab`s name
* @param {object} props.hotkeyDefinitions Hotkeys Data
* @param {object} props.windowLevelData Window level data
* @param {function} props.onSave Callback function when saving
* @param {function} props.onClose Callback function when closing
* @param {function} props.onResetToDefaults Callback function when resetting
*/
function UserPreferencesForm({
onClose,
onSave,
onResetToDefaults,
windowLevelData,
hotkeyDefinitions,
generalPreferences,
hotkeysManager,
defaultLanguage,
hotkeyDefaults,
}) {
const [tabs, setTabs] = useState(createTabs());
const createTabsState = (
windowLevelData,
hotkeyDefinitions,
generalPreferences
) => {
return {
Hotkeys: { hotkeyDefinitions },
'Window Level': { windowLevelData },
General: { generalPreferences },
};
};
constructor(props) {
super(props);
const [tabsState, setTabsState] = useState(
createTabsState(windowLevelData, hotkeyDefinitions, generalPreferences)
);
this.state = {
windowLevelData: cloneDeep(props.windowLevelData),
hotkeyDefinitions: cloneDeep(props.hotkeyDefinitions),
};
}
const [tabsError, setTabsError] = useState(
tabs.reduce((acc, tab) => {
acc[tab.name] = false;
return acc;
}, {})
);
save = () => {
this.props.onSave({
windowLevelData: this.state.windowLevelData,
hotkeyDefinitions: this.state.hotkeyDefinitions,
const snackbar = useSnackbarContext();
const { t, ready: translationsAreReady } = useTranslation(
'UserPreferencesModal'
);
const onTabStateChanged = (tabName, newState) => {
setTabsState({ ...tabsState, [tabName]: newState });
};
const onTabErrorChanged = (tabName, hasError) => {
setTabsError({ ...tabsError, [tabName]: hasError });
};
const hasAnyError = () => {
return Object.values(tabsError).reduce((acc, value) => acc || value);
};
const onResetPreferences = () => {
const defaultHotKeyDefitions = {};
hotkeyDefaults.map(item => {
const { commandName, ...values } = item;
defaultHotKeyDefitions[commandName] = { ...values };
});
// update local state
setTabsState({
...tabsState,
Hotkeys: { hotkeyDefinitions: defaultHotKeyDefitions },
General: { generalPreferences: { language: defaultLanguage } },
});
// update tabs state
setTabs(createTabs(windowLevelData, hotkeyDefinitions, generalPreferences));
// reset errors
setTabsError(
tabs.reduce((acc, tab) => {
acc[tab.name] = false;
return acc;
}, {})
);
snackbar.show({
message: (
<div dangerouslySetInnerHTML={{ __html: t('ResetDefaultMessage') }} />
),
type: 'info',
});
};
componentDidUpdate(prev, next) {
const newStateData = {};
const onSavePreferences = event => {
const toSave = Object.values(tabsState).reduce((acc, tabState) => {
return { ...acc, ...tabState };
}, {});
if (!isEqual(prev.windowLevelData, next.windowLevelData)) {
newStateData.windowLevelData = prev.windowLevelData;
}
onSave(toSave);
snackbar.show({
message: t('SaveMessage'),
type: 'success',
});
};
if (!isEqual(prev.hotkeyDefinitions, next.hotkeyDefinitions)) {
newStateData.hotkeyDefinitions = prev.hotkeyDefinitions;
}
// update local state if prop values changes
useEffect(() => {
setTabsState(
createTabsState(windowLevelData, hotkeyDefinitions, generalPreferences)
);
}, [windowLevelData, hotkeyDefinitions, generalPreferences]);
if (newStateData.hotkeyDefinitions || newStateData.windowLevelData) {
this.setState(newStateData);
}
}
render() {
return (
<div className="UserPreferencesForm">
<UserPreferences
windowLevelData={this.state.windowLevelData}
hotkeyDefinitions={this.state.hotkeyDefinitions}
/>
<div className="footer">
<button
className="btn btn-danger pull-left"
data-cy="reset-default-btn"
onClick={this.props.onResetToDefaults}
return translationsAreReady ? (
<div className="UserPreferencesForm">
<UserPreferencesTabs
tabs={tabs}
tabsState={tabsState}
tabsError={tabsError}
onTabStateChanged={onTabStateChanged}
onTabErrorChanged={onTabErrorChanged}
/>
<div className="footer">
<button
className="btn btn-danger pull-left"
data-cy="reset-default-btn"
onClick={onResetPreferences}
>
{t('Reset to Defaults')}
</button>
<div>
<div
onClick={onClose}
data-cy="cancel-btn"
className="btn btn-default"
>
{this.props.t('Reset to Defaults')}
</button>
<div>
<div
onClick={this.props.onClose}
className="btn btn-default"
data-cy="cancel-btn"
>
{this.props.t('Cancel')}
</div>
<button
className="btn btn-primary"
data-cy="save-btn"
onClick={this.save}
>
{this.props.t('Save')}
</button>
{t('Cancel')}
</div>
<button
className="btn btn-primary"
data-cy="save-btn"
disabled={hasAnyError()}
onClick={onSavePreferences}
>
{t('Save')}
</button>
</div>
</div>
);
}
</div>
) : null;
}
const connectedComponent = withTranslation('UserPreferencesForm')(
UserPreferencesForm
);
export { connectedComponent as UserPreferencesForm };
export default connectedComponent;
UserPreferencesForm.propTypes = {
onClose: PropTypes.func,
onSave: PropTypes.func,
onResetToDefaults: PropTypes.func,
windowLevelData: PropTypes.object,
hotkeyDefinitions: PropTypes.object,
generalPreferences: PropTypes.object,
hotkeysManager: PropTypes.object,
defaultLanguage: PropTypes.string,
hotkeyDefaults: PropTypes.array,
};
export { UserPreferencesForm };

View File

@ -0,0 +1,105 @@
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import './UserPreferencesTabs.styl';
/**
* Render tab component
* @param {object} tab TabObject containing tab data
* @param {function} onTabStateChanged Callback Function in case tab changes its state
* @param {function} onTabErrorChanged Callback Function in case any error on tab
*/
const renderTab = (
tab = {},
tabsState,
tabsError,
onTabStateChanged,
onTabErrorChanged
) => {
const { props, Component, name, hidden = false } = tab;
const tabState = tabsState[name];
const tabError = tabsError[name];
return !hidden ? (
<form className="form-themed themed tabs">
<div className="form-content">
<Component
key={name}
{...tabState}
{...props}
name={name}
tabError={tabError}
onTabStateChanged={onTabStateChanged}
onTabErrorChanged={onTabErrorChanged}
></Component>
</div>
</form>
) : null;
};
const renderTabsHeader = (tabs, activeTabIndex, onHeaderChanged) => {
return tabs.length > 0
? tabs.map((tab, index) => {
const { name, hidden = false } = tab;
const tabClass =
index === activeTabIndex ? 'nav-link active' : 'nav-link';
return !hidden ? (
<li
key={name}
onClick={() => {
onHeaderChanged(index);
}}
className={tabClass}
>
<button>{name}</button>
</li>
) : null;
})
: null;
};
/**
* Component to render tabs based on currentActiveTabIndex
*
* In case any tab changes its state this current component tells parent through function callback
* @param {object} props Component props
*/
function UserPreferencesTabs({
tabs,
tabsState,
tabsError,
onTabStateChanged,
onTabErrorChanged,
}) {
const [activeTabIndex, setActiveTabIndex] = useState(0);
return (
<div className="UserPreferencesTabs">
<div className="UserPreferencesTabs__selector">
<div className="dialog-separator-after">
<ul className="nav nav-tabs">
{renderTabsHeader(tabs, activeTabIndex, setActiveTabIndex)}
</ul>
</div>
</div>
{renderTab(
tabs[activeTabIndex],
tabsState,
tabsError,
onTabStateChanged,
onTabErrorChanged
)}
</div>
);
}
UserPreferencesTabs.propTypes = {
tabs: PropTypes.array.isRequired,
tabsState: PropTypes.object.isRequired,
tabsError: PropTypes.object.isRequired,
onTabStateChanged: PropTypes.func.isRequired,
onTabErrorChanged: PropTypes.func.isRequired,
};
export { UserPreferencesTabs };

View File

@ -3,7 +3,7 @@
@import './../../design/styles/common/state.styl'
@import './../../design/styles/common/global.styl'
.UserPreferences
.UserPreferencesTabs
display: flex
flex-direction: column

View File

@ -1,94 +1,132 @@
import React, { Component } from 'react';
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import './WindowLevelPreferences.styl';
/**
* WindowLevelPreferencesRow
* Renders row for window level preference
* It stores current state and whenever it changes, component messages parent of new value (through function callback)
* @param {object} props component props
* @param {string} props.description description for given preset
* @param {number} props.window window value
* @param {number} props.level level value
* @param {string} props.rowName name of given row to identify it
* @param {function} props.onSuccessChanged Callback function to communicate parent in case its states changes
*/
function WindowLevelPreferencesRow({
description,
window,
level,
rowName,
onSuccessChanged,
// onFailureChanged
}) {
const [rowState, setRowState] = useState({ description, window, level });
export class WindowLevelPreferences extends Component {
constructor(props) {
super(props);
this.state = {
data: this.props.windowLevelData,
};
}
static propTypes = {
windowLevelData: PropTypes.object.isRequired,
onChange: PropTypes.func,
const onInputChanged = (event, name) => {
const newValue = event.target.value;
setRowState({ ...rowState, [name]: newValue });
};
onChange(event, key, field) {
const data = this.state.data;
const entry = data[key];
entry[field] = event.target.value;
this.setState({ data });
useEffect(() => {
onSuccessChanged(rowName, rowState);
}, [rowState]);
if (this.props.onChange) {
this.props.onChange(data);
}
}
getWLPreferencesRows(key) {
const entry = this.state.data[key];
const renderTd = (value, name, type) => {
return (
<tr key={key}>
<td className="p-r-1 text-center">{key}</td>
<td className="p-r-1">
<label className="wrapperLabel">
<input
value={entry.description}
type="text"
className="form-control"
onChange={event => {
this.onChange(event, key, 'description');
}}
/>
</label>
</td>
<td className="p-r-1">
<label className="wrapperLabel">
<input
value={entry.window}
type="number"
className="form-control"
onChange={event => {
this.onChange(event, key, 'window');
}}
/>
</label>
</td>
<td className="p-r-1">
<label className="wrapperLabel">
<input
value={entry.level}
type="number"
className="form-control"
onChange={event => {
this.onChange(event, key, 'level');
}}
/>
</label>
</td>
</tr>
<td className="p-r-1">
<label className="wrapperLabel">
<input
value={value}
type={type}
className="form-control"
onChange={event => {
onInputChanged(event, name);
}}
/>
</label>
</td>
);
}
};
render() {
return (
<table className="full-width">
<thead>
<tr>
<th className="p-x-1 text-center presetIndex">Preset</th>
<th className="p-x-1">Description</th>
<th className="p-x-1">Window</th>
<th className="p-x-1">Level</th>
</tr>
</thead>
<tbody>
{Object.keys(this.state.data).map(key => {
return this.getWLPreferencesRows(key);
})}
</tbody>
</table>
);
}
return (
<tr key={rowName}>
<td className="p-r-1 text-center">{rowName}</td>
{renderTd(rowState.description, 'description', 'text')}
{renderTd(rowState.window, 'window', 'number')}
{renderTd(rowState.level, 'level', 'number')}
</tr>
);
}
WindowLevelPreferencesRow.propTypes = {
description: PropTypes.string.isRequired,
window: PropTypes.number.isRequired,
level: PropTypes.number.isRequired,
rowName: PropTypes.string.isRequired,
onSuccessChanged: PropTypes.func.isRequired,
//onFailureChanged: PropTypes.func.isRequired,
};
/**
* WindowLevelPreferences tab
* It renders all window level presets
*
* It stores current state and whenever it changes, component messages parent of new value (through function callback)
* @param {object} props component props
* @param {string} props.name Tab`s name
* @param {object} props.windowLevelData Data for initial state
* @param {function} props.onTabStateChanged Callback function to communicate parent in case its states changes
*/
function WindowLevelPreferences({
windowLevelData,
name,
onTabStateChanged /*onTabErrorChanged*/,
}) {
const [tabState, setTabState] = useState(windowLevelData);
// TODO to be used once error handling is implemented
//const [tabError, setTabError] = useState(false);
const onWindowLevelChanged = (key, state) => {
setTabState({ ...tabState, [key]: state });
};
// tell parent to update its state
useEffect(() => {
onTabStateChanged(name, { windowLevelData: tabState });
}, [tabState]);
return (
<table className="full-width">
<thead>
<tr>
<th className="p-x-1 text-center presetIndex">Preset</th>
<th className="p-x-1">Description</th>
<th className="p-x-1">Window</th>
<th className="p-x-1">Level</th>
</tr>
</thead>
<tbody>
{Object.keys(tabState).map(objKey => (
<WindowLevelPreferencesRow
onSuccessChanged={onWindowLevelChanged}
rowName={objKey}
key={objKey}
description={tabState[objKey].description}
window={tabState[objKey].window}
level={tabState[objKey].level}
></WindowLevelPreferencesRow>
))}
</tbody>
</table>
);
}
WindowLevelPreferences.propTypes = {
windowLevelData: PropTypes.object.isRequired,
name: PropTypes.string.isRequired,
onTabStateChanged: PropTypes.func.isRequired,
//onTabErrorChanged: PropTypes.func.isRequired,
};
export { WindowLevelPreferences };

View File

@ -1,4 +1,4 @@
@import './UserPreferences.styl'
@import './UserPreferencesTabs.styl'
.presetIndex
padding: 0px 10px 0px 10px
padding: 0px 10px 0px 10px

View File

@ -1,4 +1,4 @@
export { UserPreferences } from './UserPreferences.js';
export { UserPreferencesTabs } from './UserPreferencesTabs.js';
export { AboutContent } from '../content/aboutContent/AboutContent.js';
export { UserPreferencesForm } from './UserPreferencesForm.js';
export { GeneralPreferences } from './GeneralPreferences.js';

View File

@ -46,7 +46,7 @@ class DropdownMenu extends Component {
<button
key={key}
className="dd-item"
data-cy="about-item-menu"
data-cy="dd-item-menu"
onClick={() => this.handleOnClick(onClick)}
>
{icon && <Icon {...icon} className="dd-item-icon" />}

View File

@ -270,7 +270,7 @@ describe('OHIF Study Viewer Page', function() {
cy.get('[data-cy="options-menu"]')
.first()
.click();
cy.get('[data-cy="about-item-menu"]')
cy.get('[data-cy="dd-item-menu"]')
.first()
.click();
cy.get('[data-cy="about-modal"]')

View File

@ -59,91 +59,89 @@ describe('OHIF User Preferences', () => {
.should('have.text', 'SOLO USO PARA INVESTIGACIÓN');
// Options menu should be translated
cy.get('[data-cy="options-menu"]').should('have.text', 'Opciones');
cy.get('[data-cy="options-menu"]')
.should('have.text', 'Opciones')
.click();
//TODO: the following code is blocked by issue 1193: https://github.com/OHIF/Viewers/issues/1193
//Once the issue is fixed, the following code should be uncommented
// cy.get('[data-cy="about-item-menu"]')
// .first()
// .should('have.text', 'Acerca de');
// cy.get('[data-cy="about-item-menu"]')
// .last()
// .should('have.text', 'Preferencias');
cy.get('[data-cy="dd-item-menu"]')
.first()
.should('contain.text', 'Acerca de');
cy.get('[data-cy="dd-item-menu"]')
.last()
.should('contain.text', 'Preferencias');
// Close Options menu
cy.get('[data-cy="options-menu"]').click();
});
it('checks if user can cancel the language selection and application will be in English', function() {
cy.get('@userPreferencesGeneralTab')
.click()
.should('have.class', 'active');
// Set language to English and save
cy.setLanguage('English');
// Language dropdown should be displayed
cy.get('#language-select').should('be.visible');
// Set language to Spanish and cancel
cy.setLanguage('Spanish', false);
// Select Spanish and Cancel
cy.get('#language-select').select('Spanish');
cy.get('@cancelBtn')
// Header should be kept in English
cy.get('.research-use')
.scrollIntoView()
.should('have.text', 'INVESTIGATIONAL USE ONLY');
// Options menu should be translated
cy.get('[data-cy="options-menu"]')
.should('have.text', 'Options')
.click();
cy.get('[data-cy="dd-item-menu"]')
.first()
.should('contain.text', 'About');
cy.get('[data-cy="dd-item-menu"]')
.last()
.should('contain.text', 'Preferences');
// Close Options menu
cy.get('[data-cy="options-menu"]').click();
});
it('checks if user can restore to default the language selection and application will be in English', function() {
// Set language to Spanish
cy.setLanguage('Spanish');
//Open Preferences again
cy.openPreferences();
// Go to general tab
cy.get('@userPreferencesGeneralTab').click();
cy.get('@restoreBtn')
.scrollIntoView()
.click();
// TODO: the following code is blocked by issue 1193: https://github.com/OHIF/Viewers/issues/1193
// Once the issue is fixed, the following code should be uncommented
// // Header should be kept in English
// cy.get('.research-use')
// .scrollIntoView()
// .should('have.text', 'INVESTIGATIONAL USE ONLY');
//
// // Options menu should be translated
// cy.get('[data-cy="options-menu"]').should('have.text', 'Options');
//
// cy.get('[data-cy="about-item-menu"]')
// .first()
// .should('have.text', 'About');
// cy.get('[data-cy="about-item-menu"]')
// .last()
// .should('have.text', 'Preferences');
// Save
cy.get('@saveBtn')
.scrollIntoView()
.click();
// Header should be in English
cy.get('.research-use')
.scrollIntoView()
.should('have.text', 'INVESTIGATIONAL USE ONLY');
// Options menu should be in English
cy.get('[data-cy="options-menu"]')
.should('have.text', 'Options')
.click();
cy.get('[data-cy="dd-item-menu"]')
.first()
.should('contain.text', 'About');
cy.get('[data-cy="dd-item-menu"]')
.last()
.should('contain.text', 'Preferences');
// Close options Menu
cy.get('[data-cy="options-menu"]').click();
});
// TODO: the following code is blocked by issue 1193: https://github.com/OHIF/Viewers/issues/1193
// Once the issue is fixed, the following code should be uncommented
// it('checks if user can restore to default the language selection and application will be in English', function() {
// cy.get('@userPreferencesGeneralTab')
// .click()
// .should('have.class', 'active');
// // Language dropdown should be displayed
// cy.get('#language-select').should('be.visible');
// // Select Spanish and Save
// cy.get('#language-select').select('Spanish');
// cy.get('@saveBtn')
// .scrollIntoView()
// .click();
// //Open Preferences again
// cy.openPreferences();
// // Go to general tab
// cy.get('@userPreferencesGeneralTab').click();
// cy.get('@restoreBtn')
// .scrollIntoView()
// .click();
// Header should be in English
// cy.get('.research-use')
// .scrollIntoView()
// .should('have.text', 'INVESTIGATIONAL USE ONLY');
//
// Options menu should be in English
// cy.get('[data-cy="options-menu"]').should('have.text', 'Options');
// cy.get('[data-cy="about-item-menu"]')
// .first()
// .should('have.text', 'About');
// cy.get('[data-cy="about-item-menu"]')
// .last()
// .should('have.text', 'Preferences');
// });
it('checks if Preferences set in Study List Page will be consistent on Viewer Page', function() {
// Go go hotkeys tab
cy.get('@userPreferencesHotkeysTab')
@ -185,16 +183,12 @@ describe('OHIF User Preferences', () => {
cy.get('[data-cy="options-menu"]')
.should('have.text', 'Opciones')
.click();
cy.get('[data-cy="about-item-menu"]')
cy.get('[data-cy="dd-item-menu"]')
.first()
.should('contain.text', 'Acerca de');
cy.get('[data-cy="options-menu"]').click(); //Close Options overlay
//TODO: the following code is blocked by issue 1193: https://github.com/OHIF/Viewers/issues/1193
//Once the issue is fixed, the following code should be uncommented
// cy.get('[data-cy="about-item-menu"]')
// .last()
// .should('have.text', 'Preferencias');
cy.get('[data-cy="dd-item-menu"]')
.last()
.should('contain.text', 'Preferencias');
// Check if new hotkey is working on viewport
cy.get('body').type('{shift}Q', { release: false });
@ -266,19 +260,49 @@ describe('OHIF User Preferences', () => {
.should('have.text', 'SOLO USO PARA INVESTIGACIÓN');
// Options menu should be translated
cy.get('[data-cy="options-menu"]').should('have.text', 'Opciones');
cy.get('[data-cy="options-menu"]')
.should('have.text', 'Opciones')
.click();
//TODO: the following code is blocked by issue 1193: https://github.com/OHIF/Viewers/issues/1193
//Once the issue is fixed, the following code should be uncommented
// cy.get('[data-cy="about-item-menu"]')
// .first()
// .should('have.text', 'Acerca de');
// cy.get('[data-cy="about-item-menu"]')
// .last()
// .should('have.text', 'Preferencias');
cy.get('[data-cy="dd-item-menu"]')
.first()
.should('contain.text', 'Acerca de');
cy.get('[data-cy="dd-item-menu"]')
.last()
.should('contain.text', 'Preferencias');
// Close Options menu
cy.get('[data-cy="options-menu"]').click();
});
it('checks if user can cancel the language selection and application will be in English', function() {
// Set language to English and save
cy.setLanguage('English');
// Set language to Spanish and cancel
cy.setLanguage('Spanish', false);
// Header should be kept in English
cy.get('.research-use')
.scrollIntoView()
.should('have.text', 'INVESTIGATIONAL USE ONLY');
// Options menu should be translated
cy.get('[data-cy="options-menu"]')
.should('have.text', 'Options')
.click();
cy.get('[data-cy="dd-item-menu"]')
.first()
.should('contain.text', 'About');
cy.get('[data-cy="dd-item-menu"]')
.last()
.should('contain.text', 'Preferences');
// Close Options menu
cy.get('[data-cy="options-menu"]').click();
});
it('checks if user can restore to default the language selection and application will be in English', function() {
cy.get('@userPreferencesGeneralTab')
.click()
.should('have.class', 'active');
@ -286,76 +310,51 @@ describe('OHIF User Preferences', () => {
// Language dropdown should be displayed
cy.get('#language-select').should('be.visible');
// Select Spanish and Cancel
// Select Spanish and Save
cy.get('#language-select').select('Spanish');
cy.get('@cancelBtn')
cy.get('@saveBtn')
.scrollIntoView()
.click();
// TODO: the following code is blocked by issue 1193: https://github.com/OHIF/Viewers/issues/1193
// Once the issue is fixed, the following code should be uncommented
// // Header should be kept in English
// cy.get('.research-use')
// .scrollIntoView()
// .should('have.text', 'INVESTIGATIONAL USE ONLY');
//
// // Options menu should be translated
// cy.get('[data-cy="options-menu"]').should('have.text', 'Options');
//
// cy.get('[data-cy="about-item-menu"]')
// .first()
// .should('have.text', 'About');
// cy.get('[data-cy="about-item-menu"]')
// .last()
// .should('have.text', 'Preferences');
//Open Preferences again
cy.get('[data-cy="options-menu"]')
.scrollIntoView()
.click();
cy.get('[data-cy="dd-item-menu"]')
.last()
.click();
// Go to general tab
cy.get('@userPreferencesGeneralTab').click();
cy.get('@restoreBtn')
.scrollIntoView()
.click();
cy.get('@saveBtn')
.scrollIntoView()
.click();
// Header should be in English
cy.get('.research-use')
.scrollIntoView()
.should('have.text', 'INVESTIGATIONAL USE ONLY');
// Options menu should be in English
cy.get('[data-cy="options-menu"]')
.should('have.text', 'Options')
.click();
cy.get('[data-cy="dd-item-menu"]')
.first()
.should('contain.text', 'About');
cy.get('[data-cy="dd-item-menu"]')
.last()
.should('contain.text', 'Preferences');
// Close Options menu
cy.get('[data-cy="options-menu"]').click();
});
// TODO: the following code is blocked by issue 1193: https://github.com/OHIF/Viewers/issues/1193
// Once the issue is fixed, the following code should be uncommented
// it('checks if user can restore to default the language selection and application will be in English', function() {
// cy.get('@userPreferencesGeneralTab')
// .click()
// .should('have.class', 'active');
// // Language dropdown should be displayed
// cy.get('#language-select').should('be.visible');
// // Select Spanish and Save
// cy.get('#language-select').select('Spanish');
// cy.get('@saveBtn')
// .scrollIntoView()
// .click();
// //Open Preferences again
// cy.get('[data-cy="options-menu"]')
// .scrollIntoView()
// .click();
// cy.get('[data-cy="about-item-menu"]')
// .last()
// .click();
// // Go to general tab
// cy.get('@userPreferencesGeneralTab').click();
// cy.get('@restoreBtn')
// .scrollIntoView()
// .click();
// Header should be in English
// cy.get('.research-use')
// .scrollIntoView()
// .should('have.text', 'INVESTIGATIONAL USE ONLY');
//
// Options menu should be in English
// cy.get('[data-cy="options-menu"]').should('have.text', 'Options');
// cy.get('[data-cy="about-item-menu"]')
// .first()
// .should('have.text', 'About');
// cy.get('[data-cy="about-item-menu"]')
// .last()
// .should('have.text', 'Preferences');
//});
it('checks new hotkeys for "Rotate Right" and "Rotate Left"', function() {
// Go go hotkeys tab
cy.get('@userPreferencesHotkeysTab')

View File

@ -427,15 +427,19 @@ Cypress.Commands.add('initPreferencesModalAliases', () => {
Cypress.Commands.add('openPreferences', () => {
cy.log('Open User Preferences Modal');
// Open User Preferences modal
cy.get('[data-cy="options-menu"]')
.scrollIntoView()
.click()
.then(() => {
cy.get('[data-cy="about-item-menu"]')
.last()
cy.get('body').then(body => {
if (body.find('.OHIFModal').length === 0) {
cy.get('[data-cy="options-menu"]')
.scrollIntoView()
.click()
.wait(200);
});
.then(() => {
cy.get('[data-cy="dd-item-menu"]')
.last()
.click()
.wait(200);
});
}
});
});
Cypress.Commands.add('resetUserHoktkeyPreferences', () => {
@ -446,10 +450,7 @@ Cypress.Commands.add('resetUserHoktkeyPreferences', () => {
cy.log('Reset to Default Preferences');
cy.get('@restoreBtn').click();
//TODO: the following code is blocked by issue 1193: https://github.com/OHIF/Viewers/issues/1193
//Once the issue is fixed, the following code should be uncommented
//cy.get('@saveBtn').click();
cy.get('@saveBtn').click();
});
Cypress.Commands.add(
@ -457,11 +458,34 @@ Cypress.Commands.add(
(function_label, shortcut) => {
// Within scopes all `.get` and `.contains` to within the matched elements
// dom instead of checking from document
cy.get('.HotKeysPreferences').within(() => {
cy.contains(function_label) // label we're looking for
.parent()
.find('input') // closest input to that label
.type(shortcut, { force: true }); // Set new shortcut for that function
});
cy.get('.HotKeysPreferences')
.within(() => {
cy.contains(function_label) // label we're looking for
.parent()
.find('input') // closest input to that label
.type(shortcut, { force: true }); // Set new shortcut for that function
})
.blur();
}
);
Cypress.Commands.add('setLanguage', (language, save = true) => {
cy.openPreferences();
cy.get('@userPreferencesGeneralTab')
.click()
.should('have.class', 'active');
// Language dropdown should be displayed
cy.get('#language-select').should('be.visible');
// Select Language and Save/Cancel
cy.get('#language-select')
.select(language)
.then(() => {
const toClick = save ? '@saveBtn' : '@cancelBtn';
cy.get(toClick)
.scrollIntoView()
.click();
});
});

View File

@ -23,6 +23,7 @@ import {
createUIModalService,
createUIDialogService,
utils,
redux as reduxOHIF
} from '@ohif/core';
import i18n from '@ohif/i18n';
@ -45,6 +46,7 @@ import OHIFStandaloneViewer from './OHIFStandaloneViewer';
/** Store */
import { getActiveContexts } from './store/layout/selectors.js';
import store from './store';
const { setUserPreferences } = reduxOHIF.actions;
/** Contexts */
import WhiteLabellingContext from './context/WhiteLabellingContext';
@ -221,9 +223,29 @@ function _initExtensions(extensions, hotkeys) {
const mergedExtensions = defaultExtensions.concat(extensions);
extensionManager.registerExtensions(mergedExtensions);
const { hotkeyDefinitions = {} } = store.getState().preferences || {};
let updateStore = false;
let hotkeysToUse = hotkeyDefinitions;
// Must run after extension commands are registered
if (hotkeys) {
hotkeysManager.setHotkeys(hotkeys, true);
// if there is no hotkeys from localStorate set up from config
if (!Object.keys(hotkeyDefinitions).length) {
hotkeysToUse = hotkeys;
updateStore = true;
}
if (hotkeysToUse) {
hotkeysManager.setHotkeys(hotkeysToUse);
// set default based on app config
hotkeysManager.setDefaultHotKeys(hotkeys);
if (updateStore) {
const { hotkeyDefinitions } = hotkeysManager;
const windowLevelData = {};
store.dispatch(
setUserPreferences({ windowLevelData, hotkeyDefinitions })
);
}
}
}

View File

@ -1,4 +1,4 @@
import React, { Component } from 'react';
import React, { useState, useEffect } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { withTranslation } from 'react-i18next';
import PropTypes from 'prop-types';
@ -11,49 +11,37 @@ import './Header.css';
// Context
import AppContext from './../../context/AppContext';
class Header extends Component {
static contextType = AppContext;
static propTypes = {
home: PropTypes.bool.isRequired,
location: PropTypes.object.isRequired,
children: PropTypes.node,
t: PropTypes.func.isRequired,
userManager: PropTypes.object,
user: PropTypes.object,
modal: PropTypes.object,
};
function Header(props) {
const {
t,
user,
userManager,
modal: { show },
home,
location,
children,
} = props;
static defaultProps = {
home: true,
children: OHIFLogo(),
};
const [options, setOptions] = useState([]);
constructor(props) {
super(props);
this.state = { isOpen: false };
this.loadOptions();
}
loadOptions() {
const { t, user, userManager, modal } = this.props;
this.options = [
useEffect(() => {
const optionsValue = [
{
title: t('About'),
icon: { name: 'info' },
onClick: () =>
modal.show({
show({
content: AboutContent,
title: t('OHIF Viewer - About'),
}),
},
{
title: 'Preferences ',
title: t('Preferences'),
icon: {
name: 'user',
},
onClick: () =>
modal.show({
show({
content: ConnectedUserPreferencesForm,
title: t('User Preferences'),
}),
@ -61,61 +49,74 @@ class Header extends Component {
];
if (user && userManager) {
this.options.push({
optionsValue.push({
title: t('Logout'),
icon: { name: 'power-off' },
onClick: () => userManager.signoutRedirect(),
});
}
}
setOptions(optionsValue);
}, [setOptions, show, t, user, userManager]);
const { appConfig = {} } = AppContext;
const showStudyList =
appConfig.showStudyList !== undefined ? appConfig.showStudyList : true;
// ANTD -- Hamburger, Drawer, Menu
render() {
const { t, home, location, children } = this.props;
const { appConfig = {} } = this.context;
const showStudyList =
appConfig.showStudyList !== undefined ? appConfig.showStudyList : true;
return (
<>
<div className="notification-bar">{t('INVESTIGATIONAL USE ONLY')}</div>
<div className={`entry-header ${home ? 'header-big' : ''}`}>
<div className="header-left-box">
{location && location.studyLink && (
<Link
to={location.studyLink}
className="header-btn header-viewerLink"
>
{t('Back to Viewer')}
</Link>
)}
return (
<>
<div className="notification-bar">{t('INVESTIGATIONAL USE ONLY')}</div>
<div className={`entry-header ${home ? 'header-big' : ''}`}>
<div className="header-left-box">
{location && location.studyLink && (
<Link
to={location.studyLink}
className="header-btn header-viewerLink"
>
{t('Back to Viewer')}
</Link>
)}
{children}
{children}
{showStudyList && !home && (
<Link
className="header-btn header-studyListLinkSection"
to={{
pathname: '/',
state: { studyLink: location.pathname },
}}
>
{t('Study list')}
</Link>
)}
</div>
<div className="header-menu">
<span className="research-use">
{t('INVESTIGATIONAL USE ONLY')}
</span>
<Dropdown title={t('Options')} list={this.options} align="right" />
</div>
{showStudyList && !home && (
<Link
className="header-btn header-studyListLinkSection"
to={{
pathname: '/',
state: { studyLink: location.pathname },
}}
>
{t('Study list')}
</Link>
)}
</div>
</>
);
}
<div className="header-menu">
<span className="research-use">{t('INVESTIGATIONAL USE ONLY')}</span>
<Dropdown title={t('Options')} list={options} align="right" />
</div>
</div>
</>
);
}
Header.propTypes = {
home: PropTypes.bool.isRequired,
location: PropTypes.object.isRequired,
children: PropTypes.node,
t: PropTypes.func.isRequired,
userManager: PropTypes.object,
user: PropTypes.object,
modal: PropTypes.object,
};
Header.defaultProps = {
home: true,
children: OHIFLogo(),
};
export default withTranslation(['Header', 'AboutModal'])(
withRouter(withModal(Header))
);

View File

@ -1,17 +1,7 @@
import Header from '../components/Header/Header.js';
import { connect } from 'react-redux';
import { hotkeysManager } from '../App.js';
const mapStateToProps = state => {
const { hotkeyDefinitions = [] } = state.preferences || {};
const _hotkeyDefinitions =
hotkeyDefinitions.length > 0
? hotkeyDefinitions
: hotkeysManager.hotkeyDefaults;
hotkeysManager.setHotkeys(_hotkeyDefinitions);
return {
user: state.oidc && state.oidc.user,
};

View File

@ -1,34 +1,48 @@
import { connect } from 'react-redux';
import { UserPreferencesForm } from '@ohif/ui';
import OHIF from '@ohif/core';
import i18n from '@ohif/i18n';
import { hotkeysManager } from '../App.js';
const { setUserPreferences } = OHIF.redux.actions;
const mapStateToProps = (state, ownProps) => {
const hotkeyDefinitions =
state.preferences.hotkeyDefinitions.length > 0
? state.preferences.hotkeyDefinitions
: hotkeysManager.hotkeyDefaults;
hotkeysManager.setHotkeys(hotkeyDefinitions);
const { defaultLanguage } = i18n;
const { hotkeyDefinitions, windowLevelData = {}, generalPreferences } =
state.preferences || {};
const { hotkeyDefaults } = hotkeysManager;
return {
onClose: ownProps.hide,
windowLevelData: state.preferences ? state.preferences.windowLevelData : {},
windowLevelData,
hotkeyDefinitions,
generalPreferences,
hotkeysManager,
hotkeyDefaults,
defaultLanguage,
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onSave: ({ windowLevelData, hotkeyDefinitions }) => {
onSave: ({ windowLevelData, hotkeyDefinitions, generalPreferences }) => {
// TODO improve this strategy on windowLevel implementation
hotkeysManager.setHotkeys(hotkeyDefinitions);
const { language } = generalPreferences;
// set new language
i18n.changeLanguage(language);
ownProps.hide();
dispatch(setUserPreferences({ windowLevelData, hotkeyDefinitions }));
},
onResetToDefaults: () => {
hotkeysManager.restoreDefaultBindings();
ownProps.hide();
dispatch(setUserPreferences());
dispatch(
setUserPreferences({
windowLevelData,
hotkeyDefinitions,
generalPreferences,
})
);
},
};
};

View File

@ -30,7 +30,7 @@
--snackbar-info: rgba(54, 156, 199, 0.9);
/** z-Index **/
--snackbar-zIndex: 10;
--snackbar-zIndex: 1075;
/** DatePicker Colors **/
--datePicker-input-background: #2c363f;