lint(curly): consistent use of curly brackets in codebase (#3584)

This commit is contained in:
Alireza authored and GitHub committed 2023-08-09 10:07:33 -04:00
1 parent 9ae3d9f769
commit 5d435424e2
113 files changed
+1501 -1056

No files matched your search

@@ -71,6 +71,7 @@ describe('OHIF Cornerstone Toolbar', () => {
it('checks if Levels tool will change the window width and center of an image', () => {
//Click on button and verify if icon is active on toolbar
cy.waitDicomImage();
cy.get('@wwwcBtnPrimary')
.click()
.then($wwwcBtn => {
+3 -3
View File
@@ -60,7 +60,7 @@ Cypress.Commands.add(
cy.location('pathname').then($url => {
cy.log($url);
if (
$url == 'blank' ||
$url === 'blank' ||
!$url.includes(`/basic-test/${StudyInstanceUID}${otherParams}`)
) {
cy.openStudyInViewer(StudyInstanceUID, otherParams);
@@ -158,10 +158,10 @@ Cypress.Commands.add('addLine', (viewport, firstClick, secondClick) => {
// TODO: Added a wait which appears necessary in Cornerstone Tools >4?
cy.wrap($viewport)
.click(x1, y1)
.click(x1, y1, { force: true })
.wait(100)
.trigger('mousemove', { clientX: x2, clientY: y2 })
.click(x2, y2)
.click(x2, y2, { force: true })
.wait(100);
});
});
+3 -1
View File
@@ -4,6 +4,8 @@ const originalConsoleError = console.error;
// JSDom's CSS Parser has limited support for certain features
// This supresses error warnings caused by it
console.error = function(msg) {
if (_.startsWith(msg, 'Error: Could not parse CSS stylesheet')) return;
if (_.startsWith(msg, 'Error: Could not parse CSS stylesheet')) {
return;
}
originalConsoleError(msg);
};
+9 -3
View File
@@ -103,7 +103,9 @@ async function appInit(appConfigOrFunc, defaultExtensions, defaultModes) {
const modesById = new Set();
for (let i = 0; i < loadedModes.length; i++) {
let mode = loadedModes[i];
if (!mode) continue;
if (!mode) {
continue;
}
const { id } = mode;
if (mode.modeFactory) {
@@ -116,10 +118,14 @@ async function appInit(appConfigOrFunc, defaultExtensions, defaultModes) {
mode = mode.modeFactory({ modeConfiguration });
}
if (modesById.has(id)) continue;
if (modesById.has(id)) {
continue;
}
// Prevent duplication
modesById.add(id);
if (!mode || typeof mode !== 'object') continue;
if (!mode || typeof mode !== 'object') {
continue;
}
appConfig.loadedModes.push(mode);
}
// Hack alert - don't touch the original modes definition,
+6 -2
View File
@@ -145,7 +145,9 @@ function ViewerViewportGrid(props) {
const { unsubscribe } = measurementService.subscribe(
MeasurementService.EVENTS.JUMP_TO_MEASUREMENT_LAYOUT,
({ viewportIndex, measurement, isConsumed }) => {
if (isConsumed) return;
if (isConsumed) {
return;
}
// This occurs when no viewport has elected to consume the event
// so we need to change layouts into a layout which can consume
// the event.
@@ -292,7 +294,9 @@ function ViewerViewportGrid(props) {
});
const onInteractionHandler = event => {
if (isActive) return;
if (isActive) {
return;
}
if (event) {
event.preventDefault();
+3 -3
View File
@@ -1,6 +1,6 @@
export default class FileLoader {
fileType;
loadFile(file, imageId) { }
getDataset(image, imageId) { }
getStudies(dataset, imageId) { }
loadFile(file, imageId) {}
getDataset(image, imageId) {}
getStudies(dataset, imageId) {}
}
+9 -3
View File
@@ -11,8 +11,12 @@ type StudyMetadata = Types.StudyMetadata;
* @returns - compare a and b, returning 1 if a<b -1 if a>b and defaultCompare otherwise
*/
const compare = (a, b, defaultCompare = 0): number => {
if (a === b) return defaultCompare;
if (a < b) return 1;
if (a === b) {
return defaultCompare;
}
if (a < b) {
return 1;
}
return -1;
};
@@ -49,7 +53,9 @@ const getStudiesfromDisplaySets = (displaysets): StudyMetadata[] => {
* in the original order, as specified.
*/
const getStudiesFromUIDs = (studyUids: string[]): StudyMetadata[] => {
if (!studyUids?.length) return;
if (!studyUids?.length) {
return;
}
return studyUids.map(uid => DicomMetadataStore.getStudy(uid));
};
+28 -25
View File
@@ -361,32 +361,35 @@ function WorkList({
query.append('configUrl', filterValues.configUrl);
}
query.append('StudyInstanceUIDs', studyInstanceUid);
return mode.displayName && (
<Link
className={isValidMode ? '' : 'cursor-not-allowed'}
key={i}
to={`${dataPath ? '../../' : ''}${mode.routeName}${dataPath ||
''}?${query.toString()}`}
onClick={event => {
// In case any event bubbles up for an invalid mode, prevent the navigation.
// For example, the event bubbles up when the icon embedded in the disabled button is clicked.
if (!isValidMode) {
event.preventDefault();
}
}}
// to={`${mode.routeName}/dicomweb?StudyInstanceUIDs=${studyInstanceUid}`}
>
{/* TODO revisit the completely rounded style of buttons used for launching a mode from the worklist later - for now use LegacyButton*/}
<LegacyButton
rounded="full"
variant={isValidMode ? 'contained' : 'disabled'}
disabled={!isValidMode}
endIcon={<Icon name="launch-arrow" />} // launch-arrow | launch-info
onClick={() => {}}
return (
mode.displayName && (
<Link
className={isValidMode ? '' : 'cursor-not-allowed'}
key={i}
to={`${dataPath ? '../../' : ''}${
mode.routeName
}${dataPath || ''}?${query.toString()}`}
onClick={event => {
// In case any event bubbles up for an invalid mode, prevent the navigation.
// For example, the event bubbles up when the icon embedded in the disabled button is clicked.
if (!isValidMode) {
event.preventDefault();
}
}}
// to={`${mode.routeName}/dicomweb?StudyInstanceUIDs=${studyInstanceUid}`}
>
{t(`Modes:${mode.displayName}`)}
</LegacyButton>
</Link>
{/* TODO revisit the completely rounded style of buttons used for launching a mode from the worklist later - for now use LegacyButton*/}
<LegacyButton
rounded="full"
variant={isValidMode ? 'contained' : 'disabled'}
disabled={!isValidMode}
endIcon={<Icon name="launch-arrow" />} // launch-arrow | launch-info
onClick={() => {}}
>
{t(`Modes:${mode.displayName}`)}
</LegacyButton>
</Link>
)
);
})}
</div>
+1 -1
View File
@@ -10,7 +10,7 @@ import {
initGit,
} from './utils/index.js';
const createPackage = async (options) => {
const createPackage = async options => {
const { packageType } = options; // extension or mode
if (fs.existsSync(options.targetDir)) {
@@ -22,7 +22,9 @@ const createDirectoryContents = (
const contents = fs.readFileSync(origFilePath, 'utf8');
// Rename
if (file === '.npmignore') file = '.gitignore';
if (file === '.npmignore') {
file = '.gitignore';
}
const writePath = `${targetDirPath}/${file}`;
fs.writeFileSync(writePath, contents, 'utf8');
@@ -11,7 +11,7 @@ export default async function findRequiredOhifExtensionsForMode(yarnInfo) {
const dependencies = [];
const ohifExtensions = [];
Object.keys(peerDependencies).forEach((packageName) => {
Object.keys(peerDependencies).forEach(packageName => {
dependencies.push({
packageName,
version: peerDependencies[packageName],
+12 -9
View File
@@ -77,14 +77,14 @@ function getVersion(json, version) {
const [majorVersion] = version
.split('^')[1]
.split('.')
.map((v) => parseInt(v));
.map(v => parseInt(v));
// Find the version that matches the major version, but is the latest minor version
versions
.filter((version) => parseInt(version.split('.')[0]) === majorVersion)
.filter(version => parseInt(version.split('.')[0]) === majorVersion)
.sort((a, b) => {
const [majorA, minorA, patchA] = a.split('.').map((v) => parseInt(v));
const [majorB, minorB, patchB] = b.split('.').map((v) => parseInt(v));
const [majorA, minorA, patchA] = a.split('.').map(v => parseInt(v));
const [majorB, minorB, patchB] = b.split('.').map(v => parseInt(v));
if (majorA === majorB) {
if (minorA === minorB) {
@@ -110,13 +110,16 @@ function validate(packageName, version, keyword) {
// Gets the registry of the package. Scoped packages may not be using the global default.
const registryUrlOfPackage = registryUrl(scope);
let options = {}
if (process.env.NPM_TOKEN){
let options = {};
if (process.env.NPM_TOKEN) {
options['headers'] = {
'Authorization': `Bearer ${process.env.NPM_TOKEN}`,
}
Authorization: `Bearer ${process.env.NPM_TOKEN}`,
};
}
const response = await fetch(`${registryUrlOfPackage}${packageName}`, options);
const response = await fetch(
`${registryUrlOfPackage}${packageName}`,
options
);
const json = await response.json();
if (json.error && json.error === NOT_FOUND) {
+12 -4
View File
@@ -25,10 +25,18 @@ function convertToInt(input) {
function padFour(input) {
const l = input.length;
if (l == 0) return '0000';
if (l == 1) return '000' + input;
if (l == 2) return '00' + input;
if (l == 3) return '0' + input;
if (l === 0) {
return '0000';
}
if (l === 1) {
return '000' + input;
}
if (l === 2) {
return '00' + input;
}
if (l === 3) {
return '0' + input;
}
return input;
}
@@ -1,4 +1,4 @@
import 'isomorphic-base64'
import 'isomorphic-base64';
import user from '../user';
/**
+3 -1
View File
@@ -175,7 +175,9 @@ export class CommandsManager {
toRun: Command | Commands | Command[] | undefined,
options?: Record<string, unknown>
): unknown {
if (!toRun) return;
if (!toRun) {
return;
}
const commands =
(Array.isArray(toRun) && toRun) ||
((toRun as Command).commandName && [toRun]) ||
@@ -454,7 +454,9 @@ class MetadataProvider {
}
getUIDsFromImageID(imageId) {
if (!imageId) throw new Error('MetadataProvider::Empty imageId');
if (!imageId) {
throw new Error('MetadataProvider::Empty imageId');
}
// TODO: adding csiv here is not really correct. Probably need to use
// metadataProvider.addImageIdToUIDs(imageId, {
// StudyInstanceUID,
+6 -2
View File
@@ -2,7 +2,9 @@
function getNestedObject(shallowObject) {
const nestedObject = {};
for (let key in shallowObject) {
if (!shallowObject.hasOwnProperty(key)) continue;
if (!shallowObject.hasOwnProperty(key)) {
continue;
}
const value = shallowObject[key];
const propertyArray = key.split('.');
let currentObject = nestedObject;
@@ -28,7 +30,9 @@ function getShallowObject(nestedObject) {
const shallowObject = {};
const putValues = (baseKey, nestedObject, resultObject) => {
for (let key in nestedObject) {
if (!nestedObject.hasOwnProperty(key)) continue;
if (!nestedObject.hasOwnProperty(key)) {
continue;
}
let currentKey = baseKey ? `${baseKey}.${key}` : key;
const currentValue = nestedObject[key];
if (typeof currentValue === 'object') {
@@ -11,7 +11,7 @@ const extensionManager = {
registeredExtensionIds: [],
moduleEntries: {},
getModuleEntry: function (id) {
getModuleEntry: function(id) {
return this.moduleEntries[id];
},
};
@@ -20,7 +20,7 @@ const commandsManager = {};
const ohifOverlayItem = {
id: 'ohif.overlayItem',
content: function (props) {
content: function(props) {
return {
label: this.label,
value: props[this.attribute],
@@ -12,8 +12,12 @@ const flattenNestedStrings = (
strs: NestedStrings | string,
ret?: Record<string, string>
): Record<string, string> => {
if (!ret) ret = {};
if (!strs) return ret;
if (!ret) {
ret = {};
}
if (!strs) {
return ret;
}
if (Array.isArray(strs)) {
for (const val of strs) {
flattenNestedStrings(val, ret);
@@ -81,7 +85,9 @@ export default class CustomizationService extends PubSubService {
this.extensionManager.registeredExtensionIds.forEach(extensionId => {
const key = `${extensionId}.customizationModule.default`;
const defaultCustomizations = this.findExtensionValue(key);
if (!defaultCustomizations) return;
if (!defaultCustomizations) {
return;
}
const { value } = defaultCustomizations;
this.addReference(value, true);
});
@@ -172,9 +178,13 @@ export default class CustomizationService extends PubSubService {
* type into the new type, allowing default behaviour to be configured.
*/
public transform(customization: Customization): Customization {
if (!customization) return customization;
if (!customization) {
return customization;
}
const { customizationType } = customization;
if (!customizationType) return customization;
if (!customizationType) {
return customization;
}
const parent = this.getCustomization(customizationType);
const result = parent
? Object.assign(Object.create(parent), customization)
@@ -242,7 +252,9 @@ export default class CustomizationService extends PubSubService {
* or a customization itself.
*/
addReference(value?: Obj | string, isGlobal = true, id?: string): void {
if (!value) return;
if (!value) {
return;
}
if (typeof value === 'string') {
const extensionValue = this.findExtensionValue(value);
// The child of a reference is only a set of references when an array,
@@ -265,7 +277,9 @@ export default class CustomizationService extends PubSubService {
* or customization.
*/
addReferences(references?: Obj | Obj[], isGlobal = true): void {
if (!references) return;
if (!references) {
return;
}
if (Array.isArray(references)) {
references.forEach(item => {
this.addReference(item, isGlobal);
@@ -157,7 +157,9 @@ export default class DisplaySetService extends PubSubService {
}
public deleteDisplaySet(displaySetInstanceUID) {
if (!displaySetInstanceUID) return;
if (!displaySetInstanceUID) {
return;
}
const { activeDisplaySets, activeDisplaySetsMap } = this;
const activeDisplaySetsIndex = activeDisplaySets.findIndex(
@@ -314,7 +316,9 @@ export default class DisplaySetService extends PubSubService {
}
// This means that all instances already existed or got added to
// existing display sets, and had an invalidated event fired
if (!instances.length) return allDisplaySets;
if (!instances.length) {
return allDisplaySets;
}
}
if (!instances.length) {
@@ -329,7 +333,9 @@ export default class DisplaySetService extends PubSubService {
// creating additional display sets using the sop class handler
displaySets = handler.getDisplaySetsFromSeries(instances);
if (!displaySets || !displaySets.length) continue;
if (!displaySets || !displaySets.length) {
continue;
}
// applying hp-defined viewport settings to the displaysets
displaySets.forEach(ds => {
@@ -134,7 +134,7 @@ function checkHpsBestMatch(hps) {
displaySetOptions: {
id: 'displaySetSelector',
options: {},
},
},
},
],
});
@@ -192,6 +192,6 @@ describe('HangingProtocolService', () => {
it('matches best image match', () => {
checkHpsBestMatch(hangingProtocolService);
});
});
});
});
});
@@ -86,7 +86,9 @@ export default class HangingProtocolService extends PubSubService {
metadata.ModalitiesInStudy ??
(metadata.series || []).reduce((prev, curr) => {
const { Modality } = curr;
if (Modality && prev.indexOf(Modality) == -1) prev.push(Modality);
if (Modality && prev.indexOf(Modality) == -1) {
prev.push(Modality);
}
return prev;
}, []),
},
@@ -200,7 +202,9 @@ export default class HangingProtocolService extends PubSubService {
* protocolId, stageIndex, stageId and activeStudyUID
*/
public getState(): HangingProtocol.HPInfo {
if (!this.protocol) return;
if (!this.protocol) {
return;
}
return {
protocolId: this.protocol.id,
stageIndex: this.stageIndex,
@@ -257,8 +261,12 @@ export default class HangingProtocolService extends PubSubService {
* @returns protocol - the protocol with the given id
*/
public getProtocolById(protocolId: string): HangingProtocol.Protocol {
if (!protocolId) return;
if (protocolId === this.protocol?.id) return this.protocol;
if (!protocolId) {
return;
}
if (protocolId === this.protocol?.id) {
return this.protocol;
}
const protocol = this.protocols.get(protocolId);
if (!protocol) {
throw new Error(`No protocol ${protocolId} found`);
@@ -697,7 +705,9 @@ export default class HangingProtocolService extends PubSubService {
const { id } = displaySet;
const displaySetMatchDetail = displaySetMatchDetails.get(id);
const { displaySetInstanceUID: oldDisplaySetInstanceUID } = displaySetMatchDetail;
const {
displaySetInstanceUID: oldDisplaySetInstanceUID,
} = displaySetMatchDetail;
const displaySetInstanceUID =
displaySet.id === displaySetSelectorId
@@ -730,8 +740,12 @@ export default class HangingProtocolService extends PubSubService {
);
}
if (options === null) return options;
if (typeof options !== 'object') return options;
if (options === null) {
return options;
}
if (typeof options !== 'object') {
return options;
}
// If options is an object with a custom attribute, compute a new options object
if (options.custom) {
@@ -892,7 +906,9 @@ export default class HangingProtocolService extends PubSubService {
if (stageId) {
for (let i = 0; i < stages.length; i++) {
const stage = stages[i];
if (stage.id === stageId && stage.status !== 'disabled') return i;
if (stage.id === stageId && stage.status !== 'disabled') {
return i;
}
}
return;
}
@@ -905,7 +921,9 @@ export default class HangingProtocolService extends PubSubService {
let firstNotDisabled: number;
for (let i = 0; i < stages.length; i++) {
if (stages[i].status === 'enabled') return i;
if (stages[i].status === 'enabled') {
return i;
}
if (firstNotDisabled === undefined && stages[i].status !== 'disabled') {
firstNotDisabled = i;
}
@@ -979,7 +997,9 @@ export default class HangingProtocolService extends PubSubService {
if (stageId !== undefined) {
return protocol.stages.findIndex(it => it.id === stageId);
}
if (stageIndex !== undefined) return stageIndex;
if (stageIndex !== undefined) {
return stageIndex;
}
return 0;
}
@@ -1030,7 +1050,9 @@ export default class HangingProtocolService extends PubSubService {
const protocol = this.protocol;
const stage = protocol.stages[stageIdx];
const defaultViewport = stage.defaultViewport || protocol.defaultViewport;
if (!defaultViewport) return;
if (!defaultViewport) {
return;
}
const useViewport = { ...defaultViewport };
return this._matchViewport(useViewport, options);
@@ -1152,12 +1174,18 @@ export default class HangingProtocolService extends PubSubService {
offset: number,
options: HangingProtocol.SetProtocolOptions = {}
): HangingProtocol.DisplaySetMatchDetails {
if (!matchDetails) return;
if (offset === 0) return matchDetails;
if (!matchDetails) {
return;
}
if (offset === 0) {
return matchDetails;
}
const { matchingScores = [] } = matchDetails;
if (offset === -1) {
const { inDisplay } = options;
if (!inDisplay) return matchDetails;
if (!inDisplay) {
return matchDetails;
}
for (let i = 0; i < matchDetails.matchingScores.length; i++) {
if (
inDisplay.indexOf(
@@ -1184,12 +1212,16 @@ export default class HangingProtocolService extends PubSubService {
id: string,
displaySetUID: string
): void {
if (match.displaySetInstanceUID === displaySetUID) return;
if (match.displaySetInstanceUID === displaySetUID) {
return;
}
if (!match.matchingScores) {
throw new Error('No matchingScores found in ' + match);
}
for (const subMatch of match.matchingScores) {
if (subMatch.displaySetInstanceUID === displaySetUID) return;
if (subMatch.displaySetInstanceUID === displaySetUID) {
return;
}
}
throw new Error(
`Reused viewport details ${id} with ds ${displaySetUID} not valid`
@@ -1391,21 +1423,23 @@ export default class HangingProtocolService extends PubSubService {
const matchActiveOnly = this.protocol.numberOfPriorsReferenced === -1;
this.studies.forEach(study => {
// Skip non-active if active only
if (matchActiveOnly && this.activeStudy !== study) return;
if (matchActiveOnly && this.activeStudy !== study) {
return;
}
const studyDisplaySets = this.displaySets.filter(
it => it.StudyInstanceUID === study.StudyInstanceUID
it => it.StudyInstanceUID === study.StudyInstanceUID
);
const studyMatchDetails = this.protocolEngine.findMatch(
study,
studyMatchingRules,
{
studies: this.studies,
displaySets: studyDisplaySets,
allDisplaySets: this.displaySets,
displaySetMatchDetails: this.displaySetMatchDetails,
}
study,
studyMatchingRules,
{
studies: this.studies,
displaySets: studyDisplaySets,
allDisplaySets: this.displaySets,
displaySetMatchDetails: this.displaySetMatchDetails,
}
);
// Prevent bestMatch from being updated if the matchDetails' required attribute check has failed
@@ -1414,10 +1448,10 @@ export default class HangingProtocolService extends PubSubService {
}
this.debug(
'study',
study.StudyInstanceUID,
'display sets #',
studyDisplaySets.length
'study',
study.StudyInstanceUID,
'display sets #',
studyDisplaySets.length
);
studyDisplaySets.forEach(displaySet => {
const {
@@ -1426,15 +1460,15 @@ export default class HangingProtocolService extends PubSubService {
displaySetInstanceUID,
} = displaySet;
const seriesMatchDetails = this.protocolEngine.findMatch(
displaySet,
seriesMatchingRules,
// Todo: why we have images here since the matching type does not have it
{
studies: this.studies,
instance: displaySet.images?.[0],
displaySetMatchDetails: this.displaySetMatchDetails,
displaySets: studyDisplaySets,
}
displaySet,
seriesMatchingRules,
// Todo: why we have images here since the matching type does not have it
{
studies: this.studies,
instance: displaySet.images?.[0],
displaySetMatchDetails: this.displaySetMatchDetails,
displaySets: studyDisplaySets,
}
);
// Prevent bestMatch from being updated if the matchDetails' required attribute check has failed
@@ -13,7 +13,9 @@ const isDisplaySetFromUrl = (displaySet): boolean => {
params
);
const initialSOPInstanceUID = getSplitParam('initialsopinstanceuid', params);
if (!initialSeriesInstanceUID && !initialSOPInstanceUID) return false;
if (!initialSeriesInstanceUID && !initialSOPInstanceUID) {
return false;
}
const isSeriesMatch =
!initialSeriesInstanceUID ||
initialSeriesInstanceUID.some(
@@ -32,9 +34,13 @@ const isDisplaySetFromUrl = (displaySet): boolean => {
*/
function sopInstanceLocation(displaySets) {
const displaySet = displaySets?.[0];
if (!displaySet) return;
if (!displaySet) {
return;
}
const initialSOPInstanceUID = getSplitParam('initialsopinstanceuid');
if (!initialSOPInstanceUID) return;
if (!initialSOPInstanceUID) {
return;
}
const index = displaySet.instances.findIndex(instance =>
initialSOPInstanceUID.includes(instance.SOPInstanceUID)
@@ -1,5 +1,6 @@
export default (study, extraData) => {
const ret = extraData?.displaySets?.filter(ds => ds.numImageFrames>0)?.length;
console.log("number of display sets with images", ret);
const ret = extraData?.displaySets?.filter(ds => ds.numImageFrames > 0)
?.length;
console.log('number of display sets with images', ret);
return ret;
};
};
@@ -1 +1,2 @@
export default (study, extraData) => extraData?.displaySets?.map(ds => ds.SeriesDescription);
export default (study, extraData) =>
extraData?.displaySets?.map(ds => ds.SeriesDescription);
@@ -111,10 +111,12 @@ validate.validators.includes = function(value, options, key) {
const includedValues = testValue.filter(el => dicomArrayValue.includes(el));
if (includedValues.length === 0) {
return `${key} must include at least one of the following values: ${testValue.join(
', '
', '
)}`;
}
} else return `${key} ${testValue} must be an array`;
} else {
return `${key} ${testValue} must be an array`;
}
// else if (!value.includes(testValue)) {
// return `${key} ${value} must include ${testValue}`;
// }
@@ -151,7 +153,9 @@ validate.validators.doesNotInclude = function(value, options, key) {
if (includedValues.length > 0) {
return `${key} must not include the following value: ${includedValues}`;
}
} else return `${key} ${testValue} must be an array`;
} else {
return `${key} ${testValue} must be an array`;
}
};
// Ignore case contains.
// options testValue MUST be in lower case already, otherwise it won't match
@@ -175,31 +179,31 @@ validate.validators.containsI = function(value, options, key) {
const testValue = getTestValue(options);
if (Array.isArray(value)) {
if (
value.some(
item => !validate.validators.containsI(item.toLowerCase(), options, key)
)
value.some(
item => !validate.validators.containsI(item.toLowerCase(), options, key)
)
) {
return undefined;
}
return `No item of ${value.join(',')} contains ${JSON.stringify(
testValue
testValue
)}`;
}
if (Array.isArray(testValue)) {
if (
testValue.some(
subTest =>
!validate.validators.containsI(value, subTest.toLowerCase(), key)
)
testValue.some(
subTest =>
!validate.validators.containsI(value, subTest.toLowerCase(), key)
)
) {
return;
}
return `${key} must contain at least one of ${testValue.join(',')}`;
}
if (
testValue &&
value.indexOf &&
value.toLowerCase().indexOf(testValue.toLowerCase()) === -1
testValue &&
value.indexOf &&
value.toLowerCase().indexOf(testValue.toLowerCase()) === -1
) {
return key + 'must contain any case of' + testValue;
}
@@ -227,14 +231,14 @@ validate.validators.contains = function(value, options, key) {
return undefined;
}
return `No item of ${value.join(',')} contains ${JSON.stringify(
testValue
testValue
)}`;
}
if (Array.isArray(testValue)) {
if (
testValue.some(
subTest => !validate.validators.contains(value, subTest, key)
)
testValue.some(
subTest => !validate.validators.contains(value, subTest, key)
)
) {
return;
}
@@ -454,11 +458,13 @@ validate.validators.range = function(value, options, key) {
if (value === undefined || value < min || value > max) {
return `${key} with value ${value} must be between ${min} and ${max}`;
}
} else return `${key} must be an array of length 2`;
} else {
return `${key} must be an array of length 2`;
}
};
validate.validators.notNull = value =>
value === null || value === undefined ? 'Value is null' : undefined;
value === null || value === undefined ? 'Value is null' : undefined;
const getTestValue = options => {
if (Array.isArray(options)) {
return options.map(option => option?.value ?? option);
File diff suppressed because it is too large. Load diff
@@ -40,7 +40,7 @@ export default class StateSyncService extends PubSubService {
this.configuration = configuration || {};
}
public init(extensionManager: ExtensionManager): void { }
public init(extensionManager: ExtensionManager): void {}
/** Registers a new sync store called `id`. The state
* defines how the state is stored, and any default clearing of the
@@ -66,7 +66,9 @@ export default class ToolbarService extends PubSubService {
* called with {...commandOptions,...options}
*/
recordInteraction(interaction, options?: Record<string, unknown>) {
if (!interaction) return;
if (!interaction) {
return;
}
const commandsManager = this._commandsManager;
const { groupId, itemId, interactionType, commands } = interaction;
@@ -35,10 +35,16 @@ const addUniqueIndex = (arr, key, viewports, isUpdatingSameViewport) => {
};
const getLutId = (ds): string => {
if (!ds || !ds.options) return DEFAULT;
if (ds.options.id) return ds.options.id;
if (!ds || !ds.options) {
return DEFAULT;
}
if (ds.options.id) {
return ds.options.id;
}
const arr = Object.entries(ds.options).map(([key, val]) => `${key}=${val}`);
if (!arr.length) return DEFAULT;
if (!arr.length) {
return DEFAULT;
}
return arr.join(JOIN_STR);
};
@@ -93,7 +99,9 @@ export type PresentationIds = {
* @returns PresentationIds
*/
const getPresentationIds = (viewport, viewports): PresentationIds => {
if (!viewport) return;
if (!viewport) {
return;
}
const {
viewportOptions,
displaySetInstanceUIDs,
@@ -108,7 +116,9 @@ const getPresentationIds = (viewport, viewports): PresentationIds => {
const lutPresentationArr = [lutId];
const positionPresentationArr = [orientation || 'acquisition'];
if (id) positionPresentationArr.push(id);
if (id) {
positionPresentationArr.push(id);
}
for (const uid of displaySetInstanceUIDs) {
positionPresentationArr.push(uid);
+3 -1
View File
@@ -1,7 +1,9 @@
const absoluteUrl = path => {
let absolutePath = '/';
if (!path) return absolutePath;
if (!path) {
return absolutePath;
}
// TODO: Find another way to get root url
const absoluteUrl = window.location.origin;
+6 -2
View File
@@ -9,12 +9,16 @@ function debounce(func, wait, immediate) {
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
if (callNow) {
func.apply(context, args);
}
};
}
+3 -1
View File
@@ -58,6 +58,8 @@ const imagesTypes = [
* @returns {boolean} - true if it has image data
*/
export const isImage = SOPClassUID => {
if (!SOPClassUID) return false;
if (!SOPClassUID) {
return false;
}
return imagesTypes.indexOf(SOPClassUID) !== -1;
};
@@ -1,4 +1,10 @@
const LOW_PRIORITY_MODALITIES = Object.freeze(['SEG', 'KO', 'PR', 'SR', 'RTSTRUCT']);
const LOW_PRIORITY_MODALITIES = Object.freeze([
'SEG',
'KO',
'PR',
'SR',
'RTSTRUCT',
]);
export default function isLowPriorityModality(Modality) {
return LOW_PRIORITY_MODALITIES.includes(Modality);
+6 -2
View File
@@ -2,11 +2,15 @@ export default function makeCancelable(thenable) {
let isCanceled = false;
const promise = Promise.resolve(thenable).then(
function(result) {
if (isCanceled) throw Object.freeze({ isCanceled });
if (isCanceled) {
throw Object.freeze({ isCanceled });
}
return result;
},
function(error) {
if (isCanceled) throw Object.freeze({ isCanceled, error });
if (isCanceled) {
throw Object.freeze({ isCanceled, error });
}
throw error;
}
);
@@ -18,8 +18,9 @@ export default function fetchPaletteColorLookupTableData(
) {
const { PaletteColorLookupTableUID } = item;
const paletteData = item[tag];
if (paletteData === undefined && PaletteColorLookupTableUID === undefined)
if (paletteData === undefined && PaletteColorLookupTableUID === undefined) {
return;
}
// performance optimization - read UID and cache by UID
return _getPaletteColor(item[tag], item[descriptorTag]);
}
@@ -28,7 +29,9 @@ function _getPaletteColor(paletteColorLookupTableData, lutDescriptor) {
const numLutEntries = lutDescriptor[0];
const bits = lutDescriptor[2];
if (!paletteColorLookupTableData) return undefined;
if (!paletteColorLookupTableData) {
return undefined;
}
const arrayBufferToPaletteColorLUT = arraybuffer => {
const lut = [];
@@ -124,7 +124,9 @@ function getOverallProgress(list) {
status.total++;
if (isValidProgress(task.progress)) {
status.partial += task.progress;
if (task.progress === 1.0 && task.failed) status.failures++;
if (task.progress === 1.0 && task.failed) {
status.failures++;
}
}
task = task.next;
}
+8 -3
View File
@@ -13,7 +13,9 @@ const compareSeriesDateTime = (a, b) => {
const defaultSeriesSort = (a, b) => {
const seriesNumberA = a.SeriesNumber ?? a.seriesNumber;
const seriesNumberB = b.SeriesNumber ?? b.seriesNumber;
if (seriesNumberA === seriesNumberB) return compareSeriesDateTime(a, b);
if (seriesNumberA === seriesNumberB) {
return compareSeriesDateTime(a, b);
}
return seriesNumberA - seriesNumberB;
};
@@ -67,8 +69,11 @@ const sortStudySeries = (
seriesSortingCriteria = seriesSortCriteria.default,
sortFunction = null
) => {
if (typeof sortFunction === 'function') return sortFunction(series);
else return series.sort(seriesSortingCriteria);
if (typeof sortFunction === 'function') {
return sortFunction(series);
} else {
return series.sort(seriesSortingCriteria);
}
};
/**
+6 -2
View File
@@ -1,6 +1,8 @@
/** Splits a list of stirngs by commas within the strings */
const splitComma = (strings: string[]): string[] => {
if (!strings) return null;
if (!strings) {
return null;
}
for (let i = 0; i < strings.length; i++) {
const comma = strings[i].indexOf(',');
if (comma !== -1) {
@@ -24,7 +26,9 @@ const getSplitParam = (
const sourceKey = [...params.keys()].find(
it => it.toLowerCase() === lowerCaseKey
);
if (!sourceKey) return;
if (!sourceKey) {
return;
}
return splitComma(params.getAll(sourceKey));
};
+1 -1
View File
@@ -11,7 +11,7 @@
module.exports = {
// By default, Docusaurus generates a sidebar from the docs folder structure
tutorialSidebar: [{type: 'autogenerated', dirName: '.'}],
tutorialSidebar: [{ type: 'autogenerated', dirName: '.' }],
// But you can create a sidebar manually
/*
+10 -2
View File
@@ -4,7 +4,15 @@ const debugMode = !!(
const detectionOptions = {
// order and from where user language should be detected
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag', 'path', 'subdomain'],
order: [
'querystring',
'cookie',
'localStorage',
'navigator',
'htmlTag',
'path',
'subdomain',
],
// keys or params to lookup language from
lookupQuerystring: 'lng',
@@ -18,7 +26,7 @@ const detectionOptions = {
excludeCacheFor: ['cimode'], // languages to not persist (cookie, localStorage)
// optional htmlTag with lang attribute, the default is:
htmlTag: document.documentElement
htmlTag: document.documentElement,
};
export { debugMode, detectionOptions };
+9 -3
View File
@@ -128,7 +128,7 @@ function initI18n(
});
}
return initialized.then(function (t) {
return initialized.then(function(t) {
i18n.T = t;
customDebug(`T function available.`, 'info');
});
@@ -140,7 +140,13 @@ i18n.initializing = initI18n();
i18n.initI18n = initI18n;
i18n.addLocales = addLocales;
i18n.availableLanguages = getAvailableLanguagesInfo(locales);
i18n.defaultLanguage = { label: getLanguageLabel(DEFAULT_LANGUAGE), value: DEFAULT_LANGUAGE };
i18n.currentLanguage = () => ({ label: getLanguageLabel(i18n.language), value: i18n.language });
i18n.defaultLanguage = {
label: getLanguageLabel(DEFAULT_LANGUAGE),
value: DEFAULT_LANGUAGE,
};
i18n.currentLanguage = () => ({
label: getLanguageLabel(i18n.language),
value: i18n.language,
});
export default i18n;
+1 -1
View File
@@ -19,5 +19,5 @@ export default {
...pt_BR,
...vi,
...zh,
...test_lng
...test_lng,
};
+1 -1
View File
@@ -32,6 +32,6 @@ export default {
PatientInfo,
Modes,
SidePanel,
Modals
Modals,
},
};
+1 -1
View File
@@ -57,7 +57,7 @@ const languagesMap = {
'test-LNG': 'Test Language',
};
const getLanguageLabel = (language) => {
const getLanguageLabel = language => {
return languagesMap[language];
};
+3 -1
View File
@@ -21,7 +21,9 @@ const directories = getDirectories(directoryPath);
function writeFile(filepath, name, content) {
fs.writeFile(path.join(filepath, name), content, err => {
if (err) throw err;
if (err) {
throw err;
}
});
}
@@ -45,7 +45,7 @@ const renderYearsOptions = () => {
return options;
};
const DateRange = (props) => {
const DateRange = props => {
const { id, onChange, startDate, endDate } = props;
const [focusedInput, setFocusedInput] = useState(null);
const renderYearsOptionsCallback = useCallback(renderYearsOptions, []);
@@ -81,15 +81,15 @@ const DateRange = (props) => {
onYearSelect: PropTypes.func,
};
const handleMonthChange = (event) => {
const handleMonthChange = event => {
onMonthSelect(month, event.target.value);
};
const handleYearChange = (event) => {
const handleYearChange = event => {
onYearSelect(month, event.target.value);
};
const handleOnBlur = () => { };
const handleOnBlur = () => {};
return (
<div className="flex justify-center">
@@ -136,10 +136,10 @@ const DateRange = (props) => {
onChange({
startDate: newStartDate ? newStartDate.format('YYYYMMDD') : undefined,
endDate: newEndDate ? newEndDate.format('YYYYMMDD') : undefined,
})
});
}}
focusedInput={focusedInput}
onFocusChange={(updatedVal) => setFocusedInput(updatedVal)}
onFocusChange={updatedVal => setFocusedInput(updatedVal)}
/** OPTIONAL */
renderCalendarInfo={renderDatePresets}
renderMonthElement={renderMonthElement}
@@ -149,7 +149,7 @@ const DateRange = (props) => {
closeDatePicker: 'Close',
clearDates: 'Clear dates',
}}
isOutsideRange={(day) => !isInclusivelyBeforeDay(day, moment())}
isOutsideRange={day => !isInclusivelyBeforeDay(day, moment())}
hideKeyboardShortcutsPanel={true}
numberOfMonths={1}
showClearDates={false}
@@ -15,7 +15,14 @@ import { getKeys, formatKeysForInput } from './utils';
* @param {string} props.className input classes
* @param {Array[]} props.modifierKeys
*/
const HotkeyField = ({ disabled, keys, onChange, className, modifierKeys, hotkeys }) => {
const HotkeyField = ({
disabled,
keys,
onChange,
className,
modifierKeys,
hotkeys,
}) => {
const inputValue = formatKeysForInput(keys);
const onInputKeyDown = event => {
@@ -55,11 +62,11 @@ HotkeyField.propTypes = {
unpause: PropTypes.func.isRequired,
startRecording: PropTypes.func.isRequired,
record: PropTypes.func.isRequired,
}).isRequired
}).isRequired,
};
HotkeyField.defaultProps = {
disabled: false
disabled: false,
};
export default HotkeyField;
@@ -25,7 +25,4 @@ const getKeys = ({ sequence, modifierKeys }) => {
return [...modifiers, ...keys];
};
export {
getKeys,
formatKeysForInput
};
export { getKeys, formatKeysForInput };
@@ -72,7 +72,9 @@ const disallowedValidator = ({ pressedKeys = [] }) => {
if (hasDisallowedCombinations) {
return {
error: `"${formatPressedKeys(pressedKeys)}" shortcut combination is not allowed`,
error: `"${formatPressedKeys(
pressedKeys
)}" shortcut combination is not allowed`,
};
}
};
+2 -2
View File
@@ -13,8 +13,8 @@ const transparentClasses = {
const smallInputClasses = {
true: 'input-small',
false: ''
}
false: '',
};
const Input = ({
id,
@@ -82,45 +82,46 @@ const InputNumber: React.FC<{
);
return (
<div className={'flex flex-col flex-1'}>
<div className={'flex flex-col flex-1'}>
{label && <Label className={labelClassName} text={label}></Label>}
<div
className={`flex items-center bg-black border-2 px-1 overflow-hidden justify-center border-secondary-light rounded-md ${sizesClasses[size]
<div
className={`flex items-center bg-black border-2 px-1 overflow-hidden justify-center border-secondary-light rounded-md ${
sizesClasses[size]
} ${className ? className : ''}`}
>
<div className="flex">
<input
type="text"
value={numberValue}
onChange={handleChange}
className={`bg-black text-white text-[12px] w-full text-center input-number`}
/>
>
<div className="flex">
<input
type="text"
value={numberValue}
onChange={handleChange}
className={`bg-black text-white text-[12px] w-full text-center input-number`}
/>
<div className="up-arrowsize flex flex-col items-center justify-around">
<IconButton
id={'down-arrow-icon'}
variant="text"
color="inherit"
size="initial"
className="text-[#726f7e] transform rotate-180"
onClick={handleIncrement}
>
<Icon name="ui-arrow-down" />
</IconButton>
<IconButton
id={'down-arrow-icon'}
variant="text"
color="inherit"
size="initial"
className="text-[#726f7e]"
onClick={handleDecrement}
>
<Icon name="ui-arrow-down" />
</IconButton>
<div className="up-arrowsize flex flex-col items-center justify-around">
<IconButton
id={'down-arrow-icon'}
variant="text"
color="inherit"
size="initial"
className="text-[#726f7e] transform rotate-180"
onClick={handleIncrement}
>
<Icon name="ui-arrow-down" />
</IconButton>
<IconButton
id={'down-arrow-icon'}
variant="text"
color="inherit"
size="initial"
className="text-[#726f7e]"
onClick={handleDecrement}
>
<Icon name="ui-arrow-down" />
</IconButton>
</div>
</div>
</div>
</div>
</div>
);
};
@@ -1,7 +1,7 @@
import React, { useState } from 'react';
import PropTypes from 'prop-types';
function LayoutSelector({ onSelection, rows, columns}) {
function LayoutSelector({ onSelection, rows, columns }) {
const [hoveredIndex, setHoveredIndex] = useState();
const hoverX = hoveredIndex % columns;
const hoverY = Math.floor(hoveredIndex / columns);
@@ -12,7 +12,7 @@ function LayoutSelector({ onSelection, rows, columns}) {
return x <= hoverX && y <= hoverY;
};
const gridSize = '20px '
const gridSize = '20px ';
return (
<div
style={{
@@ -23,27 +23,31 @@ function LayoutSelector({ onSelection, rows, columns}) {
}}
className="p-2"
>
{Array.apply(null, Array(rows*columns)).map(function (_, i) {return i;}).map(index => (
<div
key={index}
style={{
border: '1px solid white',
backgroundColor: isHovered(index) ? '#5acce6' : '#0b1a42',
}}
className="cursor-pointer"
onClick={() => {
const x = index % columns;
const y = Math.floor(index / columns);
{Array.apply(null, Array(rows * columns))
.map(function(_, i) {
return i;
})
.map(index => (
<div
key={index}
style={{
border: '1px solid white',
backgroundColor: isHovered(index) ? '#5acce6' : '#0b1a42',
}}
className="cursor-pointer"
onClick={() => {
const x = index % columns;
const y = Math.floor(index / columns);
onSelection({
numRows: y + 1,
numCols: x + 1,
});
}}
onMouseEnter={() => setHoveredIndex(index)}
onMouseLeave={() => setHoveredIndex(-1)}
></div>
))}
onSelection({
numRows: y + 1,
numCols: x + 1,
});
}}
onMouseEnter={() => setHoveredIndex(index)}
onMouseLeave={() => setHoveredIndex(-1)}
></div>
))}
</div>
);
}
@@ -51,7 +55,7 @@ function LayoutSelector({ onSelection, rows, columns}) {
LayoutSelector.defaultProps = {
onSelection: () => {},
columns: 3,
rows: 3
rows: 3,
};
LayoutSelector.propTypes = {
@@ -12,11 +12,17 @@ const ListMenu = ({ items = [], renderer, onClick }) => {
const onClickHandler = () => {
setSelectedIndex(index);
onClick({ item, selectedIndex: index });
if (item.onClick) item.onClick({ ...item, index, isSelected });
if (item.onClick) {
item.onClick({ ...item, index, isSelected });
}
};
return (
<div className={classnames(flex, theme, 'cursor-pointer')} onClick={onClickHandler} data-cy={item.id}>
<div
className={classnames(flex, theme, 'cursor-pointer')}
onClick={onClickHandler}
data-cy={item.id}
>
{renderer && renderer({ ...item, index, isSelected })}
</div>
);
@@ -38,16 +44,16 @@ const ListMenu = ({ items = [], renderer, onClick }) => {
);
};
const noop = () => { };
const noop = () => {};
ListMenu.propTypes = {
items: PropTypes.array.isRequired,
renderer: PropTypes.func.isRequired,
onClick: PropTypes.func
onClick: PropTypes.func,
};
ListMenu.defaultProps = {
onClick: noop
onClick: noop,
};
export default ListMenu;
@@ -26,9 +26,9 @@ TableHead.defaultProps = {
};
TableHead.propTypes = {
children: function (props, propName, componentName) {
children: function(props, propName, componentName) {
const elements = React.Children.toArray(props.children);
const isString = elements.some((child) => typeof child === 'string');
const isString = elements.some(child => typeof child === 'string');
if (isString) {
return new Error(
@@ -37,7 +37,7 @@ TableHead.propTypes = {
}
const isInvalidElement = elements.some(
(child) => !React.isValidElement(child)
child => !React.isValidElement(child)
);
if (isInvalidElement) {
@@ -43,7 +43,9 @@ const Viewport = ({
},
]}
onSubmit={value => {
if (typeof window !== 'undefined') window.alert(value);
if (typeof window !== 'undefined') {
window.alert(value);
}
}}
/>
</div>
@@ -4,18 +4,21 @@ import classNames from 'classnames';
const WindowLevelMenuItem = ({ title, subtitle, isSelected, index }) => (
<>
<div className={classNames(
'flex flex-row items-center p-3 h-8 w-full hover:bg-primary-dark',
isSelected && 'bg-primary-dark'
)}
<div
className={classNames(
'flex flex-row items-center p-3 h-8 w-full hover:bg-primary-dark',
isSelected && 'bg-primary-dark'
)}
>
<span className='text-common-bright mr-2 text-base whitespace-nowrap'>
<span className="text-common-bright mr-2 text-base whitespace-nowrap">
{title}
</span>
<span className='flex-1 text-aqua-pale font-light text-sm whitespace-nowrap'>
<span className="flex-1 text-aqua-pale font-light text-sm whitespace-nowrap">
{subtitle}
</span>
<span className='text-primary-active ml-5 text-sm whitespace-nowrap'>{index + 1}</span>
<span className="text-primary-active ml-5 text-sm whitespace-nowrap">
{index + 1}
</span>
</div>
</>
);
@@ -27,7 +27,9 @@ export default function CineProvider({ children, service }) {
const { id, frameRate, isPlaying = undefined } = action.payload;
const cines = state.cines;
if (!cines[id]) cines[id] = { id, ...DEFAULT_CINE };
if (!cines[id]) {
cines[id] = { id, ...DEFAULT_CINE };
}
cines[id].frameRate = frameRate || cines[id].frameRate;
cines[id].isPlaying =
isPlaying !== undefined ? isPlaying : cines[id].isPlaying;
@@ -19,7 +19,7 @@ const DEFAULT_STATE = {
console.log('btn value?');
},
onOutsideClick: () => {
console.warn('default: onOutsideClick')
console.warn('default: onOutsideClick');
},
onDismiss: () => {
console.log('dismiss? -1');
@@ -135,7 +135,9 @@ export function ViewportGridProvider({ children, service }) {
// Have the initial id set contain all viewports not updated here
const viewportIdSet = new Set();
viewports.forEach((viewport, index) => {
if (!viewport.viewportId) return;
if (!viewport.viewportId) {
return;
}
const isUpdated = payload.find(
newViewport => newViewport.viewportIndex === index
);
@@ -228,7 +230,9 @@ export function ViewportGridProvider({ children, service }) {
activeViewportIndexToSet = pos;
}
const viewport = findOrCreateViewport(pos, positionId, options);
if (!viewport) continue;
if (!viewport) {
continue;
}
viewport.positionId = positionId;
// Create a new viewport object as it is getting updated here
// and it is part of the read only state
@@ -6,7 +6,7 @@ export const LinkComponent = ({
target: originalTarget,
rel,
}) => {
const onClick = (event) => {
const onClick = event => {
if (originalTarget) {
return;
}
@@ -32,7 +32,9 @@ export function createStoryMetaSettings({
}
});
if (component === Avatar) console.log(argTypes);
if (component === Avatar) {
console.log(argTypes);
}
// set icon allowed values inside argsTypes object
iconPropNamesArray?.forEach(propName => {